答:
How should I extract value of user.patron.relation?

You would use { … patron: {relation: rUser.relation}, … } as the destructuring target.

Is there a more succint way of writing the above?

If the property names don't match there's not much you can do, but in your particular case you can simplify by destructuring the parameter into multiple variables:

```<code>const rUsers = children.map(({firstName, lastName, patron: {relation}}) =>
    ({firstName, lastName, relation})
);
</code>```

Title: ES6 curly braces usage when extracting from an object and assigning to another object

Body:
How should I extract value of user.patron.relation?

You would use { … patron: {relation: rUser.relation}, … } as the destructuring target.

Is there a more succint way of writing the above?

If the property names don't match there's not much you can do, but in your particular case you can simplify by destructuring the parameter into multiple variables:

const rUsers = children.map(({firstName, lastName, patron: {relation}}) =>
    ({firstName, lastName, relation})
);


来源: stackexchange

问:
when i want to build i have this error
```<code>Error:Execution failed for task ':app:processDebugManifest'.
</code>```

Manifest merger failed : uses-sdk:minSdkVersion 11 cannot be smaller than version 14 declared in library [com.google.android.gms:play-services:11.0.4] C:\Users\kamal.android\build-cache\a14382872a293855060ea80fddf386831adf48b2\output\AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.play_services" to force usage

```<code>apply plugin: 'com.android.application'
 compileSdkVersion 23
buildToolsVersion "26.0.1"

defaultConfig {
    applicationId "com.carpedeem.bonne"
    minSdkVersion 11
    targetSdkVersion 23

    ndk {
        modandroid {
            uleName "player_shared"

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
</code>```

}

```<code>dependencies {
compile 'com.google.android.gms:play-services:+'
compile files('libs/dagger-1.2.2.jar')
compile files('libs/javax.inject-1.jar')
compile files('libs/nineoldandroids-2.4.0.jar')
compile files('libs/PTAdChartboost.jar')
compile files('libs/PTAdRevMob.jar')
compile files('libs/support-v4-19.0.1.jar')
</code>```

}

答: Change the minSdkVersion to 14 in your build.gradle app and upgrade your compileSdkVersion to 7.0 and your buildToolsVersion to 26.0.0.

ContentLicense: CC BY-SA 3.0

Title: when i want to build i have this error

Body:
Error:Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : uses-sdk:minSdkVersion 11 cannot be smaller than version 14 declared in library [com.google.android.gms:play-services:11.0.4] C:\Users\kamal.android\build-cache\a14382872a293855060ea80fddf386831adf48b2\output\AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.play_services" to force usage

apply plugin: 'com.android.application'
 compileSdkVersion 23
buildToolsVersion "26.0.1"

defaultConfig {
    applicationId "com.carpedeem.bonne"
    minSdkVersion 11
    targetSdkVersion 23

    ndk {
        modandroid {
            uleName "player_shared"

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}

}

dependencies {
compile 'com.google.android.gms:play-services:+'
compile files('libs/dagger-1.2.2.jar')
compile files('libs/javax.inject-1.jar')
compile files('libs/nineoldandroids-2.4.0.jar')
compile files('libs/PTAdChartboost.jar')
compile files('libs/PTAdRevMob.jar')
compile files('libs/support-v4-19.0.1.jar')

}


问:
How to call a method on a class through the delegate (multitasking methods)?
I need to call a "refresh method" on one of my classes every time the user returns to my app (multitasking). It seem that for multitasking I need to do this through the app delegate. So what is the best way to call the "refresh method" on my classes self, but from the app delegate?</p>

答: applicationWillEnterForeground in the application delegate will be called when your application is just about to come to foreground. Write your refresh logic there.

ContentLicense: CC BY-SA 2.5


问:
What really is a deque in STL?
I was looking at STL containers and trying to figure what they really are (i.e. the data structure used), and the deque stopped me: I thought at first that it was a double linked list, which would allow insertion and deletion from both ends in constant time, but I am troubled by the promise made by the operator [] to be done in constant time. In a linked list, arbitrary access should be O(n), right?

And if it's a dynamic array, how can it add elements in constant time? It should be mentioned  that reallocation may happen, and that O(1) is an amortized cost, like for a vector.

So I wonder what is this structure that allows arbitrary access in constant time, and at the same time never needs to be moved to a new bigger place.

答:
I was reading "Data structures and algorithms in C++" by Adam Drozdek, and found this useful.
HTH.

A very interesting aspect of STL deque is its implementation. An STL deque is not implemented as a linked list but as an array of pointers to blocks or arrays of data. The number of blocks changes dynamically depending on storage needs, and the size of the array of pointers changes accordingly.

You can notice in the middle is the array of pointers to the data (chunks on the right), and also you can notice that the array in the middle is dynamically changing.

An image is worth a thousand words.

Title: What really is a deque in STL?


问:
How do I get time of a Python program's execution?
I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.

I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program.

答:
Timeit is a class in Python used to calculate the execution time of small blocks of code.

Default_timer is a method in this class which is used to measure the wall clock timing, not CPU execution time. Thus other process execution might interfere with this. Thus it is useful for small blocks of code.

A sample of the code is as follows:

```<code>from timeit import default_timer as timer

start= timer()

# Some logic

end = timer()

print("Time taken:", end-start)
</code>```

Body:
Timeit is a class in Python used to calculate the execution time of small blocks of code.

Default_timer is a method in this class which is used to measure the wall clock timing, not CPU execution time. Thus other process execution might interfere with this. Thus it is useful for small blocks of code.

A sample of the code is as follows:

from timeit import default_timer as timer

start= timer()

# Some logic

end = timer()

print("Time taken:", end-start)

ContentLicense: CC BY-SA 4.0


问:
C# Mono NLog Could not load file or assembly When Deployed to Raspberry PI
I have just begun messing with C# on my Raspberry Pi and it seems to be going well. I am developing my C# application on my Arch Linux machine with Monodevelop and scp-ing everything in the bin/Debug/ directory to my Raspberry Pi and then running "mono my.exe". This has worked with some simple applications I have played with but I am having trouble with NLog. The executable runs fine on my development machine but I get this exception on the Raspberry Pi:

```<code>mono NLogTest.exe

Unhandled Exception:
System.TypeInitializationException: The type initializer for 'NLogTest.MainClass' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly or one of its dependencies.
  at NLog.LogFactory.get_Configuration () [0x000aa] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogFactory.GetLogger (NLog.LogFactory+LoggerCacheKey cacheKey) [0x0012c] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogFactory.GetLogger (System.String name) [0x00011] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogManager.GetCurrentClassLogger () [0x0000a] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLogTest.MainClass..cctor () [0x00000] in <689b8644ac61434f9d79427c3bf696a7>:0
   --- End of inner exception stack trace ---
</code>```

It seems as if NLog can't find the config file but it is in the same directory.

The simple example I am using is:

```<code>using System;
using NLog;
namespace NLogTest
{
    class MainClass
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public static void Main(string[] args)
        {
            Console.WriteLine("Testing NLog");
            logger.Trace("A Trace!!");
            logger.Debug("Sample debug message");
            logger.Info("Sample informational message");
            logger.Warn("Sample warning message");
            logger.Error("Sample error message");
            logger.Fatal("Sample fatal error message");
            Console.Write("DONE LOGGING!");
        }
    }
}
</code>```

and my NLog.config file is pretty simple:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="false">
    <targets>
        <target xsi:type="File"
            name="logFile"
            fileName="The.log"
            />
    </targets>
    <rules>
        <logger name="*" writeTo="logFile" minlevel="Info" />
    </rules>
</nlog>
</code>```

The directory on my Raspberry Pi contains the exe, the NLog.config file, and the NLog.dll.

I installed the mono-runtime package from apt on the Raspberry pi. On my development machine, the Monodevelop build options for the project are set to target "Mono/.NET 4.5". I didn't think it would matter that I am developing on an x86 machine and deploying to an ARM-A machine because I thought the mono runtime would handle the architecture differences.

Any help here would be appreciated, thanks.

答:
Thanks to @Rolf Kristensen, I moved the LogManager.GetCurrentClassLogger call into main. Then I got the message

Can't find custom attr constructor image: /home/pi/monotest/NLog.dll
  mtoken: 0x0a00001f due to Could not load file or assembly or one of
  its dependencies. assembly:System.Core, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b77a5c561934e089 type:
  member:

This led me to this github issue: https://github.com/NLog/NLog/issues/905

Where if I installed libmono-system-servicemodel4.0a-cil onto the target raspberry pi with apt-get, then it works!

Also this is with the target framework as .NET 4.5 and the Target Architecture as "Any".

Body:
I have just begun messing with C# on my Raspberry Pi and it seems to be going well. I am developing my C# application on my Arch Linux machine with Monodevelop and scp-ing everything in the bin/Debug/ directory to my Raspberry Pi and then running "mono my.exe". This has worked with some simple applications I have played with but I am having trouble with NLog. The executable runs fine on my development machine but I get this exception on the Raspberry Pi:

mono NLogTest.exe

Unhandled Exception:
System.TypeInitializationException: The type initializer for 'NLogTest.MainClass' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly or one of its dependencies.
  at NLog.LogFactory.get_Configuration () [0x000aa] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogFactory.GetLogger (NLog.LogFactory+LoggerCacheKey cacheKey) [0x0012c] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogFactory.GetLogger (System.String name) [0x00011] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogManager.GetCurrentClassLogger () [0x0000a] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLogTest.MainClass..cctor () [0x00000] in <689b8644ac61434f9d79427c3bf696a7>:0
   --- End of inner exception stack trace ---

It seems as if NLog can't find the config file but it is in the same directory.

The simple example I am using is:

using System;
using NLog;
namespace NLogTest
{
    class MainClass
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public static void Main(string[] args)
        {
            Console.WriteLine("Testing NLog");
            logger.Trace("A Trace!!");
            logger.Debug("Sample debug message");
            logger.Info("Sample informational message");
            logger.Warn("Sample warning message");
            logger.Error("Sample error message");
            logger.Fatal("Sample fatal error message");
            Console.Write("DONE LOGGING!");
        }
    }
}

and my NLog.config file is pretty simple:

<?xml version="1.0" encoding="UTF-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="false">
    <targets>
        <target xsi:type="File"
            name="logFile"
            fileName="The.log"
            />
    </targets>
    <rules>
        <logger name="*" writeTo="logFile" minlevel="Info" />
    </rules>
</nlog>

The directory on my Raspberry Pi contains the exe, the NLog.config file, and the NLog.dll.

I installed the mono-runtime package from apt on the Raspberry pi. On my development machine, the Monodevelop build options for the project are set to target "Mono/.NET 4.5". I didn't think it would matter that I am developing on an x86 machine and deploying to an ARM-A machine because I thought the mono runtime would handle the architecture differences.

Any help here would be appreciated, thanks.


问:
Generating QR code using Google API in Excel, the QR code is not generating on another spreadsheet in the same workbook
I found this neat spreadsheet that will generate a QR code in excel via Google API.

The website is below:
https://sites.google.com/site/e90e50fx/home/generate-qrcode-with-excel

The link to the downloadable spreadsheet is below:
https://sites.google.com/site/e90e50fx/home/generate-qrcode-with-excel/qr_code_udf.xlsm?attredirects=0&d=1

The issue I am having is that I copied the spreadsheet into another workbook.
Initially it didn't work until I also copied the GoogleAPI module into that work book as well. The QR code will generate in the copied spreadsheet.
However, what I am trying to do is generate the QR code in the same workbook but in another spreadsheet.

It errors out.

=URL_QRCode_SERIES("qr_code_1",J7:N7,,"qrCode")

I am using this formula in the spreadsheet that I am trying to get the QR barcode image to generate in but it errors out and shows this error:

#VALUE

Can't figure out what is wrong.
The value I am trying get a QR code for is using the concatenate command and it's in several merged cell columns as shown in formula above.

It generates qr codes successfully for any other single cell column value in that spreadsheet. So I'm wondering if I need to change the formula.

答:
Figured it out.
The formula below works:

=URL_QRCode_SERIES("qr_code_1",J7,,"qrCode")

Even though cell J7 through N7 are merged as one,
I just had to select the merged cell and it input J7 into the formula.
Then the QR bar code generates successfully.

I also discovered that I don't need the copied QRcode spreadsheet.
The GoogleAPI module in excel VBA is good enough as long as it's part of the workbook you are working in.


问:
Is storing a Unix timestamp a bad idea in the long term
I've recently started working on a new application and I need to be able to compare times that the user has been active so basically my logic will be something like:

```<code>func pseudo (user string) {
    v := GET Timestamp FROM users;

    if currentTimestamp - 1800 < dbTimestamp
        // Do something
</code>```

I've though about using Unix timestamps, in specific the number of seconds. However I'm not sure if storing this will become a problem as it only grows and I realize it will take a while to add more digits it does not feel like it's the best for performance reasons. Is storing and comparing a Unix timestamp a good idea for long term applications?

Side note:

My application is written in go so while I can store datetime, I have to extract the datetime from the database and attempt to use the atrocious layout numbers and it becomes more complicated attempting to format it to work with the layout numbers.

答:
There are 31,536,000 seconds in a year, so it will take over 269 years before another digit is added to unix timestamps.

```<code>(10,000,000,000 - 1,510,798,414) / 31,536,000 = 269.1908
</code>```

So, on that count I'd say you're good for a while.

Depending on the database column type that you're using, a more immediate problem might be that from January 19, 2038 onward, you will no longer be able to store your timestamps in a signed 32 bit integer as they have a max value of 2,147,483,647.

So, I'd say: put a sticky note on your monitor to change your database column type on January 18, 2038. If you're using an unsigned 32 bit integer type, you're good until 2106.

Body:
I've recently started working on a new application and I need to be able to compare times that the user has been active so basically my logic will be something like:

func pseudo (user string) {
    v := GET Timestamp FROM users;

    if currentTimestamp - 1800 < dbTimestamp
        // Do something

I've though about using Unix timestamps, in specific the number of seconds. However I'm not sure if storing this will become a problem as it only grows and I realize it will take a while to add more digits it does not feel like it's the best for performance reasons. Is storing and comparing a Unix timestamp a good idea for long term applications?

Side note:

My application is written in go so while I can store datetime, I have to extract the datetime from the database and attempt to use the atrocious layout numbers and it becomes more complicated attempting to format it to work with the layout numbers.

Body:
There are 31,536,000 seconds in a year, so it will take over 269 years before another digit is added to unix timestamps.

(10,000,000,000 - 1,510,798,414) / 31,536,000 = 269.1908

So, on that count I'd say you're good for a while.

Depending on the database column type that you're using, a more immediate problem might be that from January 19, 2038 onward, you will no longer be able to store your timestamps in a signed 32 bit integer as they have a max value of 2,147,483,647.

So, I'd say: put a sticky note on your monitor to change your database column type on January 18, 2038. If you're using an unsigned 32 bit integer type, you're good until 2106.


问:
Why symbol-type key in Object have a bracket around them
I just started JS, wondering why there are [] around Symbol. For example: in an object.

```<code>var bow = {
    [Symbol('apple')] : something,
    [Symbol('banana')] : something,
    ....
}
</code>```

Also, when it comes to iterator:

```<code>var iterableObject = {
    [Symbol.iterator] : function() {.....}
}
</code>```

Can anyone explain what is the use of these [] around them? I googled a while but didn't find satisfied answer, thank you in advance.

答:
The square brakets are just part of object literal syntax.

When you make an object using object literal syntax it is now possible to use variables to set the keys inside the object.

```<code>const string = 'whatever'
const normalObject = {
    [string]: 'something else'
}
</code>```

This results in normalObject having one property, 'whatever' pointing to 'something else'

```<code>// normalObject
{ whatever: 'something else' }
</code>```

The use of brackets in object literal syntax is just to allow you to use a variable to set the key in an object.

bringing this back to your example this is just allowing you to use Symbols as keys in your object.

You may have noticed that this is a little weird. Up until very recently an object could only have String keys. Symbols are not the other thing you can use as keys in an object.

```<code>var bow = {
    [Symbol('banana')] : something,
    [Symbol('banana')] : something,
    ....
}
</code>```

this will result in an object with two different Symbol(banana) pointing to something.

Body:
I just started JS, wondering why there are [] around Symbol. For example: in an object.

var bow = {
    [Symbol('apple')] : something,
    [Symbol('banana')] : something,
    ....
}

Also, when it comes to iterator:

var iterableObject = {
    [Symbol.iterator] : function() {.....}
}

Can anyone explain what is the use of these [] around them? I googled a while but didn't find satisfied answer, thank you in advance.

Body:
The square brakets are just part of object literal syntax.

When you make an object using object literal syntax it is now possible to use variables to set the keys inside the object.

const string = 'whatever'
const normalObject = {
    [string]: 'something else'
}

This results in normalObject having one property, 'whatever' pointing to 'something else'

// normalObject
{ whatever: 'something else' }

The use of brackets in object literal syntax is just to allow you to use a variable to set the key in an object.

bringing this back to your example this is just allowing you to use Symbols as keys in your object.

You may have noticed that this is a little weird. Up until very recently an object could only have String keys. Symbols are not the other thing you can use as keys in an object.

var bow = {
    [Symbol('banana')] : something,
    [Symbol('banana')] : something,
    ....
}

this will result in an object with two different Symbol(banana) pointing to something.


问:
MAINFRAME: SORT in JCL to convert a dataset into CSV format
hope you are OK. I have a problem and I need your help, if possible.

I'm working with Mainframe JCL and I have a dataset with records; each record has different fixed columns separated by "~" (We use that since in the column NAME the names are separated by commas). I need to convert that dataset in a CSV file format, so it needs to be:
1) separated by comma
2) with variable lenght instead of fix lenght
3) I don't need all of the columns, just 4 of them (and in different order from original)
4) the first colum must be different
5) If the name has a , (Ex: LAST NAME, NAME) use " "

This is an example of the input file:

```<code>ROLENAME~LID     ~NAME                  ~NONCNCL~ACCDATE ~SUSPEND
CARINQ  ~X       ~*** NOT FOUND ***     ~       ~        ~
CARONL  ~AZBLCH  ~*** NOT FOUND ***     ~       ~        ~
SOTHER  ~BZBWD4  ~SUAREZ, VICTOR        ~N      ~10/01/17~N
CARONL  ~BZCJHS  ~CHURCH DAVID S        ~N      ~11/10/17~N
CARONL  ~VZC2G1  ~*** NOT FOUND ***     ~       ~        ~
CARONL  ~BZDKKF  ~PLAARDRTE ALLY        ~N      ~11/13/17~N
SOTHER  ~HZDFGH  ~*** NOT FOUND ***     ~       ~        ~
CARONL  ~JZFPOI  ~LOPEZ KAREN N         ~N      ~11/10/17~N
CARONL  ~IZG0WZ  ~FOSHIL, RICHARD       ~N      ~11/13/17~N
SOTHER  ~OZG3T2  ~CARLINE KECHUA        ~N      ~11/13/17~N
CARONL  ~PZMMNB  ~BARELTINE, DUANE      ~N      ~11/13/17~N
CARONL  ~PZNSWX  ~*** NOT FOUND ***     ~       ~        ~
CARONL  ~RZPF5V  ~SLIMMORE JACK         ~N      ~10/12/17~N
</code>```

This is an example of output file:

```<code>GMID,Name,Last Login Date,Role/Group
X,*** NOT FOUND ***,,CARINQ
AZBLCH,*** NOT FOUND ***,,CARONL
BZBWD4,"SUAREZ, VICTOR",10/01/17,SOTHER
BZCJHS,CHURCH DAVID S,11/10/17,CARONL
VZC2G1,*** NOT FOUND ***,,CARONL
BZDKKF,PLAARDRTE ALLY,11/13/17,CARONL
HZDFGH,*** NOT FOUND ***,,SOTHER
JZFPOI,LOPEZ KAREN N,11/10/17,CARONL
IZG0WZ,"FOSHIL, RICHARD",11/13/17,CARONL
OZG3T2,CARLINE KECHUA,11/13/17,SOTHER
PZMMNB,"BARELTINE, DUANE",11/13/17,CARONL
PZNSWX,*** NOT FOUND ***,,CARONL
RZPF5V,SLIMMORE JACK,10/12/17,CARONL
</code>```

I'm trying to use program SORT to use INREC PARSE and BUILD but I cannot get it completly, especially to make a field variable instead of fix lenght and to change the name of the columns, which in any case I could concatenate later if necessary, not big deal (I would like to avoid using EasyTrieve since I'm not that familiar with it).
Does anybody have any example of this? I looked for similar cases using SORT and I couldn't find any. I can create the report but only with fixed columns, I cannot find the way to do it variable lenght

I'm sorry for the long text but I wanted to be clear as much as possible.
Thank you very much in advance!
Have a good day/night!

答:
If you are not worried about the header, you can use:

```<code>OPTION COPY
INREC IFTHEN=(WHEN=INIT,BUILD=(1,15,31,15,46,15,SQZ=(SHIFT=LEFT))),
      IFTHEN=(WHEN=INIT,FINDREP=(IN=C'~',OUT=C','))
</code>```

I assumed the LRECL to be 80 and also assumed that you need only 3 columns starting from columns 1, 31 and 46 with 15 bytes each.

.

Body:
hope you are OK. I have a problem and I need your help, if possible.

I'm working with Mainframe JCL and I have a dataset with records; each record has different fixed columns separated by "~" (We use that since in the column NAME the names are separated by commas). I need to convert that dataset in a CSV file format, so it needs to be:
1) separated by comma
2) with variable lenght instead of fix lenght
3) I don't need all of the columns, just 4 of them (and in different order from original)
4) the first colum must be different
5) If the name has a , (Ex: LAST NAME, NAME) use " "

This is an example of the input file:

ROLENAME~LID     ~NAME                  ~NONCNCL~ACCDATE ~SUSPEND
CARINQ  ~X       ~*** NOT FOUND ***     ~       ~        ~
CARONL  ~AZBLCH  ~*** NOT FOUND ***     ~       ~        ~
SOTHER  ~BZBWD4  ~SUAREZ, VICTOR        ~N      ~10/01/17~N
CARONL  ~BZCJHS  ~CHURCH DAVID S        ~N      ~11/10/17~N
CARONL  ~VZC2G1  ~*** NOT FOUND ***     ~       ~        ~
CARONL  ~BZDKKF  ~PLAARDRTE ALLY        ~N      ~11/13/17~N
SOTHER  ~HZDFGH  ~*** NOT FOUND ***     ~       ~        ~
CARONL  ~JZFPOI  ~LOPEZ KAREN N         ~N      ~11/10/17~N
CARONL  ~IZG0WZ  ~FOSHIL, RICHARD       ~N      ~11/13/17~N
SOTHER  ~OZG3T2  ~CARLINE KECHUA        ~N      ~11/13/17~N
CARONL  ~PZMMNB  ~BARELTINE, DUANE      ~N      ~11/13/17~N
CARONL  ~PZNSWX  ~*** NOT FOUND ***     ~       ~        ~
CARONL  ~RZPF5V  ~SLIMMORE JACK         ~N      ~10/12/17~N

This is an example of output file:

GMID,Name,Last Login Date,Role/Group
X,*** NOT FOUND ***,,CARINQ
AZBLCH,*** NOT FOUND ***,,CARONL
BZBWD4,"SUAREZ, VICTOR",10/01/17,SOTHER
BZCJHS,CHURCH DAVID S,11/10/17,CARONL
VZC2G1,*** NOT FOUND ***,,CARONL
BZDKKF,PLAARDRTE ALLY,11/13/17,CARONL
HZDFGH,*** NOT FOUND ***,,SOTHER
JZFPOI,LOPEZ KAREN N,11/10/17,CARONL
IZG0WZ,"FOSHIL, RICHARD",11/13/17,CARONL
OZG3T2,CARLINE KECHUA,11/13/17,SOTHER
PZMMNB,"BARELTINE, DUANE",11/13/17,CARONL
PZNSWX,*** NOT FOUND ***,,CARONL
RZPF5V,SLIMMORE JACK,10/12/17,CARONL

I'm trying to use program SORT to use INREC PARSE and BUILD but I cannot get it completly, especially to make a field variable instead of fix lenght and to change the name of the columns, which in any case I could concatenate later if necessary, not big deal (I would like to avoid using EasyTrieve since I'm not that familiar with it).
Does anybody have any example of this? I looked for similar cases using SORT and I couldn't find any. I can create the report but only with fixed columns, I cannot find the way to do it variable lenght

I'm sorry for the long text but I wanted to be clear as much as possible.
Thank you very much in advance!
Have a good day/night!

Body:
If you are not worried about the header, you can use:

OPTION COPY
INREC IFTHEN=(WHEN=INIT,BUILD=(1,15,31,15,46,15,SQZ=(SHIFT=LEFT))),
      IFTHEN=(WHEN=INIT,FINDREP=(IN=C'~',OUT=C','))

I assumed the LRECL to be 80 and also assumed that you need only 3 columns starting from columns 1, 31 and 46 with 15 bytes each.

.


问:
URL reload issue using "ionic serve"
Since I migrated my Ionic 2 project to Ionic 3, I seem to have an issue with ionic serve and rebuilding the project.

When I first build the project, everything works as expected. But I notice that the URL bar of the browser jumps to something like localhost:8100/#/home.page/tabs/t0/tab-0/feed.page. Before it never did that, it just showed localhost:8100 and nothing else.

My app logic is: There is a menu that changes the home.page part, and there is a tabbar within the home.page which navigates to the first tab feed.page.

Issue 1: Before the migration, I have never seen any URL changes when browsing in the application.

Issue 2: After working in my code, the Ionic CLI automatically rebuilds the code as usual. Then it should in fact show the same page as before, but it doesn't. The parent menu of home.page is suddenly hidden and only the feed.page with its content is shown. Everything outside the feed page is gone.

Why is that happening and what I can I do about it? It is probably just a configuration, but I cannot find out where.

答:
After hours of investigation, I have finally found the issue.

Scenario 1:

If you load localhost:8100/ in the browser, the application gets launched as expected.

Scenario 2:

If you load localhost:8100/#/home.page/tabs/t0/tab-0/feed.page, then all involved and lazy loaded pages were actually loaded twice and finally "killing" off the menu.

What I do know now:

I manually used this.nav.setRoot(HomePage) in my app's constructor

This made all constructors load twice instead of once

This was the reason for my issues with the menu

What I do not know:

Why does the menu get killed if the page constructors get called twice?

Why and how is the HomePageconstructor called based on the URL?

Here is a workaround:

Using this in the constructor of my app, the HomePage does not get constructed a second time if it already has been constructed:

```<code>if (this.nav.getActive() instanceof ViewController === false || this.nav.getActive().name !== "HomePage") {
    this.nav.setRoot("HomePage");
}
</code>```

Title: URL reload issue using "ionic serve"

Body:
After hours of investigation, I have finally found the issue.

Scenario 1:

If you load localhost:8100/ in the browser, the application gets launched as expected.

Scenario 2:

If you load localhost:8100/#/home.page/tabs/t0/tab-0/feed.page, then all involved and lazy loaded pages were actually loaded twice and finally "killing" off the menu.

What I do know now:

I manually used this.nav.setRoot(HomePage) in my app's constructor

This made all constructors load twice instead of once

This was the reason for my issues with the menu

What I do not know:

Why does the menu get killed if the page constructors get called twice?

Why and how is the HomePageconstructor called based on the URL?

Here is a workaround:

Using this in the constructor of my app, the HomePage does not get constructed a second time if it already has been constructed:

if (this.nav.getActive() instanceof ViewController === false || this.nav.getActive().name !== "HomePage") {
    this.nav.setRoot("HomePage");
}


问:
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
The following code:

```<code>Class.forName("com.mysql.jdbc.Driver");
Connection m_connection = DriverManager.getConnection("jdbc:mysql://localhost","root","root");
</code>```

Throws this exception on getConnection():

```<code>java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Database.<init>(Database.java:91)
    at db.Main.main(Main.java:10)
</code>```

How is this caused and how can I solve it?

EDIT:

```<code>    public static void main(String[] args) throws ClassNotFoundException, ServletException, SQLException
    {

        try
        {
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
            Statement   s = (Statement) conn.createStatement();
            int result = s.executeUpdate("CREATE DATABASE databasename");
        }

        catch ( Exception e)
        {
            e.printStackTrace();
        }
}
</code>```

Produces :

```<code>java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Main.main(Main.java:19)
</code>```

答: I had to change my SQL setup (in my host, Dreamhost in my case) to allow the username to access the database from other hosts, not just Dreamhost since I'm running a program from the IDE on my computer. I did that for now by adding % to the list of Allowable Hosts. It now works! </p>

Body:
The following code:

Class.forName("com.mysql.jdbc.Driver");
Connection m_connection = DriverManager.getConnection("jdbc:mysql://localhost","root","root");

Throws this exception on getConnection():

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Database.<init>(Database.java:91)
    at db.Main.main(Main.java:10)

How is this caused and how can I solve it?

EDIT:

    public static void main(String[] args) throws ClassNotFoundException, ServletException, SQLException
    {

        try
        {
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
            Statement   s = (Statement) conn.createStatement();
            int result = s.executeUpdate("CREATE DATABASE databasename");
        }

        catch ( Exception e)
        {
            e.printStackTrace();
        }
}

Produces :

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Main.main(Main.java:19)


问:
Cannot read property 'ref' of undefined
I'm building a simple web app with Vue + Firebase + Vuefire and I get "Uncaught TypeError: Cannot read property 'ref' of undefined" when I try to use my Firebase db variable inside a component.

In main.js

```<code>Vue.use(VueFire)

const firebaseApp = Firebase.initializeApp({ //setting })

// Export the database for components to use.
export const db = firebaseApp.database()
</code>```

And in my component

```<code>// in Recipes.vue
import {db} from '../main.js'

export default {
  recipe: {
    source: db.ref('recipes')
    // Console says: "Uncaught TypeError: Cannot read property 'ref' of undefined"
  }
}
</code>```

I followed the steps in this tutorial https://alligator.io/vuejs/vuefire-firebase/

This code db.ref('recipes') works if used inside main.js, but it never works once I import it inside my component.

答:
The problem was my Firebase code (including db variable) was inside main.js but it needed to be in it's own component. I created a firebase.js file :

```<code>import Firebase from 'firebase'

const firebaseApp = Firebase.initializeApp({
  # configuration
})

// Export the database for components to use.
export const db = firebaseApp.database()
</code>```

Then in my component I simply imported my database variable :

```<code>import {db} from '../firebase'
</code>```

Why didn't it work inside main.js? I'm not sure, maybe someone more knowledgeable can answer that.

Title: Cannot read property 'ref' of undefined

Body:
I'm building a simple web app with Vue + Firebase + Vuefire and I get "Uncaught TypeError: Cannot read property 'ref' of undefined" when I try to use my Firebase db variable inside a component.

In main.js

Vue.use(VueFire)

const firebaseApp = Firebase.initializeApp({ //setting })

// Export the database for components to use.
export const db = firebaseApp.database()

And in my component

// in Recipes.vue
import {db} from '../main.js'

export default {
  recipe: {
    source: db.ref('recipes')
    // Console says: "Uncaught TypeError: Cannot read property 'ref' of undefined"
  }
}

I followed the steps in this tutorial https://alligator.io/vuejs/vuefire-firebase/

This code db.ref('recipes') works if used inside main.js, but it never works once I import it inside my component.

Body:
The problem was my Firebase code (including db variable) was inside main.js but it needed to be in it's own component. I created a firebase.js file :

import Firebase from 'firebase'

const firebaseApp = Firebase.initializeApp({
  # configuration
})

// Export the database for components to use.
export const db = firebaseApp.database()

Then in my component I simply imported my database variable :

import {db} from '../firebase'

Why didn't it work inside main.js? I'm not sure, maybe someone more knowledgeable can answer that.


问:
Trying to parse XML file with
 tags
I have been trying to parse the contents of an XML file using PowerShell and have I have made some decent progress, but I ran into something I cant find an answer to. I hope someone can point me in the right direction or help me understand how to get the value of some content in my XML which is contained within some P tags. Here is an example of my XML file;

<?xml version="1.0"?>
<HVD version="2.0">
<Environment>

10

258

</Environment>
</HVD>
```

<p>I can get the Name label in <code><Environment></code> to show up by using the following, but I cannot figure out how to get the values from the <code><p></code> tags themselves;</p>

<pre class="lang-bsh prettyprint-override"><code>[xml]$xml = Get-Content myFile.xml;
$xml.HVD.Environment;
</code>```

Can anyone help out a beginner here?

答: The text between the tags (10 and 258) is thr innerText of the p tags. So you'll need to get the first/second element of the Environment tag and read it's innerText.</p>

Title: Trying to parse XML file with <p> tags

Body:
I have been trying to parse the contents of an XML file using PowerShell and have I have made some decent progress, but I ran into something I cant find an answer to. I hope someone can point me in the right direction or help me understand how to get the value of some content in my XML which is contained within some P tags. Here is an example of my XML file;

<?xml version="1.0"?>
<HVD version="2.0">
<Environment>

10

258

</Environment>
</HVD>

I can get the Name label in <Environment> to show up by using the following, but I cannot figure out how to get the values from the
 tags themselves;

[xml]$xml = Get-Content myFile.xml;
$xml.HVD.Environment;

Can anyone help out a beginner here?


问:
Hide 'div' after specific amount of time
I have a div, which is generally used for showing some status messsage like "you have selected some xyz thing"

Now, I need to hide it at interval of specific amount of time (say, 60 secs) after page loads.

Code:

```<code> <div id="msg">You have selected 'Time and Money' magazine</div>
</code>```

How can I perform the above mentioned thing?

Thanks

答: You can use jQuery's 1.4 delay function</p>

Body:
I have a div, which is generally used for showing some status messsage like "you have selected some xyz thing"

Now, I need to hide it at interval of specific amount of time (say, 60 secs) after page loads.

Code:

You have selected 'Time and Money' magazine

How can I perform the above mentioned thing?

Thanks

Body: You can use jQuery's 1.4 delay function


问:
How to prevent random queries from being matched to an action annotated with [Route('')]?
I currently have this controller

```<code>[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}
</code>```

I want only the following 3 urls to be matched:

api/Home (Both id and AnotherId are null)

api/Home?id=1 (Only Anotherid is null)

api/Home?AnotherId=1 (Only Id is null)

Other urls should return unregistered routes or error. Currently, api/Home?asdfanyquery also returns a match which is not what I desired.

How do I rewrite the controller so that the routes only matches to the 3 urls above?

答:
The condition you said api/Home?asdfanyquery will fall into default Route. That is id and anotherid as null.
Try the below one

```<code>[RoutePrefix("api/Home")]
    public class HomeController : ApiController
    {
        [HttpGet]
        [Route("{id=id}/{AnotherId=AnotherId}")]
        public bool GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null)
        {

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

api/Home?asdfanyquery or api/Home - Both id and AnotherId are null)

api/Home?id=1 (Only Anotherid is null)

api/Home?AnotherId=1 (Only Id is null)

Body:
I currently have this controller

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}

I want only the following 3 urls to be matched:

api/Home (Both id and AnotherId are null)

api/Home?id=1 (Only Anotherid is null)

api/Home?AnotherId=1 (Only Id is null)

Other urls should return unregistered routes or error. Currently, api/Home?asdfanyquery also returns a match which is not what I desired.

How do I rewrite the controller so that the routes only matches to the 3 urls above?

Body:
The condition you said api/Home?asdfanyquery will fall into default Route. That is id and anotherid as null.
Try the below one

[RoutePrefix("api/Home")]
    public class HomeController : ApiController
    {
        [HttpGet]
        [Route("{id=id}/{AnotherId=AnotherId}")]
        public bool GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null)
        {

            return true;
        }
    }

api/Home?asdfanyquery or api/Home - Both id and AnotherId are null)

api/Home?id=1 (Only Anotherid is null)

api/Home?AnotherId=1 (Only Id is null)


问:
How does Spark SQL read compressed csv files?
I have tried with api spark.read.csv to read compressed csv file with extension bz or gzip. It worked. But in source code I don't find any option parameter that we can declare the codec type.

Even in this link, there is only setting for codec in writing side. Could anyone tell me or give the path to source code that showing how spark 2.x version deal with the compressed csv file.

答:
You dont have to do anything special for the gz compressed csv,tsv file to get read by spark 2.x version. The below code is tried with spark 2.0.2

```<code>val options= Map("sep" -> ",")
val csvRDD = spark.read.options(options).csv("file.csv.gz")
</code>```

I have done similarly for tab separated gz files

```<code>val options= Map("sep" -> "\t")
val csvRDD = spark.read.options(options).csv("file.tsv.gz")
</code>```

Also you can specify the folder to read mulitple .gz file with combination of unzipped files

```<code> val csvRDD = spark.read.options(options).csv("/users/mithun/tsvfilelocation/")
</code>```

Body:
You dont have to do anything special for the gz compressed csv,tsv file to get read by spark 2.x version. The below code is tried with spark 2.0.2

val options= Map("sep" -> ",")
val csvRDD = spark.read.options(options).csv("file.csv.gz")

I have done similarly for tab separated gz files

val options= Map("sep" -> "\t")
val csvRDD = spark.read.options(options).csv("file.tsv.gz")

Also you can specify the folder to read mulitple .gz file with combination of unzipped files

 val csvRDD = spark.read.options(options).csv("/users/mithun/tsvfilelocation/")


问:
top bar overlapping in unsafe area
my top bar works fine in all other iPhones except iPhoneX due to safe area introduction.The top bar starts in unsafe area itself.The top bar is a custom UI.It looks as below:

The code is as follows:

```<code>    //Top Bar
    let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
    topBar.backgroundColor = UIColor.white
    topBar.layer.shadowColor = UIColor.gray.cgColor
    topBar.layer.shadowOffset = CGSize(width: 0, height: 3)
    topBar.layer.shadowOpacity = 1
    topBar.layer.masksToBounds = false
    topBar.layer.shadowRadius = 8.0;

    self.view.addSubview(topBar)
</code>```

How do I fix this.I want view to start from safe area.And I don't want to use UINavigationBar.Thanks.

答:
And I don't want to use UINavigationBar

It doesn't matter what you want. You need to anyway. You have violated the interface guidelines and now you're in trouble because of it. Do what Apple wants you to do. UINavigationBar has the ability to stretch automatically up behind the "notch" when it is configured correctly. The same for UIToolbar at the bottom. You need to use these.

Title: top bar overlapping in unsafe area

Body:
my top bar works fine in all other iPhones except iPhoneX due to safe area introduction.The top bar starts in unsafe area itself.The top bar is a custom UI.It looks as below:

The code is as follows:

    //Top Bar
    let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
    topBar.backgroundColor = UIColor.white
    topBar.layer.shadowColor = UIColor.gray.cgColor
    topBar.layer.shadowOffset = CGSize(width: 0, height: 3)
    topBar.layer.shadowOpacity = 1
    topBar.layer.masksToBounds = false
    topBar.layer.shadowRadius = 8.0;

    self.view.addSubview(topBar)

How do I fix this.I want view to start from safe area.And I don't want to use UINavigationBar.Thanks.


答:
you can use setTimeout this - </p>

```<code>$('document').ready(function(){
  window.setTimeout('test()',time in milliseconds);
});

function test(){

  $('#divid').hide();

}
</code>```

Title: Hide 'div' after specific amount of time

Body:
you can use setTimeout this -

$('document').ready(function(){
  window.setTimeout('test()',time in milliseconds);
});

function test(){

  $('#divid').hide();

}


问:
What are the packages in a setup.py?
I was reading this article, and it had this code:

```<code>from distutils.core import setup

setup(name='Distutils',
      version='1.0',
      description='Python Distribution Utilities',
      author='Greg Ward',
      author_email='gward@python.net',
      url='https://www.python.org/sigs/distutils-sig/',
      packages=['distutils', 'distutils.command'],
     )
</code>```

And I am wondering what the packages are. Are they folders/directories? or a type of file? or it it a zip or py file?

Any help will be appreciated.

答:
Straight from your own link.

(Relevant section)

The packages option tells the Distutils to process (build, distribute, install, etc.) all pure Python modules found in each package mentioned in the packages list.

...

Thus, when you say packages = ['foo'] in your setup script, you are promising that the Distutils will find a file foo/__init__.py

Title: What are the packages in a setup.py?

Body:
I was reading this article, and it had this code:

from distutils.core import setup

setup(name='Distutils',
      version='1.0',
      description='Python Distribution Utilities',
      author='Greg Ward',
      author_email='gward@python.net',
      url='https://www.python.org/sigs/distutils-sig/',
      packages=['distutils', 'distutils.command'],
     )

And I am wondering what the packages are. Are they folders/directories? or a type of file? or it it a zip or py file?

Any help will be appreciated.


问:
'struct std::string' has no member named 'c_string'
I am receiving the error message 'struct std::string' has no member named 'c_string' in my code.  I am basing the structure of this code off of a code in my textbook that successfully wrote a code with my compiler.  What syntax errors could be causing this particular error?  (it's on line 11)

```<code>#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
    string payroll = "table.dat";
    ofstream MyCout;
    MyCout.open(payroll.c_string());

        if (MyCout.fail())
       {
        cout<<"Your file was not found";
        exit(1);
       }
        MyCout<<setiosflags(ios::fixed)
              <<setiosflags(ios::showpoint)
              <<setprecision(2);
        MyCout << "B Caldwell    555-88-2222"<<17.32<<37<<endl
               << "Next Line"<<0.00<<00<<endl;
               << "Next Line"<<0.00<<00<<endl;
        MyCout.close();
        cout<<"The file "<<payroll<<" has been successfully written"<<endl;
       system ("Pause");
       return 0;
       }
</code>```

I'm not sure if this helps or not, but here is the code that I am basing it off of

```<code>#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
    string filename = "prices.dat";
    ofstream outFile;
    outFile.open(filename.c_str());

 if (outFile.fail())
    {
      cout << "The file was not successfully opened" << endl;
      exit(1);
     }
outFile << setiosflags(ios::fixed)
        << setiosflags(ios::showpoint)
        << setprecision(2);

outFile << "Mats " << 39.95 << endl
        << "Bulbs " << 3.22 << endl
        << "Fuses " << 1.08 << endl;
outFile.close();
  cout << "The file " << filename << " has been successfully written."<<endl;
  return 0;
}
</code>```

答:
std::string has no function or member called c_string, hence the exact compiler error. You can find plenty of information online about what members and functions are available to call on standard library objects, for instance here.

If you look closer at the code you're referencing, you'll see you meant to use c_str() instead.

Their code:

```<code>ofstream outFile;
outFile.open(filename.c_str());
</code>```

Your code:

```<code>ofstream MyCout;
MyCout.open(payroll.c_string());
</code>```

The solution:

```<code>ofstream MyCout;
MyCout.open(payroll.c_str());
</code>```

Body:
I am receiving the error message 'struct std::string' has no member named 'c_string' in my code.  I am basing the structure of this code off of a code in my textbook that successfully wrote a code with my compiler.  What syntax errors could be causing this particular error?  (it's on line 11)

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
    string payroll = "table.dat";
    ofstream MyCout;
    MyCout.open(payroll.c_string());

        if (MyCout.fail())
       {
        cout<<"Your file was not found";
        exit(1);
       }
        MyCout<<setiosflags(ios::fixed)
              <<setiosflags(ios::showpoint)
              <<setprecision(2);
        MyCout << "B Caldwell    555-88-2222"<<17.32<<37<<endl
               << "Next Line"<<0.00<<00<<endl;
               << "Next Line"<<0.00<<00<<endl;
        MyCout.close();
        cout<<"The file "<<payroll<<" has been successfully written"<<endl;
       system ("Pause");
       return 0;
       }

I'm not sure if this helps or not, but here is the code that I am basing it off of

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
    string filename = "prices.dat";
    ofstream outFile;
    outFile.open(filename.c_str());

 if (outFile.fail())
    {
      cout << "The file was not successfully opened" << endl;
      exit(1);
     }
outFile << setiosflags(ios::fixed)
        << setiosflags(ios::showpoint)
        << setprecision(2);

outFile << "Mats " << 39.95 << endl
        << "Bulbs " << 3.22 << endl
        << "Fuses " << 1.08 << endl;
outFile.close();
  cout << "The file " << filename << " has been successfully written."<<endl;
  return 0;
}

Body:
std::string has no function or member called c_string, hence the exact compiler error. You can find plenty of information online about what members and functions are available to call on standard library objects, for instance here.

If you look closer at the code you're referencing, you'll see you meant to use c_str() instead.

Their code:

ofstream outFile;
outFile.open(filename.c_str());

Your code:

ofstream MyCout;
MyCout.open(payroll.c_string());

The solution:

ofstream MyCout;
MyCout.open(payroll.c_str());


问:
Best way to access pixels of an image in JavaScript to do Image Processing?
I am trying to perform simple operations on image using javascript. To get the pixels of the image, I am drawing the image on canvas and then get the ImageData from canvas. But for large images, drawing them on the canvas takes a lot of time.

Is there any other way of getting the image pixels without using the canvas element?

答:
The example below uses MarvinJ. It takes a colored image having 2800x2053 resolution, iterate through each pixel calculating the gray value and setting it back. Above the canvas there is a div to print the processing time. On my machine, it took 115ms including image loading.

var time = new Date().getTime();

var canvas = document.getElementById("canvas");
image = new MarvinImage();
image.load("https://i.imgur.com/iuGXHFj.jpg", imageLoaded);

function imageLoaded(){

  for(var y=0; y<image.getHeight(); y++){
    for(var x=0; x<image.getWidth(); x++){
       var r = image.getIntComponent0(x,y);
       var g = image.getIntComponent1(x,y);
       var b = image.getIntComponent2(x,y);

       var gray = Math.floor(r * 0.21 + g * 0.72 + b * 0.07);

       image.setIntColor(x,y,255,gray,gray,gray);
     }
   }
   image.draw(canvas);

   $("#time").html("Processing time: "+(new Date().getTime()-time)+"ms");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<div id="time"></div>
<canvas id="canvas" width="2800" height="2053"></canvas></code>```

Body:
The example below uses MarvinJ. It takes a colored image having 2800x2053 resolution, iterate through each pixel calculating the gray value and setting it back. Above the canvas there is a div to print the processing time. On my machine, it took 115ms including image loading.

var time = new Date().getTime();

var canvas = document.getElementById("canvas");
image = new MarvinImage();
image.load("https://i.imgur.com/iuGXHFj.jpg", imageLoaded);

function imageLoaded(){

  for(var y=0; y<image.getHeight(); y++){
    for(var x=0; x<image.getWidth(); x++){
       var r = image.getIntComponent0(x,y);
       var g = image.getIntComponent1(x,y);
       var b = image.getIntComponent2(x,y);

       var gray = Math.floor(r * 0.21 + g * 0.72 + b * 0.07);

       image.setIntColor(x,y,255,gray,gray,gray);
     }
   }
   image.draw(canvas);

   $("#time").html("Processing time: "+(new Date().getTime()-time)+"ms");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<div id="time"></div>
<canvas id="canvas" width="2800" height="2053"></canvas>


问:
TensorFlow: No allowing GPU memory growth option in contrib.learn. Estimator
When creating estimator using contrib.learn, only GPU option that I can find is "gpu_memory_fraction" which can be found at "tf.contrib.learn.RunConfig"

```<code>classifier = learn.Estimator(
     model_fn=cnn_model_fn,
     config=learn.RunConfig(
           gpu_memory_fraction=0.9
           )
     )
</code>```

Is there a way to allow GPU memory growth option when using contrib.learn ?

答:
```<code>config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 0.9
run_config = tf.contrib.learn.RunConfig(session_config=config)
</code>```

Pass above config to Estimator's session_config

Body:
When creating estimator using contrib.learn, only GPU option that I can find is "gpu_memory_fraction" which can be found at "tf.contrib.learn.RunConfig"

classifier = learn.Estimator(
     model_fn=cnn_model_fn,
     config=learn.RunConfig(
           gpu_memory_fraction=0.9
           )
     )

Is there a way to allow GPU memory growth option when using contrib.learn ?

Body:
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 0.9
run_config = tf.contrib.learn.RunConfig(session_config=config)

Pass above config to Estimator's session_config


问:
Check C++ shared dependencies at runtime (ldd on self)
Is there a way to check or access the names of the libraries a C++ binary  is dynamically linked to within the binary itself?

Essentially I want to run ldd on a binary, without running ldd.

The use case is using dlopen from dlfcn.h. I have a C++ library which is linked to libpython, but I don't know if its libpython3.5m.so, libpython3.4m.so, libpython2.7.so, etc...

I want to call

```<code>void* handle = dlopen( "@PYTHON_LIBRARY@", RTLD_LAZY | RTLD_GLOBAL );
</code>```

where "@PYTHON_LIBRARY@" resolves to the path to whatever the current libpython the module is currently dynamically linked to.

Is there any way to do this?

答: On Linux, you can read /proc/self/maps or /proc/self/map_files, but this is not portable to other platforms.

Body:
Is there a way to check or access the names of the libraries a C++ binary  is dynamically linked to within the binary itself?

Essentially I want to run ldd on a binary, without running ldd.

The use case is using dlopen from dlfcn.h. I have a C++ library which is linked to libpython, but I don't know if its libpython3.5m.so, libpython3.4m.so, libpython2.7.so, etc...

I want to call

void* handle = dlopen( "@PYTHON_LIBRARY@", RTLD_LAZY | RTLD_GLOBAL );

where "@PYTHON_LIBRARY@" resolves to the path to whatever the current libpython the module is currently dynamically linked to.

Is there any way to do this?


问:
SQL Query to select from multiple nested subqueries
I am having a bit of trouble with this SQL query and I can't wrap my head around it. I have a site where users which have a moderator-like role can make changes to the user's account type below them, now I do have a working changelog, but I have problems displaying the correct information. I have these three tables:

Roles: Role_ID, Role_Type

Users: User_ID, Firstname, Lastname, Role_ID

Changelogs: Log_ID, Moderator_ID, User_ID, Prev_Role_ID, New_Role_ID, Logtime

To explain, the changelogs have a unique Log_ID, and then the Moderator_ID is the User_ID of the person making changes, User_ID is then the ID of user's account that hs been changed. And the Role_ID's are just what it was to what is has changed to.

So I want to display the Log ID, the first name and last name of the moderator, the first name and last name of the user, and the previous role as well as new role.

I am using nested selects, but I think my problem is with the joining of tables, because everything displays fine, except I have a LOT of records, and when I group by Log_ID at then end, it just ends up showing my records but with the incorrect changes to roles. It returns all the combinations, so I think I need a few JOINS but I am not sure what or where to put them.

```<code>SELECT changelogs.log_id, a.lastname AS mlastname, a.firstname AS mfirstname,
b.lastname AS ulastname, b.firstname AS ufirstname, c.role_type AS
pre_role, d.role_type AS new_role, changelogs.logtime

FROM (SELECT log_id, lastname, firstname FROM users, changelogs
      WHERE users.user_id = changelogs.mod_id) a,

     (SELECT log_id, lastname, firstname FROM users, changelogs
      WHERE users.user_id = changelogs.user_id) b,

     (SELECT log_id, role_type FROM roles, changelogs
      WHERE changelogs.prev_role_id = roles.role_id) c,

     (SELECT log_id, role_type FROM roles, changelogs
      WHERE roles.role_id = changelogs.role_id) d, changelogs;
</code>```

I basically just want to view my Changelogs table exactly as it is, just with the names in the place of their ID's and the roles in the place of their ID's.

RESULT: Log_ID, mLastname, mFirstname, uLastname, uFirstname, Pre_Role, New_Role, Time

Sorry for this silly question but it has been bugging me for quite a while.

答:
Give each joined table a meaningful alias (don't use a sequence a,b,c,d...) and you don't need subqueries here:

```<code>SELECT
      c.log_id
    , m.lastname  AS mlastname
    , m.firstname AS mfirstname
    , u.lastname  AS ulastname
    , u.firstname AS ufirstname
    , p.role_type AS pre_role
    , r.role_type AS new_role
    , c.logtime
FROM changelogs c
INNER JOIN users u ON c.user_id = u.user_id
INNER JOIN users m ON c.mod_id = m.user_id
INNER JOIN roles r ON c.role_id = r.role_id
INNER JOIN roles p ON c.prev_role_id = p.role_id
</code>```

tip any time you find yourself typing a comma after a table name, STOP. Remove the comma and think about you need to join this table. You will be using good explicit joins in no time.

Body:
I am having a bit of trouble with this SQL query and I can't wrap my head around it. I have a site where users which have a moderator-like role can make changes to the user's account type below them, now I do have a working changelog, but I have problems displaying the correct information. I have these three tables:

Roles: Role_ID, Role_Type

Users: User_ID, Firstname, Lastname, Role_ID

Changelogs: Log_ID, Moderator_ID, User_ID, Prev_Role_ID, New_Role_ID, Logtime

To explain, the changelogs have a unique Log_ID, and then the Moderator_ID is the User_ID of the person making changes, User_ID is then the ID of user's account that hs been changed. And the Role_ID's are just what it was to what is has changed to.

So I want to display the Log ID, the first name and last name of the moderator, the first name and last name of the user, and the previous role as well as new role.

I am using nested selects, but I think my problem is with the joining of tables, because everything displays fine, except I have a LOT of records, and when I group by Log_ID at then end, it just ends up showing my records but with the incorrect changes to roles. It returns all the combinations, so I think I need a few JOINS but I am not sure what or where to put them.

SELECT changelogs.log_id, a.lastname AS mlastname, a.firstname AS mfirstname,
b.lastname AS ulastname, b.firstname AS ufirstname, c.role_type AS
pre_role, d.role_type AS new_role, changelogs.logtime

FROM (SELECT log_id, lastname, firstname FROM users, changelogs
      WHERE users.user_id = changelogs.mod_id) a,

     (SELECT log_id, lastname, firstname FROM users, changelogs
      WHERE users.user_id = changelogs.user_id) b,

     (SELECT log_id, role_type FROM roles, changelogs
      WHERE changelogs.prev_role_id = roles.role_id) c,

     (SELECT log_id, role_type FROM roles, changelogs
      WHERE roles.role_id = changelogs.role_id) d, changelogs;

I basically just want to view my Changelogs table exactly as it is, just with the names in the place of their ID's and the roles in the place of their ID's.

RESULT: Log_ID, mLastname, mFirstname, uLastname, uFirstname, Pre_Role, New_Role, Time

Sorry for this silly question but it has been bugging me for quite a while.

Body:
Give each joined table a meaningful alias (don't use a sequence a,b,c,d...) and you don't need subqueries here:

SELECT
      c.log_id
    , m.lastname  AS mlastname
    , m.firstname AS mfirstname
    , u.lastname  AS ulastname
    , u.firstname AS ufirstname
    , p.role_type AS pre_role
    , r.role_type AS new_role
    , c.logtime
FROM changelogs c
INNER JOIN users u ON c.user_id = u.user_id
INNER JOIN users m ON c.mod_id = m.user_id
INNER JOIN roles r ON c.role_id = r.role_id
INNER JOIN roles p ON c.prev_role_id = p.role_id

tip any time you find yourself typing a comma after a table name, STOP. Remove the comma and think about you need to join this table. You will be using good explicit joins in no time.


问:
Tap on UISlider to Set the Value
I created a Slider (operating as control of the video, like YouTube has at the bottom) and set the maximum (duration) and minimum values. And then used SeekToTime to change the currentTime. Now, the user can slide the thumb of the slider to change the value

What I want to achieve is letting the user tap on anywhere on the slider and set the current time of the video.

I got an approach from this answer, and I tried to apply it to my case, but couldn't make it work

```<code>class ViewController: UIViewController, PlayerDelegate {

var slider: UISlider!

override func viewDidLoad() {
  super.viewDidLoad()

  // Setup the slider
}

func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
  //  print("A")

  let pointTapped: CGPoint = gestureRecognizer.locationInView(self.view)

  let positionOfSlider: CGPoint = slider.frame.origin
  let widthOfSlider: CGFloat = slider.frame.size.width
  let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)

  slider.setValue(Float(newValue), animated: true)
 }
}
</code>```

I thought this should work, but no luck. Then I tried debugging with trying to printing "A" to logs, but it doesn't so apparently it doesn't go into the sliderTapped() function.

What am I doing wrong? Or is there a better way to achieve what I am trying to achieve?

答:
This is my code, based on "myuiviews" answer.

I fixed 2 little "bugs" of the original code.

1 - Tapping on 0 was too difficult, so I made it easier

 2 - Sliding the slider's thumb just a little bit was also firing the "tapGestureRecognizer", which makes it return to the initial position, so I added a minimum distance filter to avoid that.

Swift 4

```<code>class ViewController: UIViewController {

    var slider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Setup the slider

        // Add a gesture recognizer to the slider
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped(gestureRecognizer:)))
        self.slider.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
        //  print("A")

        var pointTapped: CGPoint = gestureRecognizer.location(in: self.view)
        pointTapped.x -= 30  //Subtract left constraint (distance of the slider's origin from "self.view"

        let positionOfSlider: CGPoint = slider.frame.origin
        let widthOfSlider: CGFloat = slider.frame.size.width

        //If tap is too near from the slider thumb, cancel
        let thumbPosition = CGFloat((slider.value / slider.maximumValue)) * widthOfSlider
        let dif = abs(pointTapped.x - thumbPosition)
        let minDistance: CGFloat = 51.0  //You can calibrate this value, but I think this is the maximum distance that tap is recognized
        if dif < minDistance {
            print("tap too near")
            return
        }

        var newValue: CGFloat
        if pointTapped.x < 10 {
            newValue = 0  //Easier to set slider to 0
        } else {
            newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)
        }

        slider.setValue(Float(newValue), animated: true)
    }
}
</code>```

Title: Tap on UISlider to Set the Value

Body:
I created a Slider (operating as control of the video, like YouTube has at the bottom) and set the maximum (duration) and minimum values. And then used SeekToTime to change the currentTime. Now, the user can slide the thumb of the slider to change the value

What I want to achieve is letting the user tap on anywhere on the slider and set the current time of the video.

I got an approach from this answer, and I tried to apply it to my case, but couldn't make it work

class ViewController: UIViewController, PlayerDelegate {

var slider: UISlider!

override func viewDidLoad() {
  super.viewDidLoad()

  // Setup the slider
}

func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
  //  print("A")

  let pointTapped: CGPoint = gestureRecognizer.locationInView(self.view)

  let positionOfSlider: CGPoint = slider.frame.origin
  let widthOfSlider: CGFloat = slider.frame.size.width
  let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)

  slider.setValue(Float(newValue), animated: true)
 }
}

I thought this should work, but no luck. Then I tried debugging with trying to printing "A" to logs, but it doesn't so apparently it doesn't go into the sliderTapped() function.

What am I doing wrong? Or is there a better way to achieve what I am trying to achieve?

Body:
This is my code, based on "myuiviews" answer.

I fixed 2 little "bugs" of the original code.

1 - Tapping on 0 was too difficult, so I made it easier

 2 - Sliding the slider's thumb just a little bit was also firing the "tapGestureRecognizer", which makes it return to the initial position, so I added a minimum distance filter to avoid that.

Swift 4

class ViewController: UIViewController {

    var slider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Setup the slider

        // Add a gesture recognizer to the slider
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped(gestureRecognizer:)))
        self.slider.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
        //  print("A")

        var pointTapped: CGPoint = gestureRecognizer.location(in: self.view)
        pointTapped.x -= 30  //Subtract left constraint (distance of the slider's origin from "self.view"

        let positionOfSlider: CGPoint = slider.frame.origin
        let widthOfSlider: CGFloat = slider.frame.size.width

        //If tap is too near from the slider thumb, cancel
        let thumbPosition = CGFloat((slider.value / slider.maximumValue)) * widthOfSlider
        let dif = abs(pointTapped.x - thumbPosition)
        let minDistance: CGFloat = 51.0  //You can calibrate this value, but I think this is the maximum distance that tap is recognized
        if dif < minDistance {
            print("tap too near")
            return
        }

        var newValue: CGFloat
        if pointTapped.x < 10 {
            newValue = 0  //Easier to set slider to 0
        } else {
            newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)
        }

        slider.setValue(Float(newValue), animated: true)
    }
}


问:
Compiler cannot handle std::invoke
What is the problem with this?

```<code>struct foo {
    void process(int, char, bool) {}
};

foo myfoo;

template <typename Method> struct thing {
    void doit() {
        Method m = Method{};
        (myfoo.*m)(5, 'a', true);
    }
};

int main() {
    thing<decltype(&foo::process)> t;
    t.doit();
}
</code>```

I think this isolates the problem.  What is the workaround if I have to use the type Method, as in the case of my original post below?

Original post:
In the following attempted test:

```<code>struct Foo { int play (char, bool) {return 3;} };
struct Bar { double jump (int, short, float) {return 5.8;} };
struct Baz { char run (double) {return 'b';} };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<decltype(&Foo::play), decltype(&Bar::jump), decltype(&Baz::run)> func;
    func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
}
</code>```

As you can predict, func is supposed to carry out

```<code>foo.play('c', true);  bar.jump(5, 2, 4.5);  baz.run(6.8);
</code>```

My implementation of the Functor class so far (ignoring perfect forwarding and such for now) is

```<code>template <typename... Members>
struct Functor {
    using m = many_members<Members...>;
    template <typename... Args>
    typename m::return_types operator()(Args... args) const { // perfect forwarding to do later
        auto t = std::make_tuple(args...);
        auto objects = utilities::tuple_head<sizeof...(Members)>(t);
        auto arguments = utilities::extract_subtuple<sizeof...(Members), sizeof...(Args) - sizeof...(Members)>(t);
        call(objects, arguments);  // Won't compile on GCC 7.2 or clang 6.0.
    }
private:
    template <typename Tuple1, typename Tuple2>
    auto call (Tuple1& objects, const Tuple2& args) const {
        std::invoke(typename utilities::nth_element<0, Members...>::type{}, std::get<0>(objects), 'c', true);
    }
};
</code>```

where my last line using std::invoke is just to test the concept before I continue.  It however will not compile on either GCC 7.2 or clang 6.0, so I cannot continue with the generalization.  Any workaround here, or a completely different implementation altogether?

Here is everything I have so far:

```<code>namespace utilities {
    template <std::size_t N, typename... Ts>
    struct nth_element : std::tuple_element<N, std::tuple<Ts...>> { };

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple&, std::enable_if_t<(Take == 0)>* = nullptr) {
        return std::tuple<>();
    }

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple& tuple, std::enable_if_t<(Take > 0)>* = nullptr) {
        return std::tuple_cat (std::make_tuple(std::get<Skip>(tuple)), extract_subtuple<Skip + 1, Take - 1>(tuple));
    }

    template <std::size_t N, typename Tuple>
    auto tuple_head (const Tuple& tuple) {
        return extract_subtuple<0, N>(tuple);
    }
}

template <typename Rs, typename Ts, typename ArgsPacks, typename AllArgs, typename... Members> struct many_members_h;

template <typename Rs, typename Ts, typename ArgsPacks, typename AllArgs>
struct many_members_h<Rs, Ts, ArgsPacks, AllArgs> {
    using return_types = Rs;
    using classes = Ts;
    using args_packs = ArgsPacks;
    using all_args = AllArgs;
};

template <typename... Rs, typename... Ts, typename... ArgsPacks, typename... AllArgs, typename R, typename T, typename... Args, typename... Rest>
struct many_members_h<std::tuple<Rs...>, std::tuple<Ts...>, std::tuple<ArgsPacks...>, std::tuple<AllArgs...>, R(T::*)(Args...), Rest...> :
    many_members_h<std::tuple<Rs..., R>, std::tuple<Ts..., T>, std::tuple<ArgsPacks..., std::tuple<Args...>>, std::tuple<AllArgs..., Args...>, Rest...> { };

template <typename... Members>
struct many_members : many_members_h<std::tuple<>, std::tuple<>, std::tuple<>, std::tuple<>, Members...> { };

template <typename... Members>
struct Functor {
    using m = many_members<Members...>;
    template <typename... Args>
    typename m::return_types operator()(Args... args) const { // perfect forwarding to do later
        auto t = std::make_tuple(args...);
        auto objects = utilities::tuple_head<sizeof...(Members)>(t);
        auto arguments = utilities::extract_subtuple<sizeof...(Members), sizeof...(Args) - sizeof...(Members)>(t);
        call(objects, arguments);  // Won't compile on GCC 7.2 or clang 6.0.
    }
private:
    template <typename Tuple1, typename Tuple2>
    auto call (Tuple1& objects, const Tuple2& args) const {
        std::invoke(typename utilities::nth_element<0, Members...>::type{}, std::get<0>(objects), 'c', true);
    }
};

// Testing
#include <iostream>

struct Foo { int play (char, bool) {return 3;} };
struct Bar { double jump (int, short, float) {return 5.8;} };
struct Baz { char run (double) {return 'b';} };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<decltype(&Foo::play), decltype(&Bar::jump), decltype(&Baz::run)> func;
    func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
}
</code>```

答:
Taking your smaller first example, note that decltype(&foo::process) is the type called void (foo::*)(int, char, bool).

This type does not contain or imply any association with the original function foo::process itself.  Just like the type int doesn't let you get the value of some particular int elsewhere in your program, or the type SomeClass doesn't let you refer to a SomeClass object elsewhere in your program, the type alone doesn't carry a value or identity.

The expression Method{} value-initializes this pointer to member type.  Which means the resulting value is a null pointer value.  Which means calling it is undefined behavior (and on many systems is likely to result in a segfault).

If you're using C++17 mode, you could use a template <auto Method> non-type parameter and simply pass &foo::process (without using decltype) as the template argument.  Some SFINAE techniques could enforce that the argument is actually a pointer to member function, and some helper traits could be used to get the class type and parameter list tuple.

Or if you're using a standard earlier than C++17, you'll have to either make the function pointer a function argument, or make it a template parameter which follows the type, as in template <typename MethodType, MethodType Method>, then call as thing<decltype(&foo::process), &foo::process>.

Title: Compiler cannot handle std::invoke

Body:
What is the problem with this?

struct foo {
    void process(int, char, bool) {}
};

foo myfoo;

template <typename Method> struct thing {
    void doit() {
        Method m = Method{};
        (myfoo.*m)(5, 'a', true);
    }
};

int main() {
    thing<decltype(&foo::process)> t;
    t.doit();
}

I think this isolates the problem.  What is the workaround if I have to use the type Method, as in the case of my original post below?

Original post:
In the following attempted test:

struct Foo { int play (char, bool) {return 3;} };
struct Bar { double jump (int, short, float) {return 5.8;} };
struct Baz { char run (double) {return 'b';} };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<decltype(&Foo::play), decltype(&Bar::jump), decltype(&Baz::run)> func;
    func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
}

As you can predict, func is supposed to carry out

foo.play('c', true);  bar.jump(5, 2, 4.5);  baz.run(6.8);

My implementation of the Functor class so far (ignoring perfect forwarding and such for now) is

template <typename... Members>
struct Functor {
    using m = many_members<Members...>;
    template <typename... Args>
    typename m::return_types operator()(Args... args) const { // perfect forwarding to do later
        auto t = std::make_tuple(args...);
        auto objects = utilities::tuple_head<sizeof...(Members)>(t);
        auto arguments = utilities::extract_subtuple<sizeof...(Members), sizeof...(Args) - sizeof...(Members)>(t);
        call(objects, arguments);  // Won't compile on GCC 7.2 or clang 6.0.
    }
private:
    template <typename Tuple1, typename Tuple2>
    auto call (Tuple1& objects, const Tuple2& args) const {
        std::invoke(typename utilities::nth_element<0, Members...>::type{}, std::get<0>(objects), 'c', true);
    }
};

where my last line using std::invoke is just to test the concept before I continue.  It however will not compile on either GCC 7.2 or clang 6.0, so I cannot continue with the generalization.  Any workaround here, or a completely different implementation altogether?

Here is everything I have so far:

namespace utilities {
    template <std::size_t N, typename... Ts>
    struct nth_element : std::tuple_element<N, std::tuple<Ts...>> { };

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple&, std::enable_if_t<(Take == 0)>* = nullptr) {
        return std::tuple<>();
    }

    template <std::size_t Skip, std::size_t Take, typename Tuple>
    auto extract_subtuple (const Tuple& tuple, std::enable_if_t<(Take > 0)>* = nullptr) {
        return std::tuple_cat (std::make_tuple(std::get<Skip>(tuple)), extract_subtuple<Skip + 1, Take - 1>(tuple));
    }

    template <std::size_t N, typename Tuple>
    auto tuple_head (const Tuple& tuple) {
        return extract_subtuple<0, N>(tuple);
    }
}

template <typename Rs, typename Ts, typename ArgsPacks, typename AllArgs, typename... Members> struct many_members_h;

template <typename Rs, typename Ts, typename ArgsPacks, typename AllArgs>
struct many_members_h<Rs, Ts, ArgsPacks, AllArgs> {
    using return_types = Rs;
    using classes = Ts;
    using args_packs = ArgsPacks;
    using all_args = AllArgs;
};

template <typename... Rs, typename... Ts, typename... ArgsPacks, typename... AllArgs, typename R, typename T, typename... Args, typename... Rest>
struct many_members_h<std::tuple<Rs...>, std::tuple<Ts...>, std::tuple<ArgsPacks...>, std::tuple<AllArgs...>, R(T::*)(Args...), Rest...> :
    many_members_h<std::tuple<Rs..., R>, std::tuple<Ts..., T>, std::tuple<ArgsPacks..., std::tuple<Args...>>, std::tuple<AllArgs..., Args...>, Rest...> { };

template <typename... Members>
struct many_members : many_members_h<std::tuple<>, std::tuple<>, std::tuple<>, std::tuple<>, Members...> { };

template <typename... Members>
struct Functor {
    using m = many_members<Members...>;
    template <typename... Args>
    typename m::return_types operator()(Args... args) const { // perfect forwarding to do later
        auto t = std::make_tuple(args...);
        auto objects = utilities::tuple_head<sizeof...(Members)>(t);
        auto arguments = utilities::extract_subtuple<sizeof...(Members), sizeof...(Args) - sizeof...(Members)>(t);
        call(objects, arguments);  // Won't compile on GCC 7.2 or clang 6.0.
    }
private:
    template <typename Tuple1, typename Tuple2>
    auto call (Tuple1& objects, const Tuple2& args) const {
        std::invoke(typename utilities::nth_element<0, Members...>::type{}, std::get<0>(objects), 'c', true);
    }
};

// Testing
#include <iostream>

struct Foo { int play (char, bool) {return 3;} };
struct Bar { double jump (int, short, float) {return 5.8;} };
struct Baz { char run (double) {return 'b';} };

int main() {
    Foo foo;  Bar bar;  Baz baz;
    Functor<decltype(&Foo::play), decltype(&Bar::jump), decltype(&Baz::run)> func;
    func(foo, bar, baz, 'c', true, 5, 2, 4.5, 6.8);
}


问:
Encrypt text in file with ruby and cipher
I need to make an encryptor and decryptor which reads a file with text and encrypts it and then generates a txt file with the encryption.
Then you must decrypt that same txt file
So far I managed to encrypt the text and put it in the file but I still can not decrypt the text that is inside this.
The encrypt work without the files

```<code>**The problem starts here**

#Decrypt
data = ''
File.open('text2.txt','r') do |archivo|
    while line = archivo.gets
       data += line
    end
end

encrypted = data

cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.decrypt
cipher.key = key
cipher.iv = iv

# and decrypt it
decrypted = cipher.update(encrypted)
decrypted << cipher.final
puts "decrypted: #{decrypted}\n"
</code>```

The error is : encrypt.rb:48:in final': wrong final block length (OpenSSL::Cipher::CipherError)
        from encrypt.rb:48:in'

答:
The issue is in the block where you write out the encryption to the file text2.txt. You're using archivo.puts, but you want to use archivo.write. puts will append a newline character at the end of each line, so you're writing encrypted + "\n" to the file. When you try to decrypt it, that extra newline character messes it up. If you use write, it just writes exactly what you give it without the extra character.

What you want to do instead:

```<code>File.open('text2.txt', 'w') do |archivo|
  archivo.write encrypted
end
</code>```

Or even better yet:

```<code>File.write('text2.txt', encrypted)
</code>```

Body:
I need to make an encryptor and decryptor which reads a file with text and encrypts it and then generates a txt file with the encryption.
Then you must decrypt that same txt file
So far I managed to encrypt the text and put it in the file but I still can not decrypt the text that is inside this.
The encrypt work without the files

**The problem starts here**

#Decrypt
data = ''
File.open('text2.txt','r') do |archivo|
    while line = archivo.gets
       data += line
    end
end

encrypted = data

cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.decrypt
cipher.key = key
cipher.iv = iv

# and decrypt it
decrypted = cipher.update(encrypted)
decrypted << cipher.final
puts "decrypted: #{decrypted}\n"

The error is : encrypt.rb:48:in final': wrong final block length (OpenSSL::Cipher::CipherError)
        from encrypt.rb:48:in'

Body:
The issue is in the block where you write out the encryption to the file text2.txt. You're using archivo.puts, but you want to use archivo.write. puts will append a newline character at the end of each line, so you're writing encrypted + "\n" to the file. When you try to decrypt it, that extra newline character messes it up. If you use write, it just writes exactly what you give it without the extra character.

What you want to do instead:

File.open('text2.txt', 'w') do |archivo|
  archivo.write encrypted
end

Or even better yet:

File.write('text2.txt', encrypted)


问:
Liferay: Which request used send param to two portlet same time?
I am use Liferay 6.2.

I want send parameter from portlet A to portlet B. But i want portlet B received that parameter too.

Usually use this but does not work:

This is code on portlet A.

PortletURL renderURL = PortletURLFactoryUtil.create(request, portletBName, themeDisplay.getPlid(), PortletRequest.RENDER_PHASE);

renderURL.setParameter("mvcPath", "/html/carinformation/view_2.jsp");
renderURL.setParameter("carId", car.getId());

Which method can use ? Example code if can , please.

Thanks.

答: Okay, i found out. Just need config a public parameter. On portlet A create PortletURL as above. And on portlet B you can received it normal.</p>


问:
Rails 4 - Using Transactions along with Begin rescue block
I have a piece of code which is used to do following things triggered from a controller call.I am using Rails Transaction along with begin/rescue end block to make the below series of code execution more robust.Its as shown below:

Save the object

save the associations and update the attribute value

send email

send text message

redirect

```<code>###in my controller
 def verify
    @request=Request.includes(:user).find(params[:id])
    @request.transaction do
      begin
        if @request.accepted?
           ##this method will call 3 more methods in the request model
           @request.send_email_and_sms
           flash[:success] = "Request is moved to another state"
        else
          flash[:error] = "Request was not accepted and couldn't be moved to another state"
        end
      rescue
        flash[:alert] = "There was some internal error.Kindly debug"
      ensure
        @request.reload
        Rails.logger.info "================Making GO AHEAD TOKEN FALSE AND DEACTIVATE VENUE====================#{@request.attributes}==========="
        redirect_to request_hall_path(@request.user)
      end
    end
  end
</code>```

`

Is this the correct way to ensure that every piece of code will execute else it will jump on rescue with the flash.alert message.

Is there any other way that I am missing to make this code/logic more fool proof and robust?

Thanks in advance.

答:
I don't think you need a transaction block here.  You will want to use a transaction when you have an 'all or none' requirement.  An example might be something like selling a product and creating an invoice; you wouldn't want to have the sequence fail in one of the steps and have an inconsistent database state (ie: not deduct from stock qty but add to sales).

Also, in your case as you know (from comments above) sending email and sms should be done via a job async so it doesn't block the current thread.

Anyway I would think something like this would be fine:

```<code> def verify
   @request = Request.includes(:user).find(params[:id])

   if @request && @request.accepted?
     ##this method will call 3 more methods in the request model
     @request.send_email_and_sms # send async
     flash[:success] = "Request is moved to another state"
   else
     flash[:error] = "Request was not accepted and couldn't be moved to another state"
   end

   redirect_to request_hall_path(@request.user)
end
</code>```

if your #send_email_and_sms has any db writes then you can probably use a job hook (ex: a delayed_job callback) to do the write so you know for sure the job has been completed successfully.  So register a callback so that when the email and sms has been successfully sent you can do like request.update(email_sent: true)

Hope that helps :)

Body:
I have a piece of code which is used to do following things triggered from a controller call.I am using Rails Transaction along with begin/rescue end block to make the below series of code execution more robust.Its as shown below:

Save the object

save the associations and update the attribute value

send email

send text message

redirect

###in my controller
 def verify
    @request=Request.includes(:user).find(params[:id])
    @request.transaction do
      begin
        if @request.accepted?
           ##this method will call 3 more methods in the request model
           @request.send_email_and_sms
           flash[:success] = "Request is moved to another state"
        else
          flash[:error] = "Request was not accepted and couldn't be moved to another state"
        end
      rescue
        flash[:alert] = "There was some internal error.Kindly debug"
      ensure
        @request.reload
        Rails.logger.info "================Making GO AHEAD TOKEN FALSE AND DEACTIVATE VENUE====================#{@request.attributes}==========="
        redirect_to request_hall_path(@request.user)
      end
    end
  end

`

Is this the correct way to ensure that every piece of code will execute else it will jump on rescue with the flash.alert message.

Is there any other way that I am missing to make this code/logic more fool proof and robust?

Thanks in advance.

Body:
I don't think you need a transaction block here.  You will want to use a transaction when you have an 'all or none' requirement.  An example might be something like selling a product and creating an invoice; you wouldn't want to have the sequence fail in one of the steps and have an inconsistent database state (ie: not deduct from stock qty but add to sales).

Also, in your case as you know (from comments above) sending email and sms should be done via a job async so it doesn't block the current thread.

Anyway I would think something like this would be fine:

 def verify
   @request = Request.includes(:user).find(params[:id])

   if @request && @request.accepted?
     ##this method will call 3 more methods in the request model
     @request.send_email_and_sms # send async
     flash[:success] = "Request is moved to another state"
   else
     flash[:error] = "Request was not accepted and couldn't be moved to another state"
   end

   redirect_to request_hall_path(@request.user)
end

if your #send_email_and_sms has any db writes then you can probably use a job hook (ex: a delayed_job callback) to do the write so you know for sure the job has been completed successfully.  So register a callback so that when the email and sms has been successfully sent you can do like request.update(email_sent: true)

Hope that helps :)