问:
how to receive strings from user to receive empty string and print them in c
how to receive strings from user to the empty string in c
receive the string and put into an array and then print it.

```<code>int main() {
    int i=0;
    char st[LEN];
    char ch;

    while(st[0]!='\0') {
        i=0;
        printf("Enter name of student:");

        while(ch!='\n') {
            ch=getchar();
            st[i]=ch;
            i++;
        }
    }
}
</code>```

答:
You have a number of options available to you to take into consideration. First, since you are reading lines-of-input containing the names, using a line-oriented input function like fgets makes a lot of sense. Then you only have two considerations to check regarding end of input, (1) fgets returns NULL indicating EOF or (2), you check the first character of the buffer filled by fgets to see if it is the '\n' character (indicating that Enter alone has been pressed.

Next you need to consider what data structure you will use to hold the array of names until you have gathered all the input. You can use an array of struct as shown in the other answer, or you can simply use a *pointer-to-pointer-to-char` (a double-pointer) to allocate pointers, as needed, and assign the address for an allocated block of memory containing each name.

The procedure is straight forward. First allocate some reasonably anticipated number of pointers to work with. Read names, allocate storage for each, copy the name to the allocated memory and then assign the memory address to each pointer. When you reach the limit of your currently allocated pointers, simply realloc additional pointers and keep going.

Once all the names have been collected, you simply output the names (I have included the pointer index as well) and then free the memory of each name and then after all names are printed and freed, free the pointers and you are done. You can do something similar to the following:

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

enum { MAXP = 32, MAXC = 256 };  /* constants */

void *xcalloc (size_t nmemb, size_t size); /* helper functions */
void *xrealloc (void *ptr, size_t psz, size_t *nelem, size_t inc);

int main (void) {

    size_t max = MAXP, n = 0;       /* initial ptrs and counter */
    char **a = xcalloc (max, sizeof *a);  /* mem for MAXP ptrs */

    for (;;) {                 /* loop until empty line or EOF */
        size_t len = 0;
        char buf[MAXC] = "";

        /* read into buf from stdin, check if empty */
        if (!fgets (buf, MAXC, stdin) || *buf == '\n')
            break;

        len = strlen (buf);     /* get length of buf */
        if (buf[len-1] == '\n') /* test for '\n' */
            buf[--len] = 0;     /* remove '\n' */

        a[n] = xcalloc (len + 1, 1);    /* mem to hold buf  */
        strcpy (a[n++], buf);           /* copy buf to a[n] */

        if (n + 1 == max) /* ptr limit reached, realloc ptr
                           * note: +1 insures a sentinel pointer
                           * with bits zeroed as the last pointer */
            a = xrealloc (a, sizeof *a, &max, MAXP);
    }

    for (size_t i = 0; i < n; i++) {    /* print and free mem */
        printf ("a[%3zd] : %s\n", i, a[i]);
        free (a[i]);   /* free memory allocated for each name */
    }
    free (a);  /* free pointers */

    return 0;
}

/* simple calloc with error-checking */
void *xcalloc (size_t nmemb, size_t size)
{
    void *memptr = calloc (nmemb, size);
    if (!memptr) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        exit (EXIT_FAILURE);
    }

    return memptr;
}

/* simple realloc with error-checking */
void *xrealloc (void *ptr, size_t psz, size_t *nelem, size_t inc)
{
    void *memptr = realloc ((char *)ptr, (*nelem + inc) * psz);
    if (!memptr) {
        fprintf (stderr, "realloc() error: virtual memory exhausted.\n");
        exit (EXIT_FAILURE);
    }   /* zero new memory (optional) */
    memset ((char *)memptr + *nelem * psz, 0, inc * psz);
    *nelem += inc; /* update number of elements allocated */

    return memptr;
}
</code>```

Above a static buffer of 256 characters was used to read each name from stdin. If for any reason that may not be enough, you can always validate a complete line was read by adding a check for the length and checking for the trailing '\n'.

Example Use/Output

```<code>$ ./bin/readprn <dat/namesfirst.txt
a[  0] : adam
a[  1] : allice
a[  2] : barny
a[  3] : beauregard
a[  4] : bell
a[  5] : benjamin
a[  6] : betty
a[  7] : bill
a[  8] : buck
a[  9] : buddy
a[ 10] : candice
a[ 11] : caset
a[ 12] : cathy
a[ 13] : charles
a[ 14] : chris
a[ 15] : chuck
a[ 16] : clark
a[ 17] : david
a[ 18] : don
a[ 19] : eli
a[ 20] : elizabeth
a[ 21] : emma
a[ 22] : eric
a[ 23] : ester
a[ 24] : frank
</code>```

The code behaves the same if you manually type each name and then press Enter alone on the final line. (I just happened to have a names file)

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you do not attempt to write beyond/outside the bounds of your allocated block of memory, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

```<code>$ valgrind ./bin/readprn <dat/namesfirst.txt
==28428== Memcheck, a memory error detector
==28428== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==28428== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==28428== Command: ./bin/readprn
==28428==
a[  0] : adam
<snip>
a[ 24] : frank
==28428==
==28428== HEAP SUMMARY:
==28428==     in use at exit: 0 bytes in 0 blocks
==28428==   total heap usage: 26 allocs, 26 frees, 413 bytes allocated
==28428==
==28428== All heap blocks were freed -- no leaks are possible
==28428==
==28428== For counts of detected and suppressed errors, rerun with: -v
==28428== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Look things over and let me know if you have further questions.

Body:
how to receive strings from user to the empty string in c
receive the string and put into an array and then print it.

int main() {
    int i=0;
    char st[LEN];
    char ch;

    while(st[0]!='\0') {
        i=0;
        printf("Enter name of student:");

        while(ch!='\n') {
            ch=getchar();
            st[i]=ch;
            i++;
        }
    }
}

Body:
You have a number of options available to you to take into consideration. First, since you are reading lines-of-input containing the names, using a line-oriented input function like fgets makes a lot of sense. Then you only have two considerations to check regarding end of input, (1) fgets returns NULL indicating EOF or (2), you check the first character of the buffer filled by fgets to see if it is the '\n' character (indicating that Enter alone has been pressed.

Next you need to consider what data structure you will use to hold the array of names until you have gathered all the input. You can use an array of struct as shown in the other answer, or you can simply use a *pointer-to-pointer-to-char` (a double-pointer) to allocate pointers, as needed, and assign the address for an allocated block of memory containing each name.

The procedure is straight forward. First allocate some reasonably anticipated number of pointers to work with. Read names, allocate storage for each, copy the name to the allocated memory and then assign the memory address to each pointer. When you reach the limit of your currently allocated pointers, simply realloc additional pointers and keep going.

Once all the names have been collected, you simply output the names (I have included the pointer index as well) and then free the memory of each name and then after all names are printed and freed, free the pointers and you are done. You can do something similar to the following:

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

enum { MAXP = 32, MAXC = 256 };  /* constants */

void *xcalloc (size_t nmemb, size_t size); /* helper functions */
void *xrealloc (void *ptr, size_t psz, size_t *nelem, size_t inc);

int main (void) {

    size_t max = MAXP, n = 0;       /* initial ptrs and counter */
    char **a = xcalloc (max, sizeof *a);  /* mem for MAXP ptrs */

    for (;;) {                 /* loop until empty line or EOF */
        size_t len = 0;
        char buf[MAXC] = "";

        /* read into buf from stdin, check if empty */
        if (!fgets (buf, MAXC, stdin) || *buf == '\n')
            break;

        len = strlen (buf);     /* get length of buf */
        if (buf[len-1] == '\n') /* test for '\n' */
            buf[--len] = 0;     /* remove '\n' */

        a[n] = xcalloc (len + 1, 1);    /* mem to hold buf  */
        strcpy (a[n++], buf);           /* copy buf to a[n] */

        if (n + 1 == max) /* ptr limit reached, realloc ptr
                           * note: +1 insures a sentinel pointer
                           * with bits zeroed as the last pointer */
            a = xrealloc (a, sizeof *a, &max, MAXP);
    }

    for (size_t i = 0; i < n; i++) {    /* print and free mem */
        printf ("a[%3zd] : %s\n", i, a[i]);
        free (a[i]);   /* free memory allocated for each name */
    }
    free (a);  /* free pointers */

    return 0;
}

/* simple calloc with error-checking */
void *xcalloc (size_t nmemb, size_t size)
{
    void *memptr = calloc (nmemb, size);
    if (!memptr) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        exit (EXIT_FAILURE);
    }

    return memptr;
}

/* simple realloc with error-checking */
void *xrealloc (void *ptr, size_t psz, size_t *nelem, size_t inc)
{
    void *memptr = realloc ((char *)ptr, (*nelem + inc) * psz);
    if (!memptr) {
        fprintf (stderr, "realloc() error: virtual memory exhausted.\n");
        exit (EXIT_FAILURE);
    }   /* zero new memory (optional) */
    memset ((char *)memptr + *nelem * psz, 0, inc * psz);
    *nelem += inc; /* update number of elements allocated */

    return memptr;
}

Above a static buffer of 256 characters was used to read each name from stdin. If for any reason that may not be enough, you can always validate a complete line was read by adding a check for the length and checking for the trailing '\n'.

Example Use/Output

$ ./bin/readprn <dat/namesfirst.txt
a[  0] : adam
a[  1] : allice
a[  2] : barny
a[  3] : beauregard
a[  4] : bell
a[  5] : benjamin
a[  6] : betty
a[  7] : bill
a[  8] : buck
a[  9] : buddy
a[ 10] : candice
a[ 11] : caset
a[ 12] : cathy
a[ 13] : charles
a[ 14] : chris
a[ 15] : chuck
a[ 16] : clark
a[ 17] : david
a[ 18] : don
a[ 19] : eli
a[ 20] : elizabeth
a[ 21] : emma
a[ 22] : eric
a[ 23] : ester
a[ 24] : frank

The code behaves the same if you manually type each name and then press Enter alone on the final line. (I just happened to have a names file)

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you do not attempt to write beyond/outside the bounds of your allocated block of memory, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

$ valgrind ./bin/readprn <dat/namesfirst.txt
==28428== Memcheck, a memory error detector
==28428== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==28428== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==28428== Command: ./bin/readprn
==28428==
a[  0] : adam
<snip>
a[ 24] : frank
==28428==
==28428== HEAP SUMMARY:
==28428==     in use at exit: 0 bytes in 0 blocks
==28428==   total heap usage: 26 allocs, 26 frees, 413 bytes allocated
==28428==
==28428== All heap blocks were freed -- no leaks are possible
==28428==
==28428== For counts of detected and suppressed errors, rerun with: -v
==28428== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.

Look things over and let me know if you have further questions.


来源: stackexchange

问:
Getting value on the basis of Id from Enums in Javascript
It has been quite sometime when I explored different ways of implementing Enums in javaScript

say I have an Enum names as Mediumas

```<code>    Medium : {
            ONLINE : {id: 1, desc: "Online"},
            CREDIT : {id: 2, desc: "Credit Card"},
            DEBIT : {id: 3, desc: "Debit Card"},
            NETBANKING : {id: 4, desc: "Net Banking"}
   }
</code>```

say I got an information that medium is 3.
Now from this information how can I get the details like description. In this case it should return "Debit card".

Searched a lot on internet but not able to get any lead.

答:
The order of properties in a JavaScript objects aren't guaranteed, so you'd need to use an array if you want to specify the position.  See this S.O question.

Alternatively, you could get the required property by using the id value within it? (See Prasad's answer above)

ContentLicense: CC BY-SA 3.0

Body:
It has been quite sometime when I explored different ways of implementing Enums in javaScript

say I have an Enum names as Mediumas

    Medium : {
            ONLINE : {id: 1, desc: "Online"},
            CREDIT : {id: 2, desc: "Credit Card"},
            DEBIT : {id: 3, desc: "Debit Card"},
            NETBANKING : {id: 4, desc: "Net Banking"}
   }

say I got an information that medium is 3.
Now from this information how can I get the details like description. In this case it should return "Debit card".

Searched a lot on internet but not able to get any lead.


问:
Text overflow ellipsis on two lines
I know you can use a combination of CSS rules to make text end with ellipsis (...) when it's time to overflow (get out of parent's bounds).

Is it possible (feel free to just say, no) to achieve the same effect, but let the text wrap on more than one line?

Here's a demo.

```<code>div {
  width: 300px;
  height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</code>```

As you can see, the text ends with ellipsis when it goes wider than the div's width. However, there is still enough space for the text to wrap on a second line and go on. This is interrupted by white-space: nowrap, which is required for the ellipsis to work.

Any ideas?

P.S.: No JS solutions, pure CSS if possible.

答:
Here is a simple script to manage the ellipsis using jQuery.
It inspects the real height of the element and it creates a hidden original node and a truncated node.
When the user clicks it switches between the two versions.

One of the great benefits is that the "ellipsis" is near the last word, as expected.

If you use pure CSS solutions the three dots appears distant from the last word.

function manageShortMessages() {

        $('.myLongVerticalText').each(function () {
            if ($(this)[0].scrollHeight > $(this)[0].clientHeight)
                $(this).addClass('ellipsis short');
        });

        $('.myLongVerticalText.ellipsis').each(function () {
            var original = $(this).clone().addClass('original notruncation').removeClass('short').hide();
            $(this).after(original);

            //debugger;
            var shortText = '';
            shortText = $(this).html().trim().substring(0, 60) + '...';
            $(this).html(shortText);
        });

        $('.myLongVerticalText.ellipsis').click(function () {
            $(this).hide();

            if ($(this).hasClass('original'))
            {
                $(this).parent().find('.short').show();
            }
            else
            {
                $(this).parent().find('.original').show();
            }
        });
    }

  manageShortMessages();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
 border:1px solid red;
 margin:10px;
}

div.myLongVerticalText {
  height:30px;
  width:450px;
}

div.myLongVerticalText.ellipsis {
 cursor:pointer;
}

div.myLongVerticalText.original {
  display:inline-block;
  height:inherit;
}</code>```

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sit amet quam hendrerit, sagittis augue vel, placerat erat. Aliquam varius porta posuere. Aliquam erat volutpat. Phasellus ullamcorper malesuada bibendum. Etiam fringilla, massa vitae pulvinar vehicula, augue orci mollis lorem, laoreet viverra massa eros id est. Phasellus suscipit pulvinar consectetur. Proin dignissim egestas erat at feugiat. Aenean eu consectetur erat. Nullam condimentum turpis eu tristique malesuada.

Aenean sagittis ex sagittis ullamcorper auctor. Sed varius commodo dui, nec consectetur ante condimentum et. Donec nec blandit mi, vitae blandit elit. Phasellus efficitur ornare est facilisis commodo. Donec convallis nunc sed mauris vehicula, non faucibus neque vehicula. Donec scelerisque luctus dui eu commodo. Integer eu quam sit amet dui tincidunt pharetra eu ac quam. Quisque tempus pellentesque hendrerit. Sed orci quam, posuere eu feugiat at, congue sed felis. In ut lectus gravida, volutpat urna vitae, cursus justo. Nam suscipit est ac accumsan consectetur. Donec rhoncus placerat metus, ut elementum massa facilisis eget. Donec at arcu ac magna viverra tincidunt.

One Line Lorem ipsum dolor sit amet.

```

Title: Text overflow ellipsis on two lines

Body:
I know you can use a combination of CSS rules to make text end with ellipsis (...) when it's time to overflow (get out of parent's bounds).

Is it possible (feel free to just say, no) to achieve the same effect, but let the text wrap on more than one line?

Here's a demo.

div {
  width: 300px;
  height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

As you can see, the text ends with ellipsis when it goes wider than the div's width. However, there is still enough space for the text to wrap on a second line and go on. This is interrupted by white-space: nowrap, which is required for the ellipsis to work.

Any ideas?

P.S.: No JS solutions, pure CSS if possible.

Body:
Here is a simple script to manage the ellipsis using jQuery.
It inspects the real height of the element and it creates a hidden original node and a truncated node.
When the user clicks it switches between the two versions.

One of the great benefits is that the "ellipsis" is near the last word, as expected.

If you use pure CSS solutions the three dots appears distant from the last word.

function manageShortMessages() {

        $('.myLongVerticalText').each(function () {
            if ($(this)[0].scrollHeight > $(this)[0].clientHeight)
                $(this).addClass('ellipsis short');
        });

        $('.myLongVerticalText.ellipsis').each(function () {
            var original = $(this).clone().addClass('original notruncation').removeClass('short').hide();
            $(this).after(original);

            //debugger;
            var shortText = '';
            shortText = $(this).html().trim().substring(0, 60) + '...';
            $(this).html(shortText);
        });

        $('.myLongVerticalText.ellipsis').click(function () {
            $(this).hide();

            if ($(this).hasClass('original'))
            {
                $(this).parent().find('.short').show();
            }
            else
            {
                $(this).parent().find('.original').show();
            }
        });
    }

  manageShortMessages();

div {
 border:1px solid red;
 margin:10px;
}

div.myLongVerticalText {
  height:30px;
  width:450px;
}

div.myLongVerticalText.ellipsis {
 cursor:pointer;
}

div.myLongVerticalText.original {
  display:inline-block;
  height:inherit;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="myLongVerticalText">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sit amet quam hendrerit, sagittis augue vel, placerat erat. Aliquam varius porta posuere. Aliquam erat volutpat. Phasellus ullamcorper malesuada bibendum. Etiam fringilla, massa vitae pulvinar vehicula, augue orci mollis lorem, laoreet viverra massa eros id est. Phasellus suscipit pulvinar consectetur. Proin dignissim egestas erat at feugiat. Aenean eu consectetur erat. Nullam condimentum turpis eu tristique malesuada.

Aenean sagittis ex sagittis ullamcorper auctor. Sed varius commodo dui, nec consectetur ante condimentum et. Donec nec blandit mi, vitae blandit elit. Phasellus efficitur ornare est facilisis commodo. Donec convallis nunc sed mauris vehicula, non faucibus neque vehicula. Donec scelerisque luctus dui eu commodo. Integer eu quam sit amet dui tincidunt pharetra eu ac quam. Quisque tempus pellentesque hendrerit. Sed orci quam, posuere eu feugiat at, congue sed felis. In ut lectus gravida, volutpat urna vitae, cursus justo. Nam suscipit est ac accumsan consectetur. Donec rhoncus placerat metus, ut elementum massa facilisis eget. Donec at arcu ac magna viverra tincidunt.
</div>

<div class="myLongVerticalText">
One Line Lorem ipsum dolor sit amet.
</div>
</body>


问:
DateTime.ParseExact to NodaTime ZonedDateTime issue
I'm having an issue converting a parsed string into a correct NodaTime ZonedDateTime. The below method takes a string (allegedly in UTC) pushed by the brokers server, and returns a ZonedDateTime with the DateTimeZone being set to UTC. The domain model will only accept ZonedDateTime objects so this is happening at the system boundary.

For example, a string being passed as the argument being exactly '2017060623:20:10' would then return a ZonedDateTime like 2017-06-06T13-:20:10 (curiously a ten hour difference, my local time zone here in Sydney is +10 UTC).

```<code>public static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
{
    var dotNetDateTime = DateTime.ParseExact(
        dateTime,
        "yyyyMMddHH:mm:ss,
        CultureInfo.InvariantCulture)
        .ToUniversalTime();

    return new ZonedDateTime(Instant.FromDateTimeUtc(dotNetDateTime), DateTimeZone.Utc);
}
</code>```

So I changed the method to the below, which works, but I'm sure there's a better way. I'm certain my error is that I'm somehow involving my local time zone, rather than keeping everything in UTC.

```<code>public static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
{
    var parsedDateTime = DateTime.ParseExact(
        dateTime,
        "yyyyMMddHH:mm:ss",
        CultureInfo.InvariantCulture);

    var dotNetDateTime = new DateTime(
        parsedDateTime.Year,
        parsedDateTime.Month,
        parsedDateTime.Day,
        parsedDateTime.Hour,
        parsedDateTime.Minute,
        parsedDateTime.Second,
        DateTimeKind.Utc);

    return new ZonedDateTime(Instant.FromDateTimeUtc(dotNetDateTime), DateTimeZone.Utc);
}
</code>```

答:
I would suggest not using DateTime at all. You're using Noda Time - so go all in :)

To parse text as a ZonedDateTime, you use a ZonedDateTimePattern. Here's an example:

```<code>using System;
using NodaTime;
using NodaTime.Text;

class Program
{
    static void Main(string[] args)
    {
        string text = "2017060623:20:10";
        Console.WriteLine(GetZonedDateTimeUtcFromMarketDataString(text));

    }

    static readonly ZonedDateTimePattern ParsePattern =
        ZonedDateTimePattern.CreateWithInvariantCulture(
           "yyyyMMddHH:mm:ss",
           DateTimeZoneProviders.Tzdb); // Won't actually be used...

    static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
        => ParsePattern.Parse(dateTime).Value;
}
</code>```

The default template value already uses UTC as a time zone, so you don't need to worry about that.

Alternatively, you could use a LocalDateTimePattern given that the text you're using doesn't specify a time zone - parse to a LocalDateTime and then call LocalDateTime.InUtc().

All of this raises another question though, which is why you're parsing the value to a ZonedDateTime at all. If you've always got a UTC value, do you really need it to be a ZonedDateTime rather than an Instant? You don't know the time zone the value was originally observed in, so it feels more like a point in time to me.

Body:
I'm having an issue converting a parsed string into a correct NodaTime ZonedDateTime. The below method takes a string (allegedly in UTC) pushed by the brokers server, and returns a ZonedDateTime with the DateTimeZone being set to UTC. The domain model will only accept ZonedDateTime objects so this is happening at the system boundary.

For example, a string being passed as the argument being exactly '2017060623:20:10' would then return a ZonedDateTime like 2017-06-06T13-:20:10 (curiously a ten hour difference, my local time zone here in Sydney is +10 UTC).

public static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
{
    var dotNetDateTime = DateTime.ParseExact(
        dateTime,
        "yyyyMMddHH:mm:ss,
        CultureInfo.InvariantCulture)
        .ToUniversalTime();

    return new ZonedDateTime(Instant.FromDateTimeUtc(dotNetDateTime), DateTimeZone.Utc);
}

So I changed the method to the below, which works, but I'm sure there's a better way. I'm certain my error is that I'm somehow involving my local time zone, rather than keeping everything in UTC.

public static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
{
    var parsedDateTime = DateTime.ParseExact(
        dateTime,
        "yyyyMMddHH:mm:ss",
        CultureInfo.InvariantCulture);

    var dotNetDateTime = new DateTime(
        parsedDateTime.Year,
        parsedDateTime.Month,
        parsedDateTime.Day,
        parsedDateTime.Hour,
        parsedDateTime.Minute,
        parsedDateTime.Second,
        DateTimeKind.Utc);

    return new ZonedDateTime(Instant.FromDateTimeUtc(dotNetDateTime), DateTimeZone.Utc);
}

Body:
I would suggest not using DateTime at all. You're using Noda Time - so go all in :)

To parse text as a ZonedDateTime, you use a ZonedDateTimePattern. Here's an example:

using System;
using NodaTime;
using NodaTime.Text;

class Program
{
    static void Main(string[] args)
    {
        string text = "2017060623:20:10";
        Console.WriteLine(GetZonedDateTimeUtcFromMarketDataString(text));

    }

    static readonly ZonedDateTimePattern ParsePattern =
        ZonedDateTimePattern.CreateWithInvariantCulture(
           "yyyyMMddHH:mm:ss",
           DateTimeZoneProviders.Tzdb); // Won't actually be used...

    static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
        => ParsePattern.Parse(dateTime).Value;
}

The default template value already uses UTC as a time zone, so you don't need to worry about that.

Alternatively, you could use a LocalDateTimePattern given that the text you're using doesn't specify a time zone - parse to a LocalDateTime and then call LocalDateTime.InUtc().

All of this raises another question though, which is why you're parsing the value to a ZonedDateTime at all. If you've always got a UTC value, do you really need it to be a ZonedDateTime rather than an Instant? You don't know the time zone the value was originally observed in, so it feels more like a point in time to me.


问:
Use TO_CHAR function to display the Fiscal Year
Is there a way in ORACLE that can display the Fiscal Year?

For example, I can write this query in SQL SERVER to pull the FYs but don't know how to write it in ORACLE.

```<code>SELECT
DATEPART(yyyy, DATEADD(mm, 3, DATE)) AS FY
FROM MYTABLE
</code>```

Output:

```<code>FY
----
2009
2010
2011
</code>```

What can I try to resolve this?

答:
```<code>SELECT TO_CHAR(ADD_MONTHS(MYDATE, 3),'YYYY') fy FROM MYTABLE
</code>```

Is probably the same

ContentLicense: CC BY-SA 4.0

Body:
Is there a way in ORACLE that can display the Fiscal Year?

For example, I can write this query in SQL SERVER to pull the FYs but don't know how to write it in ORACLE.

SELECT
DATEPART(yyyy, DATEADD(mm, 3, DATE)) AS FY
FROM MYTABLE

Output:

FY
----
2009
2010
2011

What can I try to resolve this?

Body:
SELECT TO_CHAR(ADD_MONTHS(MYDATE, 3),'YYYY') fy FROM MYTABLE

Is probably the same

ContentLicense: CC BY-SA 2.5


问:
MKMapView setRegion: causes app to crash in iOS SDK
I want to zoom MKMapView on custom coordinates. So I using following code.

```<code>CLLocationCoordinate2D myCurrentLocationCordinate = CLLocationCoordinate2DMake(latitude, longtitude);
[myMapView setCenterCoordinate:myCurrentLocationCordinate animated:YES];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(myCurrentLocationCordinate, 500, 500);
MKCoordinateRegion adjustedRegion = [myMapView regionThatFits:viewRegion];
[myMapView setRegion:adjustedRegion animated:YES];
</code>```

But my app is randomly crashing on setRegion: Method. And getting this log when it is crashing :-

adjustedRegion description: (MKCoordinateRegion) adjustedRegion = {

  center = (latitude = 23.066432958888399, longitude =
  72.531898498535213)   span = (latitudeDelta = 0.0051205743267423998, longitudeDelta = 0.0048793707173899747) }

Also sometimes getting following error :-

* Terminating app due to uncaught exception 'NSGenericException',
  reason: '(null) must implement title when canShowCallout is YES on
  corresponding view >'
  * First throw call stack: (0x18e8b91b8 0x18d2f055c 0x19ab76244 0x19abb2c74 0x19ab74d44 0x19ab8db58 0x19477c7dc 0x19abb041c
  0x19abb0290 0x19abb1588 0x1001ae010 0x1001ad318 0x101265258
  0x101265218 0x101275080 0x101274b78 0x18d94b2a0 0x18d94ad8c)
  libc++abi.dylib: terminating with uncaught exception of type
  NSException

I am sure not why it is crashing randomly. Let me know if any other proper solution for zooming the MKMapView on custom coordinates.

Any help would be appreciated.

答:
I handle my mapView zoom this way. Could you try it this way? </p>

```<code>CLLocationCoordinate2D zoomLocation = CLLocationCoordinate2DMake(40.741168, 30.333555);
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5* 1609.344, 0.5* 1609.344);

[self.myMapview setRegion:viewRegion animated:YES];
[self.myMapview setDelegate:self];
</code>```

Body:
I want to zoom MKMapView on custom coordinates. So I using following code.

CLLocationCoordinate2D myCurrentLocationCordinate = CLLocationCoordinate2DMake(latitude, longtitude);
[myMapView setCenterCoordinate:myCurrentLocationCordinate animated:YES];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(myCurrentLocationCordinate, 500, 500);
MKCoordinateRegion adjustedRegion = [myMapView regionThatFits:viewRegion];
[myMapView setRegion:adjustedRegion animated:YES];

But my app is randomly crashing on setRegion: Method. And getting this log when it is crashing :-

adjustedRegion description: (MKCoordinateRegion) adjustedRegion = {

  center = (latitude = 23.066432958888399, longitude =
  72.531898498535213)   span = (latitudeDelta = 0.0051205743267423998, longitudeDelta = 0.0048793707173899747) }

Also sometimes getting following error :-

* Terminating app due to uncaught exception 'NSGenericException',
  reason: '(null) must implement title when canShowCallout is YES on
  corresponding view >'
  * First throw call stack: (0x18e8b91b8 0x18d2f055c 0x19ab76244 0x19abb2c74 0x19ab74d44 0x19ab8db58 0x19477c7dc 0x19abb041c
  0x19abb0290 0x19abb1588 0x1001ae010 0x1001ad318 0x101265258
  0x101265218 0x101275080 0x101274b78 0x18d94b2a0 0x18d94ad8c)
  libc++abi.dylib: terminating with uncaught exception of type
  NSException

I am sure not why it is crashing randomly. Let me know if any other proper solution for zooming the MKMapView on custom coordinates.

Any help would be appreciated.

Body:
I handle my mapView zoom this way. Could you try it this way?

CLLocationCoordinate2D zoomLocation = CLLocationCoordinate2DMake(40.741168, 30.333555);
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5* 1609.344, 0.5* 1609.344);

[self.myMapview setRegion:viewRegion animated:YES];
[self.myMapview setDelegate:self];


问:
How do I increase or decrease the size of a button in Swift?
I have a UIButton in my app that I call "buttonPlay". I am using AutoLayout but the button doesn't have any NSLayoutConstraints attached to it.

I would like to code an animation to increase and the decrease the height and the width of the button. Here's how the animation code looks like:

```<code>    // "Repeat" because the animation must repeat itself
    UIView.animateWithDuration(1.0, delay: 0.6, options: UIViewAnimationOptions.Repeat, animations: {
        // Animation code goes here
        // nil: the animation is not supposed to end
        }, completion: nil)
}
</code>```

To get the original values of the x position, y position, width and height I am using the following code:

```<code>var frmPlay : CGRect = self.buttonPlay.frame

// get the current x and y positions
        let originXbutton = frmPlay.origin.x
        let originYbutton = frmPlay.origin.y

// get the current width and height of the button
        let originWidthbutton = frmPlay.size.width
        let originHeightbutton = frmPlay.size.height

// set the frame (frmPlay) to the button frame
        self.buttonPlay.frame = frmPlay
</code>```

Okay, it's now time to increase or decrease the width and the height of the animation. I'll put this code inside the animation block:

```<code>        self.buttonPlay.frame = CGRectMake(
            originXbutton,
            originYbutton,
            originWidthbutton-100,
            originHeightbutton)

        self.buttonPlay.frame = CGRectMake(
            originXbutton,
            originYbutton,
            originWidthbutton+100,
            originHeightbutton)
</code>```

The animation code will look something like this:

```<code>    UIView.animateWithDuration(1.0, delay: 0.6, options: UIViewAnimationOptions.Repeat, animations: {

        println("Animation function animateStuff() started!")

        var frmPlay : CGRect = self.buttonPlay.frame

        let originXbutton = frmPlay.origin.x
        let originYbutton = frmPlay.origin.y

        let originWidthbutton = frmPlay.size.width
        let originHeightbutton = frmPlay.size.height

        self.buttonPlay.frame = frmPlay

        self.buttonPlay.frame = CGRectMake(
            originXbutton,
            originYbutton,
            originWidthbutton-100,
            originHeightbutton)

        self.buttonPlay.frame = CGRectMake(
            originXbutton,
            originYbutton,
            originWidthbutton+100,
            originHeightbutton)

        }, completion: nil)
</code>```

Let's run the app. Uh oh! The button (also called buttonPlay) doesn't get bigger or smaller in any way. Though it moves from right to left. But hey! I haven't touched the x and the y positions code.

What causes it?

答:
My solution in Swift 3:

```<code>func animate(sender: UIButton) {

    let buttonSize: CGRect = sender.frame

    let originXbutton = buttonSize.origin.x
    let originYbutton = buttonSize.origin.y

    let originWidthbutton = buttonSize.size.width
    let originHeightbutton = buttonSize.size.height

    UIView.animate(withDuration: 0.2, animations: {
        sender.frame = CGRect(x: originXbutton, y: originYbutton - 5, width: originWidthbutton + 3, height: originHeightbutton + 3)
    }, completion: { finished in
        sender.frame = CGRect(x: originXbutton, y: originYbutton, width: originWidthbutton, height: originHeightbutton)
    })
}
</code>```

Body:
I have a UIButton in my app that I call "buttonPlay". I am using AutoLayout but the button doesn't have any NSLayoutConstraints attached to it.

I would like to code an animation to increase and the decrease the height and the width of the button. Here's how the animation code looks like:

    // "Repeat" because the animation must repeat itself
    UIView.animateWithDuration(1.0, delay: 0.6, options: UIViewAnimationOptions.Repeat, animations: {
        // Animation code goes here
        // nil: the animation is not supposed to end
        }, completion: nil)
}

To get the original values of the x position, y position, width and height I am using the following code:

var frmPlay : CGRect = self.buttonPlay.frame

// get the current x and y positions
        let originXbutton = frmPlay.origin.x
        let originYbutton = frmPlay.origin.y

// get the current width and height of the button
        let originWidthbutton = frmPlay.size.width
        let originHeightbutton = frmPlay.size.height

// set the frame (frmPlay) to the button frame
        self.buttonPlay.frame = frmPlay

Okay, it's now time to increase or decrease the width and the height of the animation. I'll put this code inside the animation block:

        self.buttonPlay.frame = CGRectMake(
            originXbutton,
            originYbutton,
            originWidthbutton-100,
            originHeightbutton)

        self.buttonPlay.frame = CGRectMake(
            originXbutton,
            originYbutton,
            originWidthbutton+100,
            originHeightbutton)

The animation code will look something like this:

    UIView.animateWithDuration(1.0, delay: 0.6, options: UIViewAnimationOptions.Repeat, animations: {

        println("Animation function animateStuff() started!")

        var frmPlay : CGRect = self.buttonPlay.frame

        let originXbutton = frmPlay.origin.x
        let originYbutton = frmPlay.origin.y

        let originWidthbutton = frmPlay.size.width
        let originHeightbutton = frmPlay.size.height

        self.buttonPlay.frame = frmPlay

        self.buttonPlay.frame = CGRectMake(
            originXbutton,
            originYbutton,
            originWidthbutton-100,
            originHeightbutton)

        self.buttonPlay.frame = CGRectMake(
            originXbutton,
            originYbutton,
            originWidthbutton+100,
            originHeightbutton)

        }, completion: nil)

Let's run the app. Uh oh! The button (also called buttonPlay) doesn't get bigger or smaller in any way. Though it moves from right to left. But hey! I haven't touched the x and the y positions code.

What causes it?

Body:
My solution in Swift 3:

func animate(sender: UIButton) {

    let buttonSize: CGRect = sender.frame

    let originXbutton = buttonSize.origin.x
    let originYbutton = buttonSize.origin.y

    let originWidthbutton = buttonSize.size.width
    let originHeightbutton = buttonSize.size.height

    UIView.animate(withDuration: 0.2, animations: {
        sender.frame = CGRect(x: originXbutton, y: originYbutton - 5, width: originWidthbutton + 3, height: originHeightbutton + 3)
    }, completion: { finished in
        sender.frame = CGRect(x: originXbutton, y: originYbutton, width: originWidthbutton, height: originHeightbutton)
    })
}


问:
Connection of signals and slots (regarding qlistview) - Qt
I need to connect a singal and a slot but I can't seem to figure out it's structure, I need to connect a qlistview double click and I need the number starting from the top that the element was in, for example, if I had a qlistview with 5 elements, and you clicked the 2nd one I need to know that the second element was clicked. In use I'm doing a network connection and the qlistview shows the aviable networks. </p>

<p>Summing up I would like to know the snippet of code I have to use to achieve this because I can't figure it out. </p>

答:
To get the row index of the clicked item you can simply access the QModelIndex in the doubleClicked slot of your QListView, e.g.

```<code>int row = index.row();
</code>```

Maybe you should read the introduction to Qt's model view classes to get a general idea how everything is connected.

Body:
I need to connect a singal and a slot but I can't seem to figure out it's structure, I need to connect a qlistview double click and I need the number starting from the top that the element was in, for example, if I had a qlistview with 5 elements, and you clicked the 2nd one I need to know that the second element was clicked. In use I'm doing a network connection and the qlistview shows the aviable networks.

Summing up I would like to know the snippet of code I have to use to achieve this because I can't figure it out.

Body:
To get the row index of the clicked item you can simply access the QModelIndex in the doubleClicked slot of your QListView, e.g.

int row = index.row();

Maybe you should read the introduction to Qt's model view classes to get a general idea how everything is connected.


问:
I can't get HealthKit to work. Missing Entitlement
I am having a hard time to get HealthKit working for my iOS App. I have done all the steps I have found so far and none seem to solve my problem I keep getting this error when trying to authorize Healthkit:

```<code>Error Domain=com.apple.healthkit Code=4 "Missing com.apple.developer.healthkit entitlement." UserInfo=0x78fa24e0 {NSLocalizedDescription=Missing com.apple.developer.healthkit entitlement.}
</code>```

Here is my code asking for authorization:

```<code>    if([HKHealthStore isHealthDataAvailable]) {

        self.healthStore = [[HKHealthStore alloc] init];

        [self.healthStore requestAuthorizationToShareTypes:nil readTypes:[self dataTypesToRead] completion:^(BOOL success, NSError *error) {

            if (!success) {
                NSLog(@"HK Error: %@", error);
                [self presentHealthAlert:@"You didn't allow APP to access HealthKit Data. Please go to Settings and set up APP permissions." withTitle:@"Error"];
            } else {
                [self presentHealthAlert:@"Thank You For Access" withTitle:@"Success"];
            }
        }];

    } else {
        [self presentHealthAlert:@"Health Data Not Available" withTitle:@"Success"];
    }
</code>```

And Yes, I have enabled it on my project Capabilites, and yes I have enabled it in my Dev Center App ID. Is there anything else I might be missing?

答: You may find that although you have turned on the HealthKit entitlement on in xcode that there is a second entitlements file that does not contain the healthkit boolean. I found that while the obvious entitlements file (at the top level) had the correct information, a different entitlements file had been created under Resources that did not contain the healthkit entitlement. fixing that file fixed my problem.</p>

Body:
I am having a hard time to get HealthKit working for my iOS App. I have done all the steps I have found so far and none seem to solve my problem I keep getting this error when trying to authorize Healthkit:

Error Domain=com.apple.healthkit Code=4 "Missing com.apple.developer.healthkit entitlement." UserInfo=0x78fa24e0 {NSLocalizedDescription=Missing com.apple.developer.healthkit entitlement.}

Here is my code asking for authorization:

    if([HKHealthStore isHealthDataAvailable]) {

        self.healthStore = [[HKHealthStore alloc] init];

        [self.healthStore requestAuthorizationToShareTypes:nil readTypes:[self dataTypesToRead] completion:^(BOOL success, NSError *error) {

            if (!success) {
                NSLog(@"HK Error: %@", error);
                [self presentHealthAlert:@"You didn't allow APP to access HealthKit Data. Please go to Settings and set up APP permissions." withTitle:@"Error"];
            } else {
                [self presentHealthAlert:@"Thank You For Access" withTitle:@"Success"];
            }
        }];

    } else {
        [self presentHealthAlert:@"Health Data Not Available" withTitle:@"Success"];
    }

And Yes, I have enabled it on my project Capabilites, and yes I have enabled it in my Dev Center App ID. Is there anything else I might be missing?


问:
Internet Explorer doesn't expand a flexbox with flex-direction: column
I'm trying to create a container with a static header and a body that expands based on its contents up to a maximum height. After the maximum height is reached, the body should scroll. I've written code that works great in Chrome/Firefox, but in IE, the container doesn't expand correctly.

div{
  border: 1px solid #DDD;
}

.container{
  max-height: 150px;
  display: flex;
  flex-direction: column;
}

.header{
  height: 40px;
}

.scroll{
  flex: 1;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="header">
    header
  </div>
  <div class="scroll">
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
    <div>scroll</div>
  </div>
</div></code>```

If I use flex-direction: row; instead, the height expands appropriately, but obviously my header doesn't look right then.

Is there a workaround to get a growing container with a header and scrolling body to work with IE11 and Edge? I'm not opposed to abandoning flexbox if necessary.

答:
The fix from @Michael_B did not really work for me because my container must not get a fixed/relative height. Also the tip to make the height: 0 was not working on smaller screens.

The solution: Adding a flexbox wrapper around container

Adding a wrapper around your container will make it magically work:

```<code><div class="container-wrapper">
  <div class="container">
    <div class="header">header</div>
    <div class="scroll">...</div>
  </div>
</div>
</code>```

And then styling:

```<code>.container-wrapper {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.scroll {
  flex-grow: 1;
}
</code>```

Body:
I'm trying to create a container with a static header and a body that expands based on its contents up to a maximum height. After the maximum height is reached, the body should scroll. I've written code that works great in Chrome/Firefox, but in IE, the container doesn't expand correctly.

div{
  border: 1px solid #DDD;
}

.container{
  max-height: 150px;
  display: flex;
  flex-direction: column;
}

.header{
  height: 40px;
}

.scroll{
  flex: 1;
  overflow: auto;
}

    header

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

If I use flex-direction: row; instead, the height expands appropriately, but obviously my header doesn't look right then.

Is there a workaround to get a growing container with a header and scrolling body to work with IE11 and Edge? I'm not opposed to abandoning flexbox if necessary.

Body:
The fix from @Michael_B did not really work for me because my container must not get a fixed/relative height. Also the tip to make the height: 0 was not working on smaller screens.

The solution: Adding a flexbox wrapper around container

Adding a wrapper around your container will make it magically work:

<div class="container-wrapper">
  <div class="container">
    <div class="header">header</div>
    <div class="scroll">...</div>
  </div>
</div>

And then styling:

.container-wrapper {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.scroll {
  flex-grow: 1;
}


问:
Undefined offset: 6 while reading fopen
```<code>           foreach($posts as $post)
    {
        $words = preg_split("/\|/", $post);
        $author     = trim($words[0]) . ' ' . trim($words[1]);
        $title      = trim($words[2]);
        $comment    = trim($words[3]);
        $priority   = trim($words[4]);
        $filename   = trim($words[5]);
        $postedTime = $words[6];
</code>```

I'm passing a .txt file into an html form, the file is missing some information that I am not supposed to display. When reading it I get an undefined offset 6 on $postedTime, the file is missing the value. Any ideas how to avoid the message?

答:
To avoid the message You can do something like this:</p>

```<code>$postedTime = isset($words[6]) && !empty($words[6]) ? $words[6] : '';
</code>```

Title: Undefined offset: 6 while reading fopen

Body:
           foreach($posts as $post)
    {
        $words = preg_split("/\|/", $post);
        $author     = trim($words[0]) . ' ' . trim($words[1]);
        $title      = trim($words[2]);
        $comment    = trim($words[3]);
        $priority   = trim($words[4]);
        $filename   = trim($words[5]);
        $postedTime = $words[6];

I'm passing a .txt file into an html form, the file is missing some information that I am not supposed to display. When reading it I get an undefined offset 6 on $postedTime, the file is missing the value. Any ideas how to avoid the message?

Body:
To avoid the message You can do something like this:

$postedTime = isset($words[6]) && !empty($words[6]) ? $words[6] : '';


问:
Using reflection to capture error details
I have a quick question that hopefully someone has worked through before. In the system that I am currently working on, we have rolled our own custom provider for handling web exceptions. One of the things that I like about this provider is that it allows us to add in parameter values of the method that throws the exception. The code looks something like this.

```<code>Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        Dim ErrorDetails = New List(Of String)

        ErrorDetails.Add("Parameter Values:")
        ErrorDetails.Add(String.Format("Parameter 1: {0}", Parameter1))
        ErrorDetails.Add(String.Format("Parameter 2: {0}", Parameter2))

        RaiseNewCustomException(ex, ErrorDetails)
    End Try
End Sub
</code>```

In the case of this method, the capture of the parameters and their values is very manual and prone to error as more and more people touch the code base and forget to update the thrown error. Is there a way to approach this problem in a more automated / less error prone way?

I have played around with reflection, but I don't think you can ascertain the parameter values via reflection. I would like something like:

```<code>Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        RaiseNewCustomExceptionAndAutomaticallyGenerateParameterErrorString(ex, System.Reflection.MethodInfo.GetCurrentMethod())
    End Try
End Sub
</code>```

答: Reflection will not give you the parameter values. This is discussed in Stack Overflow questions Using reflection to get method name and parameters and Obtain parameter values from a stack frame in .NET?.

Body:
I have a quick question that hopefully someone has worked through before. In the system that I am currently working on, we have rolled our own custom provider for handling web exceptions. One of the things that I like about this provider is that it allows us to add in parameter values of the method that throws the exception. The code looks something like this.

Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        Dim ErrorDetails = New List(Of String)

        ErrorDetails.Add("Parameter Values:")
        ErrorDetails.Add(String.Format("Parameter 1: {0}", Parameter1))
        ErrorDetails.Add(String.Format("Parameter 2: {0}", Parameter2))

        RaiseNewCustomException(ex, ErrorDetails)
    End Try
End Sub

In the case of this method, the capture of the parameters and their values is very manual and prone to error as more and more people touch the code base and forget to update the thrown error. Is there a way to approach this problem in a more automated / less error prone way?

I have played around with reflection, but I don't think you can ascertain the parameter values via reflection. I would like something like:

Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        RaiseNewCustomExceptionAndAutomaticallyGenerateParameterErrorString(ex, System.Reflection.MethodInfo.GetCurrentMethod())
    End Try
End Sub


问:
how to set the bash scripts with in the python scripts rather than having separate scripts?
This is how I running the bash script set in myscript.sh

```<code>#!/bin/bash
import subprocess
child = subprocess.Popen(['bash', '-c', '/bin/bash myscript.sh'], stdout = subprocess.PIPE)
output=child.communicate()
print(output)
</code>```

myscript.sh

Why am I making this is because the bash script that I have to run does not have the export command so I am echoing here. Code bellow. I know echoing wont set the environment variable but I just want to echo it and fetch the value so echoing instead of exporting.

```<code>#!/bin/bash
source ia_servers
echo $IA_SRV_cs68_64
</code>```

Where, $IA_SRV_cs68_64

Here is the ia_servers file where the variable values are listed
it looks something like this

```<code>IA_SRV_cs68_64="ds1 ds2 ds3 ds5 "
</code>```

This is how the variables are in it. Many other variable are set in it eliminated because too longer.

TESTED works well from terminal:

source ia_servers

echo IA_SRV_cs68_64

prints the desired values set

Problem:
Though myscript.sh is working and printing the variables . What I want is I don't want to create a separate file write a bash script there to echo the variable as in the myscript.sh but  instead write it within the python.

How do I accomplish it within the python rather rather than making the
  script file and run that.

答:
```<code># i assume there is a file by name `ia_servers` with variable IA_SRV_cs68_64="ds1 ds2 ds3 ds5 "

import imp
ia_servers =imp.load_source('ia_servers', 'path to `ia_servers` file')

print ia_servers.IA_SRV_cs68_64 # this should print `ds1 ds2 ds3 ds5`
</code>```

Body:
This is how I running the bash script set in myscript.sh

#!/bin/bash
import subprocess
child = subprocess.Popen(['bash', '-c', '/bin/bash myscript.sh'], stdout = subprocess.PIPE)
output=child.communicate()
print(output)

myscript.sh

Why am I making this is because the bash script that I have to run does not have the export command so I am echoing here. Code bellow. I know echoing wont set the environment variable but I just want to echo it and fetch the value so echoing instead of exporting.

#!/bin/bash
source ia_servers
echo $IA_SRV_cs68_64

Where, $IA_SRV_cs68_64

Here is the ia_servers file where the variable values are listed
it looks something like this

IA_SRV_cs68_64="ds1 ds2 ds3 ds5 "

This is how the variables are in it. Many other variable are set in it eliminated because too longer.

TESTED works well from terminal:

source ia_servers

echo IA_SRV_cs68_64

prints the desired values set

Problem:
Though myscript.sh is working and printing the variables . What I want is I don't want to create a separate file write a bash script there to echo the variable as in the myscript.sh but  instead write it within the python.

How do I accomplish it within the python rather rather than making the
  script file and run that.


问:
Symfony preg_match a route
I need to preg_match my route, i try like this :

```<code>if (preg_match('surveillance', $request->headers->get('referer'))){
     var_dump("match");
} else {
     var_dump("dont match");
}
</code>```

With my headers get referer i get :

```<code>http://.../surveillance/item/veille/h/55
</code>```

and i would like get return "match" if i have "surveillance".

答:
Your search string is not variable and you are not concerned with its location in the header string, so regex is not the best method for your case.

Just use strpos() like this:

```<code>if (strpos($request->headers->get('referer'),'surveillance')!==false){
     var_dump("match");
} else {
     var_dump("dont match");
}
</code>```

But the above will match surveillance ANYWHERE in the header string.  If you want to try to check that the full string surveillance is being used as a directory value, you could wrap it in slashes (/):

```<code>if (strpos($request->headers->get('referer'),'/surveillance/')!==false){
     var_dump("match");
} else {
     var_dump("dont match");
}
</code>```

I don't know about Symfony, so Mawcel might be right on in his/her post.

Beyond these options, if you want to be really sure that surveillance is being used as a valid/existing directory on your server, then you'll have to look into other functions that check if the directory exists.  If this isn't on your server, then you might want to look into a more refined regex pattern that checks the substring location.

Title: Symfony preg_match a route

Body:
I need to preg_match my route, i try like this :

if (preg_match('surveillance', $request->headers->get('referer'))){
     var_dump("match");
} else {
     var_dump("dont match");
}

With my headers get referer i get :

http://.../surveillance/item/veille/h/55

and i would like get return "match" if i have "surveillance".

Body:
Your search string is not variable and you are not concerned with its location in the header string, so regex is not the best method for your case.

Just use strpos() like this:

if (strpos($request->headers->get('referer'),'surveillance')!==false){
     var_dump("match");
} else {
     var_dump("dont match");
}

But the above will match surveillance ANYWHERE in the header string.  If you want to try to check that the full string surveillance is being used as a directory value, you could wrap it in slashes (/):

if (strpos($request->headers->get('referer'),'/surveillance/')!==false){
     var_dump("match");
} else {
     var_dump("dont match");
}

I don't know about Symfony, so Mawcel might be right on in his/her post.

Beyond these options, if you want to be really sure that surveillance is being used as a valid/existing directory on your server, then you'll have to look into other functions that check if the directory exists.  If this isn't on your server, then you might want to look into a more refined regex pattern that checks the substring location.


问:
Launch "new email" window on Mac OS X with c++
Can I trigger my Mac to open the default mail client "new message" window from my C++ program. It should work just like a mailto link does. When the program runs it should open a "new message" window with a message body, a subject line, and a recipient already filled in. I DON'T need to include an attachment. I know there are some answers already on Stack Overflow addressing that question.
A mailto link with the functionality I need looks something like this:

```<code>    "mailto:bob@domain.com?subject=look at this website&body=Hi,I found this website."
</code>```

If it is not possible to use mailto directly in C++, is there some other way of doing what I am looking for?

Thank you for your help!

答:
This simple code does what I need! It launches the default mail client window with a given recipient address, subject, and message body.
"email", "subject", and "bodyMessage" are all string variables declared in my complete program code. This snippet doesn't include their declarations.

```<code>       string mailTo = "mailto:" + email + "?subject=" + subject + "\\&body=" + bodyMessage;
       string command = "open " + mailTo;
       system(command.c_str());
</code>```

This post on using the "open" command helped.

Body:
Can I trigger my Mac to open the default mail client "new message" window from my C++ program. It should work just like a mailto link does. When the program runs it should open a "new message" window with a message body, a subject line, and a recipient already filled in. I DON'T need to include an attachment. I know there are some answers already on Stack Overflow addressing that question.
A mailto link with the functionality I need looks something like this:

    "mailto:bob@domain.com?subject=look at this website&body=Hi,I found this website."

If it is not possible to use mailto directly in C++, is there some other way of doing what I am looking for?

Thank you for your help!

Body:
This simple code does what I need! It launches the default mail client window with a given recipient address, subject, and message body.
"email", "subject", and "bodyMessage" are all string variables declared in my complete program code. This snippet doesn't include their declarations.

       string mailTo = "mailto:" + email + "?subject=" + subject + "\\&body=" + bodyMessage;
       string command = "open " + mailTo;
       system(command.c_str());

This post on using the "open" command helped.


问:
Find order by based on column value not column name
I have a  query where I want to order based on column value not column name i.e.

Suppose I have a column "Description" in table and in my sql I have like condition as

```<code>Select * from tableName
where Description like '%Bombay%'
or Description like '%Hotel%' like Description like '%Rent%'
</code>```

I want to order the records if column Description have all the three values or two values or one value i.e. if all the three values are in Description column it should be in at top

Is it possible in sql ?

答:
```<code>drop table if exists dbo.tableName;

create table dbo.tableName (
ID int primary key
, Description varchar(100)
);

insert into dbo.tableName (ID, Description)
values (1, 'Hotel Bombay Rent')
, (2, 'Hotel Bombay')
, (3, 'Hotel')
, (4, 'Aparment');

select
t.ID
, t.Description
from dbo.tableName t
order by (case when t.Description like '%Hotel%' then 1 else 0 end)
+ (case when t.Description like '%Bombay%' then 1 else 0 end)
+ (case when t.Description like '%Rent%' then 1 else 0 end) desc
</code>```

Body:
I have a  query where I want to order based on column value not column name i.e.

Suppose I have a column "Description" in table and in my sql I have like condition as

Select * from tableName
where Description like '%Bombay%'
or Description like '%Hotel%' like Description like '%Rent%'

I want to order the records if column Description have all the three values or two values or one value i.e. if all the three values are in Description column it should be in at top

Is it possible in sql ?


问:
Writing a function for smoothing center values in specified range
I'm not sure this is the right place to ask this kind of question (maybe mathematica would be better ?).

I'm writing a program that reads input values from an analog joystick.

The values range from -100 to 100 with 0 being the center value.

My problem is, the stick values aren't very precise in the center area. For example, with the stick released, I should get an input value equal to 0 but I often get values like 2, 7, -5, etc (almost never exceeding 10 or -10).

What I'd like to do is applying a "smoothing" function to reduce the values around the 0 area.

I'm not experienced with mathematics and the best function I could find so far is:

```<code>function smooth(x)  {
    return Math.pow(x,3)/10000;
}
</code>```

This gives me this kind of values:

As you can see, this function is too "aggressive" because even f(20) ~= 0 !

Any idea of which better function I could use ?

答:
You could check if the absolute value is smaller or equal to 10 and return zero instead of the value.</p>

```<code>function smooth(x)  {
    return Math.abs(x) <= 10 ? 0 : x;
}
</code>```

Body:
I'm not sure this is the right place to ask this kind of question (maybe mathematica would be better ?).

I'm writing a program that reads input values from an analog joystick.

The values range from -100 to 100 with 0 being the center value.

My problem is, the stick values aren't very precise in the center area. For example, with the stick released, I should get an input value equal to 0 but I often get values like 2, 7, -5, etc (almost never exceeding 10 or -10).

What I'd like to do is applying a "smoothing" function to reduce the values around the 0 area.

I'm not experienced with mathematics and the best function I could find so far is:

function smooth(x)  {
    return Math.pow(x,3)/10000;
}

This gives me this kind of values:

As you can see, this function is too "aggressive" because even f(20) ~= 0 !

Any idea of which better function I could use ?

Body:
You could check if the absolute value is smaller or equal to 10 and return zero instead of the value.

function smooth(x)  {
    return Math.abs(x) <= 10 ? 0 : x;
}


答:
try with Array#find method

var   PaymentMedium ={
            ONLINE : {id: 1, desc: "Online"},
            CREDIT : {id: 2, desc: "Credit Card"},
            DEBIT : {id: 3, desc: "Debit Card"},
            NETBANKING : {id: 4, desc: "Net Banking"}
   }

   function get(id){
   return Object.values(PaymentMedium).find(a=> (a.id == id)).desc
   }
   console.log(get(3))```

Title: Getting value on the basis of Id from Enums in Javascript

Body:
It has been quite sometime when I explored different ways of implementing Enums in javaScript

say I have an Enum names as Mediumas

    Medium : {
            ONLINE : {id: 1, desc: "Online"},
            CREDIT : {id: 2, desc: "Credit Card"},
            DEBIT : {id: 3, desc: "Debit Card"},
            NETBANKING : {id: 4, desc: "Net Banking"}
   }

say I got an information that medium is 3.
Now from this information how can I get the details like description. In this case it should return "Debit card".

Searched a lot on internet but not able to get any lead.


答:
try this:</p>

```<code>$postedTime = (isset($words[6]))?$words[6]:'';
</code>```

Title: Undefined offset: 6 while reading fopen

Body:
try this:

$postedTime = (isset($words[6]))?$words[6]:'';


问:
Handle the status of JSON by Retrofit call
I want to process JSON output from Rest call based on the status. So what will be the required approach?

Here is my method from RetrofitApi class

```<code>@POST("KeepHoldTisConfirmation")
Observable<ResultOutput> putHoldTis(@Body ResultOutput body);
</code>```

Here is my MyObject class Structure

```<code>public int filterId;
public String type;
</code>```

Here is my ResultOutput class Structure

```<code>public int status;
public List<MyObject> data;
</code>```

If success my JSON output is:-

```<code>{"status":1,"data":[{"filterId":1,"type":"flower"},{"filterId":2,"type":"sand"}]}
</code>```

If error my JSON output is:-

```<code>{"status":2,"data":"Invalid key"}
</code>```

Here is my Observable code:-

```<code>Observable.fromIterable(entities)
                .filter(tisEntity -> "1".equals(tisEntity.isTisHold))
                .concatMapEager(tisEntity -> {
                    Log.d(TAG,"insert = "+tisEntity.hitachiCode);
                    return hitachiRetrofitApi.putHoldTis(new TisHoldEntity(tisEntity.projectId, tisEntity.holdReason, "76800",
                        tisEntity.holdComment,tisEntity.hitachiCode, 1));})
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<ResultOutput>() {

                    @Override
                    public void onNext(ResultOutput responseBody) {
                        // handle here status and accordingly process output
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        cancleProgressDialog();
                    }

                    @Override
                    public void onComplete() {

                        Log.d(TAG, "on complete for entity");
                        updateTisDetails();
                    }
                });
</code>```

Here, what should I write inside onNext()?

答:
You can build a bean like this

```<code>classe Result {
    public int status;
    public String data;
}
</code>```

First way parse the json from responseBody.body().string();

Second way make RetrofitApi class

```<code>@POST("KeepHoldTisConfirmation")
Observable<Result> putHoldTis(@Body ResultOutput body);
</code>```

OnNext parse the Result.data.

Another way, make ConverterFactory class

```<code>public final class ConverterFactory<T> extends Converter.Factory {

  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(final Type type, Annotation[] annotations,
      final Retrofit retrofit) {
    return new Converter<ResponseBody, T>() {

      @Override
      public T convert(ResponseBody value) throws IOException {
        String origin = value.string();

        try {
          Result response = JSON.parseObject(origin, Result.class);
          if (response.status == 1) {
              return JSON.parseObject(response.data, type);
          } else {
              throw new HttpException(Response.error(2, value));
          }
        } finally {
          value.close();
        }
      }
    };
  }
  ...
}
</code>```

When build Retrofit add the Factory

```<code>new Retrofit.Builder().addConverterFactory(ConverterFactory.create());
</code>```

Then you can handle the error in OnError()

```<code>@Override
public void onError(Throwable e) {
    if (e != null && e instanceof HttpException) {
       HttpException exception = (HttpException) e;
       int code = exception.code();
       Response response = exception.response();
       String error = null;
       if (null != response && null != response.errorBody()) {
           Result response = JSON.parseObject(origin, Result.class);
           error = response.data
       }
    }
}
</code>```

Body:
I want to process JSON output from Rest call based on the status. So what will be the required approach?

Here is my method from RetrofitApi class

@POST("KeepHoldTisConfirmation")
Observable<ResultOutput> putHoldTis(@Body ResultOutput body);

Here is my MyObject class Structure

public int filterId;
public String type;

Here is my ResultOutput class Structure

public int status;
public List<MyObject> data;

If success my JSON output is:-

{"status":1,"data":[{"filterId":1,"type":"flower"},{"filterId":2,"type":"sand"}]}

If error my JSON output is:-

{"status":2,"data":"Invalid key"}

Here is my Observable code:-

Observable.fromIterable(entities)
                .filter(tisEntity -> "1".equals(tisEntity.isTisHold))
                .concatMapEager(tisEntity -> {
                    Log.d(TAG,"insert = "+tisEntity.hitachiCode);
                    return hitachiRetrofitApi.putHoldTis(new TisHoldEntity(tisEntity.projectId, tisEntity.holdReason, "76800",
                        tisEntity.holdComment,tisEntity.hitachiCode, 1));})
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<ResultOutput>() {

                    @Override
                    public void onNext(ResultOutput responseBody) {
                        // handle here status and accordingly process output
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        cancleProgressDialog();
                    }

                    @Override
                    public void onComplete() {

                        Log.d(TAG, "on complete for entity");
                        updateTisDetails();
                    }
                });

Here, what should I write inside onNext()?

Body:
You can build a bean like this

classe Result {
    public int status;
    public String data;
}

First way parse the json from responseBody.body().string();

Second way make RetrofitApi class

@POST("KeepHoldTisConfirmation")
Observable<Result> putHoldTis(@Body ResultOutput body);

OnNext parse the Result.data.

Another way, make ConverterFactory class

public final class ConverterFactory<T> extends Converter.Factory {

  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(final Type type, Annotation[] annotations,
      final Retrofit retrofit) {
    return new Converter<ResponseBody, T>() {

      @Override
      public T convert(ResponseBody value) throws IOException {
        String origin = value.string();

        try {
          Result response = JSON.parseObject(origin, Result.class);
          if (response.status == 1) {
              return JSON.parseObject(response.data, type);
          } else {
              throw new HttpException(Response.error(2, value));
          }
        } finally {
          value.close();
        }
      }
    };
  }
  ...
}

When build Retrofit add the Factory

new Retrofit.Builder().addConverterFactory(ConverterFactory.create());

Then you can handle the error in OnError()

@Override
public void onError(Throwable e) {
    if (e != null && e instanceof HttpException) {
       HttpException exception = (HttpException) e;
       int code = exception.code();
       Response response = exception.response();
       String error = null;
       if (null != response && null != response.errorBody()) {
           Result response = JSON.parseObject(origin, Result.class);
           error = response.data
       }
    }
}


问:
Query to find the FIRST AND SECOND largest value from a group
i have a query like this:

```<code>SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)
</code>```

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

答:
Hmmm it's kind of a rig, but you can do this with subqueries... instead of using that max I'd select the some_values which have the matching year & month, row_number()=1 / row_number() = 2 respectively and order by some_value DESC.

The inability to use OFFSET / LIMIT like you can in SQLite is one of my dislikes about SQL Server.

Body:
i have a query like this:

SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)


问:
update table by getting a value from another view Yii
i'm using yii framework here. i need help, how to put a value to my textfield and update my table while the value that i take is from the other view.

i have a main table (A) where this table have id, proj_name, design_start_date, design_end_date. while my other table (B) have id, design_start, design_end. value of design_start_date will update by the minimum date from design_start and design_end_date will update by the maximum date from design_end

can anybody help me? thanks in advance

答:
try it</p>

```<code>update
tableA a
set design_start_date =
(select min(design_start) from tableB b where b.id= a.id),
design_end_date =
(select max(design_end) from tableB b where b.id= a.id)
</code>```

Body:
try it

update
tableA a
set design_start_date =
(select min(design_start) from tableB b where b.id= a.id),
design_end_date =
(select max(design_end) from tableB b where b.id= a.id)


问:
How to implement reference to another model in Relay Mutations on the server side?
I'm stuck with Refs in Relay Mutation and globalIdField.

So let's say that comment can have parent comment id, must have post id in props and I have a Mutation defined with following schema:

```<code>const createComment = mutationWithClientMutationId({
  name: 'CreateComment',
  description: 'Create comment of the post',
  inputFields: {
    content: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Content of the comment',
    },
    parent: {
      type: GraphQLID,
      description: 'Parent of the comment',
    },
    post: {
      type: new GraphQLNonNull(GraphQLID),
      description: 'Post of the comment',
    },
  },
  outputFields: {
    comment: { type: commentType, resolve: comment => comment },
  },
  mutateAndGetPayload: (input, context) => (context.user
    ? Comment.create(Object.assign(input, { author: context.user._id }))
    : new Error('Only logged in user can create new comment')),
});
</code>```

My comment has globalIdField, postType too. When I will query mutation from client I will use everywhere globalIds instead of real mongo _id of this objects. Is here the better way for it instead this piece in mutateAndGetPayload:

```<code>mutateAndGetPayload: (input, context) => {
  if (input.parent) input.parent = fromGlobalId(input.parent).id;
  if (input.post) input.post = fromGlobalId(input.post).id;
  // And other logic
}
</code>```

It can be very convinient if I can just add globalIdField() in post, but Relay can't pass this, because field in inputFields can't have a resolver function which globalIdField has.

答:
So far I can't find solution better than below:

```<code>mutateAndGetPayload: ({ content, post, parent }, context) => {
    if (!context.user) throw new Error('Only logged in user can create new comment');
    const newComment = { author: context.user._id, content };
    if (post) newComment.post = fromGlobalId(post).id;
    if (parent) newComment.parent = fromGlobalId(parent).id;
    return Comment.create(newComment);
  },
</code>```

Would be so glad if somebody will provide better experience with this.

Body:
I'm stuck with Refs in Relay Mutation and globalIdField.

So let's say that comment can have parent comment id, must have post id in props and I have a Mutation defined with following schema:

const createComment = mutationWithClientMutationId({
  name: 'CreateComment',
  description: 'Create comment of the post',
  inputFields: {
    content: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Content of the comment',
    },
    parent: {
      type: GraphQLID,
      description: 'Parent of the comment',
    },
    post: {
      type: new GraphQLNonNull(GraphQLID),
      description: 'Post of the comment',
    },
  },
  outputFields: {
    comment: { type: commentType, resolve: comment => comment },
  },
  mutateAndGetPayload: (input, context) => (context.user
    ? Comment.create(Object.assign(input, { author: context.user._id }))
    : new Error('Only logged in user can create new comment')),
});

My comment has globalIdField, postType too. When I will query mutation from client I will use everywhere globalIds instead of real mongo _id of this objects. Is here the better way for it instead this piece in mutateAndGetPayload:

mutateAndGetPayload: (input, context) => {
  if (input.parent) input.parent = fromGlobalId(input.parent).id;
  if (input.post) input.post = fromGlobalId(input.post).id;
  // And other logic
}

It can be very convinient if I can just add globalIdField() in post, but Relay can't pass this, because field in inputFields can't have a resolver function which globalIdField has.

Body:
So far I can't find solution better than below:

mutateAndGetPayload: ({ content, post, parent }, context) => {
    if (!context.user) throw new Error('Only logged in user can create new comment');
    const newComment = { author: context.user._id, content };
    if (post) newComment.post = fromGlobalId(post).id;
    if (parent) newComment.parent = fromGlobalId(parent).id;
    return Comment.create(newComment);
  },

Would be so glad if somebody will provide better experience with this.


问:
Move user object across domain
We wrote a migration tool (C#) for a large domain migration project of a customer. The customer has one forest with one parent domain and several child domains. They want to move all user objects from the child domains to the parent domain.

Apart from a lot of customer specific stuff, the migration tool moves user objects from the child to the parent domain using following ADSI method:

IADsContainer::MoveHere
https://msdn.microsoft.com/en-us/library/aa705991%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

According to the following article it is possible to move objects across domains if certain requirements are met:
https://technet.microsoft.com/en-us/library/ee198798.aspx?f=255&MSPPError=-2147217396

For test purpose I am using following VBScript which does basically the same as my C# application:

```<code>Set objOU = GetObject("LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com")
objOU.MoveHere "LDAP://cn=AckermanPilar,ou=Management,dc=fabrikam,dc=com",vbNullString
</code>```

The VBScript from above works in my test environment. If we try the same script in the production it fails with following useless error message:

```<code>Error: The server is unwilling to process the request.
Code: 80072035
Source: Active Directory
</code>```

However if we run the same script to move a user object from the parent domain to the child domain it works.

The user object we try to move doesn't have any group memberships apart from the primary group which is a universal group. We run the script from the source domain (child) and the user account we use to run the script has enterprise administrator privileges. We also double checked all the requirements from the links above.

Does anyone have an idea what the problem might be and/or how I can solve it?

答:
We tried alot of different configurations, permissions, settings and so on. In the end we tried to run the script on a different domain controller (also in the child domain) and it just worked.

We haven't found out yet what the differences are between those two domain controllers but it works for now.

Update: The server on which the script runs has the PDC role. I haven't found any article that says you have to run the script on a PDC but it looks like you have to.

Title: Move user object across domain

Body:
We wrote a migration tool (C#) for a large domain migration project of a customer. The customer has one forest with one parent domain and several child domains. They want to move all user objects from the child domains to the parent domain.

Apart from a lot of customer specific stuff, the migration tool moves user objects from the child to the parent domain using following ADSI method:

IADsContainer::MoveHere
https://msdn.microsoft.com/en-us/library/aa705991%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

According to the following article it is possible to move objects across domains if certain requirements are met:
https://technet.microsoft.com/en-us/library/ee198798.aspx?f=255&MSPPError=-2147217396

For test purpose I am using following VBScript which does basically the same as my C# application:

Set objOU = GetObject("LDAP://ou=Management,dc=NA,dc=fabrikam,dc=com")
objOU.MoveHere "LDAP://cn=AckermanPilar,ou=Management,dc=fabrikam,dc=com",vbNullString

The VBScript from above works in my test environment. If we try the same script in the production it fails with following useless error message:

Error: The server is unwilling to process the request.
Code: 80072035
Source: Active Directory

However if we run the same script to move a user object from the parent domain to the child domain it works.

The user object we try to move doesn't have any group memberships apart from the primary group which is a universal group. We run the script from the source domain (child) and the user account we use to run the script has enterprise administrator privileges. We also double checked all the requirements from the links above.

Does anyone have an idea what the problem might be and/or how I can solve it?


问:
Display the data I get from ajax on view
This is the modal where I want to display the value I get from ajax data but it's not working. I have the id="view_name" on span element. I don't know what the problem is it won't display

This is the code that triggers the fun_view function:

```<code><td>
    <a href="" data-id="" class="display" data-toggle="modal" data-target="#myModal" onclick="fun_view('{{ $dat->id }},{{ $dat->name }},{{ $dat->company_name }}, {{ $dat->mobile_phone }}, {{ $dat->timezone }}, {{ $dat->best_time_to_call }}')"><?php echo $dat->name;?></a>
</td>

<div class="modal-body">
    <p><b>Name : </b><span id="view_name" class="text-success"></span></p>
    <p><b>Company Name : </b><span id="view_company_name" class="text-success"></span></p>
    <p><b>Mobile Phone : </b><span id="view_mobile" class="text-success"></span></p>
</div>

<script>
function fun_view(id,name,company_name,mobile_phone,timezone,best_time_to_call)
{
    var view_url = $("#hidden_view").val();

    $.ajax({
        url: view_url,
        type:"GET",
        data:
        {
            "id": id,
            "name": name,
            "company_name": company_name,
            "mobile_phone": mobile_phone,
            "timezone": timezone,
            "best_time_to_call": best_time_to_call
        },
        success: function(result){
          //when I alert(result.name) it says undefined
          $("#view_name").text(result.name);
          $("#view_company_name").text(result.company_name);
          $("#view_mobile").text(result.mobile_phone);
        }
    });
}
</script>
</code>```

答:
You might have forgotten to include a reference to the JQuery script.</p>

```<code><script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
</code>```

Body:
This is the modal where I want to display the value I get from ajax data but it's not working. I have the id="view_name" on span element. I don't know what the problem is it won't display

This is the code that triggers the fun_view function:

    id }},{{ $dat->name }},{{ $dat->company_name }}, {{ $dat->mobile_phone }}, {{ $dat->timezone }}, {{ $dat->best_time_to_call }}')"><?php echo $dat->name;?>

Name :

Company Name :

Mobile Phone :

Body:
You might have forgotten to include a reference to the JQuery script.

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>


问:
"File Not Found" while trying to compile an RC file (probably dumb mistake)
Following these steps for adding a UAC manifest to my C# project embedded as a resource.

Step 1 works fine, I create the RC file in my project as a simple text file as described.

```<code>#include <winuser.h>
#define IDR_MANIFEST 1 // 2 for a DLL

IDR_MANIFEST RT_MANIFEST MOVEABLE PURE
{
 "<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
   <asmv3:trustInfo xmlns:asmv3=""urn:schemas-microsoft-com:asm.v3"">
     <asmv3:security>
       <asmv3:requestedPrivileges>
         <asmv3:requestedExecutionLevel
           level=""asInvoker""
           uiAccess=""false"" />
       </asmv3:requestedPrivileges>
     </asmv3:security>
   </asmv3:trustInfo>
  </assembly>"
}
</code>```

Then using the Visual Studio Command Prompt, I get the following output at step 2:

```<code>  c:\myproject>rc MyResourceFile.rc
  Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
  Copyright (C) Microsoft Corporation.  All rights reserved.

  ConfigurationManager.rc(4) : error RC2135 : file not found: 1
</code>```

I assume this is something quite dumb, right?

答: I ended up using mt.exe to embed the manifest in the .exe file in a post-build step. But Hans's answer was close enough. So I guess the mystery of the "File Not Found" will remain unsolved...</p>

Body:
Following these steps for adding a UAC manifest to my C# project embedded as a resource.

Step 1 works fine, I create the RC file in my project as a simple text file as described.

#include <winuser.h>
#define IDR_MANIFEST 1 // 2 for a DLL

IDR_MANIFEST RT_MANIFEST MOVEABLE PURE
{
 "<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
   <asmv3:trustInfo xmlns:asmv3=""urn:schemas-microsoft-com:asm.v3"">
     <asmv3:security>
       <asmv3:requestedPrivileges>
         <asmv3:requestedExecutionLevel
           level=""asInvoker""
           uiAccess=""false"" />
       </asmv3:requestedPrivileges>
     </asmv3:security>
   </asmv3:trustInfo>
  </assembly>"
}

Then using the Visual Studio Command Prompt, I get the following output at step 2:

  c:\myproject>rc MyResourceFile.rc
  Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
  Copyright (C) Microsoft Corporation.  All rights reserved.

  ConfigurationManager.rc(4) : error RC2135 : file not found: 1

I assume this is something quite dumb, right?


问:
How to unit test java main method?
I have a class to which I must pass 2 arguments through its main method, if passed less than 2 args, it displays a system error message. I wrote a unit test for the main method here, when I run the test, it stops at "running" (shows neither pass nor fail). Please suggest.

Example.java

```<code>public class Example
{
    private static String str1   = null;
    private static String str2   = null;

    public static void main(String[] args)
    {
        if( args.length != 2 )
        {
            call();
        }

        Example ex = new Example(args[0], args[1]);
        ex.getData();
    }

    public Example(String str1, String str2)
    {
        Example.str1 = str1;
        Example.str2 = str2;
    }

    public void getData(){
        System.out.println("Name is: "+str1);
        System.out.println("City is: "+str2);
    }

    private static void call()
    {
        System.err.println("Usage: String1 String2");
        System.err.println("Where: ");
        System.err.println("       String1 - Name");
        System.err.println("       String1 - City");
        System.exit(1);
    }
}
</code>```

ExampleTest.java

```<code>public class ExampleTest {
    @Test
    public void testPassingWrongNumberOfInputs() {
        StringBuffer sb = new StringBuffer();
        sb.append("Usage: String1 String2")
        .append("Where: ")
        .append("       String1 - Name")
        .append("       String1 - City");

        String expectedErrorMessage = sb.toString();

        ByteArrayOutputStream outContent = new ByteArrayOutputStream();
        System.setErr(new PrintStream(outContent));
        String[] args = {"one"};
        Example.main(args);

        assertEquals(expectedErrorMessage, outContent.toString());
    }
}
</code>```

答: Rename the main method, and add a return value, so you can test it. Call this new method from main.</p>

Title: How to unit test java main method?

Body:
I have a class to which I must pass 2 arguments through its main method, if passed less than 2 args, it displays a system error message. I wrote a unit test for the main method here, when I run the test, it stops at "running" (shows neither pass nor fail). Please suggest.

Example.java

public class Example
{
    private static String str1   = null;
    private static String str2   = null;

    public static void main(String[] args)
    {
        if( args.length != 2 )
        {
            call();
        }

        Example ex = new Example(args[0], args[1]);
        ex.getData();
    }

    public Example(String str1, String str2)
    {
        Example.str1 = str1;
        Example.str2 = str2;
    }

    public void getData(){
        System.out.println("Name is: "+str1);
        System.out.println("City is: "+str2);
    }

    private static void call()
    {
        System.err.println("Usage: String1 String2");
        System.err.println("Where: ");
        System.err.println("       String1 - Name");
        System.err.println("       String1 - City");
        System.exit(1);
    }
}

ExampleTest.java

public class ExampleTest {
    @Test
    public void testPassingWrongNumberOfInputs() {
        StringBuffer sb = new StringBuffer();
        sb.append("Usage: String1 String2")
        .append("Where: ")
        .append("       String1 - Name")
        .append("       String1 - City");

        String expectedErrorMessage = sb.toString();

        ByteArrayOutputStream outContent = new ByteArrayOutputStream();
        System.setErr(new PrintStream(outContent));
        String[] args = {"one"};
        Example.main(args);

        assertEquals(expectedErrorMessage, outContent.toString());
    }
}


问:
generic way of testing order by clause in rails using minitest
I have a default scope in a model defined as follows:

default_scope { order(created_at: :desc) }

and a test defined as follows:

```<code>class ItemTest < ActiveSupport::TestCase
  def setup
    @first_item = items(:one)
    @second_item = items(:two)
    @third_item = items(:three)
    @fourth_item = items(:four)
  end

  test "items should be ordered by time they got created ( default scope)" do
    assert_equal [@fourth_item,@third_item, @second_item, @first_item], Item.all
  end
</code>```

and  fixtures:

```<code>one:
  created_at: 2017-06-06 00:00:00 -0700

two:
  created_at: 2017-06-06 00:00:02 -0700

three:
  created_at: 2017-06-06 00:00:09 -0700

four:
  created_at: 2017-06-06 00:00:30 -0700
</code>```

test passes however , everytime I add a new fixture to the above fixture file , the test fails and  I have to add that new item to the array in assert_equals statement.

I tried this answer which seems very generic but test still passes when its suppose to fail

```<code>items = Items.first(3) # and items.first(3).reverse still passes as well :(
assert_equals [items[0], items[1], items[2]], items
</code>```

but unfortunately , the test passes even when I change the order to ASC where it suppose to be failing.

is there a generic way of testing a specific number of items order ?

I use minitest

答:
Your test is to check if your array of objects are ordered by the given attribute or not. Use each_cons that allows you to enumerate on the array with n consecutive elements at a time. each_cons doc</p>

```<code>assert (Item.all.each_cons(2).all?{|a,b| a.created_at >= b.created_at})
</code>```

Body:
I have a default scope in a model defined as follows:

default_scope { order(created_at: :desc) }

and a test defined as follows:

class ItemTest < ActiveSupport::TestCase
  def setup
    @first_item = items(:one)
    @second_item = items(:two)
    @third_item = items(:three)
    @fourth_item = items(:four)
  end

  test "items should be ordered by time they got created ( default scope)" do
    assert_equal [@fourth_item,@third_item, @second_item, @first_item], Item.all
  end

and  fixtures:

one:
  created_at: 2017-06-06 00:00:00 -0700

two:
  created_at: 2017-06-06 00:00:02 -0700

three:
  created_at: 2017-06-06 00:00:09 -0700

four:
  created_at: 2017-06-06 00:00:30 -0700

test passes however , everytime I add a new fixture to the above fixture file , the test fails and  I have to add that new item to the array in assert_equals statement.

I tried this answer which seems very generic but test still passes when its suppose to fail

items = Items.first(3) # and items.first(3).reverse still passes as well :(
assert_equals [items[0], items[1], items[2]], items

but unfortunately , the test passes even when I change the order to ASC where it suppose to be failing.

is there a generic way of testing a specific number of items order ?

I use minitest

Body:
Your test is to check if your array of objects are ordered by the given attribute or not. Use each_cons that allows you to enumerate on the array with n consecutive elements at a time. each_cons doc

assert (Item.all.each_cons(2).all?{|a,b| a.created_at >= b.created_at})


问:
use rails button in form as link
I have a table with sliders (part of a form) in one column and a button (link to other page)

```<code><button onclick="location.href='/main';">
   <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</button>
</code>```

Instead of opening the page, the button just submits the form. Any way I can fix this without breaking the table or the form?

答:
Why don't just use anchor tag

```<code><a href='/main'>
  <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</a>
</code>```

or

```<code># If you are using erb
<%= link_to '/main' do %>
  <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
<% end %>
</code>```

Title: use rails button in form as link

Body:
I have a table with sliders (part of a form) in one column and a button (link to other page)

<button onclick="location.href='/main';">

</button>

Instead of opening the page, the button just submits the form. Any way I can fix this without breaking the table or the form?

Body:
Why don't just use anchor tag

<a href='/main'>
  <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</a>

or

# If you are using erb
<%= link_to '/main' do %>
  <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
<% end %>