问:
Find large number of consecutive values fulfilling condition in a numpy array
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a period in time.

An extremely simple way to do this is something like this:

```<code>values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0" for x in samples))
pattern = re.compile('1{%d,}'%int(MIN_SILENCE))
for match in pattern.finditer(values):
   # code goes here
</code>```

The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.

Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?

答:
Here's a numpy-based solution.

I think (?) it should be faster than the other options. Hopefully it's fairly clear.

However, it does require a twice as much memory as the various generator-based solutions.  As long as you can hold a single temporary copy of your data in memory (for the diff), and a boolean array of the same length as your data (1-bit-per-element), it should be pretty efficient...

```<code>import numpy as np

def main():
    # Generate some random data
    x = np.cumsum(np.random.random(1000) - 0.5)
    condition = np.abs(x) < 1

    # Print the start and stop indices of each region where the absolute
    # values of x are below 1, and the min and max of each of these regions
    for start, stop in contiguous_regions(condition):
        segment = x[start:stop]
        print start, stop
        print segment.min(), segment.max()

def contiguous_regions(condition):
    """Finds contiguous True regions of the boolean array "condition". Returns
    a 2D array where the first column is the start index of the region and the
    second column is the end index."""

    # Find the indicies of changes in "condition"
    d = np.diff(condition)
    idx, = d.nonzero()

    # We need to start things after the change in "condition". Therefore,
    # we'll shift the index by 1 to the right.
    idx += 1

    if condition[0]:
        # If the start of condition is True prepend a 0
        idx = np.r_[0, idx]

    if condition[-1]:
        # If the end of condition is True, append the length of the array
        idx = np.r_[idx, condition.size] # Edit

    # Reshape the result into two columns
    idx.shape = (-1,2)
    return idx

main()
</code>```

Body:
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a period in time.

An extremely simple way to do this is something like this:

values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0" for x in samples))
pattern = re.compile('1{%d,}'%int(MIN_SILENCE))
for match in pattern.finditer(values):
   # code goes here

The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.

Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?

Body:
Here's a numpy-based solution.

I think (?) it should be faster than the other options. Hopefully it's fairly clear.

However, it does require a twice as much memory as the various generator-based solutions.  As long as you can hold a single temporary copy of your data in memory (for the diff), and a boolean array of the same length as your data (1-bit-per-element), it should be pretty efficient...

import numpy as np

def main():
    # Generate some random data
    x = np.cumsum(np.random.random(1000) - 0.5)
    condition = np.abs(x) < 1

    # Print the start and stop indices of each region where the absolute
    # values of x are below 1, and the min and max of each of these regions
    for start, stop in contiguous_regions(condition):
        segment = x[start:stop]
        print start, stop
        print segment.min(), segment.max()

def contiguous_regions(condition):
    """Finds contiguous True regions of the boolean array "condition". Returns
    a 2D array where the first column is the start index of the region and the
    second column is the end index."""

    # Find the indicies of changes in "condition"
    d = np.diff(condition)
    idx, = d.nonzero()

    # We need to start things after the change in "condition". Therefore,
    # we'll shift the index by 1 to the right.
    idx += 1

    if condition[0]:
        # If the start of condition is True prepend a 0
        idx = np.r_[0, idx]

    if condition[-1]:
        # If the end of condition is True, append the length of the array
        idx = np.r_[idx, condition.size] # Edit

    # Reshape the result into two columns
    idx.shape = (-1,2)
    return idx

main()


来源: stackexchange

问:
How to add package to conda environment without pip
How can I add a package to an existing conda environment?

If it is a python package I can use pip install <package>, but what if pip does not work?

Is it sufficient to activate the environment and use conda install <package>?

答:
There's an alternative way to do this and I have just tested it on my own mac:

example: i want to install a non-conda package at my python2.7 environment:

go to terminal

activate the desired environment by: source activate py27

after you successfully activated the environment, you can install the package you wanted by: pip install package

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Inheriting UIView - Losing instance variables
Bit of an Objective-C rookie, I've looked around for an answer but haven't been able to find one so forgive me if this is an obvious question.

Basically, I need to draw on the screen segments of a circle (for instance, a 90 degree segment, where a horizontal and vertical line meet at the bottom left and an arc connects the end points). I've managed to achieve this in a custom class called CircleSegment that inherits UIView and overrides drawRect.

My issue is achieving this programatically; I need some way of creating my CircleSegment class and storing in it the desired angle before it draws the segment itself.

Here's what I have so far:

CircleSegment.h

```<code>#import <UIKit/UIKit.h>

@interface CircleSegment : UIView {
    float angleSize;
    UIColor *backColor;
}

-(float)convertDegToRad:(float)degrees;
-(float)convertRadToDeg:(float)radians;

@property (nonatomic) float angleSize;
@property (nonatomic, retain) UIColor *backColor;

@end
</code>```

CircleSegment.m

```<code>#import "CircleSegment.h"

@implementation CircleSegment

@synthesize angleSize;
@synthesize backColor;

// INITIALISATION OVERRIDES
// ------------------------

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        self.opaque = NO;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)setBackgroundColor:(UIColor *)newBGColor
{
    // Ignore.
}
- (void)setOpaque:(BOOL)newIsOpaque
{
    // Ignore.
}

// MATH FUNCTIONS
// --------------

// Converts degrees to radians.
-(float)convertDegToRad:(float)degrees {
    return degrees * M_PI / 180;
}

// Converts radians to degrees.
-(float)convertRadToDeg:(float)radians {
    return radians * 180 / M_PI;
}

// DRAWING CODE
// ------------

- (void)drawRect:(CGRect)rect {

    float endAngle = 360 - angleSize;

    UIBezierPath* aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100)
                                                         radius:100
                                                     startAngle:[self convertDegToRad:270]
                                                       endAngle:[self convertDegToRad:endAngle]
                                                      clockwise:YES];

    [aPath addLineToPoint:CGPointMake(100.0, 100.0)];

    [aPath closePath];

    CGContextRef aRef = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(aRef, backColor.CGColor);

    CGContextSaveGState(aRef);

    aPath.lineWidth = 1;

    [aPath fill];
    [aPath stroke];

    //CGContextRestoreGState(aRef);

}

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

Note that the .m file is a bit messy with various bits of test code...

So essentially I want to create an instance of CircleSegment, store an angle in the angleSize property, draw a segment based on that angle and then add that view to the main app view to display it...

To try and achieve that, I've add the following test code to viewDidLoad on my ViewController:

```<code>CircleSegment *seg1 = [[CircleSegment alloc] init];
seg1.backColor = [UIColor greenColor];
seg1.angleSize = 10;

[self.view addSubview:seg1];
</code>```

It seems to store the UIColor and angleSize fine when I breakpoint those places, however if I place a breakpoint in drawRect which I overrode on CircleSegment.m, the values have reverted back to nil values (or whatever the correct term would be, feel free to correct me).

I'd really appreciate it if someone could point me in the right direction!

Thanks

答:
Try using self.angleSize in your DrawRect method (same with backColor).  In your test method, replace 10 with 10.0 (to ensure it's setting it as a float).

Also, don't forget to release backColor in your dealloc.

ContentLicense: CC BY-SA 2.5

Body:
Bit of an Objective-C rookie, I've looked around for an answer but haven't been able to find one so forgive me if this is an obvious question.

Basically, I need to draw on the screen segments of a circle (for instance, a 90 degree segment, where a horizontal and vertical line meet at the bottom left and an arc connects the end points). I've managed to achieve this in a custom class called CircleSegment that inherits UIView and overrides drawRect.

My issue is achieving this programatically; I need some way of creating my CircleSegment class and storing in it the desired angle before it draws the segment itself.

Here's what I have so far:

CircleSegment.h

#import <UIKit/UIKit.h>

@interface CircleSegment : UIView {
    float angleSize;
    UIColor *backColor;
}

-(float)convertDegToRad:(float)degrees;
-(float)convertRadToDeg:(float)radians;

@property (nonatomic) float angleSize;
@property (nonatomic, retain) UIColor *backColor;

@end

CircleSegment.m

#import "CircleSegment.h"

@implementation CircleSegment

@synthesize angleSize;
@synthesize backColor;

// INITIALISATION OVERRIDES
// ------------------------

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        self.opaque = NO;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)setBackgroundColor:(UIColor *)newBGColor
{
    // Ignore.
}
- (void)setOpaque:(BOOL)newIsOpaque
{
    // Ignore.
}

// MATH FUNCTIONS
// --------------

// Converts degrees to radians.
-(float)convertDegToRad:(float)degrees {
    return degrees * M_PI / 180;
}

// Converts radians to degrees.
-(float)convertRadToDeg:(float)radians {
    return radians * 180 / M_PI;
}

// DRAWING CODE
// ------------

- (void)drawRect:(CGRect)rect {

    float endAngle = 360 - angleSize;

    UIBezierPath* aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100)
                                                         radius:100
                                                     startAngle:[self convertDegToRad:270]
                                                       endAngle:[self convertDegToRad:endAngle]
                                                      clockwise:YES];

    [aPath addLineToPoint:CGPointMake(100.0, 100.0)];

    [aPath closePath];

    CGContextRef aRef = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(aRef, backColor.CGColor);

    CGContextSaveGState(aRef);

    aPath.lineWidth = 1;

    [aPath fill];
    [aPath stroke];

    //CGContextRestoreGState(aRef);

}

- (void)dealloc {
    [super dealloc];
}

@end

Note that the .m file is a bit messy with various bits of test code...

So essentially I want to create an instance of CircleSegment, store an angle in the angleSize property, draw a segment based on that angle and then add that view to the main app view to display it...

To try and achieve that, I've add the following test code to viewDidLoad on my ViewController:

CircleSegment *seg1 = [[CircleSegment alloc] init];
seg1.backColor = [UIColor greenColor];
seg1.angleSize = 10;

[self.view addSubview:seg1];

It seems to store the UIColor and angleSize fine when I breakpoint those places, however if I place a breakpoint in drawRect which I overrode on CircleSegment.m, the values have reverted back to nil values (or whatever the correct term would be, feel free to correct me).

I'd really appreciate it if someone could point me in the right direction!

Thanks


问:
Generic Method That takes unique parameter and returns unique parameters Java
I have a requirement where in the function takes different parameters and returns unique objects. All these functions perform the same operation.

ie.

```<code>public returnObject1 myfunction( paramObject1 a, int a) {
returnObject1 = new returnObject1();
returnObject1.a = paramObject1.a;
return returnObject1;
}

public returnOject2 myfunction( paramObject2 a, int a){
 returnObject2 = new returnObject2();
 returnObject2.a = paramObject2.a;
 return returnObject2;
}
</code>```

As you can see above, both the function do the same task but they take different parameters as input and return different objects.

I would like to minimize writing different functions that does the same task.

Is it possible to write a generic method for this that can substitute the parameters based on the call to the function?

paramObject and returnObject are basically two classes that have different variables. They are not related to each other.

My objective is that I do not want to do function overloading since the functions do almost the same work. I would like to have a single function that can handle different input and different return output.

my aim is to do something like this (if possible):

```<code>public static < E > myfunction( T a, int a ) {
  // do work
}
</code>```

The return type E and the input T can keep varying.

答:
Make interface Foo and implement this interface in both paramObject1 and paramObject2 class. Now your method should be look like:

```<code>public Foo myFunction(Foo foo, int a){
    //Rest of the code.
    return foo;
}
</code>```

Body:
I have a requirement where in the function takes different parameters and returns unique objects. All these functions perform the same operation.

ie.

public returnObject1 myfunction( paramObject1 a, int a) {
returnObject1 = new returnObject1();
returnObject1.a = paramObject1.a;
return returnObject1;
}

public returnOject2 myfunction( paramObject2 a, int a){
 returnObject2 = new returnObject2();
 returnObject2.a = paramObject2.a;
 return returnObject2;
}

As you can see above, both the function do the same task but they take different parameters as input and return different objects.

I would like to minimize writing different functions that does the same task.

Is it possible to write a generic method for this that can substitute the parameters based on the call to the function?

paramObject and returnObject are basically two classes that have different variables. They are not related to each other.

My objective is that I do not want to do function overloading since the functions do almost the same work. I would like to have a single function that can handle different input and different return output.

my aim is to do something like this (if possible):

public static < E > myfunction( T a, int a ) {
  // do work
}

The return type E and the input T can keep varying.

Body:
Make interface Foo and implement this interface in both paramObject1 and paramObject2 class. Now your method should be look like:

public Foo myFunction(Foo foo, int a){
    //Rest of the code.
    return foo;
}


问:
Android Background Location service keeps dying
The aim of this service is to update the current location of the user in background, I don't want a foreground service. Then every 50 location it writes a GMX file.

The issue I am facing is that the service die for no explicit reason after a random number of updates (and often before 50 location points are generated) and then the service starts again. onDestroy is not called at any time.

Here's the service code (launches with startService):

```<code>public class LocationService extends Service {

private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private static LocationManager locationManager;

private final class ServiceHandler extends android.os.Handler{
    private LocationManager locationManager;

    public ServiceHandler(Looper looper){
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        run(locationManager);

    }
}

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {

    Log.i("Service","onHandleIntent lancé");

    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    mServiceHandler.sendMessage(msg);

    Log.i("Service","onHandleIntent lancé");

    return START_STICKY; //permet de redémarrer le service s'il est tué
}

@Override
public void onDestroy() {
    Log.i("DESTROY","IsDestroyed");
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

protected void run(LocationManager locationManager){

    Log.i("Service","Service lancé");

    boolean hasLocationFeature = checkLocationFeature();

    if ( hasLocationFeature && (ACCESS_FINE_LOCATION == PackageManager.PERMISSION_GRANTED || ACCESS_COARSE_LOCATION == PackageManager.PERMISSION_GRANTED ) ) {
        sLocation(locationManager);
    }

}

protected void sLocation(LocationManager locationManagerArg){

    final List<Location> locations = new ArrayList<>();
    final LocationManager locationManager = locationManagerArg;
    Log.i("sLocation","lancé");

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            saveNewLocation(location);
            if (location != null) {
                locations.add(location);
                Log.i("Locationsize", String.valueOf(locations.size()));
                if(locations.size()%50 == 0) {
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() + ".gpx");
                    GPXWriter(file, "test1", locations);
                    locations.clear();
                }
            }
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
        }

        @Override
        public void onProviderEnabled(String s) {
        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,locationListener);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,0,locationListener);

}
</code>```

The method writing the GPX file has no issue. I have tested this on one emulator and two actual devices, the same problem occurs. It might not be related to memory pressure. I have on my phone other LocationService from other applications that have been running for more than 100 hours.

Why does this service die, and what can I do about this?
Thanks

答:
The OS can kill your service at anytime due to memory constraints,needing more resources, battery saving profiles on the device and even now in Android O the OS kill will kill your service when your app has been in the background for only a few minuets. There is nothing you can do that "guarantees" your service lives forever.

Creating a foreground service is your best option to having a long running service

Body:
The aim of this service is to update the current location of the user in background, I don't want a foreground service. Then every 50 location it writes a GMX file.

The issue I am facing is that the service die for no explicit reason after a random number of updates (and often before 50 location points are generated) and then the service starts again. onDestroy is not called at any time.

Here's the service code (launches with startService):

public class LocationService extends Service {

private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private static LocationManager locationManager;

private final class ServiceHandler extends android.os.Handler{
    private LocationManager locationManager;

    public ServiceHandler(Looper looper){
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        run(locationManager);

    }
}

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {

    Log.i("Service","onHandleIntent lancé");

    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    mServiceHandler.sendMessage(msg);

    Log.i("Service","onHandleIntent lancé");

    return START_STICKY; //permet de redémarrer le service s'il est tué
}

@Override
public void onDestroy() {
    Log.i("DESTROY","IsDestroyed");
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

protected void run(LocationManager locationManager){

    Log.i("Service","Service lancé");

    boolean hasLocationFeature = checkLocationFeature();

    if ( hasLocationFeature && (ACCESS_FINE_LOCATION == PackageManager.PERMISSION_GRANTED || ACCESS_COARSE_LOCATION == PackageManager.PERMISSION_GRANTED ) ) {
        sLocation(locationManager);
    }

}

protected void sLocation(LocationManager locationManagerArg){

    final List<Location> locations = new ArrayList<>();
    final LocationManager locationManager = locationManagerArg;
    Log.i("sLocation","lancé");

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            saveNewLocation(location);
            if (location != null) {
                locations.add(location);
                Log.i("Locationsize", String.valueOf(locations.size()));
                if(locations.size()%50 == 0) {
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() + ".gpx");
                    GPXWriter(file, "test1", locations);
                    locations.clear();
                }
            }
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
        }

        @Override
        public void onProviderEnabled(String s) {
        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,locationListener);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,0,locationListener);

}

The method writing the GPX file has no issue. I have tested this on one emulator and two actual devices, the same problem occurs. It might not be related to memory pressure. I have on my phone other LocationService from other applications that have been running for more than 100 hours.

Why does this service die, and what can I do about this?
Thanks


问:
In Bing Maps v8 can I get a pushpin object from a layer in a loop?
In Bing Maps v7 I was able to add pushpins to an entityCollection and then loop through that collection later in the code to set options or whatever.  Now, I am having trouble getting pins from the v8 layers.

Here is what I used to do in v7 after I had already added the pin to the entityCollection:

```<code>for (var i = 0; i < entityCollection.getLength() ; i++) {
    var pin = entityCollection.get(i);
    pin.setOptions({ visible: true });
}
</code>```

I have changed the object entityCollection to a layer for v8 and I am also looping through the layer while i < entityCollection.data.length

Now, in Bing Maps v8, I'm having trouble getting the pin object from the layer that I have already added it to.  The code above throws an error on the setOptions line and I have also tried getting the pin with:

```<code>entityCollection.data[i]
</code>```

instead of

```<code>entityCollection.get(i)
</code>```

But that doesn't work either.  I'm afraid my question is too generic, because I can't find anything that actually answers my question.  I have a work around, but that causes failures later when I want to hide all the pins with certain attributes. Thanks in advance!

答:
Bing Maps v8 has done away with the entityCollection - though they say it's still sort of supported, you obviously don't want to be using deprecated things any more.

Anywhere you have an entityCollection, replace it with a Layer (Microsoft.Maps.Layer). Layers expose the getPrimitives() method which will provide you with an array of the contents.

```<code>var map = new Microsoft.Maps.Map(..., ...);

var layer = new Microsoft.Maps.Layer();
// Add layer data...
layer.add(new Microsoft.Maps.Pushpin(...));

// Add layer to map
map.layers.insert(layer);

// Then you can iterate
var layerItems = layer.getPrimitives();
var len = layerItems.length;

for(var i = 0; i < len; i++){
    var pin = layerItems[i];
    // Do something with your pin
    pin.setOptions({visible: false});
}
</code>```

Note that if you're doing mass updates to the entire contents of the layer, such as showing or hiding every pin in the layer, you can do that directly on the layer. This will save you (the browser) a chunk of work setting each pin individually.

```<code>layer.setVisible(true);
</code>```

Body:
In Bing Maps v7 I was able to add pushpins to an entityCollection and then loop through that collection later in the code to set options or whatever.  Now, I am having trouble getting pins from the v8 layers.

Here is what I used to do in v7 after I had already added the pin to the entityCollection:

for (var i = 0; i < entityCollection.getLength() ; i++) {
    var pin = entityCollection.get(i);
    pin.setOptions({ visible: true });
}

I have changed the object entityCollection to a layer for v8 and I am also looping through the layer while i < entityCollection.data.length

Now, in Bing Maps v8, I'm having trouble getting the pin object from the layer that I have already added it to.  The code above throws an error on the setOptions line and I have also tried getting the pin with:

entityCollection.data[i]

instead of

entityCollection.get(i)

But that doesn't work either.  I'm afraid my question is too generic, because I can't find anything that actually answers my question.  I have a work around, but that causes failures later when I want to hide all the pins with certain attributes. Thanks in advance!

Body:
Bing Maps v8 has done away with the entityCollection - though they say it's still sort of supported, you obviously don't want to be using deprecated things any more.

Anywhere you have an entityCollection, replace it with a Layer (Microsoft.Maps.Layer). Layers expose the getPrimitives() method which will provide you with an array of the contents.

var map = new Microsoft.Maps.Map(..., ...);

var layer = new Microsoft.Maps.Layer();
// Add layer data...
layer.add(new Microsoft.Maps.Pushpin(...));

// Add layer to map
map.layers.insert(layer);

// Then you can iterate
var layerItems = layer.getPrimitives();
var len = layerItems.length;

for(var i = 0; i < len; i++){
    var pin = layerItems[i];
    // Do something with your pin
    pin.setOptions({visible: false});
}

Note that if you're doing mass updates to the entire contents of the layer, such as showing or hiding every pin in the layer, you can do that directly on the layer. This will save you (the browser) a chunk of work setting each pin individually.

layer.setVisible(true);


问:
How can I have two Window forms, from different projects, show and hide each other?

this is the code for Form1.cs of testing file:

```<code>        Testing2.Form1 t2 = new Testing2.Form1();
        t2.Show();
        this.Hide();
</code>```

When i click on "back to testing" i want Form1.cs of Testing to open.I tried to add reference on Testing2 it gives the following error:

答:
In Testing2.Form1, add a property:

```<code>public Form CallingForm {get; set;}
</code>```

Then change:

```<code>Testing2.Form1 t2 = new Testing2.Form1();
t2.Show();
this.Hide();
</code>```

to:

```<code>Testing2.Form1 t2 = new Testing2.Form1();
t2.CallingForm = this;
t2.Show();
this.Hide();
</code>```

Then when you want to show the original form from Testing2.Form1, then do:

```<code>if (CallingForm != null)
    CallingForm.Show();
</code>```

This will work for your purposes - but you will be unable to actually instantiate Testing.Form1 from Testing2.Form1 (since that will indeed introduce a circular dependency).

Body:
this is the code for Form1.cs of testing file:

        Testing2.Form1 t2 = new Testing2.Form1();
        t2.Show();
        this.Hide();

When i click on "back to testing" i want Form1.cs of Testing to open.I tried to add reference on Testing2 it gives the following error:

Body:
In Testing2.Form1, add a property:

public Form CallingForm {get; set;}

Then change:

Testing2.Form1 t2 = new Testing2.Form1();
t2.Show();
this.Hide();

to:

Testing2.Form1 t2 = new Testing2.Form1();
t2.CallingForm = this;
t2.Show();
this.Hide();

Then when you want to show the original form from Testing2.Form1, then do:

if (CallingForm != null)
    CallingForm.Show();

This will work for your purposes - but you will be unable to actually instantiate Testing.Form1 from Testing2.Form1 (since that will indeed introduce a circular dependency).


问:
How to render an element conditionally in Vue.js?
I'm new to Vue.js, I just read the documentation on conditional rendering here (https://v2.vuejs.org/v2/guide/conditional.html) but somehow can't get it to work...

My code:

```<code><button onclick="showTemplate()">Teste</button>

<template v-if="app">

    <div id="app">
      {{ message }}
    </div>

</template>

function showTemplate(){
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })
}
</code>```

I want the template tag to render only after app has been instantiated.
I have also tried variations of this code without success.
Can someone help out?

答:
Try this and remove the button. You don't need to call the instance within the function.</p>

```<code>// put it on your index.html
<div id="app">
  {{ message }}
</div>

// put it on your script make sure that you have already a CDN of vuejs.
var app = new Vue({
   el: '#app',
   data: {
      message: 'Hello Vue!'
   }
})
</code>```

Body:
I'm new to Vue.js, I just read the documentation on conditional rendering here (https://v2.vuejs.org/v2/guide/conditional.html) but somehow can't get it to work...

My code:

<button onclick="showTemplate()">Teste</button>

<template v-if="app">

      {{ message }}

</template>

function showTemplate(){
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })
}

I want the template tag to render only after app has been instantiated.
I have also tried variations of this code without success.
Can someone help out?

Body:
Try this and remove the button. You don't need to call the instance within the function.

// put it on your index.html
<div id="app">
  {{ message }}
</div>

// put it on your script make sure that you have already a CDN of vuejs.
var app = new Vue({
   el: '#app',
   data: {
      message: 'Hello Vue!'
   }
})


问:
Reasonable snprintf-like alternatives to strftime?
Are there any standard (C, C++, POSIX, Linux...) alternatives to strftime which can be used to

calculate the required size of the string buffer for a given format and time,

truncate the output (instead of leaving the array contents undefined like strftime does) if buffer size is less than required for full output.

For example, snprintf-like semantics for date/time formatting which accept strftime format strings would do perfectly.

Functions like std::put_time in C++11 and later are not an option, because these may attempt to allocate extra memory dynamically and may throw exceptions.

答:
Could keep trying larger buffers until code succeeds (or decides this is too much).  The below uses a VLA (not C++), to sneakily avoid "attempt to allocate extra memory dynamically" - wink wink.

Simply allocating a large buffer, say char buf[J_STRFTIME_MAX], should be sufficient for practical coding.  @Michaël Roy and avoid the iterative approach.

```<code>#include <stdio.h>
#include <time.h>
#define J_STRFTIME_MAX 100

size_t j_strftime(char * s, size_t maxsize, const char * fmt, const struct tm * t) {
  size_t sz = strftime(s, maxsize, fmt, t);
  if (sz) {
    return sz;
  }
  size_t new_size = maxsize ? maxsize : 1;
  do {
    new_size *= 2;
    char new_s[new_size];
    sz = strftime(new_s, sizeof new_s, fmt, t);
    if (sz) {
      s[0] = 0;
      // strncat(s, new_s, maxsize);
      strncat(s, new_s, maxsize - 1);
      return strlen(new_s);
    }
  } while (sz < J_STRFTIME_MAX/2);
  return 0;
}

int main() {
  time_t now;
  time(&now);
  struct tm tm = *gmtime(&now);
  for (size_t i = 1; i < 30; i += 3) {
    char s[i];
    size_t sz = j_strftime(s, sizeof s, "%c", &tm);
    printf("%2zu %2zu <%s>\n", i, sz, s);
  }
}
</code>```

Output

```<code> 1 24 <T>
 4 24 <Thu >
 7 24 <Thu Jul>
10 24 <Thu Jul  6>
13 24 <Thu Jul  6 14>
16 24 <Thu Jul  6 14:45>
19 24 <Thu Jul  6 14:45:00>
22 24 <Thu Jul  6 14:45:00 20>
25 24 <Thu Jul  6 14:45:00 2017>
28 24 <Thu Jul  6 14:45:00 2017>
</code>```

Non-iterative

```<code>size_t j_strftime2(char * s, size_t maxsize, const char * fmt, const struct tm * t) {
  size_t sz = strftime(s, maxsize, fmt, t);
  if (sz == 0) {
    char new_s[J_STRFTIME_MAX];
    sz = strftime(new_s, sizeof new_s, fmt, t);
    if (sz == 0) {
      return 0;  // Too too big
    }
    s[0] = 0;
    // strncat(s, new_s, maxsize);
    strncat(s, new_s, maxsize - 1);
  }
  return sz;
}
</code>```

[Edit] Code corrected.

Body:
Could keep trying larger buffers until code succeeds (or decides this is too much).  The below uses a VLA (not C++), to sneakily avoid "attempt to allocate extra memory dynamically" - wink wink.

Simply allocating a large buffer, say char buf[J_STRFTIME_MAX], should be sufficient for practical coding.  @Michaël Roy and avoid the iterative approach.

#include <stdio.h>
#include <time.h>
#define J_STRFTIME_MAX 100

size_t j_strftime(char * s, size_t maxsize, const char * fmt, const struct tm * t) {
  size_t sz = strftime(s, maxsize, fmt, t);
  if (sz) {
    return sz;
  }
  size_t new_size = maxsize ? maxsize : 1;
  do {
    new_size *= 2;
    char new_s[new_size];
    sz = strftime(new_s, sizeof new_s, fmt, t);
    if (sz) {
      s[0] = 0;
      // strncat(s, new_s, maxsize);
      strncat(s, new_s, maxsize - 1);
      return strlen(new_s);
    }
  } while (sz < J_STRFTIME_MAX/2);
  return 0;
}

int main() {
  time_t now;
  time(&now);
  struct tm tm = *gmtime(&now);
  for (size_t i = 1; i < 30; i += 3) {
    char s[i];
    size_t sz = j_strftime(s, sizeof s, "%c", &tm);
    printf("%2zu %2zu <%s>\n", i, sz, s);
  }
}

Output

 1 24 <T>
 4 24 <Thu >
 7 24 <Thu Jul>
10 24 <Thu Jul  6>
13 24 <Thu Jul  6 14>
16 24 <Thu Jul  6 14:45>
19 24 <Thu Jul  6 14:45:00>
22 24 <Thu Jul  6 14:45:00 20>
25 24 <Thu Jul  6 14:45:00 2017>
28 24 <Thu Jul  6 14:45:00 2017>

Non-iterative

size_t j_strftime2(char * s, size_t maxsize, const char * fmt, const struct tm * t) {
  size_t sz = strftime(s, maxsize, fmt, t);
  if (sz == 0) {
    char new_s[J_STRFTIME_MAX];
    sz = strftime(new_s, sizeof new_s, fmt, t);
    if (sz == 0) {
      return 0;  // Too too big
    }
    s[0] = 0;
    // strncat(s, new_s, maxsize);
    strncat(s, new_s, maxsize - 1);
  }
  return sz;
}

[Edit] Code corrected.


问:
Regex for failing if '^' is found?
I have a regex for slicing off the first integer part of a string

```<code>(^[0-9]+)|(^\-[0-9]+)
</code>```

i.e. with '12x', slicing it would return '12'. I want to expand it so that it fails if there is a '^' in the string. I tried using a negative lookahead

```<code>(?!\^)(^[0-9]+)|(^\-[0-9]+)
</code>```

but this doesn't work as it still matches e.g. '12^x'. I also tried it without the '\' before the '^' but it didn't match anything. Where am I going wrong?

答:
Here is your current negative lookahead:

```<code>(?!\^)
</code>```

The problem with this lookahead is that it uses the wrong pattern to achieve what you want.  It is only looking ahead one character, which mean it can't check the entire string until the end for the presence or absence of a carat.

```<code>^(?!.*\^)-?[0-9]+$
</code>```

Explanation:

```<code>^(?!.*\^)    from the start of the string, look ahead and assert that no carat appears
-?[0-9]+$    match an optional minus sign, followed by any number of digits
</code>```

Demo here:

Regex101

Title: Regex for failing if '^' is found?

Body:
I have a regex for slicing off the first integer part of a string

(^[0-9]+)|(^\-[0-9]+)

i.e. with '12x', slicing it would return '12'. I want to expand it so that it fails if there is a '^' in the string. I tried using a negative lookahead

(?!\^)(^[0-9]+)|(^\-[0-9]+)

but this doesn't work as it still matches e.g. '12^x'. I also tried it without the '\' before the '^' but it didn't match anything. Where am I going wrong?

Body:
Here is your current negative lookahead:

(?!\^)

The problem with this lookahead is that it uses the wrong pattern to achieve what you want.  It is only looking ahead one character, which mean it can't check the entire string until the end for the presence or absence of a carat.

^(?!.*\^)-?[0-9]+$

Explanation:

^(?!.*\^)    from the start of the string, look ahead and assert that no carat appears
-?[0-9]+$    match an optional minus sign, followed by any number of digits

Demo here:

Regex101


问:
Cannot declare variable to be of abstract type because the virtual functions are pure - with multiple inheritance
I have seen multiple answers for this kind of problem but I don't get how to resolve it. The main problem is probably that I'm working on someone else's code, but meh. Here is a reduced sample for this problem:
I have one class that links many other classes:

```<code>class Interface
  : public system_atoms,
    public system_io,
    /* etc, others */
{
/* A few functions, none that matters here - none from the inherited classes redefined */
}
</code>```

Inside system_atoms, I have:

```<code>class system_atoms {
public:
    virtual int init_atom(int atom_number) = 0;
    virtual int check_atom_id(int atom_number) = 0;
}
</code>```

And I have a class that should inherit from Interface:

```<code>class Interface_proxy : public Interface {
public:
/* stuff - no function from the inherited classes redefined */
}
</code>```

In the .cpp:

```<code>Interface_proxy global_interface_proxy;
</code>```

Compilation brings an error stating "Cannot declare variable global_interface_proxy to be of abstract type Interface_proxy because the virtual functions [the two listed in system_atoms] are pure".

I'm not really proficient in c++ either. I guess that I should redefine the two virtual functions as pure (the same without the = 0 and the virtual right ?) somewhere so that the variable isn't of abstract type. But my knowledge stops there - and the multiple inheritance just confuses me.

答:
A pure virtual function is a function that is virtual and that explicitly has no implementation (denoted with the trailing = 0). A pure virtual function is intended to force derived classes to provide their own implementation for that function. In other words, a derived class is expected to eventually define its own behavior for that function.

An abstract class is a class that has one or more pure virtual functions, either because it declares at least one or it inherits from an abstract class and does not override all of the inherited pure virtual functions. These classes cannot be instantiated (you cannot create an instance of it) since their behavior is not fully defined. They can only be used as base classes for other types.

In your case, system_atoms defines 2 pure virtual functions so it's an abstract class. Each of the classes you've listed that inherits from system_atoms is also abstract since they all inherit from those pure virtual functions and never override them.

The correct solution is to provide an implementation for those pure virtual functions in your derived class by overriding.

See the virtual functions
 and the override specifier.

Multiple inheritance does not come into play here, except that each inherited class may have its own pure virtual functions. Simply override the pure virtual functions normally.

Body:
I have seen multiple answers for this kind of problem but I don't get how to resolve it. The main problem is probably that I'm working on someone else's code, but meh. Here is a reduced sample for this problem:
I have one class that links many other classes:

class Interface
  : public system_atoms,
    public system_io,
    /* etc, others */
{
/* A few functions, none that matters here - none from the inherited classes redefined */
}

Inside system_atoms, I have:

class system_atoms {
public:
    virtual int init_atom(int atom_number) = 0;
    virtual int check_atom_id(int atom_number) = 0;
}

And I have a class that should inherit from Interface:

class Interface_proxy : public Interface {
public:
/* stuff - no function from the inherited classes redefined */
}

In the .cpp:

Interface_proxy global_interface_proxy;

Compilation brings an error stating "Cannot declare variable global_interface_proxy to be of abstract type Interface_proxy because the virtual functions [the two listed in system_atoms] are pure".

I'm not really proficient in c++ either. I guess that I should redefine the two virtual functions as pure (the same without the = 0 and the virtual right ?) somewhere so that the variable isn't of abstract type. But my knowledge stops there - and the multiple inheritance just confuses me.


问:
App's iCloud Documents Directory failes to load files after reinstall app
I'm trying to store files on the users iCloud Drive.
After I save the file on their iCloud drive, I can retrieve it, as long as I don't reinstall the App. I store the paths to the files inside NSUbiquitousKeyValueStore.

Code to save the files:

```<code> let data = UIImagePNGRepresentation(finalImage)

        let filename = "sticker\((NSUbiquitousKeyValueStore.default().longLong(forKey: "stickerCount"))+1).png"
        let filenamePath = self.getDocumentsDirectory().appendingPathComponent(filename)
        NSUbiquitousKeyValueStore.default().set(NSUbiquitousKeyValueStore.default().longLong(forKey: "stickerCount")+1, forKey: "stickerCount")

        var filenames : NSMutableArray!
        if !(NSUbiquitousKeyValueStore.default().bool(forKey: "createdArray")){
            NSUbiquitousKeyValueStore.default().set(true, forKey: "createdArray")
            filenames = NSMutableArray()
        }else{
            filenames = (NSUbiquitousKeyValueStore.default().array(forKey: "fileNames")! as NSArray).mutableCopy() as! NSMutableArray
        }
        filenames.add(filename)
        NSUbiquitousKeyValueStore.default().set(filenames, forKey: "fileNames")
        NSUbiquitousKeyValueStore.default().synchronize()

        try? data?.write(to: filenamePath)
</code>```

This is the code to get the files:

```<code>func loadTheStickers() {
    stickerNames.removeAllObjects()
    stickers.removeAllObjects()
    var filenames : NSMutableArray!
    if !(NSUbiquitousKeyValueStore.default().bool(forKey: "createdArray")){
        NSUbiquitousKeyValueStore.default().set(true, forKey: "createdArray")
        filenames = NSMutableArray()
    }else{
        filenames = (NSUbiquitousKeyValueStore.default().array(forKey: "fileNames")! as NSArray).mutableCopy() as! NSMutableArray
    }
    for stickerName in filenames {
        stickerNames.add(stickerName)
        let url = getDocumentsDirectory().appendingPathComponent(stickerName as! String)
        stickers.add(url)
    }

}
</code>```

And I get the URLS, so the NSUbiquitousKeyValueStore working properly, however if I reinstall the App, the imageFromUrl won't return the image so it isnt there. I simply use this line of code:

```<code>cell.imageView.image = UIImage(contentsOfFile: (stickers[indexPath.row] as! URL).path)
</code>```

and again it works perfectly until I try to reinstall the app.

Here is the Class that I use to get the path to the iCloud Directory:

```<code>class CloudDataManager {

static let sharedInstance = CloudDataManager() // Singleton

struct DocumentsDirectory {
    static let localDocumentsURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupID)
    static let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: iCloudContainerID)?.appendingPathComponent("Documents")
}

// Return the Document directory (Cloud OR Local)
// To do in a background thread

func getDocumentDiretoryURL() -> URL {
    if isCloudEnabled()  {
        if !FileManager.default.fileExists(atPath: (DocumentsDirectory.iCloudDocumentsURL?.path)!){
            do {
            try FileManager.default.createDirectory(at: DocumentsDirectory.iCloudDocumentsURL!, withIntermediateDirectories: true, attributes: nil)
            }catch{
                NSLog("Error")
            }
        }
        NSLog("\(DocumentsDirectory.iCloudDocumentsURL!)")
        return DocumentsDirectory.iCloudDocumentsURL!
    } else {
        NSLog("\(DocumentsDirectory.localDocumentsURL!)")
        return DocumentsDirectory.localDocumentsURL!
    }
}

// Return true if iCloud is enabled

func isCloudEnabled() -> Bool {
    if DocumentsDirectory.iCloudDocumentsURL != nil { return true }
    else { return false }
}

// Delete All files at URL

func deleteFilesInDirectory(url: URL?) {
    let fileManager = FileManager.default
    let enumerator = fileManager.enumerator(atPath: url!.path)
    while let file = enumerator?.nextObject() as? String {

        do {
            try fileManager.removeItem(at: url!.appendingPathComponent(file))
            print("Files deleted")
        } catch let error as NSError {
            print("Failed deleting files : \(error)")
        }
    }
}

// Copy local files to iCloud
// iCloud will be cleared before any operation
// No data merging

func copyFileToCloud() {
    if isCloudEnabled() {
        deleteFilesInDirectory(url: DocumentsDirectory.iCloudDocumentsURL!) // Clear all files in iCloud Doc Dir
        let fileManager = FileManager.default
        let enumerator = fileManager.enumerator(atPath: (DocumentsDirectory.localDocumentsURL?.path)!)
        while let file = enumerator?.nextObject() as? String {

            do {
                try fileManager.copyItem(at: (DocumentsDirectory.localDocumentsURL?.appendingPathComponent(file))!, to: DocumentsDirectory.iCloudDocumentsURL!.appendingPathComponent(file))

                print("Copied to iCloud")
            } catch let error as NSError {
                print("Failed to move file to Cloud : \(error)")
            }
        }
    }
}

// Copy iCloud files to local directory
// Local dir will be cleared
// No data merging

func copyFileToLocal() {
    if isCloudEnabled() {
        deleteFilesInDirectory(url: DocumentsDirectory.localDocumentsURL)
        let fileManager = FileManager.default
        let enumerator = fileManager.enumerator(atPath: DocumentsDirectory.iCloudDocumentsURL!.path)
        while let file = enumerator?.nextObject() as? String {

            do {
                try fileManager.copyItem(at: DocumentsDirectory.iCloudDocumentsURL!.appendingPathComponent(file), to: (DocumentsDirectory.localDocumentsURL?.appendingPathComponent(file))!)

                print("Moved to local dir")
            } catch let error as NSError {
                print("Failed to move file to local dir : \(error)")
            }
        }
    }
}
</code>```

}

and I've checked, it return the correct URL for the iCloud Document directory.
So my question is where is the problem, how could I correct the code, so the files are availabla after reinstalling the app or on other devices, becaise atm the iCloud directory isnt better than simply storing in the local Documents directory.

答:
After long research, I've managed to solve the problem.
You have to manually provoke iCloud to download the items from the cloud, it'll upload automatically, but not download.

You have to use the following line for all the items:

```<code>FileManager.default.startDownloadingUbiquitousItem(at: url)
</code>```

So the downloading code in the Appdelegates application:didfinish... method now looks like this:

```<code>  var filenames : NSMutableArray!
    if !(NSUbiquitousKeyValueStore.default().bool(forKey: "createdArray")){
        NSUbiquitousKeyValueStore.default().set(true, forKey: "createdArray")
        filenames = NSMutableArray()
    }else{
        filenames = (NSUbiquitousKeyValueStore.default().array(forKey: "fileNames")! as NSArray).mutableCopy() as! NSMutableArray
    }

    for stickerName in filenames {
        let url = getDocumentsDirectory().appendingPathComponent(stickerName as! String)
        if !FileManager.default.fileExists(atPath: url.path){
        do {
            try FileManager.default.startDownloadingUbiquitousItem(at: url)
        }catch{
            NSLog(error.localizedDescription)
        }
        }
    }
</code>```

Body:
I'm trying to store files on the users iCloud Drive.
After I save the file on their iCloud drive, I can retrieve it, as long as I don't reinstall the App. I store the paths to the files inside NSUbiquitousKeyValueStore.

Code to save the files:

 let data = UIImagePNGRepresentation(finalImage)

        let filename = "sticker\((NSUbiquitousKeyValueStore.default().longLong(forKey: "stickerCount"))+1).png"
        let filenamePath = self.getDocumentsDirectory().appendingPathComponent(filename)
        NSUbiquitousKeyValueStore.default().set(NSUbiquitousKeyValueStore.default().longLong(forKey: "stickerCount")+1, forKey: "stickerCount")

        var filenames : NSMutableArray!
        if !(NSUbiquitousKeyValueStore.default().bool(forKey: "createdArray")){
            NSUbiquitousKeyValueStore.default().set(true, forKey: "createdArray")
            filenames = NSMutableArray()
        }else{
            filenames = (NSUbiquitousKeyValueStore.default().array(forKey: "fileNames")! as NSArray).mutableCopy() as! NSMutableArray
        }
        filenames.add(filename)
        NSUbiquitousKeyValueStore.default().set(filenames, forKey: "fileNames")
        NSUbiquitousKeyValueStore.default().synchronize()

        try? data?.write(to: filenamePath)

This is the code to get the files:

func loadTheStickers() {
    stickerNames.removeAllObjects()
    stickers.removeAllObjects()
    var filenames : NSMutableArray!
    if !(NSUbiquitousKeyValueStore.default().bool(forKey: "createdArray")){
        NSUbiquitousKeyValueStore.default().set(true, forKey: "createdArray")
        filenames = NSMutableArray()
    }else{
        filenames = (NSUbiquitousKeyValueStore.default().array(forKey: "fileNames")! as NSArray).mutableCopy() as! NSMutableArray
    }
    for stickerName in filenames {
        stickerNames.add(stickerName)
        let url = getDocumentsDirectory().appendingPathComponent(stickerName as! String)
        stickers.add(url)
    }

}

And I get the URLS, so the NSUbiquitousKeyValueStore working properly, however if I reinstall the App, the imageFromUrl won't return the image so it isnt there. I simply use this line of code:

cell.imageView.image = UIImage(contentsOfFile: (stickers[indexPath.row] as! URL).path)

and again it works perfectly until I try to reinstall the app.

Here is the Class that I use to get the path to the iCloud Directory:

class CloudDataManager {

static let sharedInstance = CloudDataManager() // Singleton

struct DocumentsDirectory {
    static let localDocumentsURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupID)
    static let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: iCloudContainerID)?.appendingPathComponent("Documents")
}

// Return the Document directory (Cloud OR Local)
// To do in a background thread

func getDocumentDiretoryURL() -> URL {
    if isCloudEnabled()  {
        if !FileManager.default.fileExists(atPath: (DocumentsDirectory.iCloudDocumentsURL?.path)!){
            do {
            try FileManager.default.createDirectory(at: DocumentsDirectory.iCloudDocumentsURL!, withIntermediateDirectories: true, attributes: nil)
            }catch{
                NSLog("Error")
            }
        }
        NSLog("\(DocumentsDirectory.iCloudDocumentsURL!)")
        return DocumentsDirectory.iCloudDocumentsURL!
    } else {
        NSLog("\(DocumentsDirectory.localDocumentsURL!)")
        return DocumentsDirectory.localDocumentsURL!
    }
}

// Return true if iCloud is enabled

func isCloudEnabled() -> Bool {
    if DocumentsDirectory.iCloudDocumentsURL != nil { return true }
    else { return false }
}

// Delete All files at URL

func deleteFilesInDirectory(url: URL?) {
    let fileManager = FileManager.default
    let enumerator = fileManager.enumerator(atPath: url!.path)
    while let file = enumerator?.nextObject() as? String {

        do {
            try fileManager.removeItem(at: url!.appendingPathComponent(file))
            print("Files deleted")
        } catch let error as NSError {
            print("Failed deleting files : \(error)")
        }
    }
}

// Copy local files to iCloud
// iCloud will be cleared before any operation
// No data merging

func copyFileToCloud() {
    if isCloudEnabled() {
        deleteFilesInDirectory(url: DocumentsDirectory.iCloudDocumentsURL!) // Clear all files in iCloud Doc Dir
        let fileManager = FileManager.default
        let enumerator = fileManager.enumerator(atPath: (DocumentsDirectory.localDocumentsURL?.path)!)
        while let file = enumerator?.nextObject() as? String {

            do {
                try fileManager.copyItem(at: (DocumentsDirectory.localDocumentsURL?.appendingPathComponent(file))!, to: DocumentsDirectory.iCloudDocumentsURL!.appendingPathComponent(file))

                print("Copied to iCloud")
            } catch let error as NSError {
                print("Failed to move file to Cloud : \(error)")
            }
        }
    }
}

// Copy iCloud files to local directory
// Local dir will be cleared
// No data merging

func copyFileToLocal() {
    if isCloudEnabled() {
        deleteFilesInDirectory(url: DocumentsDirectory.localDocumentsURL)
        let fileManager = FileManager.default
        let enumerator = fileManager.enumerator(atPath: DocumentsDirectory.iCloudDocumentsURL!.path)
        while let file = enumerator?.nextObject() as? String {

            do {
                try fileManager.copyItem(at: DocumentsDirectory.iCloudDocumentsURL!.appendingPathComponent(file), to: (DocumentsDirectory.localDocumentsURL?.appendingPathComponent(file))!)

                print("Moved to local dir")
            } catch let error as NSError {
                print("Failed to move file to local dir : \(error)")
            }
        }
    }
}

}

and I've checked, it return the correct URL for the iCloud Document directory.
So my question is where is the problem, how could I correct the code, so the files are availabla after reinstalling the app or on other devices, becaise atm the iCloud directory isnt better than simply storing in the local Documents directory.

Body:
After long research, I've managed to solve the problem.
You have to manually provoke iCloud to download the items from the cloud, it'll upload automatically, but not download.

You have to use the following line for all the items:

FileManager.default.startDownloadingUbiquitousItem(at: url)

So the downloading code in the Appdelegates application:didfinish... method now looks like this:

  var filenames : NSMutableArray!
    if !(NSUbiquitousKeyValueStore.default().bool(forKey: "createdArray")){
        NSUbiquitousKeyValueStore.default().set(true, forKey: "createdArray")
        filenames = NSMutableArray()
    }else{
        filenames = (NSUbiquitousKeyValueStore.default().array(forKey: "fileNames")! as NSArray).mutableCopy() as! NSMutableArray
    }

    for stickerName in filenames {
        let url = getDocumentsDirectory().appendingPathComponent(stickerName as! String)
        if !FileManager.default.fileExists(atPath: url.path){
        do {
            try FileManager.default.startDownloadingUbiquitousItem(at: url)
        }catch{
            NSLog(error.localizedDescription)
        }
        }
    }


问:
How do you make an etag that matches Apache?
I want to make an etag that matches what Apache produces.  How does apache create it's etags?</p>

答:
If you're dynamically generating your page though, this probably won't make sense. If you're in PHP, you can pick the inode and file size of the main script, but the modify time won't tell you if your data has changed. Unless you have a good caching process or just generate static pages, etags aren't helpful. If you do have a good caching process, the inode and file size are probably irrelevant.

Edit: For people who don't know what etags are - they're just supposed to be a value that changes when the content has changed, for caching purposes. The browser gets the etag from the web server, compares it to the etag for its cached copy and then fetches the whole page if the etag has changed.

OwnerDisplayName: Chris Bartow

LastEditorDisplayName: Stu Thompson

OwnerDisplayName: Neall

LastEditorDisplayName: Neall


问:
How to invoke an ActionScript method from JavaScript (HTMLLoader) object in AIR?
So I have an Application Sandbox HTMLLoader object which I create in AIR and simply want to call ActionScript methods from JavaScript. In Flash, this is accomplished through our trusty ExternalInterface.addCallback() function. However in AIR, things are quite a bit different, and I just can't seem to get it to work.

Here is a simplified overview of my project:

My AIR (ActionScript) main:

```<code>public class Main extends Sprite {

    public var _as3Var:String = "testing";
    public function as3Function():void
    {
        trace("as3Function called from Javascript");
    }

    public function Main() {
        NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
    }

    protected function onInvoke(e:InvokeEvent):void {
        NativeApplication.nativeApplication.removeEventListener(InvokeEvent.INVOKE, onInvoke );
        var app = new App();
        addChild(app);
        app.init(new ExternalContainer(), e.currentDirectory, e.arguments);
    }
}
</code>```

And this is how I create my HTMLLoader object:

```<code>{
    _html = new HTMLLoader();
    _html.useCache = false;
    _html.runtimeApplicationDomain = ApplicationDomain.currentDomain;
    _html.load(new URLRequest("sandbox/AirRoot.html"));
    _html.width = 800;
    _html.height = 600;
    App.ref.addChild(_html);
}
</code>```

And at last, here is my snippet of JavaScript in my AirRoot.html file which is trying to call the public method as3Function() declared in my Main class:

```<code>Exposed.testAs3 = function()
{
    air.trace("Exposed.testAs3 called");            /* This works fine. */
    air.trace("runtimeVersion:");                   /* This works fine. */
    air.trace(air.NativeApplication.nativeApplication.runtimeVersion);  /* This works fine. */
    air.trace("seeing if I can get to AS3 params...");  /* This works fine. */

    /* This doesn't work - get the following error: TypeError: Value undefined does not allow function calls. */
    air.NativeApplication.nativeApplication.as3Function();
}
</code>```

What am I missing?

答:
OK, I am going to answer my own question. I promise this was not a ploy to gain more reputation points, but I was seriously confused today but have now found the appropriate answers and documentation - which is usually the main problem to many an engineer's question...

Anyway, the answer:

The AIR HTMLLoader object contains a magical property, HTMLLoader.window, which is a proxy to the JavaScript window object. So setting HTMLLoader.window = AS3Function; is one way - or in relation to my previously included example (assuming I setup a static property called Main which pointed to the Main class):

```<code>_html.window.as3Function = Main.as3Function;
</code>```

And now in JavaScript I can just call as3Function as:

```<code><script>
    window.as3Function();
</script>
</code>```

Another interesting property is the JavaScript "window.htmlLoader" object. It is a proxy to the AS3 HTMLLoader parent object, in my case, the _html object.  From this you can access things in relation to the _html object from JavaScript.

OwnerDisplayName: helifreak

Body:
So I have an Application Sandbox HTMLLoader object which I create in AIR and simply want to call ActionScript methods from JavaScript. In Flash, this is accomplished through our trusty ExternalInterface.addCallback() function. However in AIR, things are quite a bit different, and I just can't seem to get it to work.

Here is a simplified overview of my project:

My AIR (ActionScript) main:

public class Main extends Sprite {

    public var _as3Var:String = "testing";
    public function as3Function():void
    {
        trace("as3Function called from Javascript");
    }

    public function Main() {
        NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
    }

    protected function onInvoke(e:InvokeEvent):void {
        NativeApplication.nativeApplication.removeEventListener(InvokeEvent.INVOKE, onInvoke );
        var app = new App();
        addChild(app);
        app.init(new ExternalContainer(), e.currentDirectory, e.arguments);
    }
}

And this is how I create my HTMLLoader object:

{
    _html = new HTMLLoader();
    _html.useCache = false;
    _html.runtimeApplicationDomain = ApplicationDomain.currentDomain;
    _html.load(new URLRequest("sandbox/AirRoot.html"));
    _html.width = 800;
    _html.height = 600;
    App.ref.addChild(_html);
}

And at last, here is my snippet of JavaScript in my AirRoot.html file which is trying to call the public method as3Function() declared in my Main class:

Exposed.testAs3 = function()
{
    air.trace("Exposed.testAs3 called");            /* This works fine. */
    air.trace("runtimeVersion:");                   /* This works fine. */
    air.trace(air.NativeApplication.nativeApplication.runtimeVersion);  /* This works fine. */
    air.trace("seeing if I can get to AS3 params...");  /* This works fine. */

    /* This doesn't work - get the following error: TypeError: Value undefined does not allow function calls. */
    air.NativeApplication.nativeApplication.as3Function();
}

What am I missing?

Body:
OK, I am going to answer my own question. I promise this was not a ploy to gain more reputation points, but I was seriously confused today but have now found the appropriate answers and documentation - which is usually the main problem to many an engineer's question...

Anyway, the answer:

The AIR HTMLLoader object contains a magical property, HTMLLoader.window, which is a proxy to the JavaScript window object. So setting HTMLLoader.window = AS3Function; is one way - or in relation to my previously included example (assuming I setup a static property called Main which pointed to the Main class):

_html.window.as3Function = Main.as3Function;

And now in JavaScript I can just call as3Function as:

<script>
    window.as3Function();
</script>

Another interesting property is the JavaScript "window.htmlLoader" object. It is a proxy to the AS3 HTMLLoader parent object, in my case, the _html object.  From this you can access things in relation to the _html object from JavaScript.


问:
Extracting just JSON data, not the headers, to a string array with typescript
What I'm trying to do is extract just the data from the JSON and not the headers(for example, getting 1 but not ID or getting foo and not Name)

```<code>[{ID = 1, Name = "foo", Email = "foo@foo.com"},
{ID = 2, Name = "bar", Email = "bar@bar.com"}]
</code>```

The reason that I just want the data and not the headers is that the data could by dynamic. In one call the JSON returned could have 100 fields per object or 2 fields per object on the next call. Which is why, in the below example, I only have a string in my interface, because I have no clue what kind of data could be passed.

Here is my typescript that I'm trying to get to interpret the data

```<code>import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
    public rowData: RowInfo[];

    constructor(http: Http) {

        http.get('/api/SampleData/DatatableData').subscribe(result => {
            //This is where the magic should happen
            //This currently does not work
            var dataCarrier = result.toString();
            JSON.parse(dataCarrier).forEach(item => {
                this.rowData = item.name;
            });
        });
    }
}

interface RowInfo {
    rowData: string;
}
</code>```

How do I go about breaking up the JSON data in the http.get into just its pieces to pass through to the interface while differentiating between the different rows that could be in the same object?

答:
The ES6 way: This will give you an array consisting of 1 array per object that you originally had. Each of the sub-arrays will only be the values of those objects.

```<code>JSON.parse(dataCarrier).map(Object.values)
</code>```

So in your example it would result in:

```<code>[{ID = 1, Name = "foo", Email = "foo@foo.com"},
{ID = 2, Name = "bar", Email = "bar@bar.com"}]

// =>

[[1, "foo", "foo@foo.com"], [2, "bar", "bar@bar.com"]]
</code>```

For more info on Object.values:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Object/values

If you can't use ES6, you can do it with ES5 and Object.keys. The code will be more verbose, but it gets the job done:

```<code>JSON.parse(dataCarrier).map(function(obj) {
    return Object.keys(obj).map(function (key) {
        return obj[key];
    });
});
</code>```

*Adapted from How to get all properties values of a Javascript Object (without knowing the keys)?

Body:
What I'm trying to do is extract just the data from the JSON and not the headers(for example, getting 1 but not ID or getting foo and not Name)

[{ID = 1, Name = "foo", Email = "foo@foo.com"},
{ID = 2, Name = "bar", Email = "bar@bar.com"}]

The reason that I just want the data and not the headers is that the data could by dynamic. In one call the JSON returned could have 100 fields per object or 2 fields per object on the next call. Which is why, in the below example, I only have a string in my interface, because I have no clue what kind of data could be passed.

Here is my typescript that I'm trying to get to interpret the data

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
    public rowData: RowInfo[];

    constructor(http: Http) {

        http.get('/api/SampleData/DatatableData').subscribe(result => {
            //This is where the magic should happen
            //This currently does not work
            var dataCarrier = result.toString();
            JSON.parse(dataCarrier).forEach(item => {
                this.rowData = item.name;
            });
        });
    }
}

interface RowInfo {
    rowData: string;
}

How do I go about breaking up the JSON data in the http.get into just its pieces to pass through to the interface while differentiating between the different rows that could be in the same object?

Body:
The ES6 way: This will give you an array consisting of 1 array per object that you originally had. Each of the sub-arrays will only be the values of those objects.

JSON.parse(dataCarrier).map(Object.values)

So in your example it would result in:

[{ID = 1, Name = "foo", Email = "foo@foo.com"},
{ID = 2, Name = "bar", Email = "bar@bar.com"}]

// =>

[[1, "foo", "foo@foo.com"], [2, "bar", "bar@bar.com"]]

For more info on Object.values:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Object/values

If you can't use ES6, you can do it with ES5 and Object.keys. The code will be more verbose, but it gets the job done:

JSON.parse(dataCarrier).map(function(obj) {
    return Object.keys(obj).map(function (key) {
        return obj[key];
    });
});

*Adapted from How to get all properties values of a Javascript Object (without knowing the keys)?


答:
The following changes to your code will do what you want on all four columns (with the prices data structure as per the question)</p>

```<code>library(TTR)
library(Hmisc)
library(xts)

#I apply the EMA indicator to the prices xts dataframe
EMA20fn <- function(x) EMA(x, n=20)
EMA20prices <- xts(apply(prices, 2, EMA20fn), order.by=index(EMA20fn(prices[,1])))

#I know how to create the signals (in EMA20prices) for a single asset, but I don't know
#what kind of loop it's required to apply the signal to every asset in the dataframe
#prices

ema20tr = NULL
for (j in 1:ncol(prices)) {
ema20tr <- cbind(ema20tr,Lag(ifelse(Lag(prices[,j])<Lag(EMA20prices[,j])& prices[,j]>EMA20prices[,j],1,
                      ifelse(Lag(prices[,j])>Lag(EMA20prices[,j])& prices[,j]<EMA20prices[,j],-1,0))))
}

ema20tr[is.na(ema20tr)] <- 0
ema20sig <- ifelse(ema20tr>1,0,0)

for (j in 1:ncol(prices)) {
    for(i in 2:length(prices[,j])) {ema20sig[i,j] <- ifelse(ema20tr[i,j]==1,1,
                                                     ifelse(ema20tr[i,j]==-1,0,ema20sig[i-1,j]))}
}

ema20sig[is.na(ema20sig)] <- 1
</code>```

Title: Apply technical analysis indicator to multiple assets

Body:
I am trying to apply this simple technical analysis indicator to an xts dataframe called prices. But I can't manage to create the loop for the signal. Do you have some suggestions?

library(TTR)
library(Hmisc)
library(xts)

prices = structure(c(70.27, 70.29, 70.31, 70.67, 70.41, 70.53, 70.56,
69.61, 70.32, 69.97, 70.13, 68.88, 68.97, 70.75, 71.32, 71.32,
71.32, 72.02, 72.48, 73.33, 73.59, 73.93, 73.47, 72.13, 72.17,
73.18, 72.59, 73.34, 73.43, 72.78, 72.43, 72.3, 71.27, 71.51,
71.94, 71.1, 69.77, 70.02, 70.26, 69.6, 70.13, 70.13, 71.27,
70.58, 69.52, 69.58, 69.46, 69.62, 69.07, 69.98, 44.245, 44.125,
44.09, 44.155, 43.93, 44.305, 44.065, 43.37, 43.685, 43.285,
43.355, 42.305, 42.65, 43.64, 43.885, 43.885, 43.885, 44.12,
44.385, 44.78, 44.985, 44.985, 44.865, 44.38, 44.05, 44.65, 44.065,
44.62, 44.73, 44.32, 44.275, 44.145, 43.615, 43.975, 44.52, 44.335,
43.585, 43.715, 43.83, 43.735, 44.09, 44.005, 44.775, 44.325,
43.555, 43.535, 43.325, 43.425, 43.04, 43.45, 166.09, 166.44,
165.04, 167.69, 168.08, 169.17, 168.67, 167.19, 167.19, 164.39,
163.26, 159.64, 160.33, 162.83, 163.4, 163.4, 163.4, 164.79,
166.23, 168.3, 168.29, 169.34, 168.56, 166.81, 165.39, 165.98,
162.64, 163.78, 164.91, 164, 162.1, 162.25, 161.45, 162.08, 162.37,
160.09, 157.96, 158.45, 159.95, 159.75, 160.58, 160.51, 164.09,
161.96, 160.84, 161.41, 159.48, 159.45, 158.09, 158.49, 66, 66.19,
66.31, 67.17, 66.84, 67.32, 67.26, 66.19, 66.46, 65.62, 65.61,
63.87, 64.09, 64.73, 65.72, 65.72, 65.72, 66.11, 66.96, 67.53,
67.57, 67.53, 67.25, 65.98, 65.52, 66.19, 65.23, 66.2, 66.4,
65.53, 65.52, 65.37, 64.54, 64.57, 64.85, 64, 62.94, 63.18, 63.87,
63.3, 63.9, 63.83, 64.76, 64, 63.62, 63.92, 63.02, 63.27, 62.33,
62.65), .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", format = "%Y-%m-%d", class = c("xts",
"zoo"), index = structure(c(1301616000, 1301875200, 1301961600,
1302048000, 1302134400, 1302220800, 1302480000, 1302566400, 1302652800,
1302739200, 1302825600, 1303084800, 1303171200, 1303257600, 1303344000,
1303430400, 1303689600, 1303776000, 1303862400, 1303948800, 1304035200,
1304294400, 1304380800, 1304467200, 1304553600, 1304640000, 1304899200,
1304985600, 1305072000, 1305158400, 1305244800, 1305504000, 1305590400,
1305676800, 1305763200, 1305849600, 1306108800, 1306195200, 1306281600,
1306368000, 1306454400, 1306713600, 1306800000, 1306886400, 1306972800,
1307059200, 1307318400, 1307404800, 1307491200, 1307577600), tzone = "UTC", tclass = "Date"), .Dim = c(50L,
4L), .Dimnames = list(NULL, c("A", "B", "C", "D")))

    #I apply the EMA indicator to the prices xts dataframe
    EMA20fn <- function(x) EMA(x, n=20)
    EMA20prices <- xts(apply(prices, 2, EMA20fn), order.by=index(EMA20fn(prices[,1])))

    #I know how to create the signals (in EMA20prices) for a single asset, but I don't know
    #what kind of loop it's required to apply the signal to every asset in the dataframe
    #prices
    ema20tr <- Lag(ifelse(Lag(prices[,1])<Lag(EMA20prices[,1])& prices[,1]>EMA20prices[,1],1,
                           ifelse(Lag(prices[,1])>Lag(EMA20prices[,1])& prices[,1]<EMA20prices[,1],-1,0)))
    ema20tr[is.na(ema20tr)] <- 0
    ema20sig <- ifelse(ema20tr>1,0,0)
    for(i in 2:length(prices[,1])){ema20sig[i] <- ifelse(ema20tr[i]==1,1,
                           ifelse(ema20tr[i]==-1,0,ema20sig[i-1]))}
    ema20sig[is.na(ema20sig)] <- 1

Thank you in advance for the answers!

Body:
The following changes to your code will do what you want on all four columns (with the prices data structure as per the question)

library(TTR)
library(Hmisc)
library(xts)

#I apply the EMA indicator to the prices xts dataframe
EMA20fn <- function(x) EMA(x, n=20)
EMA20prices <- xts(apply(prices, 2, EMA20fn), order.by=index(EMA20fn(prices[,1])))

#I know how to create the signals (in EMA20prices) for a single asset, but I don't know
#what kind of loop it's required to apply the signal to every asset in the dataframe
#prices

ema20tr = NULL
for (j in 1:ncol(prices)) {
ema20tr <- cbind(ema20tr,Lag(ifelse(Lag(prices[,j])<Lag(EMA20prices[,j])& prices[,j]>EMA20prices[,j],1,
                      ifelse(Lag(prices[,j])>Lag(EMA20prices[,j])& prices[,j]<EMA20prices[,j],-1,0))))
}

ema20tr[is.na(ema20tr)] <- 0
ema20sig <- ifelse(ema20tr>1,0,0)

for (j in 1:ncol(prices)) {
    for(i in 2:length(prices[,j])) {ema20sig[i,j] <- ifelse(ema20tr[i,j]==1,1,
                                                     ifelse(ema20tr[i,j]==-1,0,ema20sig[i-1,j]))}
}

ema20sig[is.na(ema20sig)] <- 1


答:
You can use an IF statement in your ForEach-Object loop to make sure you have not dealt with this connection ID before.

As it is assigned to a variable $thisID, it is not passed to Out-File (same for $connectionIDs)

```<code>Get-Content $logFile -ReadCount 1 | % {

    $thisID = $_.Split()[0].Split(".")[1]

    if($thisID -notin $connectionIDs){
        '|' + (($_.Split()[9, 11, 4] -replace ':', '|') -join '|') + '|'
        [array]$connectionIDs += $thisID
    }
} | Out-File "C:\Log\logout.txt"
</code>```

Output matches what's in your question.

Title: Powershell Get-Content, want only the first occurrence

Body:
i'm doing a series of splits to examine each line of a file, and output a formatted version of each line.

Example of input:

02/17-07:54:32.290169  [**] [1:1:0] other [**] [Priority: 0] {TCP} 100.100.100.212:6667 -> 192.168.5.81:2848
02/17-07:54:32.335595  [**] [1:1:0] other [**] [Priority: 0] {TCP} 100.100.100.212:6667 -> 192.168.5.81:2848
02/17-07:54:32.335628  [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.5.81:2848 -> 100.100.100.212:6667
06/14-06:33:47.258621  [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.4.85:4662 -> 69.192.30.179:80
06/14-06:33:47.258621  [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.4.85:4662 -> 69.192.30.179:80
06/14-06:33:47.258621  [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.4.85:4662 -> 69.192.30.179:80

When there are strings with the same connection ID (258621, in this case), I need just the first occurrence.

This gets me the connection ID, but i'm not sure how to disregard any lines that may follow with the same connection ID.

Get-Content $logFile -ReadCount 1 | % {

$_.Split()[0].Split(".")[1]

} | Out-File "C:\Log\logout.txt"

Output, I only want the first occurrence of 258621:

290169
335595
335628
258621
258621
258621

The trickier part is that I also need to reformat each line (assuming it isn't a duplicate connection ID) using something like this (ultimately, I don't want the connection ID in the output):

'|' + (($_.Split()[9, 11, 4] -replace ':', '|') -join '|') + '|'

Desired output:

|100.100.100.212|6667|192.168.5.81|2848|other|
|100.100.100.212|6667|192.168.5.81|2848|other|
|192.168.5.81|2848|100.100.100.212|6667|other|
|192.168.4.85|4662|69.192.30.179|80|other|

Thanks!

Body:
You can use an IF statement in your ForEach-Object loop to make sure you have not dealt with this connection ID before.

As it is assigned to a variable $thisID, it is not passed to Out-File (same for $connectionIDs)

Get-Content $logFile -ReadCount 1 | % {

    $thisID = $_.Split()[0].Split(".")[1]

    if($thisID -notin $connectionIDs){
        '|' + (($_.Split()[9, 11, 4] -replace ':', '|') -join '|') + '|'
        [array]$connectionIDs += $thisID
    }
} | Out-File "C:\Log\logout.txt"

Output matches what's in your question.


问:
Confusion about repeating pattern in python Regex
I have confusion about repeating pattern in Python regular expression.
I read from the documentation that '*' means repeating zero to N times. Suppose I have a string abc123def. I want to find the position of the substring containing numeric characters, so I use the following code:

```<code>p = re.compile(r'[\d]*')
p.search('abc123def').span()
</code>```

And it outputs (0,0)
If I change the regex to [\d]+, it outputs (3,6).

Why the regex r'[\d]*' doesn't work?
Thanks.

答: It does work, it finds a zero-length string at the beginning of your string.</p>

Body:
I have confusion about repeating pattern in Python regular expression.
I read from the documentation that '*' means repeating zero to N times. Suppose I have a string abc123def. I want to find the position of the substring containing numeric characters, so I use the following code:

p = re.compile(r'[\d]*')
p.search('abc123def').span()

And it outputs (0,0)
If I change the regex to [\d]+, it outputs (3,6).

Why the regex r'[\d]*' doesn't work?
Thanks.


问:
bash - find duplicate file in directory and rename
I have a directory that has thousands of files in it with various extensions.  I also have a drop location where users drop files to be migrated to this directory.  I'm looking for a script that will scan the target directory for a duplicate file name, if found, rename the file in the drop folder, then move it to the target directory.
Example:

/target/file.doc
/drop/file.doc

Script will rename file.doc to file1.doc then move it to /target/.
It needs to maintain the file extension too.

答:
```<code>for fil in /drop/*
do
    test -f "/target/$fil"
    if [ "$?" = 0 ]
    then
        suff=$(awk -F\. '{ print "."$NF }' <<<$fil)
        bdot=$(basename -s $suff $fil)
        mv "/drop/$fil" "/drop/${bdot}1$suff"
        cp "/drop/${bdot}1.$suff" "/target/${bdot}1$suff"
    fi
done
</code>```

Take each file in the drop directory and check it is existing the /target using test -e. If it does then move (rename) and then copy.

Body:
for fil in /drop/*
do
    test -f "/target/$fil"
    if [ "$?" = 0 ]
    then
        suff=$(awk -F\. '{ print "."$NF }' <<<$fil)
        bdot=$(basename -s $suff $fil)
        mv "/drop/$fil" "/drop/${bdot}1$suff"
        cp "/drop/${bdot}1.$suff" "/target/${bdot}1$suff"
    fi
done

Take each file in the drop directory and check it is existing the /target using test -e. If it does then move (rename) and then copy.


问:
Http Posting in Xamarin.Forms
Am facing a problem in Posting data from my Entires via a parametrized url , i don't know why it's happening, the URL returns a certain message after posting  , below is my URL :

http://bbs.eamobiledirectory.com/Mobile/MobileApi.aspx?Action=NewSalesReport&username=USERNAME&assID=ASSIGNID&repdetails=details&appoi_date=date.

and this is how am posting my data :

```<code>    void OnSubmitReport(object sender, System.EventArgs e)
        {
            PostData();
        }

        public async void PostData()
        {

            string details = report_details_entry.Text;
            string date = nextappointment_entry.Text;

            var formContent = new FormUrlEncodedContent(new[]
                        {
                new KeyValuePair<string, string>("unm", USERNAME),
                new KeyValuePair<string, string >("assinID", ""+ASSIGNID),
                new KeyValuePair<string, string>("details", details),
                new KeyValuePair<string, string>("appoi_date", date)

   });

            var response = await client.PostAsync("http://bbs.eamobiledirectory.com/Mobile/MobileApi.aspx?Action=NewSalesReport",formContent);

        }
</code>```

what i want is to submit the data in the Entries after wards i return a message in a DisplayAlert Message.

答:
Until you figure out why the FormUrlEncodedContent not working(i would really like to know why its not working)

you can solve your problem by posting this way:

```<code>var url = string.Format("http://bbs.eamobiledirectory.com/Mobile/MobileApi.aspx?Action=NewSalesReport&unm={0}&assignID={1}&report_details={2}&appoi_date={3}",
                USERNAME,
                ASSIGNID,
                details,
                date);

var response = await client.PostAsync(url, null);

var responseContent = await response.Content.ReadAsStringAsync();
</code>```

Title: Http Posting in Xamarin.Forms

Body:
Am facing a problem in Posting data from my Entires via a parametrized url , i don't know why it's happening, the URL returns a certain message after posting  , below is my URL :

http://bbs.eamobiledirectory.com/Mobile/MobileApi.aspx?Action=NewSalesReport&username=USERNAME&assID=ASSIGNID&repdetails=details&appoi_date=date.

and this is how am posting my data :

    void OnSubmitReport(object sender, System.EventArgs e)
        {
            PostData();
        }

        public async void PostData()
        {

            string details = report_details_entry.Text;
            string date = nextappointment_entry.Text;

            var formContent = new FormUrlEncodedContent(new[]
                        {
                new KeyValuePair<string, string>("unm", USERNAME),
                new KeyValuePair<string, string >("assinID", ""+ASSIGNID),
                new KeyValuePair<string, string>("details", details),
                new KeyValuePair<string, string>("appoi_date", date)

   });

            var response = await client.PostAsync("http://bbs.eamobiledirectory.com/Mobile/MobileApi.aspx?Action=NewSalesReport",formContent);

        }

what i want is to submit the data in the Entries after wards i return a message in a DisplayAlert Message.

Body:
Until you figure out why the FormUrlEncodedContent not working(i would really like to know why its not working)

you can solve your problem by posting this way:

var url = string.Format("http://bbs.eamobiledirectory.com/Mobile/MobileApi.aspx?Action=NewSalesReport&unm={0}&assignID={1}&report_details={2}&appoi_date={3}",
                USERNAME,
                ASSIGNID,
                details,
                date);

var response = await client.PostAsync(url, null);

var responseContent = await response.Content.ReadAsStringAsync();


Title: transform a matrix inserting zero row

Body:
I have got a matrix, called crash.data. I would like to create a matrix which is exactly the same but with rows with zeros in between, as in the code below

> head(crash.data)
            [,1]       [,2]       [,3]
[1,]  0.14449657 -0.2289661 -0.9065017
[2,]  0.06079472 -0.1801571 -0.9796568
[3,] -0.04159815 -0.2442845 -0.9071650
[4,] -0.01820570 -0.1778194 -0.9765629
[5,] -0.06200437 -0.2801673 -0.9325789
[6,]  0.09424269 -0.2143995 -0.9233422
> graph<-matrix(0,ncol=3,nrow = 4000)
> for (i in seq(2,4000,2)){graph[i,]<-as.matrix(crash.data)[i/2,]}
> head(graph)
            [,1]       [,2]       [,3]
[1,]  0.00000000  0.0000000  0.0000000
[2,]  0.14449657 -0.2289661 -0.9065017
[3,]  0.00000000  0.0000000  0.0000000
[4,]  0.06079472 -0.1801571 -0.9796568
[5,]  0.00000000  0.0000000  0.0000000
[6,] -0.04159815 -0.2442845 -0.9071650

In order to do so, I am using a for cycle. Is there a nicer and faster way, ideally without using a for cycle?

Thanks

Body:
#DATA
set.seed(42)
m1 = matrix(rnorm(18), ncol = 3)

m2 = do.call(rbind, lapply(1:NROW(m1), function(i) rbind(rep(0, NCOL(m1)), m1[i,])))

m1
#           [,1]        [,2]       [,3]
#[1,]  1.3709584  1.51152200 -1.3888607
#[2,] -0.5646982 -0.09465904 -0.2787888
#[3,]  0.3631284  2.01842371 -0.1333213
#[4,]  0.6328626 -0.06271410  0.6359504
#[5,]  0.4042683  1.30486965 -0.2842529
#[6,] -0.1061245  2.28664539 -2.6564554

m2
#            [,1]        [,2]       [,3]
# [1,]  0.0000000  0.00000000  0.0000000
# [2,]  1.3709584  1.51152200 -1.3888607
# [3,]  0.0000000  0.00000000  0.0000000
# [4,] -0.5646982 -0.09465904 -0.2787888
# [5,]  0.0000000  0.00000000  0.0000000
# [6,]  0.3631284  2.01842371 -0.1333213
# [7,]  0.0000000  0.00000000  0.0000000
# [8,]  0.6328626 -0.06271410  0.6359504
# [9,]  0.0000000  0.00000000  0.0000000
#[10,]  0.4042683  1.30486965 -0.2842529
#[11,]  0.0000000  0.00000000  0.0000000
#[12,] -0.1061245  2.28664539 -2.6564554


问:
Robot framework: how to point to libraries folder other than default?
I've set up a Maven project that uses Selenium (as a dependency) and would like to add Robot. The thing is, according to http://robotframework.org/MavenPlugin/:

Third party libraries (e.g. Selenium Library) can be added to
  ${project.basedir}/src/test/resources/robotframework/libraries. Java
  dependencies can be expressed as dependencies to the Robotframework
  maven plugin configuration in pom.xml.

However, Maven stores the Selenium dependencies in its own repository.

Is there a way to tell Robot "this is where you'll find the libraries you'll need"? As it won't find them within the project structure.

答:
Is there a way to tell Robot "this is where you'll find the libraries
  you'll need"? As it won't find them within the project structure.

This is documented in the user guide, in a section titled Configuring where to search libraries and other extensions

In short, you can set the environment variable PYTHONPATH, or you can use the command line option --pythonpath.


答: It does work. [\d]* (BTW, brackets are unnecessary - \d* will do exactly the same) matches any sequence of digits, including 0 digits ie. an empty string. And empty string is matched anywhere, in particular at the beginning of the string. If you want a non-empty sequence of digits, use \d+ like you already did.

Title: Confusion about repeating pattern in python Regex


问:
2 column float wasted space
I have a container div, inside which I want to pack a variable number of divs of unknown (variable) height but with a given min-width. My requirements are:

If the container is wide enough to accommodate two columns, I want them to distribute themselves nicely in two columns without unnecessary whitespace.

It not, they should just go above each other.

Currently, I've given the divs width:48% margin-right:2%;float:left; which works nicely in the one-column state but when I resize the browser window, making room for two columns, every div which ends up in the left column insists on aligning itself horizontally with the bottom of the last div which went to the right:

what I have http://img602.imageshack.us/img602/5719/whatihave.png

This is how I would like them to go (no wasted space):

what I want http://img96.imageshack.us/img96/6985/whatiwantu.png

I would like a pure CSS solution if possible.

Thank you! /Gustav

EDIT:
This markup illustrates my problem:

```<code><html>
<head>
<style type="text/css">
.box {
  width: 48%;
  min-width:550px;
  margin-right:2%;
  margin-bottom: 1.5em;
  background:blue;
  color:white;
  height:180px;
  float:left;
}

.tall {
  height: 250px;
}

</style>
</head>
<body>
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box tall">4</div>
<div class="box">5</div>
<div class="box">6</div>
<div style="clear:both"/>
</body>
</html>
</code>```

The .boxes are generated dynamically, and so are their heights, I just threw in one taller to illustrate.

答:
I don't think you can achieve the desired effect with pure CSS. I've used jQuery Masonry to replicate the effect you're after and it worked really well.

I'd love to see a pure CSS solution for this but haven't seen anything come close yet.

Title: 2 column float wasted space

Body:
I have a container div, inside which I want to pack a variable number of divs of unknown (variable) height but with a given min-width. My requirements are:

If the container is wide enough to accommodate two columns, I want them to distribute themselves nicely in two columns without unnecessary whitespace.

It not, they should just go above each other.

Currently, I've given the divs width:48% margin-right:2%;float:left; which works nicely in the one-column state but when I resize the browser window, making room for two columns, every div which ends up in the left column insists on aligning itself horizontally with the bottom of the last div which went to the right:

what I have http://img602.imageshack.us/img602/5719/whatihave.png

This is how I would like them to go (no wasted space):

what I want http://img96.imageshack.us/img96/6985/whatiwantu.png

I would like a pure CSS solution if possible.

Thank you! /Gustav

EDIT:
This markup illustrates my problem:

1

2

3

4

5

6

The .boxes are generated dynamically, and so are their heights, I just threw in one taller to illustrate.


问:
Why does an attribute has a method?
I use pytorch define a Variable x, compute and get its gradient x.grad, meaning grad is an attribute of instance x. But, I can use x.grad.data.zero_() to set x.grad to zero meaning that data.zero_() is method of x.grad. Why does an attribute has a method? Thanks a lot.</p>

答: Because attribute x.grad is an object, and in most dynamic languages mostly everything is an object.

Title: Why does an attribute has a method?


问:
Hibernate ManyToMany wtih column child removal
I have Many To Many with additional column. Here realization(getters/setters generated by lombok, removed for clarity):

```<code>public class User extends BaseEntity {
@OneToMany(mappedBy = "user",
        orphanRemoval = true,
        fetch = FetchType.LAZY
        cascade = CascadeType.ALL,)
   private List<UserEvent> attendeeEvents = new ArrayList<>();
}

@Table(
        name = "UC_USER_EVENT",
        uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "event_id"})}
)
public class UserEvent extends BaseEntity {

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "event_id")
    private Event event;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_response_id")
    private UserResponse userResponse;
}

public class Event extends BaseEntity {
    @OneToMany(mappedBy = "event",
            orphanRemoval = true,
            fetch = FetchType.EAGER,
            cascade = CascadeType.ALL)
    private List<UserEvent> userEvents = new ArrayList<>();
}
</code>```

I want this - when i delete Event, All "UserEvents" connected to it should be removed. And if I delete User, all "UserEvents" should be removed too.

I delete my event(eventRepository is Spring Jpa interface):

```<code> eventRepository.delete(event);
</code>```

Then retrieving UserEvents from db:

```<code>List<UserEvent> userEvents = userEventsId.stream()
.map(id -> entityManager.find(UserEvent.class, id)).collect(Collectors.toList());
</code>```

And there is collection with 2 items(this is count of UserEvents), but they all "null".

I can't understand what happening and how to do it right.
I need them deleted and when I check collection there should be 0, instead of 2.

答:
The delete says marked for deletion, please try calling flush after deletion, and then find.

I guess find goes to the database, find the two rows, but when trying to instantiate them, find the entities marked for deletion and then you have this strange behaviour.

Recomendation: try to abstract more from the database and use less annotations. Learn the conventions of names for columns and tables (if you need to) and let JPA do its job.

Body:
I have Many To Many with additional column. Here realization(getters/setters generated by lombok, removed for clarity):

public class User extends BaseEntity {
@OneToMany(mappedBy = "user",
        orphanRemoval = true,
        fetch = FetchType.LAZY
        cascade = CascadeType.ALL,)
   private List<UserEvent> attendeeEvents = new ArrayList<>();
}

@Table(
        name = "UC_USER_EVENT",
        uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "event_id"})}
)
public class UserEvent extends BaseEntity {

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "event_id")
    private Event event;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_response_id")
    private UserResponse userResponse;
}

public class Event extends BaseEntity {
    @OneToMany(mappedBy = "event",
            orphanRemoval = true,
            fetch = FetchType.EAGER,
            cascade = CascadeType.ALL)
    private List<UserEvent> userEvents = new ArrayList<>();
}

I want this - when i delete Event, All "UserEvents" connected to it should be removed. And if I delete User, all "UserEvents" should be removed too.

I delete my event(eventRepository is Spring Jpa interface):

 eventRepository.delete(event);

Then retrieving UserEvents from db:

List<UserEvent> userEvents = userEventsId.stream()
.map(id -> entityManager.find(UserEvent.class, id)).collect(Collectors.toList());

And there is collection with 2 items(this is count of UserEvents), but they all "null".

I can't understand what happening and how to do it right.
I need them deleted and when I check collection there should be 0, instead of 2.


问:
Kubernetes - delete all jobs in bulk
I can delete all jobs inside a custer running

```<code>kubectl delete jobs --all
</code>```

However, jobs are deleted one after another which is pretty slow (for ~200 jobs I had the time to write this question and it was not even done).

Is there a faster approach ?

答:
I use this script, it's fast but it can trash CPU (a process per job), you can always adjust the sleep parameter:

```<code>#!/usr/bin/env bash

echo "Deleting all jobs (in parallel - it can trash CPU)"

kubectl get jobs --all-namespaces | sed '1d' | awk '{ print $2, "--namespace", $1 }' | while read line; do
  echo "Running with: ${line}"
  kubectl delete jobs ${line} &
  sleep 0.05
done
</code>```

Title: Kubernetes - delete all jobs in bulk

Body:
I can delete all jobs inside a custer running

kubectl delete jobs --all

However, jobs are deleted one after another which is pretty slow (for ~200 jobs I had the time to write this question and it was not even done).

Is there a faster approach ?

Body:
I use this script, it's fast but it can trash CPU (a process per job), you can always adjust the sleep parameter:

#!/usr/bin/env bash

echo "Deleting all jobs (in parallel - it can trash CPU)"

kubectl get jobs --all-namespaces | sed '1d' | awk '{ print $2, "--namespace", $1 }' | while read line; do
  echo "Running with: ${line}"
  kubectl delete jobs ${line} &
  sleep 0.05
done