问:
How to store mostly-empty data?
I want to set up a system that allows for, say, 200 different translations per post. However most translations wouldn't exist, so there'd be a lot of empty datasets. How much of a performance and storage hit is it if I save every language (including empty ones) as a specific column? I.E.

```<code>English | Arabic | Mandarin | Russian | French         | German

Potato  |        |          |         | Pomme de Terre |
Orange  |        |          |         | Orange         |
Peach   |        |          |         |                |
</code>```

I wouldn't cycle through the whole list very often, I'd use a session variable or usersetting and then load directly from that column if it exists, with a fallback to a default language, and perhaps after that a full search.

```<code>if (exists(french))
     {echo french}
else {if(exists(english))
          {echo english}}
     else {echo links to non-null language}
     }
</code>```

I'd assume that, if I tell the server which column to go to, the overhead in terms of processing would be negligible? I also assume that an empty cell would be negligible in terms of storage? However I don't know for sure, and it could potentially be a huge mistake.

The reason I'd want to work like this is so I could assign language codes, instead of every installed instance having a different order (e.g. english|french|german|mandarin versus english|mandarin|german|french).

To prevent XY-problems, here's a more global formulation:
I want to set up a system that allows for many languages, but I expect that in most cases only 1 or two are used. What would be an efficient way to store?

答:
Keyword: Relational database.

You will want to use multiple tables.
Let's say that the default langauge is english, then your "words" table will implicitly contain the english words.

```<code>Words:
Id | Word
1  | Potato
2  | Orange

Languages:
Id | Name
1  | Norwegian
2  | Danish

Translations:
Word | Language | Translated
   1 |    1     |  Potet
   2 |    1     |  Oransje
   1 |    2     |  Kartoffel
   2 |    2     |  Appelsin
</code>```

Then you can do (pseudo sql, you can look up the language and word ids first, or use a more advanced query):

```<code>SELECT Translated FROM Translations WHERE Word = (the word id) and Language = (the language id)
</code>```

This comes with the benefit that it's very simple to list all the languages you support, all the Words you support, and also all translated words for a specific language (or, find all NON translated words for a language).

A specific query for translating "Potato" into "Danish" would look like:

```<code>SELECT Translated FROM Translations
  JOIN Words ON Words.Id = Translations.Word
  JOIN Languages ON Languages.Id = Translations.Language
WHERE
  Languages.Name = "Danish" and Words.Word = "Potato"
</code>```

Title: How to store mostly-empty data?

Body:
I want to set up a system that allows for, say, 200 different translations per post. However most translations wouldn't exist, so there'd be a lot of empty datasets. How much of a performance and storage hit is it if I save every language (including empty ones) as a specific column? I.E.

English | Arabic | Mandarin | Russian | French         | German

Potato  |        |          |         | Pomme de Terre |
Orange  |        |          |         | Orange         |
Peach   |        |          |         |                |

I wouldn't cycle through the whole list very often, I'd use a session variable or usersetting and then load directly from that column if it exists, with a fallback to a default language, and perhaps after that a full search.

if (exists(french))
     {echo french}
else {if(exists(english))
          {echo english}}
     else {echo links to non-null language}
     }

I'd assume that, if I tell the server which column to go to, the overhead in terms of processing would be negligible? I also assume that an empty cell would be negligible in terms of storage? However I don't know for sure, and it could potentially be a huge mistake.

The reason I'd want to work like this is so I could assign language codes, instead of every installed instance having a different order (e.g. english|french|german|mandarin versus english|mandarin|german|french).

To prevent XY-problems, here's a more global formulation:
I want to set up a system that allows for many languages, but I expect that in most cases only 1 or two are used. What would be an efficient way to store?

Body:
Keyword: Relational database.

You will want to use multiple tables.
Let's say that the default langauge is english, then your "words" table will implicitly contain the english words.

Words:
Id | Word
1  | Potato
2  | Orange

Languages:
Id | Name
1  | Norwegian
2  | Danish

Translations:
Word | Language | Translated
   1 |    1     |  Potet
   2 |    1     |  Oransje
   1 |    2     |  Kartoffel
   2 |    2     |  Appelsin

Then you can do (pseudo sql, you can look up the language and word ids first, or use a more advanced query):

SELECT Translated FROM Translations WHERE Word = (the word id) and Language = (the language id)

This comes with the benefit that it's very simple to list all the languages you support, all the Words you support, and also all translated words for a specific language (or, find all NON translated words for a language).

A specific query for translating "Potato" into "Danish" would look like:

SELECT Translated FROM Translations
  JOIN Words ON Words.Id = Translations.Word
  JOIN Languages ON Languages.Id = Translations.Language
WHERE
  Languages.Name = "Danish" and Words.Word = "Potato"


来源: stackexchange

问:
Taking a photo with camera using Xamarin Forms nuget Xam.Plugin.Media
I just used NUGET and installed Xam.Plugin.Media so that I can take photos using my mobile app.

I wrote the following code in the click event of the button as per the sample code in the xamarin component website:

```<code>private async void btnTake1_Clicked(object sender, EventArgs e)
        {
            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
                return;
            }

            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {

                Directory = "Sample",
                Name = "test.jpg"
            });

            if (file == null)
                return;

            await DisplayAlert("File Location", file.Path, "OK");

            imgPhoto1.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                file.Dispose();
                return stream;
            });

        }
</code>```

All went well and the Solution is building successfully, I am running only UWP now. But when I click the button it breaks at some location in

```<code>if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
</code>```

Can somebody help me with this?
Thanks in advance.
Sarin Gopalan

答:
As per your comment the following applies to Xamarin.Forms and UWP

In your forms project, wherever it is you want to dispaly the gallery picker (we are doing it from a button click) you would use something like the below:

```<code>private async void ChooseExistingClicked(object sender, EventArgs e)
{
    bool hasPermission = false;

    try
    {
        await CrossMedia.Current.Initialize();
        hasPermission = CrossMedia.Current.IsPickPhotoSupported;
    }
    catch (Exception genEx)
    {
        var Error = genEx;
    }

    if (!hasPermission)
    {
        await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
        return;
    }

    var file = await CrossMedia.Current.PickPhotoAsync();

    if (file == null)
        return;
    image = file;
    imagePanel.Source = ImageSource.FromStream(() =>
    {
        var stream = file.GetStream();
        return stream;
    });
}
</code>```

You also need to set the permissions up correctly. So in your UWP project, you will see a file called 'Package.appxmanifext' double click on this, and select 'Capabilities' and make sure that 'Picture Library' in the list is ticked.

That's it, that should be all you need to do.

EDIT: As requested below are the places you would need to set permissions for the native platforms to access the photo gallery.

In your iOS project you will need to open the code of the 'Info.plist' file which will show you an XML sheet. you need to add:

```<code><key>NSCameraUsageDescription</key>
    <string></string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>This is used to upload an image of concern along with your report</string>
    <key>NSMicrophoneUsageDescription</key>
    <string></string>
</code>```

anywhere in between the   tags.

For your Android project you need to right click the project and select 'properties' this will open a new window, and on the left you need to select 'Android Manifest' then ensure that 'CAMERA', 'READ_EXTERNAL_STORAGE', and 'WRITE_EXTERNAL_STORAGE'. I believe those are the main one's for both gallery and camera access.

ContentLicense: CC BY-SA 3.0

Body:
I just used NUGET and installed Xam.Plugin.Media so that I can take photos using my mobile app.

I wrote the following code in the click event of the button as per the sample code in the xamarin component website:

private async void btnTake1_Clicked(object sender, EventArgs e)
        {
            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
                return;
            }

            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {

                Directory = "Sample",
                Name = "test.jpg"
            });

            if (file == null)
                return;

            await DisplayAlert("File Location", file.Path, "OK");

            imgPhoto1.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                file.Dispose();
                return stream;
            });

        }

All went well and the Solution is building successfully, I am running only UWP now. But when I click the button it breaks at some location in

if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();

Can somebody help me with this?
Thanks in advance.
Sarin Gopalan

Body:
As per your comment the following applies to Xamarin.Forms and UWP

In your forms project, wherever it is you want to dispaly the gallery picker (we are doing it from a button click) you would use something like the below:

private async void ChooseExistingClicked(object sender, EventArgs e)
{
    bool hasPermission = false;

    try
    {
        await CrossMedia.Current.Initialize();
        hasPermission = CrossMedia.Current.IsPickPhotoSupported;
    }
    catch (Exception genEx)
    {
        var Error = genEx;
    }

    if (!hasPermission)
    {
        await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
        return;
    }

    var file = await CrossMedia.Current.PickPhotoAsync();

    if (file == null)
        return;
    image = file;
    imagePanel.Source = ImageSource.FromStream(() =>
    {
        var stream = file.GetStream();
        return stream;
    });
}

You also need to set the permissions up correctly. So in your UWP project, you will see a file called 'Package.appxmanifext' double click on this, and select 'Capabilities' and make sure that 'Picture Library' in the list is ticked.

That's it, that should be all you need to do.

EDIT: As requested below are the places you would need to set permissions for the native platforms to access the photo gallery.

In your iOS project you will need to open the code of the 'Info.plist' file which will show you an XML sheet. you need to add:

<key>NSCameraUsageDescription</key>
    <string></string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>This is used to upload an image of concern along with your report</string>
    <key>NSMicrophoneUsageDescription</key>
    <string></string>

anywhere in between the   tags.

For your Android project you need to right click the project and select 'properties' this will open a new window, and on the left you need to select 'Android Manifest' then ensure that 'CAMERA', 'READ_EXTERNAL_STORAGE', and 'WRITE_EXTERNAL_STORAGE'. I believe those are the main one's for both gallery and camera access.


问:
How to terminate the function when it takes too many time in Scala?
Recently, I am learning the Scala language. Today I come out a question, that is,
how to terminate a function when it takes too many time.

For example:

```<code>object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, World")
    // How to terminate the sum() function
    // when the time that it takes greater than 2 second?
    val t0 = System.nanoTime : Double
    val total: BigInt = sum(1000000000)
    val t1 = System.nanoTime : Double
    println("Elapsed time " + (t1 - t0) / 1000000.0 + " msecs")

    println(total)

  }

  //Given that sum() is written by others and I cannot change it.
  def sum(k: Int): BigInt = {
    var total: BigInt = 0
    for (i <- 1 to k) {
      total += i
    }
    total
  }
}
</code>```

The above scala code takes about 70s.

答:
The computation as it is now blocks your main thread. That is the thread your program is running in. You don't have control to execute anything on that thread until your computation is finished.

You can run the computation in a seperate Thread and kill that Thread from your main thread once you think it's taking too long.

Note: As you're a Scala beginner: Threads are usually not the way to go in Scala, but in this case the abstractions provided by Scala (namely Futures) are not low level enough for what you're trying to achieve. Please don't consider the low-level Thread way as something you should be doing every day.

Body:
Recently, I am learning the Scala language. Today I come out a question, that is,
how to terminate a function when it takes too many time.

For example:

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, World")
    // How to terminate the sum() function
    // when the time that it takes greater than 2 second?
    val t0 = System.nanoTime : Double
    val total: BigInt = sum(1000000000)
    val t1 = System.nanoTime : Double
    println("Elapsed time " + (t1 - t0) / 1000000.0 + " msecs")

    println(total)

  }

  //Given that sum() is written by others and I cannot change it.
  def sum(k: Int): BigInt = {
    var total: BigInt = 0
    for (i <- 1 to k) {
      total += i
    }
    total
  }
}

The above scala code takes about 70s.


问:
How to insert key-value pair into dictionary at a specified position?
How would I insert a key-value pair at a specified location in a python dictionary that was loaded from a YAML document?

For example if a dictionary is:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

I wish to insert the element 'Phone':'1234'
before 'Age', and after 'Name' for example. The actual dictionary I shall be working on is quite large (parsed YAML file), so deleting and reinserting might be a bit cumbersome (I don't really know).

If I am given a way of inserting into a specified position in an OrderedDict, that would be okay, too.

答:
On python < 3.7 (or cpython < 3.6), you cannot control the ordering of pairs in a standard dictionary.

If you plan on performing arbitrary insertions often, my suggestion would be to use a list to store keys, and a dict to store values.

```<code>mykeys = ['Name', 'Age', 'Class']
mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # order doesn't matter

k, v = 'Phone', '123-456-7890'

mykeys.insert(mykeys.index('Name')+1, k)
mydict[k] = v

for k in mykeys:
    print(f'{k} => {mydict[k]}')

# Name => Zara
# Phone => 123-456-7890
# Age => 7
# Class => First
</code>```

If you plan on initialising a dictionary with ordering whose contents are not likely to change, you can use the collections.OrderedDict structure which maintains insertion order.

```<code>from collections import OrderedDict

data = [('Name', 'Zara'), ('Phone', '1234'), ('Age', 7), ('Class', 'First')]
odict = OrderedDict(data)
odict
# OrderedDict([('Name', 'Zara'),
#              ('Phone', '1234'),
#              ('Age', 7),
#              ('Class', 'First')])
</code>```

Note that OrderedDict does not support insertion at arbitrary positions (it only remembers the order in which keys are inserted into the dictionary).

ContentLicense: CC BY-SA 4.0

Body:
On python < 3.7 (or cpython < 3.6), you cannot control the ordering of pairs in a standard dictionary.

If you plan on performing arbitrary insertions often, my suggestion would be to use a list to store keys, and a dict to store values.

mykeys = ['Name', 'Age', 'Class']
mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # order doesn't matter

k, v = 'Phone', '123-456-7890'

mykeys.insert(mykeys.index('Name')+1, k)
mydict[k] = v

for k in mykeys:
    print(f'{k} => {mydict[k]}')

# Name => Zara
# Phone => 123-456-7890
# Age => 7
# Class => First

If you plan on initialising a dictionary with ordering whose contents are not likely to change, you can use the collections.OrderedDict structure which maintains insertion order.

from collections import OrderedDict

data = [('Name', 'Zara'), ('Phone', '1234'), ('Age', 7), ('Class', 'First')]
odict = OrderedDict(data)
odict
# OrderedDict([('Name', 'Zara'),
#              ('Phone', '1234'),
#              ('Age', 7),
#              ('Class', 'First')])

Note that OrderedDict does not support insertion at arbitrary positions (it only remembers the order in which keys are inserted into the dictionary).


问:
NSCollectionView - Not able to tab through fields after first row
My NSCollectionView uses a custom NSCollectionViewItem which contains 2 NSComboBox, 1 NSTextField and 1 NSDatePicker. When running my app and displaying multiple NSCollectionViewItems, I am able to tab through the comboboxes and the textfield of the first item, but none of the items that follow. If I select the textfield in the second or third item and hit the tab key, nothing happens.

I would like to tab through each component in my NSCollectionViewItem and then continue through to the next component in the next NSCollectionViewItem. I expected this to be the default behavior.

Because it works for the first item in my NSCollectionView, I know that it can work for the rest.

Is there something I need to set while NSCollectionView is displaying the items?

答: Switch on Recalculates View Loop of the window. Side effect: nextKeyView of the views isn't used.


答:
The following answer assumes that every entry in the duration column takes the form of a time component only, or of some number of days followed by a time component.  Assuming this, we can use a CASE expression to selectively parse either type of data.  In the case there is a days component, we can convert to seconds and add this to the number of seconds from the time component.

```<code>SELECT
    CASE WHEN duration LIKE '%days%'
         THEN CAST(SUBSTRING_INDEX(duration, ' ', 1) AS UNSIGNED) * 24*60*60 +
              TIME_TO_SEC(SUBSTRING_INDEX(duration, ' ', -1))
         ELSE TIME_TO_SEC(duration)
    END AS duration_in_seconds
FROM yourTable
</code>```

Output:

Demo here:

Rextester

Title: Converting days to seconds in MySQL

Body:
I need to convert the following column into seconds:

+----------------------+
| duration             |
+----------------------+
| 00:15:52.22          |
| 01:15:51.65          |
| 02:15:50.93          |
| 27 days, 06:22:41.11 |
| 27 days, 07:22:40.76 |
| 27 days, 08:22:40.43 |
+----------------------+

The problem is that the TIME_TO_SEC() function works correctly only for the first three rows returning the following result:

+-----------------------+
| TIME_TO_SEC(duration) |
+-----------------------+
|            952.220000 |
|           4551.650000 |
|           8150.930000 |
|             27.000000 |
|             27.000000 |
|             27.000000 |
+-----------------------+

Is there a function I can use that would convert all the rows into seconds?

Body:
The following answer assumes that every entry in the duration column takes the form of a time component only, or of some number of days followed by a time component.  Assuming this, we can use a CASE expression to selectively parse either type of data.  In the case there is a days component, we can convert to seconds and add this to the number of seconds from the time component.

SELECT
    CASE WHEN duration LIKE '%days%'
         THEN CAST(SUBSTRING_INDEX(duration, ' ', 1) AS UNSIGNED) * 24*60*60 +
              TIME_TO_SEC(SUBSTRING_INDEX(duration, ' ', -1))
         ELSE TIME_TO_SEC(duration)
    END AS duration_in_seconds
FROM yourTable

Output:

Demo here:

Rextester


问:
Can I define a macro using a macro in C?
I have a set of #defines like these:

```<code>#define MODULE1_PINMASK 0x1
#define MODULE2_PINMASK 0x2
#define MODULE3_PINMASK 0x3
</code>```

where the value of the pinmask depends on the second argument of:

```<code>#define MODULE1_PORT_PIN A,1
#define MODULE2_PORT_PIN A,2
#define MODULE3_PORT_PIN A,3
</code>```

If at any point in future, I make a change, e.g:

```<code>#define MODULE1_PORT_PIN A,1 /* changes to #define MODULE1_PORT_PIN A,4 */
</code>```

I need to also change the pinmask:

```<code>#define MODULE1_PINMASK 0x1 /* then becomes #define MODULE1_PINMASK 0x4 */
</code>```

I'm trying to automate the process by not having to manually change the pinmask. So far I've got these macros to extract the second argument of MODULEX_PORT_PIN (I don't care about the first argument in this case):

```<code>#define GET_SECOND(X, Y) Y
#define GET_PIN(PORT_PIN) GET_SECOND(PORT_PIN)
</code>```

If i use them in functions, I get the correct result, for instance:

```<code>uint8_t pinmask=0x0;

switch (GET_PIN(MODULE2_PORT_PIN))
{
    case 1:
        pinmask = 0x1;
        break;
    case 2:
        pinmask = 0x2;
        break;
    case 3:
        pinmask = 0x3;
        break;
    default:
        break;
}

printf ("%#x", pinmask); /* prints "0x2" */
</code>```

but I want to keep the pinmasks as #defines. Is there a way to implement a #define GET_PINMASK macro which uses the switch case to define the pinmask? I'm aiming for something like:

```<code>#define MODULE1_PINMASK ASSIGN_PINMASK(GET_PIN(MODULE1_PORT_PIN))
</code>```

which in this case would define MODULE1_PINMASK as 0x1.

EDIT: The second argument in #define MODULE1_PORT_PIN A,1 is an uint8_t and not a hex value and so I can't pass it directly.

答:
I think you may be overthinking the problem.  If the second field of each MODULEn_PORT_PIN  define is always an integer constant expression, then this should work:

```<code>#define MODULE1_PORT_PIN A,1
#define MODULE2_PORT_PIN A,2
#define MODULE3_PORT_PIN A,3

#define GET_SECOND(X, Y) (Y)
#define PIN_TO_MASK(PIN) (1ul << GET_SECOND(PIN))

#define MODULE1_PINMASK PIN_TO_MASK(MODULE1_PORT_PIN)
#define MODULE2_PINMASK PIN_TO_MASK(MODULE2_PORT_PIN)
#define MODULE3_PINMASK PIN_TO_MASK(MODULE3_PORT_PIN)
</code>```

It is not clear from your question whether the second field can be something other than an integer constant expression.  If the second field ever involves an enum constant, then the MODULEn_PINMASK macros can still be used in any context except for #if expressions.  If it ever involves a variable, then they can only be used inside the body of a function.  (Since this is C and not C++, that's true even if the variable is const.)

There is no way to avoid having to write each #define individually.  If that is a problem, you should be thinking about writing a program that generates the list of #defines.  Generating source code from a DSL of your own invention, at build time, is an under-valued technique.

Body:
I have a set of #defines like these:

#define MODULE1_PINMASK 0x1
#define MODULE2_PINMASK 0x2
#define MODULE3_PINMASK 0x3

where the value of the pinmask depends on the second argument of:

#define MODULE1_PORT_PIN A,1
#define MODULE2_PORT_PIN A,2
#define MODULE3_PORT_PIN A,3

If at any point in future, I make a change, e.g:

#define MODULE1_PORT_PIN A,1 /* changes to #define MODULE1_PORT_PIN A,4 */

I need to also change the pinmask:

#define MODULE1_PINMASK 0x1 /* then becomes #define MODULE1_PINMASK 0x4 */

I'm trying to automate the process by not having to manually change the pinmask. So far I've got these macros to extract the second argument of MODULEX_PORT_PIN (I don't care about the first argument in this case):

#define GET_SECOND(X, Y) Y
#define GET_PIN(PORT_PIN) GET_SECOND(PORT_PIN)

If i use them in functions, I get the correct result, for instance:

uint8_t pinmask=0x0;

switch (GET_PIN(MODULE2_PORT_PIN))
{
    case 1:
        pinmask = 0x1;
        break;
    case 2:
        pinmask = 0x2;
        break;
    case 3:
        pinmask = 0x3;
        break;
    default:
        break;
}

printf ("%#x", pinmask); /* prints "0x2" */

but I want to keep the pinmasks as #defines. Is there a way to implement a #define GET_PINMASK macro which uses the switch case to define the pinmask? I'm aiming for something like:

#define MODULE1_PINMASK ASSIGN_PINMASK(GET_PIN(MODULE1_PORT_PIN))

which in this case would define MODULE1_PINMASK as 0x1.

EDIT: The second argument in #define MODULE1_PORT_PIN A,1 is an uint8_t and not a hex value and so I can't pass it directly.

Body:
I think you may be overthinking the problem.  If the second field of each MODULEn_PORT_PIN  define is always an integer constant expression, then this should work:

#define MODULE1_PORT_PIN A,1
#define MODULE2_PORT_PIN A,2
#define MODULE3_PORT_PIN A,3

#define GET_SECOND(X, Y) (Y)
#define PIN_TO_MASK(PIN) (1ul << GET_SECOND(PIN))

#define MODULE1_PINMASK PIN_TO_MASK(MODULE1_PORT_PIN)
#define MODULE2_PINMASK PIN_TO_MASK(MODULE2_PORT_PIN)
#define MODULE3_PINMASK PIN_TO_MASK(MODULE3_PORT_PIN)

It is not clear from your question whether the second field can be something other than an integer constant expression.  If the second field ever involves an enum constant, then the MODULEn_PINMASK macros can still be used in any context except for #if expressions.  If it ever involves a variable, then they can only be used inside the body of a function.  (Since this is C and not C++, that's true even if the variable is const.)

There is no way to avoid having to write each #define individually.  If that is a problem, you should be thinking about writing a program that generates the list of #defines.  Generating source code from a DSL of your own invention, at build time, is an under-valued technique.


问:
Angular's Json.stringify with property problems
I'm trying to stringify objects in Typescript that was implemented usign private properties like this

```<code>export class Foo {
   private _property1:string;
   private _property2:string;
   private _property3:string;

   get property1(): string {
        return this._property1;
   }
   set property1(value: string) {
        this._property1 = value;
   }
   get property2(): string {
        return this._property2;
   }
   set property2(value: string) {
        this._property2 = value;
   }
   get property3(): string {
        return this._property3;
   }
   set property3(value: string) {
        this._property3 = value;
   }

}
</code>```

But when i use JSON.stringfy(), the private properties are read and does'nt go through the get and set methods.

Expected:

```<code>{
  "property1": "",
  "property2": "",
  "property3": "",

}
</code>```

Received:

```<code>{
  "_property1": "",
  "_property2": "",
  "_property3": "",

}
</code>```

It is noticed that the property is underlined, but should not, Json should come with the name that was implemented in the getters and setters and not in private properties

答:
JSON.stringify only looks at object fields, not at methods or properties (getters/setters).

If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object)

...

A getter or setter is defined as a function, and will therefore be ignored in the conversion. Only the private fields of the object will find their way in the JSON. And they will only be there, if they are actually initialised.

Body:
I'm trying to stringify objects in Typescript that was implemented usign private properties like this

export class Foo {
   private _property1:string;
   private _property2:string;
   private _property3:string;

   get property1(): string {
        return this._property1;
   }
   set property1(value: string) {
        this._property1 = value;
   }
   get property2(): string {
        return this._property2;
   }
   set property2(value: string) {
        this._property2 = value;
   }
   get property3(): string {
        return this._property3;
   }
   set property3(value: string) {
        this._property3 = value;
   }

}

But when i use JSON.stringfy(), the private properties are read and does'nt go through the get and set methods.

Expected:

{
  "property1": "",
  "property2": "",
  "property3": "",

}

Received:

{
  "_property1": "",
  "_property2": "",
  "_property3": "",

}

It is noticed that the property is underlined, but should not, Json should come with the name that was implemented in the getters and setters and not in private properties


问:
Loading all DLL functions
Is there a way to load all functions from runtime loaded DLL? Current code:

```<code>hGetProcIDDLL = LoadLibrary(dll);

typedef int(*f_connection_a)(args);
typedef int(*f_connection_b)(args);
typedef int(*f_connection_c)(args);

f_connection_a connection_a = (f_connection_a)GetProcAddress(hGetProcIDDLL, "connection_a");
f_connection_b connection_b = (f_connection_b)GetProcAddress(hGetProcIDDLL, "connection_b");
f_connection_c connection_c = (f_connection_c)GetProcAddress(hGetProcIDDLL, "connection_c");
</code>```

As you can see, this gets cumbersome quickly as you have to define every DLL function like this. Is there a way to load all DLL functions instead of having to list them?

答:
Since here the "connection_*" are only a variables, there is no way to initialize them other than to run a code such as calling a function to get an address of a function. WinAPI doesn't have bulk method for binding functions at run time. This is limitation of WinAPI. The intention of this method was to check the presence of a functions individually and to delay loading library up to the point when it will actually be needed (or to avoid loading at all if it is not used).

But you can avoid such messy code by binding DLL at program loading stage using Import Table feature. In this case Windows loads executable image into memory, then loads all dependent DLLs and automatically binds the imported functions before launching executable code. For this you need:

Prepare *.def file for the library you need to load. The simplest method is to launch "impdef.exe my.dll" command on dll file. You may find tiny impdef.exe that doesn't need installation in TinyC package (see https://bellard.org/tcc/).

Then prepare corresponding *.lib file by launching "lib /def:my.def /out:my.lib"

After that link produced library with your project as regular library.

The drawback of this method is that if DLL is absent or corrupted, your executable file won't start at all. But this is a small payment for the convenience of importing functions.

Title: Loading all DLL functions

Body:
Is there a way to load all functions from runtime loaded DLL? Current code:

hGetProcIDDLL = LoadLibrary(dll);

typedef int(*f_connection_a)(args);
typedef int(*f_connection_b)(args);
typedef int(*f_connection_c)(args);

f_connection_a connection_a = (f_connection_a)GetProcAddress(hGetProcIDDLL, "connection_a");
f_connection_b connection_b = (f_connection_b)GetProcAddress(hGetProcIDDLL, "connection_b");
f_connection_c connection_c = (f_connection_c)GetProcAddress(hGetProcIDDLL, "connection_c");

As you can see, this gets cumbersome quickly as you have to define every DLL function like this. Is there a way to load all DLL functions instead of having to list them?


问:
How can I change the url for a project in GitLab?
I have a project in Gitlab that is available over HTTP/SSH:

```<code>git@192.168.1.10:MyGroup/MyProject.git
</code>```

I want to change that using another IP, i.e.:

```<code>git@192.168.1.20:MyGroup/MyProject.git
</code>```

Where or how can I change that?

答: You can find all repositories remotes inside the file .git/config. You can edit it by hand or use command git remote.

Body:
I have a project in Gitlab that is available over HTTP/SSH:

git@192.168.1.10:MyGroup/MyProject.git

I want to change that using another IP, i.e.:

git@192.168.1.20:MyGroup/MyProject.git

Where or how can I change that?


问:
Redux unsubscribe within componentWillUnmount still calls subscribe callback
I am manually hooking a React component up to a Redux store. Yes, I realize Dan Abramov of Redux recommends against this. I will be getting around to looking at react-redux eventually, but for now I want to understand what's going on.

```<code>componentDidMount() {
    this.unsubscribe = store.subscribe(() => {
        const storeState = store.getState();
        this.setState({
            someData: storeState.someData
        });
    }.bind(this));
}
componentWillUnmount () {
    this.unsubscribe();
}
</code>```

This is some code I have in a tab  page component. These tab pages get swapped in and out in a parent component as the user changes tabs to display different data. I have stepped through the debugger and confirmed that as a user changes tabs, the following occurs in order:

The previous tab is unmounted (componentWillUnmount fires and this.unsubscribe() is called. this is the previous tab component, as expected)

The new tab is mounted. (componentDidMount fires and this is the new tab component, as expected)

setState gets called in the subscribe callback with this being the PREVIOUS TAB, and react complains with an error:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Tab component.

This seems strange to me. Shouldn't calling unsubscribe as I have prevent this callback from being called on the unmounted component? The post that I'm following along with seems to suggest that doing what I've done should make this warning go away, and is simply questioning if this is a good idea. But in my case, it persists.

I don't think it matters, but I am using the ES6 "class" syntax whereas the original appears not to be.

答:
```<code>subscribe(listener: () => void): Unsubscribe;
</code>```

Lets read subscribe method doc.

The subscriptions are snapshotted just before every dispatch() call.
  If you subscribe or unsubscribe while the listeners are being invoked,
  this will not have any effect on the dispatch() that is currently in
  progress. However, the next dispatch() call, whether nested or not,
  will use a more recent snapshot of the subscription list.

Since you first have called dispatch method, all listeners are invoken and your unsubsribe call will only take place on next dispatch call.

Body:
I am manually hooking a React component up to a Redux store. Yes, I realize Dan Abramov of Redux recommends against this. I will be getting around to looking at react-redux eventually, but for now I want to understand what's going on.

componentDidMount() {
    this.unsubscribe = store.subscribe(() => {
        const storeState = store.getState();
        this.setState({
            someData: storeState.someData
        });
    }.bind(this));
}
componentWillUnmount () {
    this.unsubscribe();
}

This is some code I have in a tab  page component. These tab pages get swapped in and out in a parent component as the user changes tabs to display different data. I have stepped through the debugger and confirmed that as a user changes tabs, the following occurs in order:

The previous tab is unmounted (componentWillUnmount fires and this.unsubscribe() is called. this is the previous tab component, as expected)

The new tab is mounted. (componentDidMount fires and this is the new tab component, as expected)

setState gets called in the subscribe callback with this being the PREVIOUS TAB, and react complains with an error:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Tab component.

This seems strange to me. Shouldn't calling unsubscribe as I have prevent this callback from being called on the unmounted component? The post that I'm following along with seems to suggest that doing what I've done should make this warning go away, and is simply questioning if this is a good idea. But in my case, it persists.

I don't think it matters, but I am using the ES6 "class" syntax whereas the original appears not to be.

Body:
subscribe(listener: () => void): Unsubscribe;

Lets read subscribe method doc.

The subscriptions are snapshotted just before every dispatch() call.
  If you subscribe or unsubscribe while the listeners are being invoked,
  this will not have any effect on the dispatch() that is currently in
  progress. However, the next dispatch() call, whether nested or not,
  will use a more recent snapshot of the subscription list.

Since you first have called dispatch method, all listeners are invoken and your unsubsribe call will only take place on next dispatch call.


问:
redefine < operator to use in stl algorithms for strings
Is it possible to redefine operator < for strings without modifying std namespace, to make this operator use in standard algorithms?
For example, I can write:

```<code>namespace std
{

    bool operator <(const std::string & rhs, const std::string & lhs)
    {
        std::cout << "lol";
        return false;
    }

}

int main()
{
    std::vector<std::string> lol = { "a", "b", "ba", "aa" };
    std::sort(lol.begin(), lol.end());
}
</code>```

and "lol" will be printed several times. But if I move operator < outside from std namespace, default operator < will be used and nothing will be printed. Is it possible to make std::sort using custom operator < without including it to std namespace?

Yes I know, I can pass another comparator to std::sort but it's interesting for me if I could do what I asked and how?

Also am I correct, that it's correct to add such template specialization to std namespace?

Update: This is not practical question, I just want to know how can I do that if it's possible.

答:
No, it is not.  Adding a function to the standard namespace is undefined behavior.  [namespace.std]/1 states:

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

If you want to change how std::sort sorts then you can provide a lambda and define what you want

```<code>std::sort(std::begin(foo), std::end(foo), [](const auto& lhs, const auto& rhs) { /* your code here */ });
</code>```

Body:
Is it possible to redefine operator < for strings without modifying std namespace, to make this operator use in standard algorithms?
For example, I can write:

namespace std
{

    bool operator <(const std::string & rhs, const std::string & lhs)
    {
        std::cout << "lol";
        return false;
    }

}

int main()
{
    std::vector<std::string> lol = { "a", "b", "ba", "aa" };
    std::sort(lol.begin(), lol.end());
}

and "lol" will be printed several times. But if I move operator < outside from std namespace, default operator < will be used and nothing will be printed. Is it possible to make std::sort using custom operator < without including it to std namespace?

Yes I know, I can pass another comparator to std::sort but it's interesting for me if I could do what I asked and how?

Also am I correct, that it's correct to add such template specialization to std namespace?

Update: This is not practical question, I just want to know how can I do that if it's possible.

Body:
No, it is not.  Adding a function to the standard namespace is undefined behavior.  [namespace.std]/1 states:

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

If you want to change how std::sort sorts then you can provide a lambda and define what you want

std::sort(std::begin(foo), std::end(foo), [](const auto& lhs, const auto& rhs) { /* your code here */ });


问:
Server-side comments: What's the equivalent of <%-- --%> in ASP Classic?
What's the equivalent of <%-- --%> in ASP Classic?

I have to modify a legacy ASP application and I'd like to comment out a block of HTML:

```<code><td>
    some table cell I'd like to comment out, including
    some <%= inlineServerSideVBScriptExpressions() %>
</td>
</code>```

Wrapping everything in <%-- ... --%>, as I'd do in ASP.NET, doesn't work and results in the compilation error "Expected statement". HTML comments  are not an option either, since the inline ASP expressions would get evaluated and fail.

答:
Try this:-

```<code><!-- METADATA
  Your comments here
-->
</code>```

The METADATA indicates to the ASP processor that this is a comment that does not need to be sent to the client.

Body:
What's the equivalent of <%-- --%> in ASP Classic?

I have to modify a legacy ASP application and I'd like to comment out a block of HTML:

    some table cell I'd like to comment out, including
    some <%= inlineServerSideVBScriptExpressions() %>

Wrapping everything in <%-- ... --%>, as I'd do in ASP.NET, doesn't work and results in the compilation error "Expected statement". HTML comments  are not an option either, since the inline ASP expressions would get evaluated and fail.

Body:
Try this:-

<!-- METADATA
  Your comments here
-->

The METADATA indicates to the ASP processor that this is a comment that does not need to be sent to the client.

ContentLicense: CC BY-SA 2.5


问:
Xamarin Forms Android, hide the title bar border
How can I hide the border from the title bar in Xamarin Android? I am using Xamarin Forms & Following code is used in MainActivity.cs to hide the rest of the title bar. </p>

```<code>[Activity(Label = "", MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait)]
protected override void OnCreate(Bundle bundle)
    {

        this.RequestWindowFeature(WindowFeatures.ActionBarOverlay);

        base.OnCreate(bundle);

        //Transperent Action Bar
        ActionBar.SetIcon(Android.Resource.Color.Transparent);
        ActionBar.SetBackgroundDrawable(new ColorDrawable(Color.ParseColor("#000000ff")));
        ActionBar.SetStackedBackgroundDrawable(new ColorDrawable(Color.ParseColor("#000000ff")));

        Xamarin.Forms.Forms.Init(this, bundle);

        SetPage(App.GetMainPage());
    }
</code>```

答:
Just use your NavigationPage</p>

```<code>    public HelloWorlPage()
    {
        InitializeComponent();
        NavigationPage.SetHasBackButton(this, false);
        NavigationPage.SetHasNavigationBar(this, false);
    }
</code>```

Body:
How can I hide the border from the title bar in Xamarin Android? I am using Xamarin Forms & Following code is used in MainActivity.cs to hide the rest of the title bar.

[Activity(Label = "", MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait)]
protected override void OnCreate(Bundle bundle)
    {

        this.RequestWindowFeature(WindowFeatures.ActionBarOverlay);

        base.OnCreate(bundle);

        //Transperent Action Bar
        ActionBar.SetIcon(Android.Resource.Color.Transparent);
        ActionBar.SetBackgroundDrawable(new ColorDrawable(Color.ParseColor("#000000ff")));
        ActionBar.SetStackedBackgroundDrawable(new ColorDrawable(Color.ParseColor("#000000ff")));

        Xamarin.Forms.Forms.Init(this, bundle);

        SetPage(App.GetMainPage());
    }

Body:
Just use your NavigationPage

    public HelloWorlPage()
    {
        InitializeComponent();
        NavigationPage.SetHasBackButton(this, false);
        NavigationPage.SetHasNavigationBar(this, false);
    }


问:
Dynamically positioned popup definitions that show on hover
I am looking to create popup definitions that show when a div is hovered over. My site will show detailed specifications on cameras, I would like it when the user hovers over the megapixel class named '.mp' then a small popup shows above with a short definition. One of the key ways I would like it to work is so I can add the class '.mp' on to any existing div/class and when it is hovered over then the popup shows above that div/class also allowing me to reuse definitions in multiple places around the site.

I am looking for the most efficient way possible, I know how to do what I'm looking to do however my way is very inefficient and cumbersome.

This is how I lay out the specifications are layed out on my site, in photoshop I have just added the type of effect I would like to receive on hover.

The specs are outputted all with PHP from my database, each one has the wrapper '.spec_item' I currently store the names of the specs in an array which can be added onto each div in a for loop

```<code>$sensor_db = array("mp", "sensor_size", "sensor_type", "light_sensitivity");
</code>```

This creates divs as such:

```<code><div class="spec_item mp">
    12.9
</div>
<div class="spec_item sensor_size">
    0.95X
</div>
<div class="spec_item sensor_type">
    APS-C
</div>
</code>```

When the user hovers over any div with the name '.mp' for example, then the definition shows below it in a little popup as shown in my picture example. To achieve this, I know I could store all the definitions in another array and just have the div as display none and on hover display block, however if i did this, I could not simply add the class '.mp' onto any div and it show the definition, this is what I'm trying to achieve.

I appreciate any help or direction to how I could go about this.

答:
Maybe this will help you. You would have to generate the correct HTML in your PHP script.

.tooltip-container {
  width: 200px;
  position: absolute;
  display: none;
  margin-top: 12px;
}

.arrow-up {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 5px 12px 5px;
  border-color: transparent transparent #a6a6a6 transparent;
  position: absolute;
  top: -12px;
  left: 15%;
}

.tooltip {
  border: thin solid darkgray;
  padding: 10px;
}

h5 {
  margin: 0;
  text-align: left;
}

.mp {
  width: 200px;
  height: 50px;
  border-radius: 5%;
  background-color: red;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  position: relative;
}

.mp:hover +.tooltip-container {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mp">
  <p>12.9</p>
</div>
<div class="tooltip-container">
  <span class="arrow-up"></span>
  <div class="tooltip">
    <h5>Hello World</h5>
    <span>Lorem ipsum dolor sit amet</span>
  </div>
</div></code>```

Body:
I am looking to create popup definitions that show when a div is hovered over. My site will show detailed specifications on cameras, I would like it when the user hovers over the megapixel class named '.mp' then a small popup shows above with a short definition. One of the key ways I would like it to work is so I can add the class '.mp' on to any existing div/class and when it is hovered over then the popup shows above that div/class also allowing me to reuse definitions in multiple places around the site.

I am looking for the most efficient way possible, I know how to do what I'm looking to do however my way is very inefficient and cumbersome.

This is how I lay out the specifications are layed out on my site, in photoshop I have just added the type of effect I would like to receive on hover.

The specs are outputted all with PHP from my database, each one has the wrapper '.spec_item' I currently store the names of the specs in an array which can be added onto each div in a for loop

$sensor_db = array("mp", "sensor_size", "sensor_type", "light_sensitivity");

This creates divs as such:

    12.9

    0.95X

    APS-C

When the user hovers over any div with the name '.mp' for example, then the definition shows below it in a little popup as shown in my picture example. To achieve this, I know I could store all the definitions in another array and just have the div as display none and on hover display block, however if i did this, I could not simply add the class '.mp' onto any div and it show the definition, this is what I'm trying to achieve.

I appreciate any help or direction to how I could go about this.

Body:
Maybe this will help you. You would have to generate the correct HTML in your PHP script.

.tooltip-container {
  width: 200px;
  position: absolute;
  display: none;
  margin-top: 12px;
}

.arrow-up {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 5px 12px 5px;
  border-color: transparent transparent #a6a6a6 transparent;
  position: absolute;
  top: -12px;
  left: 15%;
}

.tooltip {
  border: thin solid darkgray;
  padding: 10px;
}

h5 {
  margin: 0;
  text-align: left;
}

.mp {
  width: 200px;
  height: 50px;
  border-radius: 5%;
  background-color: red;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  position: relative;
}

.mp:hover +.tooltip-container {
  display: block;
}

<div class="mp">
  <p>12.9</p>
</div>
<div class="tooltip-container">
  <span class="arrow-up"></span>
  <div class="tooltip">
    <h5>Hello World</h5>
    <span>Lorem ipsum dolor sit amet</span>
  </div>
</div>


问:
JavaScript URL looper
I am trying create a page that will run some given URLs, in time this will be a database populated list of URLs loaded into an array. I have it working using some code I have altered, however I don't want it to keep looping, I just want it to stop once the list is complete.

So basically loads first URL, waits .5 of a second after the pages loads, then moves onto the next until the list of URLS is finished.

However, my code keeps looping. How do I prevent this?

var urls1 =
[
 'http://localhost:8500/SupportTools/t1.cfm',
 'http://localhost:8500/SupportTools/t2.cfm',
 'http://localhost:8500/SupportTools/t3.cfm',
 'http://localhost:8500/SupportTools/t4.cfm',
 'http://localhost:8500/SupportTools/t5.cfm'
];

function showUrl1(idx)
{
 var f1 = document.getElementById("f1");
 f1.onload = function()
 {
  var next = ++idx % urls1.length;
  setTimeout(function()
  {
   showUrl1(next);
  }, 500);
 }
 f1.src = urls1[idx];
}

function start()
{
 showUrl1(0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe class="show1" id="f1" src="about:blank"></iframe></code>```

答:
The reason it's looping is because you're using the remainder operator %. Just check the to see if next is greater than or equal to the length and then don't call setTimeout(). I've changed the snippet so that you can see it output in the console but you should get the idea.

var urls1 = [
  'http://localhost:8500/SupportTools/t1.cfm',
  'http://localhost:8500/SupportTools/t2.cfm',
  'http://localhost:8500/SupportTools/t3.cfm',
  'http://localhost:8500/SupportTools/t4.cfm',
  'http://localhost:8500/SupportTools/t5.cfm'
];

function showUrl1(idx) {

  if (idx >= urls1.length) {
    return;
  }
  console.log(urls1[idx]);
  var next = ++idx;
  setTimeout(function() {
    showUrl1(next);
  }, 500);

}

function start() {
  showUrl1(0);
}

start();```

Title: JavaScript URL looper


问:
How to display the number of subroutines and their names in a perl script at the time of its execution?
Consider the following Perl script script.pl as an example:

```<code>use strict;
use warnings;
sub f1
{statements}
sub f2
{statements}
sub f3
{statements}
f1();f2();f3();
</code>```

When I execute the script, it should show the following output:

./script.pl

number of subroutines:3

  names of subroutines:f1 f2 f3

When the code is executed, how can I count the number of subroutines, get their names, and then print them during runtime?

答:
Devel::Examine::Subs can do these types of things.

```<code>use strict;
use warnings;
use feature 'say';

use Devel::Examine::Subs;

my $des = Devel::Examine::Subs->new(file => $0);

my $subs = $des->objects;

say "number of subs:" . @$subs . "\n";

for my $sub (@$subs){
    say "name:  " . $sub->name;       # name of sub
    say "start: " . $sub->start;      # first line number of sub in file
    say "end: "   . $sub->end;        # last line number of sub in file
    say "lines: " . $sub->line_count; # number of lines in sub
    # $sub->code;                     # entire sub code from file
    # $sub->lines;                    # lines that match search term
    say "\n";
}

sub func1 {}
sub func2 {}
sub func3 {}
</code>```

Output:

```<code>number of subs:3

name:  func3
start: 25
end: 25
lines: 1

name:  func2
start: 24
end: 24
lines: 1

name:  func1
start: 23
end: 23
lines: 1
</code>```

Body:
Consider the following Perl script script.pl as an example:

use strict;
use warnings;
sub f1
{statements}
sub f2
{statements}
sub f3
{statements}
f1();f2();f3();

When I execute the script, it should show the following output:

./script.pl

number of subroutines:3

  names of subroutines:f1 f2 f3

When the code is executed, how can I count the number of subroutines, get their names, and then print them during runtime?

Body:
Devel::Examine::Subs can do these types of things.

use strict;
use warnings;
use feature 'say';

use Devel::Examine::Subs;

my $des = Devel::Examine::Subs->new(file => $0);

my $subs = $des->objects;

say "number of subs:" . @$subs . "\n";

for my $sub (@$subs){
    say "name:  " . $sub->name;       # name of sub
    say "start: " . $sub->start;      # first line number of sub in file
    say "end: "   . $sub->end;        # last line number of sub in file
    say "lines: " . $sub->line_count; # number of lines in sub
    # $sub->code;                     # entire sub code from file
    # $sub->lines;                    # lines that match search term
    say "\n";
}

sub func1 {}
sub func2 {}
sub func3 {}

Output:

number of subs:3

name:  func3
start: 25
end: 25
lines: 1

name:  func2
start: 24
end: 24
lines: 1

name:  func1
start: 23
end: 23
lines: 1


问:
Round date long value
In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

```<code>long time = 12136219;
Date date = new Date(time);
</code>```

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?

答:
Since time is
"milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT"
You could calculate the seconds like this:</p>

```<code>secondsInMillis = time % (60 * 1000) //get remainder (modulo): seconds * milliseconds
if (secondsInMillis < 30000) {
  time -= secondsInMillis; //round down
} else {
  time += (60000 - secondsInMillis); // round up
}
</code>```

Title: Round date long value

Body:
In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

long time = 12136219;
Date date = new Date(time);

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?

Body:
Since time is
"milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT"
You could calculate the seconds like this:

secondsInMillis = time % (60 * 1000) //get remainder (modulo): seconds * milliseconds
if (secondsInMillis < 30000) {
  time -= secondsInMillis; //round down
} else {
  time += (60000 - secondsInMillis); // round up
}


问:
printing the next hour with .date("h:i:sa"); php function
This php function .date("h:i:sa"); prints the time now what I should do if I want to prints the time now  plus one hour?

I have tried this but with same result.

```<code>echo "" . date("h:i:sa"+3600) ;
</code>```

答:
There's multiple ways to do this in PHP. The easiest is to combine date() and strtotime():

```<code>echo date('h:i:sa', strtotime('+1 hour'));
</code>```

You can also use DateTime() which is daylight savings time aware:

```<code>echo (new DateTime('+1 hour'))->format('h:i:sa');
</code>```

Both of these use the relative date format "+1 hour" to add one hour to the current date and time.

Output:- https://eval.in/812700

Body:
This php function .date("h:i:sa"); prints the time now what I should do if I want to prints the time now  plus one hour?

I have tried this but with same result.

echo "" . date("h:i:sa"+3600) ;

Body:
There's multiple ways to do this in PHP. The easiest is to combine date() and strtotime():

echo date('h:i:sa', strtotime('+1 hour'));

You can also use DateTime() which is daylight savings time aware:

echo (new DateTime('+1 hour'))->format('h:i:sa');

Both of these use the relative date format "+1 hour" to add one hour to the current date and time.

Output:- https://eval.in/812700


问:
How to run ansible command on a single server during deployment to many servers?
I'm using Ansistrano to deploy my Symfony2 application. Application uses Doctrine, oso I'm also using DoctrineMigrationsBundle. Now, my problem is that I would like to run database migration at the end of deployment process, but I want this operation to be called only once, and I know that ansible by default run all commands from playbook on all given servers. Is there any way to tell ansible to run a specific command on a single server from a set of all servers to which I deploy my code?</p>

答:
There's run_once for this.

Example from the docs:

```<code>---
# ...

  tasks:

    # ...

    - command: /opt/application/upgrade_db.py
      run_once: true

    # ...
</code>```

Body:
There's run_once for this.

Example from the docs:

---
# ...

  tasks:

    # ...

    - command: /opt/application/upgrade_db.py
      run_once: true

    # ...


问:
How to narrow down a rounding issue in a Java program?
```<code>public class Rest {
    public static void main(String[] args) {
        double mealCost;
        int tipPercent;
        int taxPercent;
        double totalCost;

        Scanner scan = new Scanner(System.in);

        mealCost = scan.nextDouble();
        tipPercent = scan.nextInt();
        taxPercent = scan.nextInt();

        double tipInD = mealCost * (double)tipPercent / 100;
        double taxInD = mealCost * (double)taxPercent / 100;

        totalCost = (double)mealCost + (double)tipInD + (double)taxInD;

        System.out.println("The total meal cost is "+(int)totalCost+" dollars.");
    }
}
</code>```

This is the program i have created and I have to pass 4 different input cases, 3 of which am passing with this code, but the fourth 1 am not able to.

input cases with expected o/p.

Input for 1st - 3rd cases

```<code>---------
12.00 20 8
----------
15.50 15 10
----------
20.75 10 3
</code>```

Output for 1st - 3rd cases

```<code>---------
The total meal cost is 15 dollars.
---------
The total meal cost is 19 dollars.
---------
The total meal cost is 23 dollars.
</code>```

For the 4th case, the code I have written is not able to give the wanted O/P for it.

Input

```<code>--------
10.25
17
5
</code>```

Output Should Be

The total meal cost is 13 dollars.
And am Getting The total meal cost is 12 dollars.

答:
Change the way you write the totalCost to:

```<code>System.out.println("The total meal cost is "+ Math.round(totalCost) +" dollars.");
</code>```

This will actually round off your output as per it should be calculated rather than just strip the decimal value directly.

Body:
public class Rest {
    public static void main(String[] args) {
        double mealCost;
        int tipPercent;
        int taxPercent;
        double totalCost;

        Scanner scan = new Scanner(System.in);

        mealCost = scan.nextDouble();
        tipPercent = scan.nextInt();
        taxPercent = scan.nextInt();

        double tipInD = mealCost * (double)tipPercent / 100;
        double taxInD = mealCost * (double)taxPercent / 100;

        totalCost = (double)mealCost + (double)tipInD + (double)taxInD;

        System.out.println("The total meal cost is "+(int)totalCost+" dollars.");
    }
}

This is the program i have created and I have to pass 4 different input cases, 3 of which am passing with this code, but the fourth 1 am not able to.

input cases with expected o/p.

Input for 1st - 3rd cases

---------
12.00 20 8
----------
15.50 15 10
----------
20.75 10 3

Output for 1st - 3rd cases

---------
The total meal cost is 15 dollars.
---------
The total meal cost is 19 dollars.
---------
The total meal cost is 23 dollars.

For the 4th case, the code I have written is not able to give the wanted O/P for it.

Input

--------
10.25
17
5

Output Should Be

The total meal cost is 13 dollars.
And am Getting The total meal cost is 12 dollars.

Body:
Change the way you write the totalCost to:

System.out.println("The total meal cost is "+ Math.round(totalCost) +" dollars.");

This will actually round off your output as per it should be calculated rather than just strip the decimal value directly.


答:
Is it possible to redefine operator < for strings without modifiying std namespace

You can define the overload in another namespace, sure. But as you have found out, it will not be found by overload resolution unless explicitly qualified.

Is it possible to make std::sort using custom operator < without including it to std namespace?

Yes, and you already seem to know how:

Yes I know, I can pass another comparator to std::sort

This is exactly what the comparator argument is for.

Also am I correct, that it's corect to add such template specialization to std namespace?

That is not a template specialization; It is a function definition and you may not add function definitions to std namespace - or else the behaviour is undefined. You would be allowed to add template specializations, but only if at least one type argument is a user defined type.

Title: redefine < operator to use in stl algorithms for strings

Body:
Is it possible to redefine operator < for strings without modifying std namespace, to make this operator use in standard algorithms?
For example, I can write:

namespace std
{

    bool operator <(const std::string & rhs, const std::string & lhs)
    {
        std::cout << "lol";
        return false;
    }

}

int main()
{
    std::vector<std::string> lol = { "a", "b", "ba", "aa" };
    std::sort(lol.begin(), lol.end());
}

and "lol" will be printed several times. But if I move operator < outside from std namespace, default operator < will be used and nothing will be printed. Is it possible to make std::sort using custom operator < without including it to std namespace?

Yes I know, I can pass another comparator to std::sort but it's interesting for me if I could do what I asked and how?

Also am I correct, that it's correct to add such template specialization to std namespace?

Update: This is not practical question, I just want to know how can I do that if it's possible.


问:
Inheritance vs. Delegation
The code below shows how method m() can be reused by inheritance. How works for delegation? Thanks!</p>

```<code>  class A{
  int m();
  }

 class B extends A{}

 B b =new B()
 b.m();
</code>```

答:
Inheritance means IS-A: "An instance of class B IS-A instance of class A".

Composition means HAS-A: "An instance of class B HAS-A instance of class A".

Like this:

```<code>class B {

    private A a;

    public B(A a) { this.a = a; }

    public int m() { return a.m(); }
}
</code>```

Class B delegates its call to m() to its instance of class A.

It helps if both implement a common interface.

```<code>public interface DoSomething {
    int m();
}

class A implements DoSomething {
    public int m() { return 1; }
}

class B implements DoSomething {

    private A a;

    public B(A a) { this.a = a; }

    public int m() { return a.m(); }
}
</code>```

Title: Inheritance vs. Delegation

Body:
The code below shows how method m() can be reused by inheritance. How works for delegation? Thanks!

  class A{
  int m();
  }

 class B extends A{}

 B b =new B()
 b.m();

Body:
Inheritance means IS-A: "An instance of class B IS-A instance of class A".

Composition means HAS-A: "An instance of class B HAS-A instance of class A".

Like this:

class B {

    private A a;

    public B(A a) { this.a = a; }

    public int m() { return a.m(); }
}

Class B delegates its call to m() to its instance of class A.

It helps if both implement a common interface.

public interface DoSomething {
    int m();
}

class A implements DoSomething {
    public int m() { return 1; }
}

class B implements DoSomething {

    private A a;

    public B(A a) { this.a = a; }

    public int m() { return a.m(); }
}


答:
Dont showUrl when the list ends</p>

```<code>function showUrl1(idx)
{
    var f1 = document.getElementById("f1");
    f1.onload = function()
    {

        var next = idx === urls1.length? null: ++idx ;
        setTimeout(function()
        {   if(next != null){
              showUrl1(next);
            }

        }, 500);
    }
    f1.src = urls1[idx];
}
</code>```

Title: JavaScript URL looper

Body:
I am trying create a page that will run some given URLs, in time this will be a database populated list of URLs loaded into an array. I have it working using some code I have altered, however I don't want it to keep looping, I just want it to stop once the list is complete.

So basically loads first URL, waits .5 of a second after the pages loads, then moves onto the next until the list of URLS is finished.

However, my code keeps looping. How do I prevent this?

var urls1 =
[
 'http://localhost:8500/SupportTools/t1.cfm',
 'http://localhost:8500/SupportTools/t2.cfm',
 'http://localhost:8500/SupportTools/t3.cfm',
 'http://localhost:8500/SupportTools/t4.cfm',
 'http://localhost:8500/SupportTools/t5.cfm'
];

function showUrl1(idx)
{
 var f1 = document.getElementById("f1");
 f1.onload = function()
 {
  var next = ++idx % urls1.length;
  setTimeout(function()
  {
   showUrl1(next);
  }, 500);
 }
 f1.src = urls1[idx];
}

function start()
{
 showUrl1(0);
}

Body:
Dont showUrl when the list ends

function showUrl1(idx)
{
    var f1 = document.getElementById("f1");
    f1.onload = function()
    {

        var next = idx === urls1.length? null: ++idx ;
        setTimeout(function()
        {   if(next != null){
              showUrl1(next);
            }

        }, 500);
    }
    f1.src = urls1[idx];
}


问:
pointer in function on C
I'm revisiting linked list data structure, and my textbook created a function like this :

```<code>void *insert_beginning(){
    struct node *new_node;
    new_node = (struct node*)malloc(sizeof(struct node));

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    new_node->next = link;
    link = new_node;
}
</code>```

What does void *insert_beginning mean?
This method also giving me a warning No return, in function returning non-void

And why does it will error if I delete the *?

NB : My linked list project run flawlessly with those functions, but I'm just curious. It has nothing to do with linked list

答:
The declaration void *insert_beginning means that the name of the function is insert_beginning and that the return type should be a void pointer, which is, in a certain sense, an untyped pointer. However, the implementation of the funtion has no return statement, which causes the warning.

It is difficult to tell without more context, but either the return type should be void instead of void * or there should be some return statement like return new_node which passes a pointer to the newly allocated memory to the caller.

Title: pointer in function on C

Body:
I'm revisiting linked list data structure, and my textbook created a function like this :

void *insert_beginning(){
    struct node *new_node;
    new_node = (struct node*)malloc(sizeof(struct node));

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    new_node->next = link;
    link = new_node;
}

What does void *insert_beginning mean?
This method also giving me a warning No return, in function returning non-void

And why does it will error if I delete the *?

NB : My linked list project run flawlessly with those functions, but I'm just curious. It has nothing to do with linked list


问:
How do I remove an array item in TypeScript?
I have an array that I've created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?</p>

答:
```<code>let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);
</code>```


答:
Simply use the next hour. I love PHP due to simple datetime methods :)

```<code>echo date('h:i:sa', strtotime('next hour'));
</code>```

Title: printing the next hour with .date("h:i:sa"); php function

Body:
Simply use the next hour. I love PHP due to simple datetime methods :)

echo date('h:i:sa', strtotime('next hour'));


答:
Narrowing Primitive Conversion :

double to byte, short, char, int, long, or float

if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:

If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.

Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.

```<code>(int)totalCost => (int) 12.504999999999999 => 12 (decimal part stripped)
</code>```

Instead you may want to use Math.round( totalCost ) to get the closest integral value.

```<code>Math.round( totalCost ) => Math.round( 12.504999999999999 ) => 13
</code>```

Title: How to narrow down a rounding issue in a Java program?

Body:
Narrowing Primitive Conversion :

double to byte, short, char, int, long, or float

if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:

If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.

Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.

(int)totalCost => (int) 12.504999999999999 => 12 (decimal part stripped)

Instead you may want to use Math.round( totalCost ) to get the closest integral value.

Math.round( totalCost ) => Math.round( 12.504999999999999 ) => 13


问:
What is the use of #region and #endregion in c#?
give me an example what can I achieved if I use this block or not and
what is the use behind the name after start region </p>

```<code>#region MyClass definition
//Some code
#endregion
</code>```

答:
Basically #region-#endregion is used to separate your block of code (it may be your class of function or collection of function whatever you want to specify in.)

Which helps you to identify your block of code with the Key name that explain what you have done inside that region.

It helps you to expand or collapse your code block.
It simplify the way you write your code.
like below

```<code>    #region "This Is My Function"
    public void MyFunction()
    {
       //Some Code
    }
    #endregion
</code>```

For more details #region (C# Reference)

Body:
give me an example what can I achieved if I use this block or not and
what is the use behind the name after start region

#region MyClass definition
//Some code
#endregion

Body:
Basically #region-#endregion is used to separate your block of code (it may be your class of function or collection of function whatever you want to specify in.)

Which helps you to identify your block of code with the Key name that explain what you have done inside that region.

It helps you to expand or collapse your code block.
It simplify the way you write your code.
like below

    #region "This Is My Function"
    public void MyFunction()
    {
       //Some Code
    }
    #endregion

For more details #region (C# Reference)


问:
How to use a Jenkins Environment Variable as Input to a Plugin
I would like to set the release number for an Octopus Deploy release using the Jenkins build number.  In the OctopusDeploy Release plugin I have tried for the following in the release number field:

```<code> 1.0.%BUILD_NUMBER%
</code>```

and

```<code> 1.0.${BUILD_NUMBER}
</code>```

The variable is not replaced with it's value and I get an error like this:

The release number '1.0.%BUILD_NUMBER%' does not appear to be a valid semantic version number. At a minimum, release numbers require at least two parts, such as '1.3'.

It seems the above conventions only work as inputs in scripts.  How can I refer to the build number as input in a plugin field?

答:
For powershell install powershell plugin into jenkins, then add Windows Powershell step, below you may see link:

It will redirect you to the page with standard variables, in order to get build number variable you refer to it as described on that page, i.e.:

```<code>$env:BUILD_NUMBER
</code>```

Also, I would recommend creating powershell variable before passing it to smwhere else, in your case it should look like this:

```<code>$var="1.0." + $env:BUILD_NUMBER
</code>```

You may check variable before passing it any further by calling echo:

```<code>echo $var
</code>```

Also, windows have powerful built-in tool that could help you write your powershell scripts: Windows Powershell ISE

Body:
I would like to set the release number for an Octopus Deploy release using the Jenkins build number.  In the OctopusDeploy Release plugin I have tried for the following in the release number field:

 1.0.%BUILD_NUMBER%

and

 1.0.${BUILD_NUMBER}

The variable is not replaced with it's value and I get an error like this:

The release number '1.0.%BUILD_NUMBER%' does not appear to be a valid semantic version number. At a minimum, release numbers require at least two parts, such as '1.3'.

It seems the above conventions only work as inputs in scripts.  How can I refer to the build number as input in a plugin field?

Body:
For powershell install powershell plugin into jenkins, then add Windows Powershell step, below you may see link:

It will redirect you to the page with standard variables, in order to get build number variable you refer to it as described on that page, i.e.:

$env:BUILD_NUMBER

Also, I would recommend creating powershell variable before passing it to smwhere else, in your case it should look like this:

$var="1.0." + $env:BUILD_NUMBER

You may check variable before passing it any further by calling echo:

echo $var

Also, windows have powerful built-in tool that could help you write your powershell scripts: Windows Powershell ISE


问:
In Eclipse, how to set JavaDoc URL on a classpath entry programmatically?
I have an Eclipse plugin, that among other things, can create a project and give it several classpath entries.  This in and of itself works fine.

These jars do not have source included in the, however there is a URL that can be used for Javadoc.  I want to set this up programmatically for these classpath entries that the plug-in creates.  This is what I'm doing:

```<code>  IClasspathEntry cpEntry;

  File[] jarFile = installFilePath.listFiles();

  IPath jarFilePath;
  for (int fileCount = 0; fileCount < jarFile.length; fileCount++)
  {
      jarFilePath = new Path(jarFile[fileCount].getAbsolutePath());
      cpEntry = JavaCore.newLibraryEntry(jarFilePath, null, null);
      entries.add(cpEntry);
  }
</code>```

I could not figure out how to set the JavaDoc URL location on a claspath entry.  This can be done in the Eclipse UI - for instance, if you right-click the project, go to Properties... -> Java Build Path, and expand one of the JAR entries and edit the "Javadoc Location", you can specify a URL.  How do I do this from within a plug-in?

答:
I use the following:

```<code>        Path   pth = new Path( MY_JARFILE_LOCATION );
        Path   pthd = new Path( MY_JAVADOC_LOCATION );
        ClasspathAttribute att = new ClasspathAttribute("javadoc_location", "file:" + pthd.toOSString());
        IClasspathAttribute[] atts = new IClasspathAttribute[] { att };
        IClasspathEntry cpISDI = JavaCore.newLibraryEntry(pth, null, null, null, atts, false);
        cpEntries.add(1, cpISDI);
</code>```

(edited formatting)

OwnerDisplayName: Nathan

Body:
I have an Eclipse plugin, that among other things, can create a project and give it several classpath entries.  This in and of itself works fine.

These jars do not have source included in the, however there is a URL that can be used for Javadoc.  I want to set this up programmatically for these classpath entries that the plug-in creates.  This is what I'm doing:

  IClasspathEntry cpEntry;

  File[] jarFile = installFilePath.listFiles();

  IPath jarFilePath;
  for (int fileCount = 0; fileCount < jarFile.length; fileCount++)
  {
      jarFilePath = new Path(jarFile[fileCount].getAbsolutePath());
      cpEntry = JavaCore.newLibraryEntry(jarFilePath, null, null);
      entries.add(cpEntry);
  }

I could not figure out how to set the JavaDoc URL location on a claspath entry.  This can be done in the Eclipse UI - for instance, if you right-click the project, go to Properties... -> Java Build Path, and expand one of the JAR entries and edit the "Javadoc Location", you can specify a URL.  How do I do this from within a plug-in?

Body:
I use the following:

        Path   pth = new Path( MY_JARFILE_LOCATION );
        Path   pthd = new Path( MY_JAVADOC_LOCATION );
        ClasspathAttribute att = new ClasspathAttribute("javadoc_location", "file:" + pthd.toOSString());
        IClasspathAttribute[] atts = new IClasspathAttribute[] { att };
        IClasspathEntry cpISDI = JavaCore.newLibraryEntry(pth, null, null, null, atts, false);
        cpEntries.add(1, cpISDI);

(edited formatting)


问:
Only 2 emoji return an incorrect length when compared against a character set containing them
```<code>let myString = "☺"

let emoji = "☺☹"

let characterSet = CharacterSet(charactersIn: emoji)

let range = (myString as NSString).rangeOfCharacter(from: characterSet)
(myString as NSString).substring(with: range)
(range as NSRange).location
(range as NSRange).length
(myString as NSString).length

substring == myString
</code>```

This code can be ran in Playgrounds. Try changing myString to be any emoji face.

I'm using NSString and NSRange here as their values are easier to demonstrate, but this has the exact same behaviour with a Swift String or Range.

When I set myString to most of the face emojis, the range comes back as having a length of 2, and the substring can be used appropriately elsewhere. With only 2 face emojis - the "smiling face" emoji and "frowning face" emoji, the range comes back as a length of 1. In all cases, the length of the string comes back as 2. The substring with the given range of 1 is incomplete, and you can see that comparing it back to myString, as an example of comparing it to itself, gives a result of false. The result for the range of those 2 emojis should be 2.

Interestingly, looking at the unicode spec, those 2 emojis have vastly differently unicode values to their neighbours.

This seems like it may be an iOS bug. I can't think of anything I could be personally doing incorrectly here, as it works with all other emoji.

答:
Hardly an answer but to much to fit into a comment so bear with me :)

I don't know if you've already seen this but I think your problem is addressed in the Platform State of the Union talk from WWDC 2017 (https://developer.apple.com/videos/play/wwdc2017/102/) in the section about what is new in Swift 4.

If you look at the video at about the 23 minutes 12 seconds mark you'll see Ted Kremenek talk about how they've fixed separating unicode characters out as expected in Swift 4 using Unicode 9 Grapheme Braking.

Also, have a look at this question and answer.

Yes...Don't ask me in detail what all this means, but it seems as if they're working on it :)

Body:
let myString = "☺"

let emoji = "☺☹"

let characterSet = CharacterSet(charactersIn: emoji)

let range = (myString as NSString).rangeOfCharacter(from: characterSet)
(myString as NSString).substring(with: range)
(range as NSRange).location
(range as NSRange).length
(myString as NSString).length

substring == myString

This code can be ran in Playgrounds. Try changing myString to be any emoji face.

I'm using NSString and NSRange here as their values are easier to demonstrate, but this has the exact same behaviour with a Swift String or Range.

When I set myString to most of the face emojis, the range comes back as having a length of 2, and the substring can be used appropriately elsewhere. With only 2 face emojis - the "smiling face" emoji and "frowning face" emoji, the range comes back as a length of 1. In all cases, the length of the string comes back as 2. The substring with the given range of 1 is incomplete, and you can see that comparing it back to myString, as an example of comparing it to itself, gives a result of false. The result for the range of those 2 emojis should be 2.

Interestingly, looking at the unicode spec, those 2 emojis have vastly differently unicode values to their neighbours.

This seems like it may be an iOS bug. I can't think of anything I could be personally doing incorrectly here, as it works with all other emoji.


问:
Why does it give me a "Failed to resolve" error in Android Studio?
I am trying to learn Android and I tried to make an example from a tutorial. I have to include two libraries in the build.gradle, but when I sync the project with the gradle files it gives me this error: "Failed to resolve".

Here is the dependecies part from build.gradle:

```<code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.loopj.android:android-async-http:1.4.4'
compile 'com.squareup.picasso:picasso:2.1.1'
</code>```

}

Is there somethig wrong with the versions of the libraries or is it something else?

答:
in my case adding mavencentral to gradle worked
I took it from here

Could not find com.squareup.picasso:picasso:2.5.2

```<code>enter repositories {
    jcenter()
    mavenCentral()
}
</code>```

Body:
I am trying to learn Android and I tried to make an example from a tutorial. I have to include two libraries in the build.gradle, but when I sync the project with the gradle files it gives me this error: "Failed to resolve".

Here is the dependecies part from build.gradle:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.loopj.android:android-async-http:1.4.4'
compile 'com.squareup.picasso:picasso:2.1.1'

}

Is there somethig wrong with the versions of the libraries or is it something else?

Body:
in my case adding mavencentral to gradle worked
I took it from here

Could not find com.squareup.picasso:picasso:2.5.2

enter repositories {
    jcenter()
    mavenCentral()
}


问:
Does MariaDB support nested transactions?
Does MariaDB support nested transactions (not savepoints)?

I want to be able to use nested transactions in stored procedures.  Currently in MySQL I am passing a parameter, "useTransaction" to each stored procedure, which controls if I start a new transaction in the body of that stored procedure.

It would more more convenient if transactions could be nested like this.

答:
No, but both MariaDB and MySQL have chained transactions:</p>

```<code>START TRANSACTION;
[do e.g. an insert here]
COMMIT AND CHAIN;
[do e.g. another insert here]
COMMIT AND CHAIN;
[do e.g. yet another insert here]
COMMIT;
</code>```

Body:
No, but both MariaDB and MySQL have chained transactions:

START TRANSACTION;
[do e.g. an insert here]
COMMIT AND CHAIN;
[do e.g. another insert here]
COMMIT AND CHAIN;
[do e.g. yet another insert here]
COMMIT;


问:
Splitting CCK Node Content into Multiple Pages in Drupal?
I've a relatively long customized content type in Drupal that I'm trying to split across a few pages. The page has a bunch of custom CCK fields and I'd like to do something like node-name/general/, node-name/pricing/, node-name/photos, etc. What are the modules and techniques I would need to do this? I'm still a relative newbie to Drupal so I'm not sure if this is something that could be done with Views, Panels, or something else. </p>

答:
I recommend using views for this. Views and CCK go together very well as a set.

In views you can add a new 'page' view then based on the url to get the correct record (you use the settings Arguments for this)

You can add separate views for the different sections in your cck using the 'Page settings' path.

Although this explanation will not in itself be easy enough to get straight up and do this in views. This is the way of doing it without writing your own module. Once familiar with views it should be fairly simple though.

A good place to start with views might be Here


问:
How to select particular database using InfluxDB web user interface
I am using InfluxDB and caught up with interesting situation. I have created around 20 plus instances of D.B. as shown below.

Now, some of the Database names are not showing as they are way down below in the drop down list. I did apply zoom in, reducing font size, giving name of database so that they can come up at the staring of the list, but these all are temporary solutions. Wondering how to scroll database list or select specific database using some InfluxDB command?

InfluxDB version i am using is V 1.2.2

答:
You can do either of these:

Issue a SHOW DATABASES query to gather the list of your databases

Prefix with the database name, e.g.

```<code>SELECT * from DATABASENAME..MEASUREMENTNAME
</code>```

to query a specific database

Body:
You can do either of these:

Issue a SHOW DATABASES query to gather the list of your databases

Prefix with the database name, e.g.

SELECT * from DATABASENAME..MEASUREMENTNAME

to query a specific database


Title: Compare (greater than or less than) 1st row value with 2nd row value based on Paid date for the Key, and then check if 3rd row is greater than 2nd

Body:
Current result

-- Scenario1--For ID 1 and 2, I want to compare if Diff Between (DD,Begin date of ID 2    , End Date OF ID 1) < = 1, then the value should be true and be displayed other wise don't display the value

Scenario2 For ID 10 and 11 -- Begin Date for ID 10 and Begin Date of ID 11 is same, so I want to compare based on Paid date, As Paid Date of ID 11 is > Paid date of ID 10. I want the value to be displayed which is greater

Id  Employeekey ReceiptNo   BeginDate   endDate     PaidDate    main    Supplier    RollNo
1   101         5505        3/28/2016   3/29/2016   4/29/2016   1       2001    655
2   101         5506        3/30/2016   4/1/2016    4/30/2016   1       2001    666
3   101         5507        4/5/2016    4/6/2016    4/30/2016   1       2001    155
4   101         5508        4/7/2016    4/10/2016   5/1/2016    1       2001    155
5   101         5509        4/11/2016   4/14/2016   5/5/2016    1       2001    155
6   101         5510        5/1/2016    5/3/2016    6/24/2016   1       2001    255
7   101         5511        5/1/2016    5/3/2016    6/30/2016   1       2001    265
8   102         5512        3/28/2017   3/29/2016   4/29/2017   1       2001    655
9   102         5513        3/28/2017   3/29/2016   4/29/2017   1       2001    655
10  102         5514        3/28/2017   3/29/2016   4/29/2017   1       2001    655
11  102         5515        3/28/2016   3/29/2016   5/29/2016   1       2001    655
12  102         5515        3/28/2016   3/29/2016   5/29/2016   1       2001    659

Body:
Look at the dates for your second scenario. The dates aren't the same for BeginDate for ID 10 and ID 11. Also, the PaidDate is not >, it's < (look at the years in both cases). With that being said, i edited your test data. Here is how you would do this. You can alter it to fit your needs but this will get you going.

declare @table table (id int,
                     Employeekey int,
                     RecieptNo int,
                     BeginDate datetime,
                     endDate datetime,
                     PaidDate datetime,
                     main int,
                     Supplier int,
                     RollNo int)
 insert into @table
 values
(1,101,5505,'3/28/2016','3/29/2016','4/29/2016',1,2001,655),
(2,101,5506,'3/30/2016','4/1/2016','4/30/2016',1,2001,666),
(3,101,5507,'4/5/2016','4/6/2016','4/30/2016',1,2001,155),
(4,101,5508,'4/7/2016','4/10/2016','5/1/2016',1,2001,155),
(5,101,5509,'4/11/2016','4/14/2016','5/5/2016',1,2001,155),
(6,101,5510,'5/1/2016','5/3/2016','6/24/2016',1,2001,255),
(7,101,5511,'5/1/2016','5/3/2016','6/30/2016',1,2001,265),
(8,102,5512,'3/28/2017','3/29/2016','4/29/2017',1,2001,655),
(9,102,5513,'3/28/2017','3/29/2016','4/29/2017',1,2001,655),
(10,102,5514,'3/28/2016','3/29/2016','4/29/2016',1,2001,655),   --changed this to 2016 for being date and paid date
(11,102,5515,'3/28/2016','3/29/2016','5/29/2017',1,2001,655),   --changed this to 2017 for paid date
(12,102,5515,'3/28/2016','3/29/2016','5/29/2016',1,2001,659)

select
    *
    --scenario 1
    ,case
        when datediff(day,lead(BeginDate) over (partition by EmployeeKey order by Id),endDate) <=1 then 'True'
    end
    --scenario 2... id 10 and 11 have different years in your test but i fixed this in my test
    ,case
        when lead(BeginDate) over (partition by EmployeeKey order by Id) = BeginDate
             and  lead(PaidDate) over (partition by EmployeeKey order by Id) > PaidDate then 'True'
    end
from @table


问:
Database design: should nested objects have their own table?
I'm somewhat new to database design, so I'd like some pointers on how best to lay my current tables out.

I have a table Jobs that holds various jobs. Users can create Subjobs. A Subjob has a Job as a parent. A Subjob has all the same properties as a Job, but some of them are read-only, whereas they are all read/write for a Job. A Job can have many Subjobs. At the moment, there may only be one layer of subjobs, but I'd like the flexibility to allow for infinite nesting of Subjobs in the future. The objects will be interacted with through a MVC web app.

I've considered two options for layout:

Jobs and Subjobs each have their own table.

This seems like "good design" because I don't introduce columns in Job with the sole purpose of nesting with itself.

It's a bit of a pain for coding the web app, since a Job and Subjob would have to have two separate Controllers/sets of Views, despite them being identical in properties.

It makes less sense from a design perspective if infinite nesting is introduced.

Jobs and Subjobs are on the same table. Jobs are just given a nullable parent_job_id property that is non-null if it is a Subjob.

Makes sense for infinite nesting.

Less of a pain for coding the web app.

A weird nesting property is introduced to the Job table that has nothing to do with the actual properties of a Job.

Any advice on how to handle this? Are there additional design patterns I haven't considered? I'm using Entity Framework 6 Code First, if that matters.

答:
The first option is fine if you were not describing a hierarchy with multiple levels, but you are. The pattern you are describing is commonly known as an Adjacency List which is stored as you describe your second option.

Some other options for storing a hierarchy are:

Nested sets (more complicated implementation but potentially faster queries without recursion).

Materialized Path (Stores a character representation of the hierarchy path, e.g. like a file storage system)

Modifications / Helper tables for Adjacency List (Flat table, bridge table)

Custom implementations like HierarchyId

Hierarchy Reference:

StackOverflow - What are the options for storing hierarchical data in a relational-database

Louis Davidson - Presentations - How to Optimize a Hierarchy In SQL Server - Presentations & Demo Code


问:
Enable Annotation Buttons using R's Highcharter Library
I am using the highcharter library for a project in R and really need the ability to draw freehand lines on the chart. I see the highcharts library can add annotations to the chart. Is there a way to enable the annotation buttons on my chart with the highcharter library?
https://www.highcharts.com/plugin-registry/single/17/Annotations
Below is a code example that uses the hc_annotations(). I’m not sure what needs to be added to the hc_annotations() to enable the buttons.

```<code>library("highcharter")
data("citytemp")

hc <- highchart() %>%
  hc_xAxis(categories = citytemp$month) %>%
  hc_add_series(name = "Tokyo", data = citytemp$tokyo) %>%
  hc_add_series(name = "New York", data = citytemp$new_york)
hc

hc %>%
  hc_add_series(name = "London", data = citytemp$london, type = "area") %>%
  hc_rm_series(name = "New York") %>%
  hc_annotations(list(enabledButtons=TRUE, xValue = 10, yValue = 10, title =list(text = 'Annotated chart!')))
</code>```

答:
Here's an example of how to add the default annotation buttons in highcharter.  After a couple attempts with hc_annotations() it seems just passing a list of options to the initial highchart() call might be easier.

```<code>library("highcharter")
data("citytemp")

hc_opts <- list(enabledButtons=TRUE)
hc <- highchart(hc_opts) %>%
  hc_xAxis(categories = citytemp$month) %>%
  hc_add_series(name = "Tokyo", data = citytemp$tokyo) %>%
  hc_add_series(name = "New York", data = citytemp$new_york)
hc
</code>```

output

Body:
I am using the highcharter library for a project in R and really need the ability to draw freehand lines on the chart. I see the highcharts library can add annotations to the chart. Is there a way to enable the annotation buttons on my chart with the highcharter library?
https://www.highcharts.com/plugin-registry/single/17/Annotations
Below is a code example that uses the hc_annotations(). I’m not sure what needs to be added to the hc_annotations() to enable the buttons.

library("highcharter")
data("citytemp")

hc <- highchart() %>%
  hc_xAxis(categories = citytemp$month) %>%
  hc_add_series(name = "Tokyo", data = citytemp$tokyo) %>%
  hc_add_series(name = "New York", data = citytemp$new_york)
hc

hc %>%
  hc_add_series(name = "London", data = citytemp$london, type = "area") %>%
  hc_rm_series(name = "New York") %>%
  hc_annotations(list(enabledButtons=TRUE, xValue = 10, yValue = 10, title =list(text = 'Annotated chart!')))

Body:
Here's an example of how to add the default annotation buttons in highcharter.  After a couple attempts with hc_annotations() it seems just passing a list of options to the initial highchart() call might be easier.

library("highcharter")
data("citytemp")

hc_opts <- list(enabledButtons=TRUE)
hc <- highchart(hc_opts) %>%
  hc_xAxis(categories = citytemp$month) %>%
  hc_add_series(name = "Tokyo", data = citytemp$tokyo) %>%
  hc_add_series(name = "New York", data = citytemp$new_york)
hc

output