问:
MATLAB automatically assigns unwanted dimensions to a dynamically updated cell array
I want to generate a 3D cell array called timeData so that timeData(:,:,a) for some integer a is an nx1 matrix of data, and the number of rows n varies with the value of a in a 1:1 correspondence. To do this, I am generating a 2D array of data called data that is nx1. This assignment statement takes place within a for loop as follows:

```<code>% Before iterating, I define an array of indices where I want to store the
% data sets in timeData. This choice of storage location is for
% organizational purposes.

A = [2, 5, 9, 21, 34, 100]; % Notice they are in ascending order, but have
                            % gaps that have no predictability.
sizeA = size(A);
numIter = A(1);

for m = 1:numIter % numIter is the number of data sets that I need to store
                  % in timeData

  % At this point, some code that is entirely irrelevant to my question
  % generates a nx1 array of data. One example of this data array is below.

  data = [1.1;2.3;5.5;4.4]; % This is one example of what data could be. Its
                            % number of rows, n, changes each iteration, as
                            % do its contents.

  B = size(data);
  timeData(1:B(1),1,A(m)) = num2cell(data);
end
</code>```

This code does put all contents of data in the appropriate locations within timeData as I want. However, it also adds {0x0 double} rows to all 2D arrays of timeData(:,:,a) for any a whose corresponding number of rows n was not the largest number of rows. Thus, there are many of these 2D arrays that have 10 to a couple hundred 0-valued rows that I don't want. For values of a that did not have a corresponding data set, the content of timeData(:,:,a) is an nx1 array of {0x0 double}.

I need to iterate over the contents of timeData in subsequent code, and I need to be able to find the size of the data set that is in timeData(:,:,a) without somehow discounting all the {0x0 double}.

How can I modify my assignment statement to fix this?

Edit: Desired output of the above example is the following with n = 5. Let this data set be represented by a = 9.

```<code>timeData(:,:,9) = {[1.1]}
                  {[2.3]}
                  {[5.5]}
                  {[8.6]}
                  {[4.4]}
</code>```

Now, consider the possibility that a previous or subsequent value of the A matrix had a data set with n = 7, and n = 7 is the largest data set (largest n value). timeData(:,:,9) outputs like so in my code:

```<code>timeData(:,:,9) = {[1.1]}
                  {[2.3]}
                  {[5.5]}
                  {[8.6]}
                  {[4.4]}
                  {[0x0 double]}
                  {[0x0 double]}
</code>```

@Dev-iL, as I understand it, your answer gives me the ability to delete the cells that have {[0x0 double]} in them (this is what I mean by "discounting"). This is a good plan B, but is there a way to prevent the {[0x0 double]} cells from showing up in the first place?

Edit 2: Update to the above statement "your answer gives me the ability to delete the cells that have {[0x0 double]} in them (this is what I mean by "discounting")". The cellfun(@isempty... ) function makes the {[0x0 double]}cells go to {[0x0 cell]}, it does not remove them. In other words, size(timeData(:,:,9)) is the same before and after the command is performed. This is not what I want. I want size(timeData(:,:,9)) to be 5x1 no matter what n is for any other value of a.

Edit 3: I just realized that the most desired output would be the following:

```<code>timeData(:,:,9) = {[1.1;2.3;5.5;8.6;4.4]} % An n x 1 column matrix within
                                          % the cell.
</code>```

but I can work with this outcome or the outcome as described above.

答:
Unfortunately, I don't understand the structure of your dataset, which is why I can't suggest a better assignment method. However, I'd like to point out an operation that can you help deal with your data after it's been created:

```<code>cellfun(@isempty,timeData);
</code>```

What the above does is return a logical array the size of timeData, indicating which cells contain something "empty". Typically, an array of arbitrary datatype is considered "empty" when it has at least one dimension that is equal to 0.

How can you use it to your advantage?

```<code>%% Example 1: counting non-empty cells:
nData = sum(~cellfun(@isempty,timeData(:)));

%% Example 2: assigning empty cells in place of empty double arrays:
timeData(cellfun(@isempty,timeData)) = {{}};
</code>```

Body:
I want to generate a 3D cell array called timeData so that timeData(:,:,a) for some integer a is an nx1 matrix of data, and the number of rows n varies with the value of a in a 1:1 correspondence. To do this, I am generating a 2D array of data called data that is nx1. This assignment statement takes place within a for loop as follows:

% Before iterating, I define an array of indices where I want to store the
% data sets in timeData. This choice of storage location is for
% organizational purposes.

A = [2, 5, 9, 21, 34, 100]; % Notice they are in ascending order, but have
                            % gaps that have no predictability.
sizeA = size(A);
numIter = A(1);

for m = 1:numIter % numIter is the number of data sets that I need to store
                  % in timeData

  % At this point, some code that is entirely irrelevant to my question
  % generates a nx1 array of data. One example of this data array is below.

  data = [1.1;2.3;5.5;4.4]; % This is one example of what data could be. Its
                            % number of rows, n, changes each iteration, as
                            % do its contents.

  B = size(data);
  timeData(1:B(1),1,A(m)) = num2cell(data);
end

This code does put all contents of data in the appropriate locations within timeData as I want. However, it also adds {0x0 double} rows to all 2D arrays of timeData(:,:,a) for any a whose corresponding number of rows n was not the largest number of rows. Thus, there are many of these 2D arrays that have 10 to a couple hundred 0-valued rows that I don't want. For values of a that did not have a corresponding data set, the content of timeData(:,:,a) is an nx1 array of {0x0 double}.

I need to iterate over the contents of timeData in subsequent code, and I need to be able to find the size of the data set that is in timeData(:,:,a) without somehow discounting all the {0x0 double}.

How can I modify my assignment statement to fix this?

Edit: Desired output of the above example is the following with n = 5. Let this data set be represented by a = 9.

timeData(:,:,9) = {[1.1]}
                  {[2.3]}
                  {[5.5]}
                  {[8.6]}
                  {[4.4]}

Now, consider the possibility that a previous or subsequent value of the A matrix had a data set with n = 7, and n = 7 is the largest data set (largest n value). timeData(:,:,9) outputs like so in my code:

timeData(:,:,9) = {[1.1]}
                  {[2.3]}
                  {[5.5]}
                  {[8.6]}
                  {[4.4]}
                  {[0x0 double]}
                  {[0x0 double]}

@Dev-iL, as I understand it, your answer gives me the ability to delete the cells that have {[0x0 double]} in them (this is what I mean by "discounting"). This is a good plan B, but is there a way to prevent the {[0x0 double]} cells from showing up in the first place?

Edit 2: Update to the above statement "your answer gives me the ability to delete the cells that have {[0x0 double]} in them (this is what I mean by "discounting")". The cellfun(@isempty... ) function makes the {[0x0 double]}cells go to {[0x0 cell]}, it does not remove them. In other words, size(timeData(:,:,9)) is the same before and after the command is performed. This is not what I want. I want size(timeData(:,:,9)) to be 5x1 no matter what n is for any other value of a.

Edit 3: I just realized that the most desired output would be the following:

timeData(:,:,9) = {[1.1;2.3;5.5;8.6;4.4]} % An n x 1 column matrix within
                                          % the cell.

but I can work with this outcome or the outcome as described above.

Body:
Unfortunately, I don't understand the structure of your dataset, which is why I can't suggest a better assignment method. However, I'd like to point out an operation that can you help deal with your data after it's been created:

cellfun(@isempty,timeData);

What the above does is return a logical array the size of timeData, indicating which cells contain something "empty". Typically, an array of arbitrary datatype is considered "empty" when it has at least one dimension that is equal to 0.

How can you use it to your advantage?

%% Example 1: counting non-empty cells:
nData = sum(~cellfun(@isempty,timeData(:)));

%% Example 2: assigning empty cells in place of empty double arrays:
timeData(cellfun(@isempty,timeData)) = {{}};


来源: stackexchange

问:
c# What happens if I use code a .NET 3.5 function on a machine that has .Net 2 installed
Just out of interest, if I built some code using the Enumerable.Distinct function which appeared in .Net 3.5 and then ran it on a machine with .Net 2.0 on it, what would happen?</p>

答: The program will crash as soon as the assembly that defines Enumerable.Distinct (System.Core) is needed. However, you can make it work if you target .NET 2.0 and use LinqBridge instead of System.Core.

ContentLicense: CC BY-SA 2.5


问:
tensorflow hangs before initializing global variables in joblib
I have a multi-layer CNN in CPU tensorflow.

I'm using the Parallel and delayed functions in joblib to learn multiple instances of my CNN, trained on the same set of data.

When I try to run this, the program will hang after a joblib worker starts its tf.Session(), but before any tensorflow variables are initialized, and before I get any output from the verbose argument of the Parallel function.

I don't really know why this would happen. So I am looking for general debugging strategies from other people who may have combined tensorflow and joblib.

答:
I was able to get the program to work by changing the backend option of
Parallel to "threading". Apparently, the "multiprocessing" option was creating too much communication and memory overhead when exchanging input and output data.

ContentLicense: CC BY-SA 3.0


问:
How to use React$Element in FlowType?
Here is my simple <ListItem /> react component. I want it to have a marker prop that only allows two types of components, either an <Icon /> or a .

```<code>import React, { Element } from 'react';

import { Icon } from '../Icon';
import { Label } from '../Label';

type Props = {
  marker?: Element<Icon> | Element<Label>,
};

const ListItem = ({ marker }: Props) => {
  return (
    <div>{marker}</div>
  );
};

export default ListItem;
</code>```

How shall I represent the simple use case in FlowType? I tried the following but all of them seem to not work. That is why I wonder, how to properly use React$Element to exactly allow two particular types of react components?

```<code>type Marker = Icon | Label;

type Props = {
  marker?: Element<Marker>,
};
</code>```

```<code>type Props = {
  marker?: Element<Icon> | Element<Label>,
};
</code>```

答:
The pattern that you are attempting will work in Flow versions 0.53.0 and later with a minor change: the type parameter of Element is a type expression position, but Icon and Label are values. You need to use typeof to refer to their types:

```<code>type Props = {
  marker?: Element<typeof Icon> | Element<typeof Label>,
};
</code>```

Flow's type definitions for React changed substantially in v0.53.0, including a change that switched Element's type parameter from a Config to a React$ElementType which makes it much easier to talk about elements created by specific components.

Hack for Flow v0.52.0 and earlier

@Lewis Chung pointed out in a comment that the Config parameter to Element before Flow v0.53.0 is created by the expression $Diff<Props, DefaultProps>. If Icon and Label have distinct props types then you can distinguish elements created by those components in older versions of Flow using a hack like this:

```<code>type Props = {
  marker?: Element<IconProps> | Element<LabelProps>,
};
</code>```

That assumes that Icon and Label do not have default props. If they do then you need to expand the type to produce the appropriate diffs:

```<code>type Props = {
  marker?:
    | Element<$Diff<IconProps, IconDefaultProps>>
    | Element<$Diff<LabelProps, LabelDefaultProps>>,
};
</code>```

Title: How to use React$Element in FlowType?

Body:
Here is my simple <ListItem /> react component. I want it to have a marker prop that only allows two types of components, either an <Icon /> or a .

import React, { Element } from 'react';

import { Icon } from '../Icon';
import { Label } from '../Label';

type Props = {
  marker?: Element<Icon> | Element,
};

const ListItem = ({ marker }: Props) => {
  return (

{marker}

  );
};

export default ListItem;

How shall I represent the simple use case in FlowType? I tried the following but all of them seem to not work. That is why I wonder, how to properly use React$Element to exactly allow two particular types of react components?

type Marker = Icon | Label;

type Props = {
  marker?: Element<Marker>,
};

type Props = {
  marker?: Element<Icon> | Element,
};

Body:
The pattern that you are attempting will work in Flow versions 0.53.0 and later with a minor change: the type parameter of Element is a type expression position, but Icon and Label are values. You need to use typeof to refer to their types:

type Props = {
  marker?: Element<typeof Icon> | Element<typeof Label>,
};

Flow's type definitions for React changed substantially in v0.53.0, including a change that switched Element's type parameter from a Config to a React$ElementType which makes it much easier to talk about elements created by specific components.

Hack for Flow v0.52.0 and earlier

@Lewis Chung pointed out in a comment that the Config parameter to Element before Flow v0.53.0 is created by the expression $Diff<Props, DefaultProps>. If Icon and Label have distinct props types then you can distinguish elements created by those components in older versions of Flow using a hack like this:

type Props = {
  marker?: Element<IconProps> | Element<LabelProps>,
};

That assumes that Icon and Label do not have default props. If they do then you need to expand the type to produce the appropriate diffs:

type Props = {
  marker?:
    | Element<$Diff<IconProps, IconDefaultProps>>
    | Element<$Diff<LabelProps, LabelDefaultProps>>,
};


问:
iPad app crash on launch : Help me analyze this crash log
Some user's of our iPad application are reporting a crash on launch of the application. Though I have the same device (and the same OS version 4.2.1) I am unable to replicate the crash on my device. I managed to get this crash log from ITC but unsure if this is related to the crash on launch issue.

Please help me analyze this crash log. Thanks in advance.

```<code>Incident Identifier: 0D92B20E-8859-4DB4-9DE0-70222FACBAEB
Hardware Model: iPad1,1
Process: MyiPadApp [479]
Path: /var/mobile/Applications/3BA6269C-7616-41ED-A1BF-1D23CA81CFA1/MyiPadApp.app/MyiPadApp
Identifier: MyiPadApp
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]

Date/Time: 2011-01-13 18:40:44.967 +0100
OS Version: iPhone OS 4.2.1 (8C148)
Report Version: 104

Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x782e6d6f
Crashed Thread: 0

Thread 0 Crashed:
0 libobjc.A.dylib 0x34a80466 objc_msgSend + 18
1 UIKit 0x3424847e -[UIViewController unloadViewForced:]
2 UIKit 0x342483ca -[UIViewController unloadViewIfReloadable]
3 UIKit 0x342e1dde -[UIViewController purgeMemoryForReason:]
4 UIKit 0x342e1dfe -[UIViewController didReceiveMemoryWarning]
5 MyiPadApp 0x00002886 -[MajorIndicesController didReceiveMemoryWarning] + 22
6 UIKit 0x342e1e14 -[UIViewController _didReceiveMemoryWarning:]
7 Foundation 0x3117561c _nsnote_callback
8 CoreFoundation 0x3580111c __CFXNotificationPost_old
9 CoreFoundation 0x35800dbc _CFXNotificationPostNotification
10 Foundation 0x31164d1c -[NSNotificationCenter postNotificationName:object:userInfo:]
11 Foundation 0x3116e23a -[NSNotificationCenter postNotificationName:object:]
12 UIKit 0x342aada2 -[UIApplication _performMemoryWarning]
13 UIKit 0x342ab9c4 -[UIApplication _receivedMemoryNotification]
14 UIKit 0x342a8770 _memoryStatusChanged
15 CoreFoundation 0x358310c6 __CFNotificationCenterDarwinCallBack
16 CoreFoundation 0x35817be0 __CFMachPortPerform
17 CoreFoundation 0x3580f6f8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
18 CoreFoundation 0x3580f6bc __CFRunLoopDoSource1
19 CoreFoundation 0x35801f76 __CFRunLoopRun
20 CoreFoundation 0x35801c80 CFRunLoopRunSpecific
21 CoreFoundation 0x35801b88 CFRunLoopRunInMode
22 GraphicsServices 0x320c84a4 GSEventRunModal
23 GraphicsServices 0x320c8550 GSEventRun
24 UIKit 0x341dc322 -[UIApplication _run]
25 UIKit 0x341d9e8c UIApplicationMain
26 MyiPadApp 0x0000218a main + 42
27 MyiPadApp 0x00002154 start + 32

Thread 1:
0 libSystem.B.dylib 0x30d30974 kevent + 24
1 libSystem.B.dylib 0x30dda704 _dispatch_mgr_invoke
2 libSystem.B.dylib 0x30dda174 _dispatch_queue_invoke
3 libSystem.B.dylib 0x30dd9b98 _dispatch_worker_thread2
4 libSystem.B.dylib 0x30d7e24a _pthread_wqthread
5 libSystem.B.dylib 0x30d76970 start_wqthread + 0

Thread 2:
0 libSystem.B.dylib 0x30d04268 mach_msg_trap + 20
1 libSystem.B.dylib 0x30d06354 mach_msg
2 CoreFoundation 0x35802648 __CFRunLoopServiceMachPort
3 CoreFoundation 0x35801ed2 __CFRunLoopRun
4 CoreFoundation 0x35801c80 CFRunLoopRunSpecific
5 CoreFoundation 0x35801b88 CFRunLoopRunInMode
6 WebCore 0x34bf6124 RunWebThread
7 libSystem.B.dylib 0x30d7d886 _pthread_start
8 libSystem.B.dylib 0x30d72a88 thread_start + 0

Thread 3:
0 libSystem.B.dylib 0x30d04268 mach_msg_trap + 20
1 libSystem.B.dylib 0x30d06354 mach_msg
2 CoreFoundation 0x35802648 __CFRunLoopServiceMachPort
3 CoreFoundation 0x35801ed2 __CFRunLoopRun
4 CoreFoundation 0x35801c80 CFRunLoopRunSpecific
5 CoreFoundation 0x35811efe CFRunLoopRun
6 MyiPadApp 0x00017c84 +[ASIHTTPRequest runRequests] + 120
7 Foundation 0x3116c192 -[NSThread main]
8 Foundation 0x31165242 __NSThread__main__
9 libSystem.B.dylib 0x30d7d886 _pthread_start
10 libSystem.B.dylib 0x30d72a88 thread_start + 0

Thread 4:
0 libSystem.B.dylib 0x30d04268 mach_msg_trap + 20
1 libSystem.B.dylib 0x30d06354 mach_msg
2 CoreFoundation 0x35802648 __CFRunLoopServiceMachPort
3 CoreFoundation 0x35801ed2 __CFRunLoopRun
4 CoreFoundation 0x35801c80 CFRunLoopRunSpecific
5 CoreFoundation 0x35801b88 CFRunLoopRunInMode
6 Foundation 0x3118e5f6 +[NSURLConnection(NSURLConnectionReallyInternal) _resourceLoadLoop:]
7 Foundation 0x3116c192 -[NSThread main]
8 Foundation 0x31165242 __NSThread__main__
9 libSystem.B.dylib 0x30d7d886 _pthread_start
10 libSystem.B.dylib 0x30d72a88 thread_start + 0

Thread 5:
0 libSystem.B.dylib 0x30d2868c select$DARWIN_EXTSN + 20
1 CoreFoundation 0x35839662 __CFSocketManager
2 libSystem.B.dylib 0x30d7d886 _pthread_start
3 libSystem.B.dylib 0x30d72a88 thread_start + 0

Thread 6:
0 libSystem.B.dylib 0x30d7e9e0 __workq_kernreturn + 8
1 libSystem.B.dylib 0x30d7e364 _pthread_wqthread
2 libSystem.B.dylib 0x30d76970 start_wqthread + 0

Thread 7:
0 libSystem.B.dylib 0x30d7e9e0 __workq_kernreturn + 8
1 libSystem.B.dylib 0x30d7e364 _pthread_wqthread
2 libSystem.B.dylib 0x30d76970 start_wqthread + 0

Thread 0 crashed with ARM Thread State:
r0: 0x00198930 r1: 0x344b6ce1 r2: 0x001bec59 r3: 0x000000a0
r4: 0x0019a3f2 r5: 0x782e6d6f r6: 0x344bec7c r7: 0x2fdfea54
r8: 0x00000000 r9: 0x001fc098 r10: 0x00000003 r11: 0x00000029
ip: 0x3e3cf960 sp: 0x2fdfea3c lr: 0x00002999 pc: 0x34a80466
cpsr: 0x200f0030

Binary Images:
0x1000 - 0x36fff +MyiPadApp armv7 <ddf465b3fdd191b2fcb6cfb0e5be2d68> /var/mobile/Applications/3BA6269C-7616-41ED-A1BF-1D23CA81CFA1/MyiPadApp.app/MyiPadApp
0xf6000 - 0xf7fff dns.so armv7 <fcefecb2d5e095ba88127eec3af57ec0> /usr/lib/info/dns.so
0x2fe00000 - 0x2fe27fff dyld armv7 <06e6959cebb4a72e66c833e26ae64d26> /usr/lib/dyld
0x3001f000 - 0x30026fff libbz2.1.0.dylib armv7 <2989ea7a5cad2cfe91bd632b041d0ff4> /usr/lib/libbz2.1.0.dylib
0x30054000 - 0x3016afff libicucore.A.dylib armv7 <e7fbb2ac586567e574dc33d7bb5c4dc9> /usr/lib/libicucore.A.dylib
0x302b7000 - 0x30366fff WebKit armv7 <644a1c6120578f896bed7121307aa2af> /System/Library/PrivateFrameworks/WebKit.framework/WebKit
0x303fc000 - 0x3051cfff CoreGraphics armv7 <2d7b40a7baca915ce78b1dd9a0d6433b> /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
0x3056b000 - 0x3056bfff vecLib armv7 <e53d234e808c77d286161095f92c58cf> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/vecLib
0x30641000 - 0x30700fff CFNetwork armv7 <02fe0e30e54fffdcbbbd02e8cb812c3a> /System/Library/Frameworks/CFNetwork.framework/CFNetwork
0x3076f000 - 0x307c4fff libvDSP.dylib armv7 <9365fc6cae1bff737257e74faf3b1f26> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libvDSP.dylib
0x307e6000 - 0x307e8fff libgcc_s.1.dylib armv7 <e66758bcda6da5d7f9b54fa5c4de6da2> /usr/lib/libgcc_s.1.dylib
0x30821000 - 0x30853fff AppSupport armv7 <47c8055ac99f187174ca373b702ffa68> /System/Library/PrivateFrameworks/AppSupport.framework/AppSupport
0x30854000 - 0x30854fff Accelerate armv7 <29dd5f17440bbb6e8e42e11b6fceda9a> /System/Library/Frameworks/Accelerate.framework/Accelerate
0x3091c000 - 0x30931fff libresolv.9.dylib armv7 <ea156820997ae9a2baf664d0f79f18d7> /usr/lib/libresolv.9.dylib
0x30b44000 - 0x30b46fff IOMobileFramebuffer armv7 <1040629f37795146c9dcac8ab1a868fc> /System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer
0x30c45000 - 0x30c74fff SystemConfiguration armv7 <3f982c11b5526fc39a92d585c60d8a90> /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration
0x30d03000 - 0x30e14fff libSystem.B.dylib armv7 <138a43ab528bb428651e6aa7a2a7293c> /usr/lib/libSystem.B.dylib
0x30e37000 - 0x30f1ffff libGLProgrammability.dylib armv7 <1f478a71783cd7eb4ae9ef6f2dcea803> /System/Library/Frameworks/OpenGLES.framework/libGLProgrammability.dylib
0x30f20000 - 0x30f2bfff libz.1.dylib armv7 <fabaddbcbc8c02bab0261df9d78e0e25> /usr/lib/libz.1.dylib
0x31066000 - 0x31114fff QuartzCore armv7 <83a8e5f0033369e437069c1e758fed83> /System/Library/Frameworks/QuartzCore.framework/QuartzCore
0x31161000 - 0x31280fff Foundation armv7 <81d36041f04318cb51db5aafed9ce504> /System/Library/Frameworks/Foundation.framework/Foundation
0x31307000 - 0x31347fff CoreAudio armv7 <f32e03ee4c68f0db23f05afc9a3cc94c> /System/Library/Frameworks/CoreAudio.framework/CoreAudio
0x318b5000 - 0x318d5fff PrintKit armv7 <02a9c6f4173a0673c4637a3b570345cd> /System/Library/PrivateFrameworks/PrintKit.framework/PrintKit
0x31bd9000 - 0x31c02fff MobileCoreServices armv7 <54484a513761868149405df7fc29b5c0> /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices
0x31c6d000 - 0x31d16fff libxml2.2.dylib armv7 <b3d82f80a777cb1434052ea2d232e3df> /usr/lib/libxml2.2.dylib
0x31d29000 - 0x31d2cfff IOSurface armv7 <deff02882166bf16d0765d68f0542cc8> /System/Library/PrivateFrameworks/IOSurface.framework/IOSurface
0x31d2d000 - 0x31d2ffff MobileInstallation armv7 <8e6b0d9f642be06729ffdaaee97053b0> /System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation
0x31d46000 - 0x31d4dfff AggregateDictionary armv7 <71372c95d4af7af787d0682a939e40ac> /System/Library/PrivateFrameworks/AggregateDictionary.framework/AggregateDictionary
0x31e09000 - 0x31e4bfff CoreTelephony armv7 <96d3af505b9f2887e62c7e99c157733e> /System/Library/Frameworks/CoreTelephony.framework/CoreTelephony
0x31e4c000 - 0x31f6cfff libmecabra.dylib armv7 <b2293b8acb00a14bace7520a63f39439> /usr/lib/libmecabra.dylib
0x320c4000 - 0x320d0fff GraphicsServices armv7 <0099670dccd99466653956bf918d667a> /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
0x32100000 - 0x33a79fff TextInput armv7 <557601a7d93124fd5860606f294e900a> /System/Library/PrivateFrameworks/TextInput.framework/TextInput
0x33ae9000 - 0x33aebfff libAccessibility.dylib armv7 <3f0b58ea13d30f0cdb73f6ffe6d4e75c> /usr/lib/libAccessibility.dylib
0x33b49000 - 0x33c82fff AudioToolbox armv7 <657b327f2ceee9f22f9474f2f9bddbe6> /System/Library/Frameworks/AudioToolbox.framework/AudioToolbox
0x33d2c000 - 0x33d2ffff libGFXShared.dylib armv7 <3a385ed495379116abbe50bc8cd5a612> /System/Library/Frameworks/OpenGLES.framework/libGFXShared.dylib
0x33d30000 - 0x33d31fff CoreSurface armv7 <f7caaf43609cfe0e475dfe83790edb4d> /System/Library/PrivateFrameworks/CoreSurface.framework/CoreSurface
0x33d61000 - 0x33d7afff libRIP.A.dylib armv7 <ee16b5cee12a8947c8e511ed51ae7fef> /System/Library/Frameworks/CoreGraphics.framework/Resources/libRIP.A.dylib
0x340dc000 - 0x34112fff CoreText armv7 <b9b5c21b2d2a28abc47842c78c026ddf> /System/Library/Frameworks/CoreText.framework/CoreText
0x3415c000 - 0x3418ffff AddressBook armv7 <7c87e0175c8649d6832419da8a1cfac1> /System/Library/Frameworks/AddressBook.framework/AddressBook
0x341a5000 - 0x34526fff UIKit armv7 <de1cbd3219a74e4d41b30428f428e223> /System/Library/Frameworks/UIKit.framework/UIKit
0x34527000 - 0x345bafff ImageIO armv7 <5b5a294d4250eff866fdbf891b1e8b34> /System/Library/Frameworks/ImageIO.framework/ImageIO
0x34632000 - 0x34636fff AssetsLibraryServices armv7 <e861a330d14702f148ca5133dcbe954c> /System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices
0x34775000 - 0x34822fff JavaScriptCore armv7 <3f2df600942dc72aad312b3cc98ec479> /System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore
0x34852000 - 0x3485bfff CoreVideo armv7 <2092d5deb6b234e04678b7c1878ccd81> /System/Library/Frameworks/CoreVideo.framework/CoreVideo
0x3492e000 - 0x3493afff SpringBoardServices armv7 <137b75e19b2450c234dec88d538798ff> /System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices
0x3493d000 - 0x34987fff libstdc++.6.dylib armv7 <53a6e7239c3908fa8c2915b65ff3b056> /usr/lib/libstdc++.6.dylib
0x34a7d000 - 0x34b3efff libobjc.A.dylib armv7 <aaf5671a35f9ac20d5846703dafaf4c6> /usr/lib/libobjc.A.dylib
0x34b3f000 - 0x35127fff WebCore armv7 <d6bd9cf88ee82ab6b0e33e0ae1190772> /System/Library/PrivateFrameworks/WebCore.framework/WebCore
0x3520f000 - 0x352fcfff libiconv.2.dylib armv7 <c72b45f471df092dbd849081f7a3ef53> /usr/lib/libiconv.2.dylib
0x353e7000 - 0x353ecfff MobileKeyBag armv7 <cec3f3271fc267c32c169ed03e312d63> /System/Library/PrivateFrameworks/MobileKeyBag.framework/MobileKeyBag
0x3549d000 - 0x354d5fff libCGFreetype.A.dylib armv7 <374bd566263e8929c10d50d6a6a48a46> /System/Library/Frameworks/CoreGraphics.framework/Resources/libCGFreetype.A.dylib
0x35553000 - 0x35560fff OpenGLES armv7 <a12565ffb5bb42e3019f1957cd4951d0> /System/Library/Frameworks/OpenGLES.framework/OpenGLES
0x355b6000 - 0x355bcfff liblockdown.dylib armv7 <5bbd9b3f5cfece328f80c403a8805ce9> /usr/lib/liblockdown.dylib
0x356d2000 - 0x357d9fff CoreData armv7 <29b1ab7d339e42a6ff6923e54cf43e7b> /System/Library/Frameworks/CoreData.framework/CoreData
0x357da000 - 0x358c0fff CoreFoundation armv7 <01441e01f5141a50ee723362e59ca400> /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
0x35992000 - 0x3599ffff libbsm.0.dylib armv7 <0f4e595e6eb2170aceb729f32b5de8c2> /usr/lib/libbsm.0.dylib
0x35b60000 - 0x35babfff libBLAS.dylib armv7 <251c5ac7380802a16e30d827c027c637> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libBLAS.dylib
0x35bac000 - 0x35e46fff libLAPACK.dylib armv7 <2e77d87e96af938aacf0a6008e6fb89d> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libLAPACK.dylib
0x3601b000 - 0x3603afff Bom armv7 <0f5fd6057bad5e1677869500d636821f> /System/Library/PrivateFrameworks/Bom.framework/Bom
0x3603d000 - 0x360acfff ProofReader armv7 <d2e62a8ab7e1460c7f6de8913c703e6d> /System/Library/PrivateFrameworks/ProofReader.framework/ProofReader
0x3612f000 - 0x36137fff libkxld.dylib armv7 <854e82fe66feef01e54c7c8a209851ac> /usr/lib/system/libkxld.dylib
0x36138000 - 0x3616ffff Security armv7 <cd28e102950634ae7167ddee9c686d36> /System/Library/Frameworks/Security.framework/Security
0x36170000 - 0x361bdfff libsqlite3.dylib armv7 <55038e5c1d4d0dbdd94295e8cad7a9a4> /usr/lib/libsqlite3.dylib
0x361be000 - 0x361f8fff IOKit armv7 <eb932cc42d60e55d9a4d0691bcc3d9ad> /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit
0x3623f000 - 0x3627efff libGLImage.dylib armv7 <a7c117c92607a512823d307b8fdd0151> /System/Library/Frameworks/OpenGLES.framework/libGLImage.dylib
</code>```

答:
Your application is indeed getting a memory warning, but the reason of the crash seems to be that you are trying to access bad memory (for example, trying to access an object that's been released earlier) while trying to free up memory in response to the memory warning. In other words, the memory warning seems to be the indirect cause of your crash.

Brindy is right. The question is, are you loading any assets or data into memory on launch? If so, I'd suggest to postpone this until the application is up and running.

More importantly, however, is to check what your application does when it receives a memory warning. Memory warnings are nothing to be afraid of. You just have to make sure that you handle them correctly.

Body:
Some user's of our iPad application are reporting a crash on launch of the application. Though I have the same device (and the same OS version 4.2.1) I am unable to replicate the crash on my device. I managed to get this crash log from ITC but unsure if this is related to the crash on launch issue.

Please help me analyze this crash log. Thanks in advance.

Incident Identifier: 0D92B20E-8859-4DB4-9DE0-70222FACBAEB
Hardware Model: iPad1,1
Process: MyiPadApp [479]
Path: /var/mobile/Applications/3BA6269C-7616-41ED-A1BF-1D23CA81CFA1/MyiPadApp.app/MyiPadApp
Identifier: MyiPadApp
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]

Date/Time: 2011-01-13 18:40:44.967 +0100
OS Version: iPhone OS 4.2.1 (8C148)
Report Version: 104

Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x782e6d6f
Crashed Thread: 0

Thread 0 Crashed:
0 libobjc.A.dylib 0x34a80466 objc_msgSend + 18
1 UIKit 0x3424847e -[UIViewController unloadViewForced:]
2 UIKit 0x342483ca -[UIViewController unloadViewIfReloadable]
3 UIKit 0x342e1dde -[UIViewController purgeMemoryForReason:]
4 UIKit 0x342e1dfe -[UIViewController didReceiveMemoryWarning]
5 MyiPadApp 0x00002886 -[MajorIndicesController didReceiveMemoryWarning] + 22
6 UIKit 0x342e1e14 -[UIViewController _didReceiveMemoryWarning:]
7 Foundation 0x3117561c _nsnote_callback
8 CoreFoundation 0x3580111c __CFXNotificationPost_old
9 CoreFoundation 0x35800dbc _CFXNotificationPostNotification
10 Foundation 0x31164d1c -[NSNotificationCenter postNotificationName:object:userInfo:]
11 Foundation 0x3116e23a -[NSNotificationCenter postNotificationName:object:]
12 UIKit 0x342aada2 -[UIApplication _performMemoryWarning]
13 UIKit 0x342ab9c4 -[UIApplication _receivedMemoryNotification]
14 UIKit 0x342a8770 _memoryStatusChanged
15 CoreFoundation 0x358310c6 __CFNotificationCenterDarwinCallBack
16 CoreFoundation 0x35817be0 __CFMachPortPerform
17 CoreFoundation 0x3580f6f8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
18 CoreFoundation 0x3580f6bc __CFRunLoopDoSource1
19 CoreFoundation 0x35801f76 __CFRunLoopRun
20 CoreFoundation 0x35801c80 CFRunLoopRunSpecific
21 CoreFoundation 0x35801b88 CFRunLoopRunInMode
22 GraphicsServices 0x320c84a4 GSEventRunModal
23 GraphicsServices 0x320c8550 GSEventRun
24 UIKit 0x341dc322 -[UIApplication _run]
25 UIKit 0x341d9e8c UIApplicationMain
26 MyiPadApp 0x0000218a main + 42
27 MyiPadApp 0x00002154 start + 32

Thread 1:
0 libSystem.B.dylib 0x30d30974 kevent + 24
1 libSystem.B.dylib 0x30dda704 _dispatch_mgr_invoke
2 libSystem.B.dylib 0x30dda174 _dispatch_queue_invoke
3 libSystem.B.dylib 0x30dd9b98 _dispatch_worker_thread2
4 libSystem.B.dylib 0x30d7e24a _pthread_wqthread
5 libSystem.B.dylib 0x30d76970 start_wqthread + 0

Thread 2:
0 libSystem.B.dylib 0x30d04268 mach_msg_trap + 20
1 libSystem.B.dylib 0x30d06354 mach_msg
2 CoreFoundation 0x35802648 __CFRunLoopServiceMachPort
3 CoreFoundation 0x35801ed2 __CFRunLoopRun
4 CoreFoundation 0x35801c80 CFRunLoopRunSpecific
5 CoreFoundation 0x35801b88 CFRunLoopRunInMode
6 WebCore 0x34bf6124 RunWebThread
7 libSystem.B.dylib 0x30d7d886 _pthread_start
8 libSystem.B.dylib 0x30d72a88 thread_start + 0

Thread 3:
0 libSystem.B.dylib 0x30d04268 mach_msg_trap + 20
1 libSystem.B.dylib 0x30d06354 mach_msg
2 CoreFoundation 0x35802648 __CFRunLoopServiceMachPort
3 CoreFoundation 0x35801ed2 __CFRunLoopRun
4 CoreFoundation 0x35801c80 CFRunLoopRunSpecific
5 CoreFoundation 0x35811efe CFRunLoopRun
6 MyiPadApp 0x00017c84 +[ASIHTTPRequest runRequests] + 120
7 Foundation 0x3116c192 -[NSThread main]
8 Foundation 0x31165242 __NSThread__main__
9 libSystem.B.dylib 0x30d7d886 _pthread_start
10 libSystem.B.dylib 0x30d72a88 thread_start + 0

Thread 4:
0 libSystem.B.dylib 0x30d04268 mach_msg_trap + 20
1 libSystem.B.dylib 0x30d06354 mach_msg
2 CoreFoundation 0x35802648 __CFRunLoopServiceMachPort
3 CoreFoundation 0x35801ed2 __CFRunLoopRun
4 CoreFoundation 0x35801c80 CFRunLoopRunSpecific
5 CoreFoundation 0x35801b88 CFRunLoopRunInMode
6 Foundation 0x3118e5f6 +[NSURLConnection(NSURLConnectionReallyInternal) _resourceLoadLoop:]
7 Foundation 0x3116c192 -[NSThread main]
8 Foundation 0x31165242 __NSThread__main__
9 libSystem.B.dylib 0x30d7d886 _pthread_start
10 libSystem.B.dylib 0x30d72a88 thread_start + 0

Thread 5:
0 libSystem.B.dylib 0x30d2868c select$DARWIN_EXTSN + 20
1 CoreFoundation 0x35839662 __CFSocketManager
2 libSystem.B.dylib 0x30d7d886 _pthread_start
3 libSystem.B.dylib 0x30d72a88 thread_start + 0

Thread 6:
0 libSystem.B.dylib 0x30d7e9e0 __workq_kernreturn + 8
1 libSystem.B.dylib 0x30d7e364 _pthread_wqthread
2 libSystem.B.dylib 0x30d76970 start_wqthread + 0

Thread 7:
0 libSystem.B.dylib 0x30d7e9e0 __workq_kernreturn + 8
1 libSystem.B.dylib 0x30d7e364 _pthread_wqthread
2 libSystem.B.dylib 0x30d76970 start_wqthread + 0

Thread 0 crashed with ARM Thread State:
r0: 0x00198930 r1: 0x344b6ce1 r2: 0x001bec59 r3: 0x000000a0
r4: 0x0019a3f2 r5: 0x782e6d6f r6: 0x344bec7c r7: 0x2fdfea54
r8: 0x00000000 r9: 0x001fc098 r10: 0x00000003 r11: 0x00000029
ip: 0x3e3cf960 sp: 0x2fdfea3c lr: 0x00002999 pc: 0x34a80466
cpsr: 0x200f0030

Binary Images:
0x1000 - 0x36fff +MyiPadApp armv7 <ddf465b3fdd191b2fcb6cfb0e5be2d68> /var/mobile/Applications/3BA6269C-7616-41ED-A1BF-1D23CA81CFA1/MyiPadApp.app/MyiPadApp
0xf6000 - 0xf7fff dns.so armv7 <fcefecb2d5e095ba88127eec3af57ec0> /usr/lib/info/dns.so
0x2fe00000 - 0x2fe27fff dyld armv7 <06e6959cebb4a72e66c833e26ae64d26> /usr/lib/dyld
0x3001f000 - 0x30026fff libbz2.1.0.dylib armv7 <2989ea7a5cad2cfe91bd632b041d0ff4> /usr/lib/libbz2.1.0.dylib
0x30054000 - 0x3016afff libicucore.A.dylib armv7 <e7fbb2ac586567e574dc33d7bb5c4dc9> /usr/lib/libicucore.A.dylib
0x302b7000 - 0x30366fff WebKit armv7 <644a1c6120578f896bed7121307aa2af> /System/Library/PrivateFrameworks/WebKit.framework/WebKit
0x303fc000 - 0x3051cfff CoreGraphics armv7 <2d7b40a7baca915ce78b1dd9a0d6433b> /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
0x3056b000 - 0x3056bfff vecLib armv7 <e53d234e808c77d286161095f92c58cf> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/vecLib
0x30641000 - 0x30700fff CFNetwork armv7 <02fe0e30e54fffdcbbbd02e8cb812c3a> /System/Library/Frameworks/CFNetwork.framework/CFNetwork
0x3076f000 - 0x307c4fff libvDSP.dylib armv7 <9365fc6cae1bff737257e74faf3b1f26> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libvDSP.dylib
0x307e6000 - 0x307e8fff libgcc_s.1.dylib armv7 <e66758bcda6da5d7f9b54fa5c4de6da2> /usr/lib/libgcc_s.1.dylib
0x30821000 - 0x30853fff AppSupport armv7 <47c8055ac99f187174ca373b702ffa68> /System/Library/PrivateFrameworks/AppSupport.framework/AppSupport
0x30854000 - 0x30854fff Accelerate armv7 <29dd5f17440bbb6e8e42e11b6fceda9a> /System/Library/Frameworks/Accelerate.framework/Accelerate
0x3091c000 - 0x30931fff libresolv.9.dylib armv7 <ea156820997ae9a2baf664d0f79f18d7> /usr/lib/libresolv.9.dylib
0x30b44000 - 0x30b46fff IOMobileFramebuffer armv7 <1040629f37795146c9dcac8ab1a868fc> /System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer
0x30c45000 - 0x30c74fff SystemConfiguration armv7 <3f982c11b5526fc39a92d585c60d8a90> /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration
0x30d03000 - 0x30e14fff libSystem.B.dylib armv7 <138a43ab528bb428651e6aa7a2a7293c> /usr/lib/libSystem.B.dylib
0x30e37000 - 0x30f1ffff libGLProgrammability.dylib armv7 <1f478a71783cd7eb4ae9ef6f2dcea803> /System/Library/Frameworks/OpenGLES.framework/libGLProgrammability.dylib
0x30f20000 - 0x30f2bfff libz.1.dylib armv7 <fabaddbcbc8c02bab0261df9d78e0e25> /usr/lib/libz.1.dylib
0x31066000 - 0x31114fff QuartzCore armv7 <83a8e5f0033369e437069c1e758fed83> /System/Library/Frameworks/QuartzCore.framework/QuartzCore
0x31161000 - 0x31280fff Foundation armv7 <81d36041f04318cb51db5aafed9ce504> /System/Library/Frameworks/Foundation.framework/Foundation
0x31307000 - 0x31347fff CoreAudio armv7 <f32e03ee4c68f0db23f05afc9a3cc94c> /System/Library/Frameworks/CoreAudio.framework/CoreAudio
0x318b5000 - 0x318d5fff PrintKit armv7 <02a9c6f4173a0673c4637a3b570345cd> /System/Library/PrivateFrameworks/PrintKit.framework/PrintKit
0x31bd9000 - 0x31c02fff MobileCoreServices armv7 <54484a513761868149405df7fc29b5c0> /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices
0x31c6d000 - 0x31d16fff libxml2.2.dylib armv7 <b3d82f80a777cb1434052ea2d232e3df> /usr/lib/libxml2.2.dylib
0x31d29000 - 0x31d2cfff IOSurface armv7 <deff02882166bf16d0765d68f0542cc8> /System/Library/PrivateFrameworks/IOSurface.framework/IOSurface
0x31d2d000 - 0x31d2ffff MobileInstallation armv7 <8e6b0d9f642be06729ffdaaee97053b0> /System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation
0x31d46000 - 0x31d4dfff AggregateDictionary armv7 <71372c95d4af7af787d0682a939e40ac> /System/Library/PrivateFrameworks/AggregateDictionary.framework/AggregateDictionary
0x31e09000 - 0x31e4bfff CoreTelephony armv7 <96d3af505b9f2887e62c7e99c157733e> /System/Library/Frameworks/CoreTelephony.framework/CoreTelephony
0x31e4c000 - 0x31f6cfff libmecabra.dylib armv7 <b2293b8acb00a14bace7520a63f39439> /usr/lib/libmecabra.dylib
0x320c4000 - 0x320d0fff GraphicsServices armv7 <0099670dccd99466653956bf918d667a> /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
0x32100000 - 0x33a79fff TextInput armv7 <557601a7d93124fd5860606f294e900a> /System/Library/PrivateFrameworks/TextInput.framework/TextInput
0x33ae9000 - 0x33aebfff libAccessibility.dylib armv7 <3f0b58ea13d30f0cdb73f6ffe6d4e75c> /usr/lib/libAccessibility.dylib
0x33b49000 - 0x33c82fff AudioToolbox armv7 <657b327f2ceee9f22f9474f2f9bddbe6> /System/Library/Frameworks/AudioToolbox.framework/AudioToolbox
0x33d2c000 - 0x33d2ffff libGFXShared.dylib armv7 <3a385ed495379116abbe50bc8cd5a612> /System/Library/Frameworks/OpenGLES.framework/libGFXShared.dylib
0x33d30000 - 0x33d31fff CoreSurface armv7 <f7caaf43609cfe0e475dfe83790edb4d> /System/Library/PrivateFrameworks/CoreSurface.framework/CoreSurface
0x33d61000 - 0x33d7afff libRIP.A.dylib armv7 <ee16b5cee12a8947c8e511ed51ae7fef> /System/Library/Frameworks/CoreGraphics.framework/Resources/libRIP.A.dylib
0x340dc000 - 0x34112fff CoreText armv7 <b9b5c21b2d2a28abc47842c78c026ddf> /System/Library/Frameworks/CoreText.framework/CoreText
0x3415c000 - 0x3418ffff AddressBook armv7 <7c87e0175c8649d6832419da8a1cfac1> /System/Library/Frameworks/AddressBook.framework/AddressBook
0x341a5000 - 0x34526fff UIKit armv7 <de1cbd3219a74e4d41b30428f428e223> /System/Library/Frameworks/UIKit.framework/UIKit
0x34527000 - 0x345bafff ImageIO armv7 <5b5a294d4250eff866fdbf891b1e8b34> /System/Library/Frameworks/ImageIO.framework/ImageIO
0x34632000 - 0x34636fff AssetsLibraryServices armv7 <e861a330d14702f148ca5133dcbe954c> /System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices
0x34775000 - 0x34822fff JavaScriptCore armv7 <3f2df600942dc72aad312b3cc98ec479> /System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore
0x34852000 - 0x3485bfff CoreVideo armv7 <2092d5deb6b234e04678b7c1878ccd81> /System/Library/Frameworks/CoreVideo.framework/CoreVideo
0x3492e000 - 0x3493afff SpringBoardServices armv7 <137b75e19b2450c234dec88d538798ff> /System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices
0x3493d000 - 0x34987fff libstdc++.6.dylib armv7 <53a6e7239c3908fa8c2915b65ff3b056> /usr/lib/libstdc++.6.dylib
0x34a7d000 - 0x34b3efff libobjc.A.dylib armv7 <aaf5671a35f9ac20d5846703dafaf4c6> /usr/lib/libobjc.A.dylib
0x34b3f000 - 0x35127fff WebCore armv7 <d6bd9cf88ee82ab6b0e33e0ae1190772> /System/Library/PrivateFrameworks/WebCore.framework/WebCore
0x3520f000 - 0x352fcfff libiconv.2.dylib armv7 <c72b45f471df092dbd849081f7a3ef53> /usr/lib/libiconv.2.dylib
0x353e7000 - 0x353ecfff MobileKeyBag armv7 <cec3f3271fc267c32c169ed03e312d63> /System/Library/PrivateFrameworks/MobileKeyBag.framework/MobileKeyBag
0x3549d000 - 0x354d5fff libCGFreetype.A.dylib armv7 <374bd566263e8929c10d50d6a6a48a46> /System/Library/Frameworks/CoreGraphics.framework/Resources/libCGFreetype.A.dylib
0x35553000 - 0x35560fff OpenGLES armv7 <a12565ffb5bb42e3019f1957cd4951d0> /System/Library/Frameworks/OpenGLES.framework/OpenGLES
0x355b6000 - 0x355bcfff liblockdown.dylib armv7 <5bbd9b3f5cfece328f80c403a8805ce9> /usr/lib/liblockdown.dylib
0x356d2000 - 0x357d9fff CoreData armv7 <29b1ab7d339e42a6ff6923e54cf43e7b> /System/Library/Frameworks/CoreData.framework/CoreData
0x357da000 - 0x358c0fff CoreFoundation armv7 <01441e01f5141a50ee723362e59ca400> /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
0x35992000 - 0x3599ffff libbsm.0.dylib armv7 <0f4e595e6eb2170aceb729f32b5de8c2> /usr/lib/libbsm.0.dylib
0x35b60000 - 0x35babfff libBLAS.dylib armv7 <251c5ac7380802a16e30d827c027c637> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libBLAS.dylib
0x35bac000 - 0x35e46fff libLAPACK.dylib armv7 <2e77d87e96af938aacf0a6008e6fb89d> /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libLAPACK.dylib
0x3601b000 - 0x3603afff Bom armv7 <0f5fd6057bad5e1677869500d636821f> /System/Library/PrivateFrameworks/Bom.framework/Bom
0x3603d000 - 0x360acfff ProofReader armv7 <d2e62a8ab7e1460c7f6de8913c703e6d> /System/Library/PrivateFrameworks/ProofReader.framework/ProofReader
0x3612f000 - 0x36137fff libkxld.dylib armv7 <854e82fe66feef01e54c7c8a209851ac> /usr/lib/system/libkxld.dylib
0x36138000 - 0x3616ffff Security armv7 <cd28e102950634ae7167ddee9c686d36> /System/Library/Frameworks/Security.framework/Security
0x36170000 - 0x361bdfff libsqlite3.dylib armv7 <55038e5c1d4d0dbdd94295e8cad7a9a4> /usr/lib/libsqlite3.dylib
0x361be000 - 0x361f8fff IOKit armv7 <eb932cc42d60e55d9a4d0691bcc3d9ad> /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit
0x3623f000 - 0x3627efff libGLImage.dylib armv7 <a7c117c92607a512823d307b8fdd0151> /System/Library/Frameworks/OpenGLES.framework/libGLImage.dylib


问:
liferay display connected user in jsp
I work with liferay 5.2

in my jsp I can get the connected user  with this code :

```<code><%@page import="com.nbs.fw.portal.PortalUtil"%>
String id_employe=PortalUtil.getConnectedUserID(request).toUpperCase();
</code>```

but now I want to know the role of connected user

Updated :

```<code><%@page import="com.liferay.portal.service.RoleServiceUtil"%>
<%@ page import="com.liferay.portal.model.User" %>
<%@ page import="com.liferay.portal.model.Role" %>
<%@page import="com.liferay.portal.theme.ThemeDisplay"%>
<%@page import="com.liferay.portal.util.WebKeys"%>

<%
User user = ((ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY)).getUser();
List<Role> roles = (List<Role>) RoleServiceUtil.getUserRoles(user.getUserId());
for (Role role : roles) {
out.println( role.getRoleId() );
}

%>
</code>```

but when I test I have an error :

```<code>Caused by: org.apache.jasper.JasperException: Impossible de compiler la classe pour la JSP:

An error occurred at line: 13 in the generated java file
Only a type can be imported. com.liferay.portal.util.WebKeys resolves to a package

Une erreur s'est produite ï¿½ la ligne: 1 208 dans le fichier jsp: /jsp/_correspondencelist/html/correspondenceList.jsp
WebKeys.THEME_DISPLAY cannot be resolved to a type
1205:               %>
1206:
1207: <%
1208: User user = ((ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY)).getUser();
1209: List<Role> roles = (List<Role>) RoleServiceUtil.getUserRoles(user.getUserId());
1210: for (Role role : roles) {
1211: out.println( role.getRoleId() );

Stacktrace:
    at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
</code>```

答:
It seems that you didn't import all classes like WebKeys or ThemeDisplay

```<code><%@ page import="com.liferay.portal.theme.ThemeDisplay" %>
<%@ page import="com.liferay.portal.util.WebKeys" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>

<liferay-theme:defineObjects />
</code>```

Title: liferay display connected user in jsp

Body:
I work with liferay 5.2

in my jsp I can get the connected user  with this code :

<%@page import="com.nbs.fw.portal.PortalUtil"%>
String id_employe=PortalUtil.getConnectedUserID(request).toUpperCase();

but now I want to know the role of connected user

Updated :

<%@page import="com.liferay.portal.service.RoleServiceUtil"%>
<%@ page import="com.liferay.portal.model.User" %>
<%@ page import="com.liferay.portal.model.Role" %>
<%@page import="com.liferay.portal.theme.ThemeDisplay"%>
<%@page import="com.liferay.portal.util.WebKeys"%>

<%
User user = ((ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY)).getUser();
List<Role> roles = (List<Role>) RoleServiceUtil.getUserRoles(user.getUserId());
for (Role role : roles) {
out.println( role.getRoleId() );
}

%>

but when I test I have an error :

Caused by: org.apache.jasper.JasperException: Impossible de compiler la classe pour la JSP:

An error occurred at line: 13 in the generated java file
Only a type can be imported. com.liferay.portal.util.WebKeys resolves to a package

Une erreur s'est produite ï¿½ la ligne: 1 208 dans le fichier jsp: /jsp/_correspondencelist/html/correspondenceList.jsp
WebKeys.THEME_DISPLAY cannot be resolved to a type
1205:               %>
1206:
1207: <%
1208: User user = ((ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY)).getUser();
1209: List<Role> roles = (List<Role>) RoleServiceUtil.getUserRoles(user.getUserId());
1210: for (Role role : roles) {
1211: out.println( role.getRoleId() );

Stacktrace:
    at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)

Body:
It seems that you didn't import all classes like WebKeys or ThemeDisplay

<%@ page import="com.liferay.portal.theme.ThemeDisplay" %>
<%@ page import="com.liferay.portal.util.WebKeys" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>

<liferay-theme:defineObjects />


问:
Failed to exec start script
Angular: 5.0.1 /
Angular CLI: 1.5.0 /
Node: 8.9.1 /
npm: 5.5.1 /
Os: win32 x64

I get the below error when executing "npm start" in the terminal/command prompt. Can anyone help me resolve this? I have spent a whole day trying to fix it with no luck.

Here is the scripts section of my package.json

```<code>"scripts": {
    "start": "webpack-dev-server --inline --progress --port 8080"
  },
</code>```

webpack.config.js

```<code>module.exports = require('./config/webpack.dev.js');
</code>```

webpack.common.js

```<code>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['.ts', '.js']
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        loaders: [
          {
            loader: 'awesome-typescript-loader',
            options: { configFileName: helpers.root('src', 'tsconfig.json') }
          } , 'angular2-template-loader'
        ]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file-loader?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw-loader'
      }
    ]
  },

  plugins: [
    // Workaround for angular/angular#11580
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)@angular/,
      helpers.root('./src'), // location of your src
      {} // a map of your routes
    ),

    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
};
</code>```

webpack.dev.js

```<code>var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-module-eval-source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
  },

  plugins: [
    new ExtractTextPlugin('[name].css')
  ],

  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});
</code>```

webpack.prod.js

```<code>var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

module.exports = webpackMerge(commonConfig, {
  devtool: 'source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].[hash].js',
    chunkFilename: '[id].[hash].chunk.js'
  },

  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
      mangle: {
        keep_fnames: true
      }
    }),
    new ExtractTextPlugin('[name].[hash].css'),
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(ENV)
      }
    }),
    new webpack.LoaderOptionsPlugin({
      htmlLoader: {
        minimize: false // workaround for ng2
      }
    })
  ]
});
</code>```

Here is the error

0 info it worked if it ends with ok 1 verbose cli [ 'C:\Program
  Files\nodejs\node.exe', 1 verbose cli   'C:\Program
  Files\nodejs\node_modules\npm\bin\npm-cli.js', 1 verbose cli

  'start' ] 2 info using npm@5.5.1 3 info using node@v8.9.1 4 verbose
  run-script [ 'prestart', 'start', 'poststart' ] 5 info lifecycle
  angular-io-example@1.0.0~prestart: angular-io-example@1.0.0 6 info
  lifecycle angular-io-example@1.0.0~start: angular-io-example@1.0.0 7
  verbose lifecycle angular-io-example@1.0.0~start: unsafe-perm in
  lifecycle true 8 verbose lifecycle angular-io-example@1.0.0~start:
  PATH: C:\Program
  Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\Users\cbonsu\Downloads\sample_pro\webpack\node_modules.bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
  Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program
  Files\Git\cmd;C:\Program Files (x86)\Microsoft SQL
  Server\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files\Microsoft SQL Server\Client
  SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files
  (x86)\Microsoft SQL
  Server\130\Tools\Binn\ManagementStudio\;C:\WINDOWS\system32\config\systemprofile.dnx\bin;C:\Program
  Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft\Web Platform
  Installer\;C:\Program Files\dotnet\;C:\Program
  Files\nodejs\;C:\Users\cbonsu\AppData\Local\Microsoft\WindowsApps;C:\Program
  Files\nodejs;C:\Program Files\Microsoft VS
  Code\bin;C:\Users\cbonsu\AppData\Roaming\npm 9 verbose lifecycle
  angular-io-example@1.0.0~start: CWD:
  C:\Users\cbonsu\Downloads\sample_pro\webpack 10 silly lifecycle
  angular-io-example@1.0.0~start: Args: [ '/d /s /c', 10 silly lifecycle
  'webpack-dev-server --inline --progress --port 8080' ] 11 silly
  lifecycle angular-io-example@1.0.0~start: Returned: code: 1  signal:
  null 12 info lifecycle angular-io-example@1.0.0~start: Failed to exec
  start script 13 verbose stack Error: angular-io-example@1.0.0 start:
  webpack-dev-server --inline --progress --port 8080 13 verbose stack
  Exit status 1 13 verbose stack     at EventEmitter.
  (C:\Program
  Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:280:16)
  13 verbose stack     at emitTwo (events.js:126:13) 13 verbose stack

  at EventEmitter.emit (events.js:214:7) 13 verbose stack     at
  ChildProcess. (C:\Program
  Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
  13 verbose stack     at emitTwo (events.js:126:13) 13 verbose stack

  at ChildProcess.emit (events.js:214:7) 13 verbose stack     at
  maybeClose (internal/child_process.js:925:16) 13 verbose stack     at
  Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
  14 verbose pkgid angular-io-example@1.0.0 15 verbose cwd
  C:\Users\cbonsu\Downloads\sample_pro\webpack 16 verbose Windows_NT
  10.0.15063 17 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js"
  "start" 18 verbose node v8.9.1 19 verbose npm  v5.5.1 20 error code
  ELIFECYCLE 21 error errno 1 22 error angular-io-example@1.0.0 start:
  webpack-dev-server --inline --progress --port 8080 22 error Exit
  status 1 23 error Failed at the angular-io-example@1.0.0 start script.
  23 error This is probably not a problem with npm. There is likely
  additional logging output above. 24 verbose exit [ 1, true ]

答: I have discovered an easier approach to this. Discard the "npm start" and webpack approach altogether and use angular-cli. With angular-cli, calling "ng build --prod" handles everything (aot etc). Behind the scene it uses webpack but it handles all the complications involved so developers don't have to.</p>

Title: Failed to exec start script

Body:
Angular: 5.0.1 /
Angular CLI: 1.5.0 /
Node: 8.9.1 /
npm: 5.5.1 /
Os: win32 x64

I get the below error when executing "npm start" in the terminal/command prompt. Can anyone help me resolve this? I have spent a whole day trying to fix it with no luck.

Here is the scripts section of my package.json

"scripts": {
    "start": "webpack-dev-server --inline --progress --port 8080"
  },

webpack.config.js

module.exports = require('./config/webpack.dev.js');

webpack.common.js

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['.ts', '.js']
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        loaders: [
          {
            loader: 'awesome-typescript-loader',
            options: { configFileName: helpers.root('src', 'tsconfig.json') }
          } , 'angular2-template-loader'
        ]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file-loader?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw-loader'
      }
    ]
  },

  plugins: [
    // Workaround for angular/angular#11580
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)@angular/,
      helpers.root('./src'), // location of your src
      {} // a map of your routes
    ),

    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
};

webpack.dev.js

var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-module-eval-source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
  },

  plugins: [
    new ExtractTextPlugin('[name].css')
  ],

  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});

webpack.prod.js

var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

module.exports = webpackMerge(commonConfig, {
  devtool: 'source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].[hash].js',
    chunkFilename: '[id].[hash].chunk.js'
  },

  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
      mangle: {
        keep_fnames: true
      }
    }),
    new ExtractTextPlugin('[name].[hash].css'),
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(ENV)
      }
    }),
    new webpack.LoaderOptionsPlugin({
      htmlLoader: {
        minimize: false // workaround for ng2
      }
    })
  ]
});

Here is the error

0 info it worked if it ends with ok 1 verbose cli [ 'C:\Program
  Files\nodejs\node.exe', 1 verbose cli   'C:\Program
  Files\nodejs\node_modules\npm\bin\npm-cli.js', 1 verbose cli

  'start' ] 2 info using npm@5.5.1 3 info using node@v8.9.1 4 verbose
  run-script [ 'prestart', 'start', 'poststart' ] 5 info lifecycle
  angular-io-example@1.0.0~prestart: angular-io-example@1.0.0 6 info
  lifecycle angular-io-example@1.0.0~start: angular-io-example@1.0.0 7
  verbose lifecycle angular-io-example@1.0.0~start: unsafe-perm in
  lifecycle true 8 verbose lifecycle angular-io-example@1.0.0~start:
  PATH: C:\Program
  Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\Users\cbonsu\Downloads\sample_pro\webpack\node_modules.bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
  Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program
  Files\Git\cmd;C:\Program Files (x86)\Microsoft SQL
  Server\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files\Microsoft SQL Server\Client
  SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files
  (x86)\Microsoft SQL
  Server\130\Tools\Binn\ManagementStudio\;C:\WINDOWS\system32\config\systemprofile.dnx\bin;C:\Program
  Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft\Web Platform
  Installer\;C:\Program Files\dotnet\;C:\Program
  Files\nodejs\;C:\Users\cbonsu\AppData\Local\Microsoft\WindowsApps;C:\Program
  Files\nodejs;C:\Program Files\Microsoft VS
  Code\bin;C:\Users\cbonsu\AppData\Roaming\npm 9 verbose lifecycle
  angular-io-example@1.0.0~start: CWD:
  C:\Users\cbonsu\Downloads\sample_pro\webpack 10 silly lifecycle
  angular-io-example@1.0.0~start: Args: [ '/d /s /c', 10 silly lifecycle
  'webpack-dev-server --inline --progress --port 8080' ] 11 silly
  lifecycle angular-io-example@1.0.0~start: Returned: code: 1  signal:
  null 12 info lifecycle angular-io-example@1.0.0~start: Failed to exec
  start script 13 verbose stack Error: angular-io-example@1.0.0 start:
  webpack-dev-server --inline --progress --port 8080 13 verbose stack
  Exit status 1 13 verbose stack     at EventEmitter.
  (C:\Program
  Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:280:16)
  13 verbose stack     at emitTwo (events.js:126:13) 13 verbose stack

  at EventEmitter.emit (events.js:214:7) 13 verbose stack     at
  ChildProcess. (C:\Program
  Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
  13 verbose stack     at emitTwo (events.js:126:13) 13 verbose stack

  at ChildProcess.emit (events.js:214:7) 13 verbose stack     at
  maybeClose (internal/child_process.js:925:16) 13 verbose stack     at
  Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
  14 verbose pkgid angular-io-example@1.0.0 15 verbose cwd
  C:\Users\cbonsu\Downloads\sample_pro\webpack 16 verbose Windows_NT
  10.0.15063 17 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js"
  "start" 18 verbose node v8.9.1 19 verbose npm  v5.5.1 20 error code
  ELIFECYCLE 21 error errno 1 22 error angular-io-example@1.0.0 start:
  webpack-dev-server --inline --progress --port 8080 22 error Exit
  status 1 23 error Failed at the angular-io-example@1.0.0 start script.
  23 error This is probably not a problem with npm. There is likely
  additional logging output above. 24 verbose exit [ 1, true ]


问:
Why does PHP not process my request?
I have a PHP project in which I have an index.html with a simple form:

```<code>    <p>Test connection</p>
    <form action="Servicios.php" method="post">
        <input type='submit' name='Test' value='Test'>
    </form>
</code>```

in Servicios.php Im trying to process it like this

```<code><?php
   echo "can you print this";
    if($_SERVER["REQUEST_METHOD"]=="POST" )
    {
      if(!empty($_POST["Test"]))
      {
         echo "Hello world";
      }
    }
</code>```

But it doesn't works, thats because it never evaluates the first if like "true". The first echo at the top does works but if I do an echo to $_SERVER["REQUEST_METHOD"] it doesn't give me anything. I've tried with isset($_POST['Hola']) but I had the same result.

This only happens in the project I have in an internet host. I wrote this exact same code in my local computer using netbeans and xampp and it works perfectly. I have no idea why.

I have the feeling that I'm making some silly mistake but I cant find it.

My host is an Ubuntu server from the ec2 Amazon Web Services.

Edit
this is the output of <?=print_r($_SERVER);?> in Servicios.php
I replaced the parts where my ip is showed with [ip]

```<code>Array (
    [HTTP_HOST] => [ip]
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => es-MX,es-ES;q=0.9,es;q=0.7,es-AR;q=0.6,es-CL;q=0.4,en-US;q=0.3,en;q=0.1
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_REFERER] => http://[ip]/ProyectoPM/
    [CONTENT_TYPE] => application/x-www-form-urlencoded
    [CONTENT_LENGTH] => 11
    [HTTP_CONNECTION] => keep-alive
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    [SERVER_SIGNATURE] => Apache/2.4.18 (Ubuntu) Server at [ip] Port 80
    [SERVER_SOFTWARE] => Apache/2.4.18 (Ubuntu)
    [SERVER_NAME] => [ip]
    [SERVER_ADDR] => 172.31.43.105
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => 189.208.87.127
    [DOCUMENT_ROOT] => /var/www/html
    [REQUEST_SCHEME] => http
    [CONTEXT_PREFIX] =>
    [CONTEXT_DOCUMENT_ROOT] => /var/www/html
    [SERVER_ADMIN] => webmaster@localhost
    [SCRIPT_FILENAME] => /var/www/html/ProyectoPM/Servicios.php
    [REMOTE_PORT] => 5672
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => POST
    [QUERY_STRING] =>
    [REQUEST_URI] => /ProyectoPM/Servicios.php
    [SCRIPT_NAME] => /ProyectoPM/Servicios.php
    [PHP_SELF] => /ProyectoPM/Servicios.php
    [REQUEST_TIME_FLOAT] => 1510846404.812
    [REQUEST_TIME] => 1510846404 ) 1
</code>```

This is in the array it returns with <?=var_dump($_SERVER); ?>

```<code> ["SERVER_PROTOCOL"]=> string(8) "HTTP/1.1"
 ["REQUEST_METHOD"]=> string(4) "POST"
 ["QUERY_STRING"]=> string(0) ""
 ["REQUEST_URI"]=> string(25) "/ProyectoPM/Servicios.php"
 ["SCRIPT_NAME"]=> string(25) "/ProyectoPM/Servicios.php"
 ["PHP_SELF"]=> string(25) "/ProyectoPM/Servicios.php"
 ["REQUEST_TIME_FLOAT"]=> float(1510847672.582)
 ["REQUEST_TIME"]=> int(1510847672) }
</code>```

A more important edit
At first I said that a simple echo "can you print this"; worked in the host, now I see that it doesn't either. When I move to Servicios.php in by clicking my button in index.html the browser moves to Servicios.php (it displays it in the url) but it simply doesnt show anything. It only shows something if i delete all the code an put a instrucion like <?=print_r($_SERVER);?>  which result I already put above.

答:
```<code>if(isset($_POST['Test'])){
echo 'Hello world';
}
</code>```

This should work. This is checking is button is submitted using POST method. This should be enough check to see if form has been submitted.

Title: Why does PHP not process my request?

Body:
I have a PHP project in which I have an index.html with a simple form:

Test connection

    <form action="Servicios.php" method="post">
        <input type='submit' name='Test' value='Test'>
    </form>

in Servicios.php Im trying to process it like this

<?php
   echo "can you print this";
    if($_SERVER["REQUEST_METHOD"]=="POST" )
    {
      if(!empty($_POST["Test"]))
      {
         echo "Hello world";
      }
    }

But it doesn't works, thats because it never evaluates the first if like "true". The first echo at the top does works but if I do an echo to $_SERVER["REQUEST_METHOD"] it doesn't give me anything. I've tried with isset($_POST['Hola']) but I had the same result.

This only happens in the project I have in an internet host. I wrote this exact same code in my local computer using netbeans and xampp and it works perfectly. I have no idea why.

I have the feeling that I'm making some silly mistake but I cant find it.

My host is an Ubuntu server from the ec2 Amazon Web Services.

Edit
this is the output of <?=print_r($_SERVER);?> in Servicios.php
I replaced the parts where my ip is showed with [ip]

Array (
    [HTTP_HOST] => [ip]
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => es-MX,es-ES;q=0.9,es;q=0.7,es-AR;q=0.6,es-CL;q=0.4,en-US;q=0.3,en;q=0.1
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_REFERER] => http://[ip]/ProyectoPM/
    [CONTENT_TYPE] => application/x-www-form-urlencoded
    [CONTENT_LENGTH] => 11
    [HTTP_CONNECTION] => keep-alive
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    [SERVER_SIGNATURE] => Apache/2.4.18 (Ubuntu) Server at [ip] Port 80
    [SERVER_SOFTWARE] => Apache/2.4.18 (Ubuntu)
    [SERVER_NAME] => [ip]
    [SERVER_ADDR] => 172.31.43.105
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => 189.208.87.127
    [DOCUMENT_ROOT] => /var/www/html
    [REQUEST_SCHEME] => http
    [CONTEXT_PREFIX] =>
    [CONTEXT_DOCUMENT_ROOT] => /var/www/html
    [SERVER_ADMIN] => webmaster@localhost
    [SCRIPT_FILENAME] => /var/www/html/ProyectoPM/Servicios.php
    [REMOTE_PORT] => 5672
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => POST
    [QUERY_STRING] =>
    [REQUEST_URI] => /ProyectoPM/Servicios.php
    [SCRIPT_NAME] => /ProyectoPM/Servicios.php
    [PHP_SELF] => /ProyectoPM/Servicios.php
    [REQUEST_TIME_FLOAT] => 1510846404.812
    [REQUEST_TIME] => 1510846404 ) 1

This is in the array it returns with <?=var_dump($_SERVER); ?>

 ["SERVER_PROTOCOL"]=> string(8) "HTTP/1.1"
 ["REQUEST_METHOD"]=> string(4) "POST"
 ["QUERY_STRING"]=> string(0) ""
 ["REQUEST_URI"]=> string(25) "/ProyectoPM/Servicios.php"
 ["SCRIPT_NAME"]=> string(25) "/ProyectoPM/Servicios.php"
 ["PHP_SELF"]=> string(25) "/ProyectoPM/Servicios.php"
 ["REQUEST_TIME_FLOAT"]=> float(1510847672.582)
 ["REQUEST_TIME"]=> int(1510847672) }

A more important edit
At first I said that a simple echo "can you print this"; worked in the host, now I see that it doesn't either. When I move to Servicios.php in by clicking my button in index.html the browser moves to Servicios.php (it displays it in the url) but it simply doesnt show anything. It only shows something if i delete all the code an put a instrucion like <?=print_r($_SERVER);?>  which result I already put above.

Body:
if(isset($_POST['Test'])){
echo 'Hello world';
}

This should work. This is checking is button is submitted using POST method. This should be enough check to see if form has been submitted.


问:
Deploy Python virtualenv on no internet machine with different system
I need to deploy python application to a no internet server.

I have created a virtual environment on my host machine which uses Ubuntu. This contains python script with a variety of non-standard libraries. I have used option --relocatable to make the links relative.

I have copied over the environment to my client machine which uses RedHat and has no access to the internet.

After activating it using source my_project/bin/activate the environment does not seem to be working - the python used is standard system one and the libraries don't work.

How can the virtual environment be deployed on a different server?

Edit: this is normally done through the creation of requirement.txt file and then using pip to install the libraries on the target machine, however in this case it's not possible as the machine is offline.

答:
For anyone dealing with the same problem:
The quickest way for me was to:

Create a VirtualBox with the target system on the internet machine

Download wheel files using pip download

Migrate to the target machine

Install with pip install --no-index --find-links pip_libs/ requests


问:
Underlying element not clickable
I have to render two elements in two different (bootstrap's) rows, the bottom one must be behind the topmost. I can't understand why the underlying one is not catching pointer events.

.smaller-square {
  width: 50px;
  height: 50px;
  background-color: yellow
}

.bigger-square {
  width: 100px;
  height: 100px;
  background-color: green
}

.overlay {
  z-index: 0;
}

.underlay {
  z-index: -1;
  position: relative;
  top: -5px;
  left: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row overlay">
  <div class="smaller-square" onclick="alert('yellow');">
  </div>
  </div>
  <div class="row underlay">
  <div class="bigger-square" onclick="alert('green');">
  </div>
  </div>
</div></code>```

答:
It's because you have a z-index: -1 on the green one which places it behind the body and html elements.  Your event is probably being captured by the body.  Try adding a wrapper and setting a z-index on it or applying z-index to the container.

.smaller-square {
  width: 50px;
  height: 50px;
  background-color: yellow
}

.bigger-square {
  width: 100px;
  height: 100px;
  background-color: green
}

.overlay {
  z-index: 0;
}

.underlay {
  z-index: -1;
  position: relative;
  top: -5px;
  left: 0px;
}

.container {
  position: relative;
  z-index: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row overlay">
  <div class="smaller-square" onclick="alert('yellow');">
  </div>
  </div>
  <div class="row underlay">
  <div class="bigger-square" onclick="alert('green');">
  </div>
  </div>
</div></code>```

Title: Underlying element not clickable

Body:
I have to render two elements in two different (bootstrap's) rows, the bottom one must be behind the topmost. I can't understand why the underlying one is not catching pointer events.

.smaller-square {
  width: 50px;
  height: 50px;
  background-color: yellow
}

.bigger-square {
  width: 100px;
  height: 100px;
  background-color: green
}

.overlay {
  z-index: 0;
}

.underlay {
  z-index: -1;
  position: relative;
  top: -5px;
  left: 0px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Body:
It's because you have a z-index: -1 on the green one which places it behind the body and html elements.  Your event is probably being captured by the body.  Try adding a wrapper and setting a z-index on it or applying z-index to the container.

.smaller-square {
  width: 50px;
  height: 50px;
  background-color: yellow
}

.bigger-square {
  width: 100px;
  height: 100px;
  background-color: green
}

.overlay {
  z-index: 0;
}

.underlay {
  z-index: -1;
  position: relative;
  top: -5px;
  left: 0px;
}

.container {
  position: relative;
  z-index: 0;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row overlay">
  <div class="smaller-square" onclick="alert('yellow');">
  </div>
  </div>
  <div class="row underlay">
  <div class="bigger-square" onclick="alert('green');">
  </div>
  </div>
</div>


问:
Type mismatch in AutoHotkey Excel
I am trying to get input from a user, lookup the input value in an Excel column and return the value of the cell on the right side of the matching value.

This is what I came up with. As long as I replace %index% with a number, it will return a value from the Excel file.

The error I receive tells me there is a 'type mismatch' where I use %index% in

```<code>value := workbook.Sheets("Sheet1").Cells(%index%, 1).Value
</code>```

Any ideas how to fix the type mismatch?

```<code>#a::
workbook := ComObjGet("somepath\tester.xlsx")

InputBox, OutputVar, Question 1, What are you looking for?
if (OutputVar)
   MsgBox, Let me do this for you.
   intent = OutputVar

index = 1
value = ""

Loop {
    index := %index% + 1
    value := workbook.Sheets("Sheet1").Cells(%index%, 1).Value
}
Until %intent% = %value%

SendInput, workbook.Sheets("Sheet1").Cells(%index%, 2).Value

Return
</code>```

答:
Use index, not %index%, in expressions. Also, you can use the built-in A_INDEX variable inside of loops

Here's your corrected code:

```<code>#a::
  workbook := ComObjGet("somepath\tester.xlsx")
  MAX_ROWS := 10

  InputBox intent, Question 1, What are you looking for?

  if ( ErrorLevel == 0 && intent ) {
    Loop %MAX_ROWS% {
      if ( intent == workbook.Sheets("Sheet1").Cells(A_Index, 1).Value ) {
         SendInput % workbook.Sheets("Sheet1").Cells(A_Index, 2).Value
         return
      }
    }
    MsgBox 48, Not Found, "%intent%" not found in column a
  }
  return
</code>```

Notes:

You cannot use substitution when a command takes an expression

ErrorLevel == 0 means OK was pressed. See InputBox

SendInput % makes the line use expression mode; everything following "% " is evaluated as an expression

Your loop never exits if intent is not found in the spreadsheet

Title: Type mismatch in AutoHotkey Excel

Body:
I am trying to get input from a user, lookup the input value in an Excel column and return the value of the cell on the right side of the matching value.

This is what I came up with. As long as I replace %index% with a number, it will return a value from the Excel file.

The error I receive tells me there is a 'type mismatch' where I use %index% in

value := workbook.Sheets("Sheet1").Cells(%index%, 1).Value

Any ideas how to fix the type mismatch?

#a::
workbook := ComObjGet("somepath\tester.xlsx")

InputBox, OutputVar, Question 1, What are you looking for?
if (OutputVar)
   MsgBox, Let me do this for you.
   intent = OutputVar

index = 1
value = ""

Loop {
    index := %index% + 1
    value := workbook.Sheets("Sheet1").Cells(%index%, 1).Value
}
Until %intent% = %value%

SendInput, workbook.Sheets("Sheet1").Cells(%index%, 2).Value

Return

Body:
Use index, not %index%, in expressions. Also, you can use the built-in A_INDEX variable inside of loops

Here's your corrected code:

#a::
  workbook := ComObjGet("somepath\tester.xlsx")
  MAX_ROWS := 10

  InputBox intent, Question 1, What are you looking for?

  if ( ErrorLevel == 0 && intent ) {
    Loop %MAX_ROWS% {
      if ( intent == workbook.Sheets("Sheet1").Cells(A_Index, 1).Value ) {
         SendInput % workbook.Sheets("Sheet1").Cells(A_Index, 2).Value
         return
      }
    }
    MsgBox 48, Not Found, "%intent%" not found in column a
  }
  return

Notes:

You cannot use substitution when a command takes an expression

ErrorLevel == 0 means OK was pressed. See InputBox

SendInput % makes the line use expression mode; everything following "% " is evaluated as an expression

Your loop never exits if intent is not found in the spreadsheet


问:
Secure method of saving credentials in Android
I'm developing an Android app. For authentication the user needs to enter the user name and password and the server returns an expiring authentication token.

Currently I'm saving the token but not the credentials. What is the preferred safest method to save the credentials locally so that when the token authentication fails I can re-login the user using the saved credentials in the background without having the user to enter their credentials again.

I'm aware of saving data using SharedPreferences. But are they really secure? Can I use AccountManager for this purpose?

答:
Having a background service that when the token expires would login the user again automatically would not be very secure.

Is it not possible to make the expiry time of the told longer? As saving the credentials and trying to login periodically would not be very secure.


问:
Entity Framework generic Where for entities that inherit from a specific class
Here I have a generic Repository class I copied from a tutorial page, but specifically my problem is on the two last functions. On my project I have several catalog entities that inherit from CRUDProperties class and there is a property "Activo" in all of them, what I currently want to do is that if the entity inherits from CRUDProperties class I get all the entities with Activo property on true, and if they do not inherit from that class it just gets all entities. But the compiler throws an error stating T is already defined. What should I do?</p>

```<code>public class Repository<T> where T : class
{
    private readonly projectEntities context;
    private IDbSet<T> entities;
    string errorMessage = string.Empty;

    public Repository(projectEntities context)
    {
        this.context = context;
    }

    public T GetById(object id)
    {
        return context.Set<T>().Find(id);
    }

    // This is the function that throws me a compilation error
    public virtual IList<T> GetAll<T>() where T : CRUDProperties
    {
        return context.Set<T>().Where(c => c.Activo).ToList();
    }

    public virtual IList<T> GetAll()
    {
        return context.Set<T>().ToList();
    }
}
</code>```

答:
using this method you can pass custom where clause to to your GetAll Method

```<code>public virtual IList<T> GetAll<T>(Expression<Func<T, bool>> predicate)
{
    return context.Set<T>().Where(predicate).ToList();
}
</code>```

In this method we first check if the T type have Activo property, If find this property so we create a custom expression tree and replace with default predicate that returns all records, this function only returns records that have true value in activo property.

```<code>public virtual IList<T> GetAll<T>()
{
    Expression<Func<T, bool>> predicate = t => true;
    if(typeof(T).GetProperty("Activo") != null)
    {

        var epx = Expression.Parameter(typeof(T), "x");
        Expression left =  Expression.PropertyOrField(epx, "Activo");
        Expression right = Expression.Constant(true);
        Expression e1 = Expression.Equal(left, right);

        predicate = Expression.Lambda<Func<T, bool>>(e1, new ParameterExpression[] { epx });
    }
    return context.Set<T>().Where(predicate);
}
</code>```

Body:
Here I have a generic Repository class I copied from a tutorial page, but specifically my problem is on the two last functions. On my project I have several catalog entities that inherit from CRUDProperties class and there is a property "Activo" in all of them, what I currently want to do is that if the entity inherits from CRUDProperties class I get all the entities with Activo property on true, and if they do not inherit from that class it just gets all entities. But the compiler throws an error stating T is already defined. What should I do?

public class Repository<T> where T : class
{
    private readonly projectEntities context;
    private IDbSet<T> entities;
    string errorMessage = string.Empty;

    public Repository(projectEntities context)
    {
        this.context = context;
    }

    public T GetById(object id)
    {
        return context.Set<T>().Find(id);
    }

    // This is the function that throws me a compilation error
    public virtual IList<T> GetAll<T>() where T : CRUDProperties
    {
        return context.Set<T>().Where(c => c.Activo).ToList();
    }

    public virtual IList<T> GetAll()
    {
        return context.Set<T>().ToList();
    }
}

Body:
using this method you can pass custom where clause to to your GetAll Method

public virtual IList<T> GetAll<T>(Expression<Func<T, bool>> predicate)
{
    return context.Set<T>().Where(predicate).ToList();
}

In this method we first check if the T type have Activo property, If find this property so we create a custom expression tree and replace with default predicate that returns all records, this function only returns records that have true value in activo property.

public virtual IList<T> GetAll<T>()
{
    Expression<Func<T, bool>> predicate = t => true;
    if(typeof(T).GetProperty("Activo") != null)
    {

        var epx = Expression.Parameter(typeof(T), "x");
        Expression left =  Expression.PropertyOrField(epx, "Activo");
        Expression right = Expression.Constant(true);
        Expression e1 = Expression.Equal(left, right);

        predicate = Expression.Lambda<Func<T, bool>>(e1, new ParameterExpression[] { epx });
    }
    return context.Set<T>().Where(predicate);
}


问:
How to find the cumulative sum of numbers in a list?
```<code>time_interval = [4, 6, 12]
</code>```

I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22].

I tried the following:

```<code>t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2
print(t1, t2, t3)  # -> 4 10 22
</code>```

答:
If You want a pythonic way without numpy working in 2.7 this would be my way of doing it

```<code>l = [1,2,3,4]
_d={-1:0}
cumsum=[_d.setdefault(idx, _d[idx-1]+item) for idx,item in enumerate(l)]
</code>```

now let's try it and test it against all other implementations

```<code>import timeit, sys
L=list(range(10000))
if sys.version_info >= (3, 0):
    reduce = functools.reduce
    xrange = range

def sum1(l):
    cumsum=[]
    total = 0
    for v in l:
        total += v
        cumsum.append(total)
    return cumsum

def sum2(l):
    import numpy as np
    return list(np.cumsum(l))

def sum3(l):
    return [sum(l[:i+1]) for i in xrange(len(l))]

def sum4(l):
    return reduce(lambda c, x: c + [c[-1] + x], l, [0])[1:]

def this_implementation(l):
    _d={-1:0}
    return [_d.setdefault(idx, _d[idx-1]+item) for idx,item in enumerate(l)]

# sanity check
sum1(L)==sum2(L)==sum3(L)==sum4(L)==this_implementation(L)
>>> True

# PERFORMANCE TEST
timeit.timeit('sum1(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.001018061637878418

timeit.timeit('sum2(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.000829620361328125

timeit.timeit('sum3(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.4606760001182556

timeit.timeit('sum4(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.18932826995849608

timeit.timeit('this_implementation(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.002348129749298096
</code>```

ContentLicense: CC BY-SA 4.0

Body:
time_interval = [4, 6, 12]

I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22].

I tried the following:

t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2
print(t1, t2, t3)  # -> 4 10 22

Body:
If You want a pythonic way without numpy working in 2.7 this would be my way of doing it

l = [1,2,3,4]
_d={-1:0}
cumsum=[_d.setdefault(idx, _d[idx-1]+item) for idx,item in enumerate(l)]

now let's try it and test it against all other implementations

import timeit, sys
L=list(range(10000))
if sys.version_info >= (3, 0):
    reduce = functools.reduce
    xrange = range

def sum1(l):
    cumsum=[]
    total = 0
    for v in l:
        total += v
        cumsum.append(total)
    return cumsum

def sum2(l):
    import numpy as np
    return list(np.cumsum(l))

def sum3(l):
    return [sum(l[:i+1]) for i in xrange(len(l))]

def sum4(l):
    return reduce(lambda c, x: c + [c[-1] + x], l, [0])[1:]

def this_implementation(l):
    _d={-1:0}
    return [_d.setdefault(idx, _d[idx-1]+item) for idx,item in enumerate(l)]

# sanity check
sum1(L)==sum2(L)==sum3(L)==sum4(L)==this_implementation(L)
>>> True

# PERFORMANCE TEST
timeit.timeit('sum1(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.001018061637878418

timeit.timeit('sum2(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.000829620361328125

timeit.timeit('sum3(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.4606760001182556

timeit.timeit('sum4(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.18932826995849608

timeit.timeit('this_implementation(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
>>> 0.002348129749298096


问:
Updating Python on Mac
I wanted to update my python 2.6.1 to 3.x on mac but I was wondering if it's possible to do it using the terminal or I have to download the installer from python website?

I am asking this question because the installer is not updating my terminal python version.

答:
First, install Homebrew (The missing package manager for macOS) if you haven': Type this in your terminal

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Now you can update your Python to python 3 by this command

brew install python3 && cp /usr/local/bin/python3 /usr/local/bin/python

Python 2 and python 3 can coexist so to open python 3, type python3 instead of python

That's the easiest and the best way.

Title: Updating Python on Mac


问:
Selenium Compound Class Name [unable to insert a value]
I am currently having a hard time inserting a value into a field which is within a Frame, I have tried removing the spaces in the class name but it didn't work

class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"

<textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{
    'input-sm': true,
    'form-control': true,
    'nc-pristine': $ctrl.getPristine(),
    'nc-not-pristine': $ctrl.getNotPristine()
   }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea>```
</div>
</div>
</p>

<p>I have tried in Chrome Developer tool and it worked with this javascript code</p>

<p><strong>Chrome Console Developper Javascript</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';</code>```

In Selenium I tried with these 2 ways none of them work:

Using Javascript

```<code>IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';");
</code>```

Error Message:

```<code> System.InvalidOperationException occurred
  HResult=0x80131509
  Message=unknown error: Cannot set property 'value' of undefined
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
   at ConsoleApp5.Program.Main(String[] args)
</code>```

Using cssSelector, removing the spacing in the Class Name and replacing it with dots

```<code>driver.FindElement(By.CssSelector("ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched")).SendKeys("Hello World");
</code>```

Error Message

```<code>  OpenQA.Selenium.NoSuchElementException occurred
  HResult=0x80131500
  Message=no such element: Unable to locate element: {"method":"css selector","selector":"ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched"}
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByCssSelector(String cssSelector)
   at OpenQA.Selenium.By.<>c__DisplayClass23_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
</code>```

答:
Try the following code block :</p>

```<code>IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].click()");
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World'");
</code>```

Body:
I am currently having a hard time inserting a value into a field which is within a Frame, I have tried removing the spaces in the class name but it didn't work

class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"

<textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{
    'input-sm': true,
    'form-control': true,
    'nc-pristine': $ctrl.getPristine(),
    'nc-not-pristine': $ctrl.getNotPristine()
   }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea>

I have tried in Chrome Developer tool and it worked with this javascript code

Chrome Console Developper Javascript

document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';

In Selenium I tried with these 2 ways none of them work:

Using Javascript

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';");

Error Message:

 System.InvalidOperationException occurred
  HResult=0x80131509
  Message=unknown error: Cannot set property 'value' of undefined
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
   at ConsoleApp5.Program.Main(String[] args)

Using cssSelector, removing the spacing in the Class Name and replacing it with dots

driver.FindElement(By.CssSelector("ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched")).SendKeys("Hello World");

Error Message

  OpenQA.Selenium.NoSuchElementException occurred
  HResult=0x80131500
  Message=no such element: Unable to locate element: {"method":"css selector","selector":"ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched"}
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByCssSelector(String cssSelector)
   at OpenQA.Selenium.By.<>c__DisplayClass23_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)

Body:
Try the following code block :

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].click()");
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World'");