问:
Semantic UI React item image as link
I am using Item (Semantic UI React) and I would like to set the image as a link. But how do I reference the link URL?

```<code><Item>
    <Item.Image src={this.props.fileUrl} size='tiny' as='a' />
    <Item.Content>
    </Item.Content>
</Item>
</code>```

If I wrap Item.Image in a a-container, the padding gets messed up...

答:
You're on right way, you need to use the SUIR's augmentation, all non Item.Image props will be by-passed:

```<code><Item.Image
  as='a'
  href='http://example.com'
  src={this.props.fileUrl}
  size='tiny'
/>
</code>```

Title: Semantic UI React item image as link

Body:
I am using Item (Semantic UI React) and I would like to set the image as a link. But how do I reference the link URL?

<Item>
    <Item.Image src={this.props.fileUrl} size='tiny' as='a' />
    <Item.Content>
    </Item.Content>
</Item>

If I wrap Item.Image in a a-container, the padding gets messed up...

Body:
You're on right way, you need to use the SUIR's augmentation, all non Item.Image props will be by-passed:

<Item.Image
  as='a'
  href='http://example.com'
  src={this.props.fileUrl}
  size='tiny'
/>


来源: stackexchange

问:
How to configure Spring AOP to use AspectJ
I want to use AOP concept to time execution time of some methods that I mark with an annotation that I created. My problem however is that I refer to the annotated method internally, from within the same class. For example:

```<code>public void login(params) {
    some logic ...
    performLogin();
    some logic ...
}

@Measured
public void performLogin() {
     some logic ...
}
</code>```

This is a known issue caused by the fact that Spring AOP is using proxy based approach that does not "see" the internal calls within the same class. Apparently I can solve this situation by using AspectJ instead of Spring AOP. If I understand correctly, it can be configured from within Spring itself. From what I found, it looks like I should include @EnableAspectJAutoProxy annotation to configure Spring to use AspectJ instead of its own AOP. Unfortunately, it did not help and after adding the annotation, the interception of the annotated method did not occur.

There is a lot of information on this topic in Spring reference documentation and I got a bit lost. Is there anything else I am supposed to do so that AspectJ will be used?

P.S. Please note that I cannot refactor the whole class and move the calling method outside.

P.P.S. I also verified my pointcut configuration. I annotated the calling method which is invoked externally and it worked fine.

答:
Proxies can only achieve a sub-set of the full capabilities of the actual AspectJ system, basically advice that wraps methods. Due to their nature proxies have following limitations:

interception on external calls only (while breaching proxy boundary)

interception on public members only (private/protected can't be intercepted)
unawareness to local calls (or calls with this or super)

<aop:aspectj-autoproxy /> is not enough - it only wraps methods, you need something like this: <context:load-time-weaver/>

If you want to be able to advise fields for example, you would need to enable the use of Native AspectJ.

ContentLicense: CC BY-SA 3.0

Body:
I want to use AOP concept to time execution time of some methods that I mark with an annotation that I created. My problem however is that I refer to the annotated method internally, from within the same class. For example:

public void login(params) {
    some logic ...
    performLogin();
    some logic ...
}

@Measured
public void performLogin() {
     some logic ...
}

This is a known issue caused by the fact that Spring AOP is using proxy based approach that does not "see" the internal calls within the same class. Apparently I can solve this situation by using AspectJ instead of Spring AOP. If I understand correctly, it can be configured from within Spring itself. From what I found, it looks like I should include @EnableAspectJAutoProxy annotation to configure Spring to use AspectJ instead of its own AOP. Unfortunately, it did not help and after adding the annotation, the interception of the annotated method did not occur.

There is a lot of information on this topic in Spring reference documentation and I got a bit lost. Is there anything else I am supposed to do so that AspectJ will be used?

P.S. Please note that I cannot refactor the whole class and move the calling method outside.

P.P.S. I also verified my pointcut configuration. I annotated the calling method which is invoked externally and it worked fine.


问:
How to save matplotlib plot with the same file name as its filename.py
I run the python code for Matplotlib plotting from thisfilename.py. Is there a variable that stores this filename without file path? As I want to save the plot as thisfilename.png without typing the file name like this every time?

```<code>if __name__ == '__main__':
  ...
  plt.savefig('thisfilename.png')
</code>```

I want to change the last line to something like

```<code>  # pseudocode
  plt.savefig(variable, '.png')
</code>```

I tested

```<code>  plt.savefig(__file__, ".png")
</code>```

The saved filename had .py, the file path, and the space before .png which I don't want

答:
```<code>import inspect
import matplotlib.pyplot as plt
import numpy as np

frame = inspect.currentframe()
path = inspect.getfile(frame)
fname = path.split('.')[0]

t = np.linspace(0,1, 1000)
plt.plot(t, np.sin(2*np.pi*t*4))
plt.savefig(fname + ".jpg")
</code>```

Body:
I run the python code for Matplotlib plotting from thisfilename.py. Is there a variable that stores this filename without file path? As I want to save the plot as thisfilename.png without typing the file name like this every time?

if __name__ == '__main__':
  ...
  plt.savefig('thisfilename.png')

I want to change the last line to something like

  # pseudocode
  plt.savefig(variable, '.png')

I tested

  plt.savefig(__file__, ".png")

The saved filename had .py, the file path, and the space before .png which I don't want


问:
Is there a standard C function for computing the string length up to some limit?
Consider a situation: I have a buffer of known length that presumably stores a null-terminated string and I need to know the length of the string.

The problem is if I use strlen() and the string turns out to be not null-terminated the program runs into undefined behavior while reading beyond the buffer end. So I'd like to have a function like the following:

```<code> size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }
</code>```

so that it returns the length of the string but never tries to read beyond the buffer end.

Is there such function already in C library or do I have to use my own?

答:
According to my documentation, POSIX has size_t strnlen(const char *src, size_t maxlen);

```<code>n = strnlen("foobar", 7); // n = 6;
n = strnlen("foobar", 6); // n = 6;
n = strnlen("foobar", 5); // n = 5;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Consider a situation: I have a buffer of known length that presumably stores a null-terminated string and I need to know the length of the string.

The problem is if I use strlen() and the string turns out to be not null-terminated the program runs into undefined behavior while reading beyond the buffer end. So I'd like to have a function like the following:

 size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }

so that it returns the length of the string but never tries to read beyond the buffer end.

Is there such function already in C library or do I have to use my own?

Body:
According to my documentation, POSIX has size_t strnlen(const char *src, size_t maxlen);

n = strnlen("foobar", 7); // n = 6;
n = strnlen("foobar", 6); // n = 6;
n = strnlen("foobar", 5); // n = 5;


问:
ios - Convert CGPoints (CIRectangleFeature) from Image to ImageView
I am creating an iPhone app that detects Rectangle and captures image using Camera. I create an overlay over the biggest rectangle detected and once captured i have 4 CGPoints using CIRectangleFeature and an Image.

All 4 points in CIRectangleFeature are in landscape and my app is in Portrait.

When i display image in UIImageView on next controller the  the coordinates they are disturbed. The Image View is in AspectFit Mode. I searched and found a few of solutions, one was

```<code>extension CGPoint {
func scalePointByCeficient(ƒ_x: CGFloat, ƒ_y: CGFloat, viewWidth: CGSize, imageWidth: CGSize) -> CGPoint {
    let scale: CGFloat;
    scale = min(ƒ_x, ƒ_y)

    var p: CGPoint = CGPoint(x: self.x, y: self.y)

    p.x *= scale
    p.y *= scale

    p.x += (viewWidth.width - imageWidth.width * scale) / 2.0
    p.y += (viewWidth.height - imageWidth.height * scale) / 2.0

    return p

}

func reversePointCoordinates() -> CGPoint {
    return CGPoint(x: self.y, y: self.x)
}

func sumPointCoordinates(add: CGPoint) -> CGPoint {
    return CGPoint(x: self.x + add.x, y: self.y + add.y)
}

func substractPointCoordinates(sub: CGPoint) -> CGPoint {
    return CGPoint(x: self.x - sub.x, y: self.y - sub.y)
}}

class ObyRectangleFeature : NSObject {

public var topLeft: CGPoint
public var topRight: CGPoint
public var bottomLeft: CGPoint
public var bottomRight: CGPoint

var myRect: CIRectangleFeature?

public var viewWidth: CGSize
public var imageWidth: CGSize

var centerPoint_OLD : CGPoint{
    get {

        myRect?.topLeft = self.topLeft
        myRect?.topRight = self.topRight
        myRect?.bottomLeft = self.bottomLeft
        myRect?.bottomRight = self.bottomRight

        let superCenter: CGPoint = CGPoint(x: (myRect?.bounds().midX)!, y: (myRect?.bounds().midY)!)

        return superCenter
    }

}
var centerPoint : CGPoint{
    get {
        myRect?.topLeft = self.topLeft
        myRect?.topRight = self.topRight
        myRect?.bottomLeft = self.bottomLeft
        myRect?.bottomRight = self.bottomRight

        let superCenter: CGPoint = CGPoint(x: (myRect?.bounds().midX)!, y: (myRect?.bounds().midY)!)

        return superCenter
    }

}

convenience init(rectObj rectangleFeature: CIRectangleFeature) {
    self.init()

    myRect = rectangleFeature

    topLeft = rectangleFeature.topLeft
    topRight = rectangleFeature.topRight
    bottomLeft = rectangleFeature.bottomLeft
    bottomRight = rectangleFeature.bottomRight
}

override init() {

    self.topLeft = CGPoint.zero
    self.topRight = CGPoint.zero
    self.bottomLeft = CGPoint.zero
    self.bottomRight = CGPoint.zero

    self.viewWidth = CGSize.zero
    self.imageWidth = CGSize.zero

    super.init()

}

public func rotate90Degree() -> Void {

    let centerPoint =  self.centerPoint

    //        /rotate cos(90)=0, sin(90)=1
    topLeft = CGPoint(x: centerPoint.x + (topLeft.y - centerPoint.y), y: centerPoint.y + (topLeft.x - centerPoint.x))
    topRight = CGPoint(x: centerPoint.x + (topRight.y - centerPoint.y), y: centerPoint.y + (topRight.x - centerPoint.x))
    bottomLeft = CGPoint(x: centerPoint.x + (bottomLeft.y - centerPoint.y), y: centerPoint.y + (bottomLeft.x - centerPoint.x))
    bottomRight = CGPoint(x: centerPoint.x + (bottomRight.y - centerPoint.y), y: centerPoint.y + (bottomRight.x - centerPoint.x))

    print(self.centerPoint)
}

public func  scaleRectWithCoeficient(ƒ_x: CGFloat, ƒ_y: CGFloat) -> Void {
    topLeft =  topLeft.scalePointByCeficient(ƒ_x: ƒ_x, ƒ_y: ƒ_y, viewWidth: self.viewWidth, imageWidth: self.imageWidth)
    topRight = topRight.scalePointByCeficient(ƒ_x: ƒ_x, ƒ_y: ƒ_y, viewWidth: self.viewWidth, imageWidth: self.imageWidth)
    bottomLeft = bottomLeft.scalePointByCeficient(ƒ_x: ƒ_x, ƒ_y: ƒ_y, viewWidth: self.viewWidth, imageWidth: self.imageWidth)
    bottomRight = bottomRight.scalePointByCeficient(ƒ_x: ƒ_x, ƒ_y: ƒ_y, viewWidth: self.viewWidth, imageWidth: self.imageWidth)
}

public func correctOriginPoints() -> Void {

    let deltaCenter = self.centerPoint.reversePointCoordinates().substractPointCoordinates(sub: self.centerPoint)

    let TL = topLeft
    let TR = topRight
    let BL = bottomLeft
    let BR = bottomRight

    topLeft = BL.sumPointCoordinates(add: deltaCenter)
    topRight = TL.sumPointCoordinates(add: deltaCenter)
    bottomLeft = BR.sumPointCoordinates(add: deltaCenter)
    bottomRight = TR.sumPointCoordinates(add: deltaCenter)

    print(self.centerPoint)
}}
</code>```

Its calling is like

```<code>ObyRectangleFeature *scaledRect = [[ObyRectangleFeature alloc] initWithRectObj:(id)rect_rect];

    float f_x = _sourceImageView.frame.size.width / _sourceImageView.image.size.width;
    float f_y = _sourceImageView.frame.size.height / _sourceImageView.image.size.height;

    [scaledRect setViewWidth:_sourceImageView.bounds.size];
    [scaledRect setImageWidth:_sourceImageView.image.size];

    [scaledRect scaleRectWithCoeficientWithƒ_x:f_y ƒ_y:f_x];
    [scaledRect rotate90Degree];
    [scaledRect correctOriginPoints];
</code>```

Basically it checks scale factor and convert points to UIImageView coordinates and then considering Landscape factor it rotates it by 90 degree or more according to requirement. But the result i get is a bit problemetic

As you can see the rect that is made is displaced below the card. Any Ideas on how to solve this problem?

答: The issue is the contentMode of the UIImageView changes where the Image is placed in the view.  It appears that you are using aspect fit, so you have to calculate how much of the UImageView is the black bars and then divide the image size by the imageView size and then add the offset based on the black bars.  It is really not that hard, but the math can be tricky.  I would recommend using https://github.com/nubbel/UIImageView-GeometryConversion which does the math for all the different content modes.  </p>

Body:
I am creating an iPhone app that detects Rectangle and captures image using Camera. I create an overlay over the biggest rectangle detected and once captured i have 4 CGPoints using CIRectangleFeature and an Image.

All 4 points in CIRectangleFeature are in landscape and my app is in Portrait.

When i display image in UIImageView on next controller the  the coordinates they are disturbed. The Image View is in AspectFit Mode. I searched and found a few of solutions, one was

extension CGPoint {
func scalePointByCeficient(ƒ_x: CGFloat, ƒ_y: CGFloat, viewWidth: CGSize, imageWidth: CGSize) -> CGPoint {
    let scale: CGFloat;
    scale = min(ƒ_x, ƒ_y)

    var p: CGPoint = CGPoint(x: self.x, y: self.y)

    p.x *= scale
    p.y *= scale

    p.x += (viewWidth.width - imageWidth.width * scale) / 2.0
    p.y += (viewWidth.height - imageWidth.height * scale) / 2.0

    return p

}

func reversePointCoordinates() -> CGPoint {
    return CGPoint(x: self.y, y: self.x)
}

func sumPointCoordinates(add: CGPoint) -> CGPoint {
    return CGPoint(x: self.x + add.x, y: self.y + add.y)
}

func substractPointCoordinates(sub: CGPoint) -> CGPoint {
    return CGPoint(x: self.x - sub.x, y: self.y - sub.y)
}}

class ObyRectangleFeature : NSObject {

public var topLeft: CGPoint
public var topRight: CGPoint
public var bottomLeft: CGPoint
public var bottomRight: CGPoint

var myRect: CIRectangleFeature?

public var viewWidth: CGSize
public var imageWidth: CGSize

var centerPoint_OLD : CGPoint{
    get {

        myRect?.topLeft = self.topLeft
        myRect?.topRight = self.topRight
        myRect?.bottomLeft = self.bottomLeft
        myRect?.bottomRight = self.bottomRight

        let superCenter: CGPoint = CGPoint(x: (myRect?.bounds().midX)!, y: (myRect?.bounds().midY)!)

        return superCenter
    }

}
var centerPoint : CGPoint{
    get {
        myRect?.topLeft = self.topLeft
        myRect?.topRight = self.topRight
        myRect?.bottomLeft = self.bottomLeft
        myRect?.bottomRight = self.bottomRight

        let superCenter: CGPoint = CGPoint(x: (myRect?.bounds().midX)!, y: (myRect?.bounds().midY)!)

        return superCenter
    }

}

convenience init(rectObj rectangleFeature: CIRectangleFeature) {
    self.init()

    myRect = rectangleFeature

    topLeft = rectangleFeature.topLeft
    topRight = rectangleFeature.topRight
    bottomLeft = rectangleFeature.bottomLeft
    bottomRight = rectangleFeature.bottomRight
}

override init() {

    self.topLeft = CGPoint.zero
    self.topRight = CGPoint.zero
    self.bottomLeft = CGPoint.zero
    self.bottomRight = CGPoint.zero

    self.viewWidth = CGSize.zero
    self.imageWidth = CGSize.zero

    super.init()

}

public func rotate90Degree() -> Void {

    let centerPoint =  self.centerPoint

    //        /rotate cos(90)=0, sin(90)=1
    topLeft = CGPoint(x: centerPoint.x + (topLeft.y - centerPoint.y), y: centerPoint.y + (topLeft.x - centerPoint.x))
    topRight = CGPoint(x: centerPoint.x + (topRight.y - centerPoint.y), y: centerPoint.y + (topRight.x - centerPoint.x))
    bottomLeft = CGPoint(x: centerPoint.x + (bottomLeft.y - centerPoint.y), y: centerPoint.y + (bottomLeft.x - centerPoint.x))
    bottomRight = CGPoint(x: centerPoint.x + (bottomRight.y - centerPoint.y), y: centerPoint.y + (bottomRight.x - centerPoint.x))

    print(self.centerPoint)
}

public func  scaleRectWithCoeficient(ƒ_x: CGFloat, ƒ_y: CGFloat) -> Void {
    topLeft =  topLeft.scalePointByCeficient(ƒ_x: ƒ_x, ƒ_y: ƒ_y, viewWidth: self.viewWidth, imageWidth: self.imageWidth)
    topRight = topRight.scalePointByCeficient(ƒ_x: ƒ_x, ƒ_y: ƒ_y, viewWidth: self.viewWidth, imageWidth: self.imageWidth)
    bottomLeft = bottomLeft.scalePointByCeficient(ƒ_x: ƒ_x, ƒ_y: ƒ_y, viewWidth: self.viewWidth, imageWidth: self.imageWidth)
    bottomRight = bottomRight.scalePointByCeficient(ƒ_x: ƒ_x, ƒ_y: ƒ_y, viewWidth: self.viewWidth, imageWidth: self.imageWidth)
}

public func correctOriginPoints() -> Void {

    let deltaCenter = self.centerPoint.reversePointCoordinates().substractPointCoordinates(sub: self.centerPoint)

    let TL = topLeft
    let TR = topRight
    let BL = bottomLeft
    let BR = bottomRight

    topLeft = BL.sumPointCoordinates(add: deltaCenter)
    topRight = TL.sumPointCoordinates(add: deltaCenter)
    bottomLeft = BR.sumPointCoordinates(add: deltaCenter)
    bottomRight = TR.sumPointCoordinates(add: deltaCenter)

    print(self.centerPoint)
}}

Its calling is like

ObyRectangleFeature *scaledRect = [[ObyRectangleFeature alloc] initWithRectObj:(id)rect_rect];

    float f_x = _sourceImageView.frame.size.width / _sourceImageView.image.size.width;
    float f_y = _sourceImageView.frame.size.height / _sourceImageView.image.size.height;

    [scaledRect setViewWidth:_sourceImageView.bounds.size];
    [scaledRect setImageWidth:_sourceImageView.image.size];

    [scaledRect scaleRectWithCoeficientWithƒ_x:f_y ƒ_y:f_x];
    [scaledRect rotate90Degree];
    [scaledRect correctOriginPoints];

Basically it checks scale factor and convert points to UIImageView coordinates and then considering Landscape factor it rotates it by 90 degree or more according to requirement. But the result i get is a bit problemetic

As you can see the rect that is made is displaced below the card. Any Ideas on how to solve this problem?


问:
Tasks for production prepared Ionic app
I'm trying to figure out what's the best process to pass from the code to the final deployable apk/ipa.

So far I have a testsuite using Karma + Jasmine, which transpiles the TypeScript to JS and runs some unit tests. I start that process via gulp.

After that all I know is to ionic build android --release what generates (an unsigned yet) apk.
But I'm not sure of how ofuscated/minificated the generated apk is.

So, keeping in mind the code has to be as private as possible, is the minification and the ofuscation of the ionic build enough or should I do all those prebuild tasks manually via gulp?
And in that case, whats are the right tasks I should run, do I have to transpile all the TypeScript files to JS manually? and in what order should I run the tasks?

E.g. transpile -> tests -> minify -> uglify -> build apk or minify -> uglify -> transpile -> tests -> build apk

I'm a bit lost with this, and the only thing I can figure out is that the tests should be ran first, because is case of test failure the process should be aborted.

答:
Preparing an Ionic Cordova app for release in production

1. Building

In your terminal execute the following command according to your platform (android / ios):

ionic build android --prod --release

2. Releasing

In order to be able to install a production application on a device and furthermore in order to be able to publish it in app stores, your .apk or .ipa
file needs to be signed. How you do that depends on the platform.

Here is the procedure in detail for Android and for iOS.

Preparing an Ionic Progressive Web App (PWA) for release in production

1. Building

In your package.json file, you should make sure to have something like the following:

```<code>"scripts": {
     // ...
     "build:www": "rm -rf www && ionic-app-scripts build --prod",
     // ...
},
</code>```

Now in your terminal run:

npm run build:www

2. Releasing

Your app is built in the folder www ready for you to serve in production using any webserver like NginX, Apache or a custom Node + Express webserver.

Valid as of Ionic v3.3

Learn more about ionic-scripts, what they do and which other scripts you could possibly find useful.

Title: Tasks for production prepared Ionic app

Body:
Preparing an Ionic Cordova app for release in production

1. Building

In your terminal execute the following command according to your platform (android / ios):

ionic build android --prod --release

2. Releasing

In order to be able to install a production application on a device and furthermore in order to be able to publish it in app stores, your .apk or .ipa
file needs to be signed. How you do that depends on the platform.

Here is the procedure in detail for Android and for iOS.

Preparing an Ionic Progressive Web App (PWA) for release in production

1. Building

In your package.json file, you should make sure to have something like the following:

"scripts": {
     // ...
     "build:www": "rm -rf www && ionic-app-scripts build --prod",
     // ...
},

Now in your terminal run:

npm run build:www

2. Releasing

Your app is built in the folder www ready for you to serve in production using any webserver like NginX, Apache or a custom Node + Express webserver.

Valid as of Ionic v3.3

Learn more about ionic-scripts, what they do and which other scripts you could possibly find useful.


问:
Adding fragment destroys activity
I have an Activity with a container being a FrameLayout. I need to add a fragment to that container, but doing so throws an IllegalStateException, destroying my Activity.

This is my container in the activity layout:

```<code><FrameLayout
    android:id="@+id/seeMoreContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>
</code>```

This is how I add the fragment to the activity

```<code>PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();
</code>```

And this is the logcat

```<code>java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
                                                                   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
                                                                   at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)
</code>```

What am I doing wrong here?

EDIT:

I add the fragment to the activity from a public method, which I call from onItemClickListener of a ListView

This is the whole method

```<code>public void openPlaceSeeMore(int poiID){
    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}
</code>```

And this is how the method is called

```<code>mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PlacesActivity placesActivity = new PlacesActivity();
            placesActivity.openPlaceSeeMore(poi.getId());
        }
    });
</code>```

答:
Use below code....</p>

```<code> Fragment fragment = new PlacesSeeMoreFragment();
                FragmentManager fm = getActivity().getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.commit();
                Bundle bundle = new Bundle();
                bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
                fragment.setArguments(bundle);
</code>```

Title: Adding fragment destroys activity

Body:
I have an Activity with a container being a FrameLayout. I need to add a fragment to that container, but doing so throws an IllegalStateException, destroying my Activity.

This is my container in the activity layout:

<FrameLayout
    android:id="@+id/seeMoreContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

This is how I add the fragment to the activity

PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();

And this is the logcat

java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
                                                                   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
                                                                   at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)

What am I doing wrong here?

EDIT:

I add the fragment to the activity from a public method, which I call from onItemClickListener of a ListView

This is the whole method

public void openPlaceSeeMore(int poiID){
    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}

And this is how the method is called

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PlacesActivity placesActivity = new PlacesActivity();
            placesActivity.openPlaceSeeMore(poi.getId());
        }
    });

Body:
Use below code....

 Fragment fragment = new PlacesSeeMoreFragment();
                FragmentManager fm = getActivity().getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.commit();
                Bundle bundle = new Bundle();
                bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
                fragment.setArguments(bundle);


问:
Angular 2 *ngFor handles update wrong
I have the following Problem:
I am using this *ngFor loop:

```<code><app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>
</code>```

if the Array "subsectors" looks like this:

```<code>var subsectors = [
    {text: 'test', title: 'test', id: 'abc'},
    {text: 'test123', title: 'test123', id: 'def'},
    {text: 'test321', title: 'test321', id: 'ghi'}
]
</code>```

It adds 3 "app-sector"-Components as expected. Those "app-sector"-Components are being added inside an "app-sector"-Component. The parent gets his subsectors from his parent via "@Input" in my "app-component".

This is how the HTML-Structure looks like:

```<code><app-root>
    <app-sector *ngIf="playlist" [sector]="playlist">
        <app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>
    </app-sector>
</app-root>
</code>```

Now here is where the Problem starts:
When I update the subsectors like this:

```<code>//Add new subsectors
this.subsectors.push({text: 'Blah', title: 'Blah', id: '123'});
this.subsectors.push({text: 'Blah123', title: 'Blah123', id: '456'});
this.subsectors.push({text: 'Blah321', title: 'Blah321', id: '789'});

//Remove old subsectors
this.subsectors.splice(2, 1);
this.subsectors.splice(1, 1);
this.subsectors.splice(0, 1);
</code>```

The *ngFor doesn't create new Components and only destroys a few. I can't really see a pattern. It seems to decide randomly if it destroys or creates new Components.

Here is what i've tried sofar:
Use trackBy. I added a trackBy filter which returned the "id" property but it didn't change anything. Here is how:

```<code><app-sector *ngFor="let subsector of sector.subsectors; trackBy:identify;" [sector]="subsector"></app-sector>

identify(index,item){
    return item.id;
}
</code>```

then i tried some Tricks i've seen while researching this issue, like using slice instead of splice. Or in the Parent i tried to do this:

```<code>ngOnChanges(changes) {
    if(this.sector['subsectors']) {
        setTimeout(() => {
            console.log('spliced subsectores for reinitialization');
            this.sector['subsectors'] = this.sector['subsectors'].slice();
        }, 1000);
    }
}
</code>```

I hope you can help me! Please ask me in the comments if you need any further information to help me :)

kind regards.

答: I have solved this. I had to add changeDetection: ChangeDetectionStrategy.OnPush inside my @Component({}). It tells Angular2 to treat any input as if they're immutable. - Solved.

Title: Angular 2 *ngFor handles update wrong

Body:
I have the following Problem:
I am using this *ngFor loop:

<app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>

if the Array "subsectors" looks like this:

var subsectors = [
    {text: 'test', title: 'test', id: 'abc'},
    {text: 'test123', title: 'test123', id: 'def'},
    {text: 'test321', title: 'test321', id: 'ghi'}
]

It adds 3 "app-sector"-Components as expected. Those "app-sector"-Components are being added inside an "app-sector"-Component. The parent gets his subsectors from his parent via "@Input" in my "app-component".

This is how the HTML-Structure looks like:

<app-root>
    <app-sector *ngIf="playlist" [sector]="playlist">
        <app-sector *ngFor="let subsector of sector.subsectors" [sector]="subsector"></app-sector>
    </app-sector>
</app-root>

Now here is where the Problem starts:
When I update the subsectors like this:

//Add new subsectors
this.subsectors.push({text: 'Blah', title: 'Blah', id: '123'});
this.subsectors.push({text: 'Blah123', title: 'Blah123', id: '456'});
this.subsectors.push({text: 'Blah321', title: 'Blah321', id: '789'});

//Remove old subsectors
this.subsectors.splice(2, 1);
this.subsectors.splice(1, 1);
this.subsectors.splice(0, 1);

The *ngFor doesn't create new Components and only destroys a few. I can't really see a pattern. It seems to decide randomly if it destroys or creates new Components.

Here is what i've tried sofar:
Use trackBy. I added a trackBy filter which returned the "id" property but it didn't change anything. Here is how:

<app-sector *ngFor="let subsector of sector.subsectors; trackBy:identify;" [sector]="subsector"></app-sector>

identify(index,item){
    return item.id;
}

then i tried some Tricks i've seen while researching this issue, like using slice instead of splice. Or in the Parent i tried to do this:

ngOnChanges(changes) {
    if(this.sector['subsectors']) {
        setTimeout(() => {
            console.log('spliced subsectores for reinitialization');
            this.sector['subsectors'] = this.sector['subsectors'].slice();
        }, 1000);
    }
}

I hope you can help me! Please ask me in the comments if you need any further information to help me :)

kind regards.


问:
The request is missing when the page jumped
```<code>fetch(url, { method: 'POST', body: data, mode: 'cors' }).then(
    () => Promise.resolve(success),
    () => Promise.reject(error),
);
</code>```

I have a page, the page has a jump button, when I click this button my page was jumped to another page, by location.href or window.open ().

But I would like to sending a request when the jump button is clicked, through the above fetch function.

Now, the problem is the page jumps too fast, the request is failed. When I set a long delay the jump is success, there is better way to handle it.

Forgive me，My English is not good, hope you can understand.

答:
If you care more about the redirection than the request being successful, you can use Promise.race() to induce a timeout:

```<code>// Helper that creates a Promise that resolves after n milliseconds
const delay = n => new Promise(resolve => setTimeout(resolve, n));

Promise.race([fetch(url), delay(1000)])
  .then(() => redirectElsewhere())
  .catch(() => {/* handle error */});
</code>```

Promise.race() takes an iterable of Promises, and resolves immediately when the first of them resolves (or rejects when the first rejects).

The effect this will give you is that you'll redirect when the request Promise resolves, or after 1000ms, whichever comes first.

Body:
fetch(url, { method: 'POST', body: data, mode: 'cors' }).then(
    () => Promise.resolve(success),
    () => Promise.reject(error),
);

I have a page, the page has a jump button, when I click this button my page was jumped to another page, by location.href or window.open ().

But I would like to sending a request when the jump button is clicked, through the above fetch function.

Now, the problem is the page jumps too fast, the request is failed. When I set a long delay the jump is success, there is better way to handle it.

Forgive me，My English is not good, hope you can understand.

Body:
If you care more about the redirection than the request being successful, you can use Promise.race() to induce a timeout:

// Helper that creates a Promise that resolves after n milliseconds
const delay = n => new Promise(resolve => setTimeout(resolve, n));

Promise.race([fetch(url), delay(1000)])
  .then(() => redirectElsewhere())
  .catch(() => {/* handle error */});

Promise.race() takes an iterable of Promises, and resolves immediately when the first of them resolves (or rejects when the first rejects).

The effect this will give you is that you'll redirect when the request Promise resolves, or after 1000ms, whichever comes first.


问:
Convert string type to 8 digit in c#
I need to convert this value to 8 digit format. (example : 1 --> 00000001).any help? here's my code</p>

```<code>foreach(DataRow dr in _dsGridCsv.Tables[0].Rows)
  {
     byte empfrmat =byte.Parse(dr["emp_id"].ToString());
     csv += empfrmat;
     csv += "\r\n";
  }
</code>```

答:
So you want to change the value to 8 digit format, according to the example that you specified, you can try the following code for this:</p>

```<code>int value = 1;
String outputStr = value.ToString("00000000");
Console.WriteLine(outputStr) // this will print 00000001
</code>```

Title: Convert string type to 8 digit in c#

Body:
I need to convert this value to 8 digit format. (example : 1 --> 00000001).any help? here's my code

foreach(DataRow dr in _dsGridCsv.Tables[0].Rows)
  {
     byte empfrmat =byte.Parse(dr["emp_id"].ToString());
     csv += empfrmat;
     csv += "\r\n";
  }

Body:
So you want to change the value to 8 digit format, according to the example that you specified, you can try the following code for this:

int value = 1;
String outputStr = value.ToString("00000000");
Console.WriteLine(outputStr) // this will print 00000001


问:
Searching or filtering on a multi value field
I have a MySQL database with a table that contains 2 importants fields title and age_range.

That table saves documents  like this '45;60' for documents designed for users between 45 and 60 years old, '18;70'  for users between 18 and 70 years old and so on...

Now I would like to fire the query  'test' on the field title  with the filter '18;50' for the field age_range that will return all documents matching 'test' with the age range field contained in this interval including the 2 cases above for example.

For instance, I use Logstash to index my data.

How can I achieve this?

Any treatment to do while indexing my data with logstash?

Any filter, tokenizer to use while indexing using ES analyzer?

Thank you in advance

答:
You can split the data as two fields with grok filter. To ship data to Elasticsearch, you can use logstash jdbc_streaming input and elasticsearch output firstly. And you configure your input like below:

```<code>input {
    jdbc_streaming {
        # Configuration of jdbc
        # https://www.elastic.co/guide/en/logstash/current/plugins-filters-jdbc_streaming.html
    }
}

filter {
    # Split the field as separeted two fields
    grok {
        match => { "age_range" => "%{NUMBER:age_range_top};%{NUMBER:age_range_bottom}" }
    }
}

output {
    elasticsearch {
        # elasticsearch output configuration
    }
}
</code>```

Analysis depends on your search method. How can you want to search these fields. Range fields is necessary default one if you want to do only range filter. But you should do some work about title. For example you can follow this example to handle autocomplete.

Body:
You can split the data as two fields with grok filter. To ship data to Elasticsearch, you can use logstash jdbc_streaming input and elasticsearch output firstly. And you configure your input like below:

input {
    jdbc_streaming {
        # Configuration of jdbc
        # https://www.elastic.co/guide/en/logstash/current/plugins-filters-jdbc_streaming.html
    }
}

filter {
    # Split the field as separeted two fields
    grok {
        match => { "age_range" => "%{NUMBER:age_range_top};%{NUMBER:age_range_bottom}" }
    }
}

output {
    elasticsearch {
        # elasticsearch output configuration
    }
}

Analysis depends on your search method. How can you want to search these fields. Range fields is necessary default one if you want to do only range filter. But you should do some work about title. For example you can follow this example to handle autocomplete.


问:
How to Split row into multiple columns in MySQL

Hi can somebody help me, i have some question on how to separate this row into columns with the same id number. I have tried some SQL function like GROUP_CONCAT() or SUBSTRING_INDEX() function but i dont know how it works

I want the output to look something like this

答:
It should resolve your problem:</p>

```<code>INSERT INTO output SELECT
    input.ID,
    MIN(input.Unit_Cost),
    MAX(input.Unit_Cost)
FROM input
GROUP BY input.ID
</code>```

Body:
It should resolve your problem:

INSERT INTO output SELECT
    input.ID,
    MIN(input.Unit_Cost),
    MAX(input.Unit_Cost)
FROM input
GROUP BY input.ID


问:
How to throw compile time exception, if certain value is not set.
I have created an Android library, there is a method setContext()in it. Client need to pass context other wise app will crash at runtime. I need to throw an error on compile time, if user does not set context. I can't pass it throw constructor as its a singleton class.

Client

```<code>SampleLibrary sl= SampleLibrary.getInstance();
sl.setContext(this);
</code>```

Class

```<code>public void setContext(Context context){
  this.context= context;
}
</code>```

Kindly guide me How to throw compile time exception, if certain value is not set or null.

答:
Avoid setting Context in a singleton. It could be null, or worth, create a memory leak.
You should pass the Context to the class constructor when you need it

If you want to throw an Exception at Runtime :

```<code>  private setField(String value) throws IllegalStateException {
            if (TextUtils.isEmpty(value) {
                throw new IllegalStateException("Missing values");
// set your value here
     }
</code>```

Body:
I have created an Android library, there is a method setContext()in it. Client need to pass context other wise app will crash at runtime. I need to throw an error on compile time, if user does not set context. I can't pass it throw constructor as its a singleton class.

Client

SampleLibrary sl= SampleLibrary.getInstance();
sl.setContext(this);

Class

public void setContext(Context context){
  this.context= context;
}

Kindly guide me How to throw compile time exception, if certain value is not set or null.

Body:
Avoid setting Context in a singleton. It could be null, or worth, create a memory leak.
You should pass the Context to the class constructor when you need it

If you want to throw an Exception at Runtime :

  private setField(String value) throws IllegalStateException {
            if (TextUtils.isEmpty(value) {
                throw new IllegalStateException("Missing values");
// set your value here
     }


问:
How to launch two separate instances of Shell Exec to run at the same time
I've got a need for some php code to launch more than one instance of Shell exec and run a command.
At present my code trys to run both commands in the same window which makes the second command fail. As the commands need to run at the same time a separate windows is best for me, the command is launching an adobe product.
Any help would be much appreciated.</p>

答:
You need to use threading to do that.
One simple method would be to trigger your shell exec calls through ajax calls, so you can hit 2 parallel ajax url's to trigger your shell exec.

Most by default iis servers allow up to 6 parallel connections from the same client.


问:
Addressing instance name string in __init__(self) in Python
I am doing something like this:

```<code>class Class(object):
    def __init__(self):
        self.var=#new instance name string#
</code>```

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

```<code>c=Class()
</code>```

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

答: I don't think this would be possible because the assignment to the variable of your new instance occours after the object is fully constructed and initialized and so you don't know the variable name it will be assigned to within init method

OwnerDisplayName: xktybot

Body:
I am doing something like this:

class Class(object):
    def __init__(self):
        self.var=#new instance name string#

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

c=Class()

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

LastEditorDisplayName: xktybot


答:
```<code>public void setContext(Context context){
</code>```

should be

```<code>public synchronized void setContext(Context context){
</code>```

And of course it assumes that a single client uses the class.

Otherwise you could overwrite the singleton state between thread calls and it seems rather inappropriate that one thread works with the context set by another tread (in a race condition case).

Client need to pass context other wise app will crash at runtime. I
  need to throw an error on compile time, if user does not set context.

A compiler is not designed to check the functional validation of the code.
It checks you respect the language rules and it is already very fine.

What you need is a runtime exeption that should be thrown if the user tries to manipulate the class while the context is not set.

To achieve it, you could do a check as first task in all public methods where the context is required.

Of course, you could create a private method and reuse it in each one of these places.

If the check fails, you throw a RuntimeException with the appropriate message.

If you want to really avoid to do these checks at many places, you can still use AOP.

Title: How to throw compile time exception, if certain value is not set.

Body:
public void setContext(Context context){

should be

public synchronized void setContext(Context context){

And of course it assumes that a single client uses the class.

Otherwise you could overwrite the singleton state between thread calls and it seems rather inappropriate that one thread works with the context set by another tread (in a race condition case).

Client need to pass context other wise app will crash at runtime. I
  need to throw an error on compile time, if user does not set context.

A compiler is not designed to check the functional validation of the code.
It checks you respect the language rules and it is already very fine.

What you need is a runtime exeption that should be thrown if the user tries to manipulate the class while the context is not set.

To achieve it, you could do a check as first task in all public methods where the context is required.

Of course, you could create a private method and reuse it in each one of these places.

If the check fails, you throw a RuntimeException with the appropriate message.

If you want to really avoid to do these checks at many places, you can still use AOP.


问:
Keras model.compile: metrics to be evaluated by the model
I am following some Keras tutorials and I understand the model.compile method creates a model and takes the 'metrics' parameter to define what metrics are used for evaluation during training and testing.

```<code>compile(self, optimizer, loss, metrics=[], sample_weight_mode=None)
</code>```

The tutorials I follow typically use "metrics=['accuracy']". I would like to use other metrics such as fmeasure, and reading https://keras.io/metrics/ I know there is a wide range of options. but I do not know how to pass them to the compile method?

For example:

```<code>model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['fmeasure'])
</code>```

will generate an error saying that there is no such metric.

Any suggestions highly appreciated

Thanks

答:
I believe that your question is similar to https://stackoverflow.com/a/43354147/6701627. Please check the answer in the given post.

PS: I intended to put this as a comment, but don't have sufficient reputation points.

Body:
I am following some Keras tutorials and I understand the model.compile method creates a model and takes the 'metrics' parameter to define what metrics are used for evaluation during training and testing.

compile(self, optimizer, loss, metrics=[], sample_weight_mode=None)

The tutorials I follow typically use "metrics=['accuracy']". I would like to use other metrics such as fmeasure, and reading https://keras.io/metrics/ I know there is a wide range of options. but I do not know how to pass them to the compile method?

For example:

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['fmeasure'])

will generate an error saying that there is no such metric.

Any suggestions highly appreciated

Thanks


问:
Highcart data not shown from MySQL to JSON data
```<code>$sql = "SELECT * FROM `demo_viewer` WHERE 1 ";

$viewer = mysqli_query($mysqli,$sql);

$view = array();

while ($row = mysqli_fetch_array($viewer)){

    $view[] = $row;
}

$viewer = json_encode($view,JSON_NUMERIC_CHECK);
</code>```

why this is code no showing data...
db connection ok,but if the code like below this data showing..

```<code>$sql = "SELECT SUM(numberofview) as count FROM demo_viewer

        GROUP BY YEAR(created_at) ORDER BY created_at";

$viewer = mysqli_query($mysqli,$sql);

$viewer = mysqli_fetch_all($viewer,MYSQLI_ASSOC);

$viewer = json_encode(array_column($viewer, 'count'),JSON_NUMERIC_CHECK);
</code>```

答:
Try this,

```<code>mysqli_query($mysqli,'SET NAMES utf8mb4');

$sql = "SELECT * FROM `demo_viewer` WHERE 1 ";

$viewer = mysqli_query($mysqli,$sql);

$view = array();

while ($row = mysqli_fetch_array($viewer,MYSQLI_ASSOC)){

    $view[] = $row;
}

$viewer = json_encode($view, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);
</code>```

EDIT

```<code>mysqli_query($mysqli,'SET NAMES utf8mb4');

$sql = "SELECT numberofclick FROM `demo_viewer` GROUP BY YEAR(created_at) ORDER BY created_at ";

$viewer = mysqli_query($mysqli,$sql);

$view = array();

while ($row = mysqli_fetch_array($viewer,MYSQLI_ASSOC)){

    $view[] = $row['numberofclick'];
}

$viewer = json_encode($view, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);
</code>```

PS: you you should not use select * from table. Because Highchart needs one column value. not all the columns.

Body:
$sql = "SELECT * FROM `demo_viewer` WHERE 1 ";

$viewer = mysqli_query($mysqli,$sql);

$view = array();

while ($row = mysqli_fetch_array($viewer)){

    $view[] = $row;
}

$viewer = json_encode($view,JSON_NUMERIC_CHECK);

why this is code no showing data...
db connection ok,but if the code like below this data showing..

$sql = "SELECT SUM(numberofview) as count FROM demo_viewer

        GROUP BY YEAR(created_at) ORDER BY created_at";

$viewer = mysqli_query($mysqli,$sql);

$viewer = mysqli_fetch_all($viewer,MYSQLI_ASSOC);

$viewer = json_encode(array_column($viewer, 'count'),JSON_NUMERIC_CHECK);

Body:
Try this,

mysqli_query($mysqli,'SET NAMES utf8mb4');

$sql = "SELECT * FROM `demo_viewer` WHERE 1 ";

$viewer = mysqli_query($mysqli,$sql);

$view = array();

while ($row = mysqli_fetch_array($viewer,MYSQLI_ASSOC)){

    $view[] = $row;
}

$viewer = json_encode($view, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);

EDIT

mysqli_query($mysqli,'SET NAMES utf8mb4');

$sql = "SELECT numberofclick FROM `demo_viewer` GROUP BY YEAR(created_at) ORDER BY created_at ";

$viewer = mysqli_query($mysqli,$sql);

$view = array();

while ($row = mysqli_fetch_array($viewer,MYSQLI_ASSOC)){

    $view[] = $row['numberofclick'];
}

$viewer = json_encode($view, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);

PS: you you should not use select * from table. Because Highchart needs one column value. not all the columns.


问:
PHP never returns readyState 4 or status 200 in ajax
I have the following generic Ajax function:

```<code>//run post request
function ajaxPost (divid, parameters, file) {

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  } else {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function() {
    alert ("ok")
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert ("ready");
      alert (xmlhttp.responseText);
    divid.innerHTML=xmlhttp.responseText;
    }
  }

  xmlhttp.open("POST", file,true);

  //Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.send(parameters);
}
</code>```

The problem being that this section does not work as expected:

```<code>xmlhttp.onreadystatechange=function() {
    alert ("ok")
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert ("ready");
      alert (xmlhttp.responseText);
    divid.innerHTML=xmlhttp.responseText;
    }
  }
</code>```

In browser I get muliple "ok" alerts as I expected but the statements in the if statement never fire. I take this to mean the php is returning state updates but for some reason is never returning ready codes. How that can happen - I have no idea.

Can anyone tell me why I wouldn't recieve the ready codes?

The php itself is not the problem:

```<code><?php

echo "new";

?>
</code>```

I have tested the function input (divid, parameters and file), and these are ok.
This function was previously working in  a seperate project.

答:
I would hazard a guess that your server is not returning a valid 200 response, therefore the if statement xmlhttp.readyState == 4 && xmlhttp.status == 200 will never equate true.

Try using Firebug to see what request is being made (if any) and what response you get back. If you don't use Firefox, try using a proxy tool like Charles.

Further to all this, I would highly recommend using a stable open source Javascript library such as jQuery. This has AJAX code built in (among other things) which is all rigorously tested. Not only will this save you time, it will eliminate further possibility of errors from your own code, e.g.,

```<code>$.get('url.php', function(data) {
    // 'data' is responseText
});
</code>```

Body:
I have the following generic Ajax function:

//run post request
function ajaxPost (divid, parameters, file) {

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  } else {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function() {
    alert ("ok")
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert ("ready");
      alert (xmlhttp.responseText);
    divid.innerHTML=xmlhttp.responseText;
    }
  }

  xmlhttp.open("POST", file,true);

  //Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.send(parameters);
}

The problem being that this section does not work as expected:

xmlhttp.onreadystatechange=function() {
    alert ("ok")
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert ("ready");
      alert (xmlhttp.responseText);
    divid.innerHTML=xmlhttp.responseText;
    }
  }

In browser I get muliple "ok" alerts as I expected but the statements in the if statement never fire. I take this to mean the php is returning state updates but for some reason is never returning ready codes. How that can happen - I have no idea.

Can anyone tell me why I wouldn't recieve the ready codes?

The php itself is not the problem:

<?php

echo "new";

?>

I have tested the function input (divid, parameters and file), and these are ok.
This function was previously working in  a seperate project.

Body:
I would hazard a guess that your server is not returning a valid 200 response, therefore the if statement xmlhttp.readyState == 4 && xmlhttp.status == 200 will never equate true.

Try using Firebug to see what request is being made (if any) and what response you get back. If you don't use Firefox, try using a proxy tool like Charles.

Further to all this, I would highly recommend using a stable open source Javascript library such as jQuery. This has AJAX code built in (among other things) which is all rigorously tested. Not only will this save you time, it will eliminate further possibility of errors from your own code, e.g.,

$.get('url.php', function(data) {
    // 'data' is responseText
});


问:
How to get the value of geolocation in a javascript function
I have the following function which takes two values: latitude and longitude:

```<code>    getgps(latitude , longitude);
</code>```

and I need for this to get the data from the geolocation function:

```<code> <script>

function getLocation() {
   if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
   }
}
function showPosition(position) {
  var x = position.coords.latitude;
  var y = position.coords.longitude;
 getgps(x , y);

}
  </script>
</code>```

but it is not working

The good script

```<code>navigator.geolocation.getCurrentPosition(function(position) {
 findGps(position.coords.latitude, position.coords.longitude); });
</code>```

答:
you have to call the navigator.geolocation function, that have success and error callbacks functions.

Try to call your gepgps function in the success callback, like this :

```<code>        var onGeoSuccess = function(position) {
            getgps(position.coords.latitude, position.coords.longitude)
        };

        function onGeoError(error) {
            alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
        }

        navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
</code>```

Body:
I have the following function which takes two values: latitude and longitude:

    getgps(latitude , longitude);

and I need for this to get the data from the geolocation function:

but it is not working

The good script

navigator.geolocation.getCurrentPosition(function(position) {
 findGps(position.coords.latitude, position.coords.longitude); });

Body:
you have to call the navigator.geolocation function, that have success and error callbacks functions.

Try to call your gepgps function in the success callback, like this :

        var onGeoSuccess = function(position) {
            getgps(position.coords.latitude, position.coords.longitude)
        };

        function onGeoError(error) {
            alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
        }

        navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);


问:
angular ng-if or ng-show responds slow (2second delay?)
I'm trying to show or hide a loading indicator on a button when a request is busy. I do that with angular by changing the $scope.loading variable when a request is loading or when it's done loading.

```<code> $scope.login = function(){
     $scope.loading = true;
    apiFactory.getToken()
        .success(function(data){

        })
        .error(function(error){

        })
         .finally(function(){
               $timeout(function() {
                 $scope.loading = false;
               }, 0);
         });
 };
</code>```

In the frontend:

```<code><button ng-disabled="loading" class="button button-outline button-positive" type="submit">
Log in
<span ng-if="loading" class="ion-refreshing"></span>
</button>
</code>```

This works fine, but the loading icon (ion-refreshing) is shown for about 2 seconds, while the $scope variable is updated immediately. I tried $scope.$apply but that doesn't seem to be what's wrong here, the scope is updated just fine and immediately after the request. It's just the icon that isn't responding quickly enough.

答:
I was facing a similar issue, I used $scope.$evalAsync() to force update the binding.

It works like a charm.

Avoid using $scope.$apply as it can conflict with an already-running $digest phase.

```<code>if(selectedStatistics.length === 0 || selectedWorkgroups.length === 0){
    ctrl.isSaveDisabled = true;
    $scope.$evalAsync();
} else{
    ctrl.isSaveDisabled = false;
    $scope.$evalAsync();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to show or hide a loading indicator on a button when a request is busy. I do that with angular by changing the $scope.loading variable when a request is loading or when it's done loading.

 $scope.login = function(){
     $scope.loading = true;
    apiFactory.getToken()
        .success(function(data){

        })
        .error(function(error){

        })
         .finally(function(){
               $timeout(function() {
                 $scope.loading = false;
               }, 0);
         });
 };

In the frontend:

<button ng-disabled="loading" class="button button-outline button-positive" type="submit">
Log in

</button>

This works fine, but the loading icon (ion-refreshing) is shown for about 2 seconds, while the $scope variable is updated immediately. I tried $scope.$apply but that doesn't seem to be what's wrong here, the scope is updated just fine and immediately after the request. It's just the icon that isn't responding quickly enough.

Body:
I was facing a similar issue, I used $scope.$evalAsync() to force update the binding.

It works like a charm.

Avoid using $scope.$apply as it can conflict with an already-running $digest phase.

if(selectedStatistics.length === 0 || selectedWorkgroups.length === 0){
    ctrl.isSaveDisabled = true;
    $scope.$evalAsync();
} else{
    ctrl.isSaveDisabled = false;
    $scope.$evalAsync();
}


问:
Could not read JSON: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
I was trying to get the getAccessToken with spring rest template as given below. I am getting the below error, while calling oAuthRestTemplate.getAccessToken()

```<code>Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
</code>```

Code:

```<code>ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

resource.setAccessTokenUri("https://../oauth2/token");
resource.setUsername("u");
resource.setPassword("p");
resource.setClientSecret("...s");
resource.setClientId("...i");
resource.setGrantType("password");
List<String> scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setScope(scopes);

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJackson2HttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
OAuth2RestTemplate oAuthRestTemplate =  new OAuth2RestTemplate(resource,clientContext);
oAuthRestTemplate.setMessageConverters(messageConverters);

try {
    SSLUtil.turnOffSslChecking();
    System.out.println(oAuthRestTemplate.getAccessToken());
    String result = oAuthRestTemplate.getForObject("url" + "/api/version", String.class);
} catch (RestClientException e) {
    e.printStackTrace();
}
</code>```

Full Errortrace:

```<code>Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@44908881; line: 1, column: 159]; nested exception is com.fasterxml.jackson.core.JsonParseException: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@44908881; line: 1, column: 159]
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:171)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:163)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:94)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:491)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:454)
    at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:113)
    at org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider.obtainAccessToken(ResourceOwnerPasswordAccessTokenProvider.java:47)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:142)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:118)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:216)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:168)
    at com.ClientTemplate.main(ClientTemplate.java:69)
Caused by: com.fasterxml.jackson.core.JsonParseException: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@44908881; line: 1, column: 159]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1419)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:508)
    at com.fasterxml.jackson.core.base.ParserBase._parseNumericValue(ParserBase.java:748)
    at com.fasterxml.jackson.core.base.ParserBase.getLongValue(ParserBase.java:619)
    at org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Deserializer.deserialize(OAuth2AccessTokenJackson2Deserializer.java:75)
    at org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Deserializer.deserialize(OAuth2AccessTokenJackson2Deserializer.java:44)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3051)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2206)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:168)
    ... 11 more
</code>```

Tried without messageConverters.Still the same error.

答:
By the look of your stacktrace I can suggest that you are using spring oauth version 1.0.1 which has this code inside OAuth2AccessTokenJackson2Deserializer at line 75:

```<code>...
else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
    expiresIn = jp.getLongValue();
}
...
</code>```

it expects field expires_in to be numeric. And your exception suggests that in your response it is in fact a string.

To fix this you can upgrade to latest version (2.1.1 at the moment) where they fixed this part to accept string value also:

```<code>....
else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
    try {
        expiresIn = jp.getLongValue();
    } catch (JsonParseException e) {
        expiresIn = Long.valueOf(jp.getText());
    }
}
....
</code>```

Body:
I was trying to get the getAccessToken with spring rest template as given below. I am getting the below error, while calling oAuthRestTemplate.getAccessToken()

Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Current token (VALUE_STRING) not numeric, can not use numeric value accessors

Code:

ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

resource.setAccessTokenUri("https://../oauth2/token");
resource.setUsername("u");
resource.setPassword("p");
resource.setClientSecret("...s");
resource.setClientId("...i");
resource.setGrantType("password");
List<String> scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setScope(scopes);

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJackson2HttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
OAuth2RestTemplate oAuthRestTemplate =  new OAuth2RestTemplate(resource,clientContext);
oAuthRestTemplate.setMessageConverters(messageConverters);

try {
    SSLUtil.turnOffSslChecking();
    System.out.println(oAuthRestTemplate.getAccessToken());
    String result = oAuthRestTemplate.getForObject("url" + "/api/version", String.class);
} catch (RestClientException e) {
    e.printStackTrace();
}

Full Errortrace:

Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@44908881; line: 1, column: 159]; nested exception is com.fasterxml.jackson.core.JsonParseException: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@44908881; line: 1, column: 159]
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:171)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:163)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:94)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:491)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:454)
    at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:113)
    at org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider.obtainAccessToken(ResourceOwnerPasswordAccessTokenProvider.java:47)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:142)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:118)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:216)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:168)
    at com.ClientTemplate.main(ClientTemplate.java:69)
Caused by: com.fasterxml.jackson.core.JsonParseException: Current token (VALUE_STRING) not numeric, can not use numeric value accessors
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@44908881; line: 1, column: 159]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1419)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:508)
    at com.fasterxml.jackson.core.base.ParserBase._parseNumericValue(ParserBase.java:748)
    at com.fasterxml.jackson.core.base.ParserBase.getLongValue(ParserBase.java:619)
    at org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Deserializer.deserialize(OAuth2AccessTokenJackson2Deserializer.java:75)
    at org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Deserializer.deserialize(OAuth2AccessTokenJackson2Deserializer.java:44)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3051)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2206)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:168)
    ... 11 more

Tried without messageConverters.Still the same error.

Body:
By the look of your stacktrace I can suggest that you are using spring oauth version 1.0.1 which has this code inside OAuth2AccessTokenJackson2Deserializer at line 75:

...
else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
    expiresIn = jp.getLongValue();
}
...

it expects field expires_in to be numeric. And your exception suggests that in your response it is in fact a string.

To fix this you can upgrade to latest version (2.1.1 at the moment) where they fixed this part to accept string value also:

....
else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
    try {
        expiresIn = jp.getLongValue();
    } catch (JsonParseException e) {
        expiresIn = Long.valueOf(jp.getText());
    }
}
....


答:
By using padLeft

eg. "1".PadLeft(8, '0');

Ref. Add zero-padding to a string

Title: Convert string type to 8 digit in c#

Body:
I need to convert this value to 8 digit format. (example : 1 --> 00000001).any help? here's my code

foreach(DataRow dr in _dsGridCsv.Tables[0].Rows)
  {
     byte empfrmat =byte.Parse(dr["emp_id"].ToString());
     csv += empfrmat;
     csv += "\r\n";
  }


问:
LISP file reading Loop condtion and sequential number
Hello I have question about LISP LOOP condition in file reading
and about sequential number in the loop

What I want to do is read a file and save data (I implemented it simply)

But to do this iterative, I don't know how to finish the loop.

I just want to finish the loop when end of file reached.

And I hope to use sequential number in the loop.

For example, I want to save data in struct s1, s2, s3, s4..... at loop cycles each time, But how to do that?

It is simply express this in C language pseudo code

```<code>int i=0;
while( != EOF){

    read file in line
    save data into struct[i]
    i++
}
</code>```

And my codes are this

```<code>(loop
    ??(setf p(n) (make-player
        :name (read-line *file nil)
        :team (read-line *file nil)
        :game-number (read-line *file nil)
    )
    ??(setf (gethash (player-name p(n) Player_DB) p(n))

    ??(when ( = (read-line *file) " ") (return 0))
)
</code>```

)

答:
you have two options:

with read-line it returns nil, so you can stop with that that or specify a value to when the line is nil to stop it

As a example:

stop with custom symbol

```<code>(with-open-file (stream "/Users/toni/learn/lisp/cl-l/stackoverflow/scripts/list-file.txt")
  (loop for line = (read-line stream nil 'foo)
        until (eq line 'foo)
        do (print line)))
</code>```

RESULTS:

```<code>"-rw-r--r--  1 toni  staff     22 18 abr 09:34 calimero_1.txt"
"-rw-r--r--  1 toni  staff      1 18 abr 09:34 calimero_2.txt"
"-rw-r--r--  1 toni  staff      0 18 abr 09:34 calimero_3.txt"
"-rw-r--r--  1 toni  staff    149 18 abr 09:34 charpos.lisp"
"-rw-r--r--  1 toni  staff    485  3 may 16:14 distributive-lists.org"
"-rw-r--r--  1 toni  staff   1237 18 abr 09:34 do-macro.lisp"
"-rw-r--r--  1 toni  staff    120 18 abr 09:34 download-all-pdfs.lisp"
"-rw-r--r--  1 toni  staff   3111 18 abr 09:34 emacs-rest-client"
"-rw-r--r--  1 toni  staff   1111 30 may 15:46 equal-function-in-common-lisp.org"
"-rw-r--r--  1 toni  staff     12 18 abr 09:34 filename.txt"
"-rw-r--r--  1 toni  staff    757 18 abr 09:34 find-all-objects-in-apackage.lisp"
"-rw-r--r--  1 toni  staff    355 18 abr 09:34 flatten-one-level.lisp"
"-rw-r--r--  1 toni  staff    813 18 abr 09:34 format-money.lisp"
"-rw-r--r--  1 toni  staff   2137 18 abr 09:34 hash-table-eficiency.lisp"
"-rw-r--r--  1 toni  staff   4230 18 abr 09:34 instrospection.lisp"
"-rw-r--r--  1 toni  staff    919 18 abr 09:34 mapcar_and_lambda.lisp"
"-rw-r--r--  1 toni  staff  11713 18 abr 09:34 mastermind.lisp"
"-rw-r--r--  1 toni  staff    368 18 abr 09:34 method-missing.lisp"
"-rw-r--r--  1 toni  staff    614 18 abr 09:34 method_missing.rb"
"-rw-r--r--  1 toni  staff      2 18 abr 09:34 patofante_1.txt"
"-rw-r--r--  1 toni  staff    314 24 may 18:29 profiling.org"
"-rw-r--r--  1 toni  staff   1265 18 abr 09:34 recursion-more-one-function.lisp"
"-rw-r--r--  1 toni  staff   1154 18 abr 09:34 size-explosing-file.lisp"
"-rw-r--r--  1 toni  staff    592 18 abr 09:34 sorting-coordinates.lisp"
"-rw-r--r--  1 toni  staff    485 18 abr 09:34 stackoverflow-mongo.lisp"
"-rw-r--r--  1 toni  staff   8174 29 may 14:06 test-with-c-variables.org"
"-rw-r--r--  1 toni  staff  11121 25 abr 11:18 test.html"
"-rw-r--r--  1 toni  staff    690 25 abr 13:45 test.org"
"-rw-r--r--  1 toni  staff    236 18 abr 09:34 text.txt"
"-rw-r--r--  1 toni  staff  61194 18 abr 09:34 train.csv"
"-rw-r--r--  1 toni  staff    218 26 abr 17:17 variables-package.lisp"
"-rw-r--r--  1 toni  staff   1792 18 abr 09:34 vectors-vs-lisp.lisp"
"-rw-r--r--  1 toni  staff    190 18 abr 09:34 weird-code.lisp"
"-rw-r--r--  1 toni  staff    629 18 abr 09:34 write-a-list.lisp"
</code>```

stop with nil

```<code>(with-open-file (stream "/Users/toni/learn/lisp/cl-l/stackoverflow/scripts/list-file.txt")
  (loop for line = (read-line stream nil)
        until (null line)
        do (print line)))
</code>```

RESULTS:

```<code>"-rw-r--r--  1 toni  staff     22 18 abr 09:34 calimero_1.txt"
"-rw-r--r--  1 toni  staff      1 18 abr 09:34 calimero_2.txt"
"-rw-r--r--  1 toni  staff      0 18 abr 09:34 calimero_3.txt"
"-rw-r--r--  1 toni  staff    149 18 abr 09:34 charpos.lisp"
"-rw-r--r--  1 toni  staff    485  3 may 16:14 distributive-lists.org"
"-rw-r--r--  1 toni  staff   1237 18 abr 09:34 do-macro.lisp"
"-rw-r--r--  1 toni  staff    120 18 abr 09:34 download-all-pdfs.lisp"
"-rw-r--r--  1 toni  staff   3111 18 abr 09:34 emacs-rest-client"
"-rw-r--r--  1 toni  staff   1111 30 may 15:46 equal-function-in-common-lisp.org"
"-rw-r--r--  1 toni  staff     12 18 abr 09:34 filename.txt"
"-rw-r--r--  1 toni  staff    757 18 abr 09:34 find-all-objects-in-apackage.lisp"
"-rw-r--r--  1 toni  staff    355 18 abr 09:34 flatten-one-level.lisp"
"-rw-r--r--  1 toni  staff    813 18 abr 09:34 format-money.lisp"
"-rw-r--r--  1 toni  staff   2137 18 abr 09:34 hash-table-eficiency.lisp"
"-rw-r--r--  1 toni  staff   4230 18 abr 09:34 instrospection.lisp"
"-rw-r--r--  1 toni  staff    919 18 abr 09:34 mapcar_and_lambda.lisp"
"-rw-r--r--  1 toni  staff  11713 18 abr 09:34 mastermind.lisp"
"-rw-r--r--  1 toni  staff    368 18 abr 09:34 method-missing.lisp"
"-rw-r--r--  1 toni  staff    614 18 abr 09:34 method_missing.rb"
"-rw-r--r--  1 toni  staff      2 18 abr 09:34 patofante_1.txt"
"-rw-r--r--  1 toni  staff    314 24 may 18:29 profiling.org"
"-rw-r--r--  1 toni  staff   1265 18 abr 09:34 recursion-more-one-function.lisp"
"-rw-r--r--  1 toni  staff   1154 18 abr 09:34 size-explosing-file.lisp"
"-rw-r--r--  1 toni  staff    592 18 abr 09:34 sorting-coordinates.lisp"
"-rw-r--r--  1 toni  staff    485 18 abr 09:34 stackoverflow-mongo.lisp"
"-rw-r--r--  1 toni  staff   8174 29 may 14:06 test-with-c-variables.org"
"-rw-r--r--  1 toni  staff  11121 25 abr 11:18 test.html"
"-rw-r--r--  1 toni  staff    690 25 abr 13:45 test.org"
"-rw-r--r--  1 toni  staff    236 18 abr 09:34 text.txt"
"-rw-r--r--  1 toni  staff  61194 18 abr 09:34 train.csv"
"-rw-r--r--  1 toni  staff    218 26 abr 17:17 variables-package.lisp"
"-rw-r--r--  1 toni  staff   1792 18 abr 09:34 vectors-vs-lisp.lisp"
"-rw-r--r--  1 toni  staff    190 18 abr 09:34 weird-code.lisp"
"-rw-r--r--  1 toni  staff    629 18 abr 09:34 write-a-list.lisp"
</code>```

Body:
Hello I have question about LISP LOOP condition in file reading
and about sequential number in the loop

What I want to do is read a file and save data (I implemented it simply)

But to do this iterative, I don't know how to finish the loop.

I just want to finish the loop when end of file reached.

And I hope to use sequential number in the loop.

For example, I want to save data in struct s1, s2, s3, s4..... at loop cycles each time, But how to do that?

It is simply express this in C language pseudo code

int i=0;
while( != EOF){

    read file in line
    save data into struct[i]
    i++
}

And my codes are this

(loop
    ??(setf p(n) (make-player
        :name (read-line *file nil)
        :team (read-line *file nil)
        :game-number (read-line *file nil)
    )
    ??(setf (gethash (player-name p(n) Player_DB) p(n))

    ??(when ( = (read-line *file) " ") (return 0))
)

)

Body:
you have two options:

with read-line it returns nil, so you can stop with that that or specify a value to when the line is nil to stop it

As a example:

stop with custom symbol

(with-open-file (stream "/Users/toni/learn/lisp/cl-l/stackoverflow/scripts/list-file.txt")
  (loop for line = (read-line stream nil 'foo)
        until (eq line 'foo)
        do (print line)))

RESULTS:

"-rw-r--r--  1 toni  staff     22 18 abr 09:34 calimero_1.txt"
"-rw-r--r--  1 toni  staff      1 18 abr 09:34 calimero_2.txt"
"-rw-r--r--  1 toni  staff      0 18 abr 09:34 calimero_3.txt"
"-rw-r--r--  1 toni  staff    149 18 abr 09:34 charpos.lisp"
"-rw-r--r--  1 toni  staff    485  3 may 16:14 distributive-lists.org"
"-rw-r--r--  1 toni  staff   1237 18 abr 09:34 do-macro.lisp"
"-rw-r--r--  1 toni  staff    120 18 abr 09:34 download-all-pdfs.lisp"
"-rw-r--r--  1 toni  staff   3111 18 abr 09:34 emacs-rest-client"
"-rw-r--r--  1 toni  staff   1111 30 may 15:46 equal-function-in-common-lisp.org"
"-rw-r--r--  1 toni  staff     12 18 abr 09:34 filename.txt"
"-rw-r--r--  1 toni  staff    757 18 abr 09:34 find-all-objects-in-apackage.lisp"
"-rw-r--r--  1 toni  staff    355 18 abr 09:34 flatten-one-level.lisp"
"-rw-r--r--  1 toni  staff    813 18 abr 09:34 format-money.lisp"
"-rw-r--r--  1 toni  staff   2137 18 abr 09:34 hash-table-eficiency.lisp"
"-rw-r--r--  1 toni  staff   4230 18 abr 09:34 instrospection.lisp"
"-rw-r--r--  1 toni  staff    919 18 abr 09:34 mapcar_and_lambda.lisp"
"-rw-r--r--  1 toni  staff  11713 18 abr 09:34 mastermind.lisp"
"-rw-r--r--  1 toni  staff    368 18 abr 09:34 method-missing.lisp"
"-rw-r--r--  1 toni  staff    614 18 abr 09:34 method_missing.rb"
"-rw-r--r--  1 toni  staff      2 18 abr 09:34 patofante_1.txt"
"-rw-r--r--  1 toni  staff    314 24 may 18:29 profiling.org"
"-rw-r--r--  1 toni  staff   1265 18 abr 09:34 recursion-more-one-function.lisp"
"-rw-r--r--  1 toni  staff   1154 18 abr 09:34 size-explosing-file.lisp"
"-rw-r--r--  1 toni  staff    592 18 abr 09:34 sorting-coordinates.lisp"
"-rw-r--r--  1 toni  staff    485 18 abr 09:34 stackoverflow-mongo.lisp"
"-rw-r--r--  1 toni  staff   8174 29 may 14:06 test-with-c-variables.org"
"-rw-r--r--  1 toni  staff  11121 25 abr 11:18 test.html"
"-rw-r--r--  1 toni  staff    690 25 abr 13:45 test.org"
"-rw-r--r--  1 toni  staff    236 18 abr 09:34 text.txt"
"-rw-r--r--  1 toni  staff  61194 18 abr 09:34 train.csv"
"-rw-r--r--  1 toni  staff    218 26 abr 17:17 variables-package.lisp"
"-rw-r--r--  1 toni  staff   1792 18 abr 09:34 vectors-vs-lisp.lisp"
"-rw-r--r--  1 toni  staff    190 18 abr 09:34 weird-code.lisp"
"-rw-r--r--  1 toni  staff    629 18 abr 09:34 write-a-list.lisp"

stop with nil

(with-open-file (stream "/Users/toni/learn/lisp/cl-l/stackoverflow/scripts/list-file.txt")
  (loop for line = (read-line stream nil)
        until (null line)
        do (print line)))

RESULTS:

"-rw-r--r--  1 toni  staff     22 18 abr 09:34 calimero_1.txt"
"-rw-r--r--  1 toni  staff      1 18 abr 09:34 calimero_2.txt"
"-rw-r--r--  1 toni  staff      0 18 abr 09:34 calimero_3.txt"
"-rw-r--r--  1 toni  staff    149 18 abr 09:34 charpos.lisp"
"-rw-r--r--  1 toni  staff    485  3 may 16:14 distributive-lists.org"
"-rw-r--r--  1 toni  staff   1237 18 abr 09:34 do-macro.lisp"
"-rw-r--r--  1 toni  staff    120 18 abr 09:34 download-all-pdfs.lisp"
"-rw-r--r--  1 toni  staff   3111 18 abr 09:34 emacs-rest-client"
"-rw-r--r--  1 toni  staff   1111 30 may 15:46 equal-function-in-common-lisp.org"
"-rw-r--r--  1 toni  staff     12 18 abr 09:34 filename.txt"
"-rw-r--r--  1 toni  staff    757 18 abr 09:34 find-all-objects-in-apackage.lisp"
"-rw-r--r--  1 toni  staff    355 18 abr 09:34 flatten-one-level.lisp"
"-rw-r--r--  1 toni  staff    813 18 abr 09:34 format-money.lisp"
"-rw-r--r--  1 toni  staff   2137 18 abr 09:34 hash-table-eficiency.lisp"
"-rw-r--r--  1 toni  staff   4230 18 abr 09:34 instrospection.lisp"
"-rw-r--r--  1 toni  staff    919 18 abr 09:34 mapcar_and_lambda.lisp"
"-rw-r--r--  1 toni  staff  11713 18 abr 09:34 mastermind.lisp"
"-rw-r--r--  1 toni  staff    368 18 abr 09:34 method-missing.lisp"
"-rw-r--r--  1 toni  staff    614 18 abr 09:34 method_missing.rb"
"-rw-r--r--  1 toni  staff      2 18 abr 09:34 patofante_1.txt"
"-rw-r--r--  1 toni  staff    314 24 may 18:29 profiling.org"
"-rw-r--r--  1 toni  staff   1265 18 abr 09:34 recursion-more-one-function.lisp"
"-rw-r--r--  1 toni  staff   1154 18 abr 09:34 size-explosing-file.lisp"
"-rw-r--r--  1 toni  staff    592 18 abr 09:34 sorting-coordinates.lisp"
"-rw-r--r--  1 toni  staff    485 18 abr 09:34 stackoverflow-mongo.lisp"
"-rw-r--r--  1 toni  staff   8174 29 may 14:06 test-with-c-variables.org"
"-rw-r--r--  1 toni  staff  11121 25 abr 11:18 test.html"
"-rw-r--r--  1 toni  staff    690 25 abr 13:45 test.org"
"-rw-r--r--  1 toni  staff    236 18 abr 09:34 text.txt"
"-rw-r--r--  1 toni  staff  61194 18 abr 09:34 train.csv"
"-rw-r--r--  1 toni  staff    218 26 abr 17:17 variables-package.lisp"
"-rw-r--r--  1 toni  staff   1792 18 abr 09:34 vectors-vs-lisp.lisp"
"-rw-r--r--  1 toni  staff    190 18 abr 09:34 weird-code.lisp"
"-rw-r--r--  1 toni  staff    629 18 abr 09:34 write-a-list.lisp"


问:
Issue on looping over a list of ViewModel using for loop
In the following controller, I need to loop through each element of a List. MyVieModel has quite a number of attrubutes (columns) and the list has thousands of rows. So, for brevity I need to use an outer and an inner loop. But, the VS2015 is complaining at the following lines in the controller. How can I resolve the issue?

Error at inner loop for (var j = 0; j < testlist[i].Count(); j++){...}: MyViewModel does not contain a definition of Count()

Error at line if (testlist[i][j] ....){...}: cannot apply indexing with [] to an extension of type MyViewModel

ViewModel:

```<code>public class MyViewModel
{
    [Key]
    public int ProductId { get; set; }
    public float laborCost { get; set; }
    public float ManufCost { get; set; }
    public float Price { get; set; }
    ....
    ....
}
</code>```

Controller:

```<code>....
....
var testlist = (qry to load MyViewModel).ToList();

for (var i = 0; i < testlist.Count; i++)
{
    for (var j = 0; j < testlist[i].Count(); j++)
    {
      if (testlist[i][j] ....)
      {
         ....
         ....
      }
    }
}
</code>```

答:
In your code testlist[i] is an instance of MyViewModel class. You can't simply iterate over all it's members (properties, methods etc) with a for/foreach loop.

1) Use System.Reflection to obtain list of properties in your object (slow!)

2) Manually make array from required property values

```<code>var testlist = (qry to load MyViewModel)
         .Select(x => new object[] { x.ProductId, x.laborCost, x.ManufCost ...})
         .ToList();
</code>```

Your model will be List<object[]> instead of List<MyViewModel>

3) Manually check required properties:

```<code>if (testlist[i].ManufCost  ....)
</code>```

Body:
In the following controller, I need to loop through each element of a List. MyVieModel has quite a number of attrubutes (columns) and the list has thousands of rows. So, for brevity I need to use an outer and an inner loop. But, the VS2015 is complaining at the following lines in the controller. How can I resolve the issue?

Error at inner loop for (var j = 0; j < testlist[i].Count(); j++){...}: MyViewModel does not contain a definition of Count()

Error at line if (testlist[i][j] ....){...}: cannot apply indexing with [] to an extension of type MyViewModel

ViewModel:

public class MyViewModel
{
    [Key]
    public int ProductId { get; set; }
    public float laborCost { get; set; }
    public float ManufCost { get; set; }
    public float Price { get; set; }
    ....
    ....
}

Controller:

....
....
var testlist = (qry to load MyViewModel).ToList();

for (var i = 0; i < testlist.Count; i++)
{
    for (var j = 0; j < testlist[i].Count(); j++)
    {
      if (testlist[i][j] ....)
      {
         ....
         ....
      }
    }
}

Body:
In your code testlist[i] is an instance of MyViewModel class. You can't simply iterate over all it's members (properties, methods etc) with a for/foreach loop.

1) Use System.Reflection to obtain list of properties in your object (slow!)

2) Manually make array from required property values

var testlist = (qry to load MyViewModel)
         .Select(x => new object[] { x.ProductId, x.laborCost, x.ManufCost ...})
         .ToList();

Your model will be List<object[]> instead of List<MyViewModel>

3) Manually check required properties:

if (testlist[i].ManufCost  ....)


问:
Replace array value with new one
I have array of array, where i want to change date format. I am trying to get it as below

```<code>foreach ($toReturn as $value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}
</code>```

here format gets changed but it is not replacing array value with new one?? Why??

答:
Alternately, if you do not wish to use the "Pass by reference" method, you can use this, or even create new variable.

```<code>foreach ($toReturn as $key => $value) {

    $start_date = new DateTime($value['start_date']);
    $toReturn[$key]['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $toReturn[$key]['end_date'] = $end_date->format('m-d-Y');
}
</code>```

Note: If you wish to use pass by reference, do not forget to unset($value) after the loop which is not necessary for given example.

Title: Replace array value with new one

Body:
I have array of array, where i want to change date format. I am trying to get it as below

foreach ($toReturn as $value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}

here format gets changed but it is not replacing array value with new one?? Why??

Body:
Alternately, if you do not wish to use the "Pass by reference" method, you can use this, or even create new variable.

foreach ($toReturn as $key => $value) {

    $start_date = new DateTime($value['start_date']);
    $toReturn[$key]['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $toReturn[$key]['end_date'] = $end_date->format('m-d-Y');
}

Note: If you wish to use pass by reference, do not forget to unset($value) after the loop which is not necessary for given example.


答:
You can also use access $toReturn[$index]

```<code>foreach ($toReturn as $index => $value) {

    $start_date = new DateTime($value['start_date']);
    $toReturn[$index]['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $toReturn[$index]['end_date'] = $end_date->format('m-d-Y');
}
</code>```

Title: Replace array value with new one

Body:
You can also use access $toReturn[$index]

foreach ($toReturn as $index => $value) {

    $start_date = new DateTime($value['start_date']);
    $toReturn[$index]['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $toReturn[$index]['end_date'] = $end_date->format('m-d-Y');
}


问:
Possible to statically link shared object libraries?
I'm building a library that needs to be dynamically linked to my project. The output is a .so file, so I think I'm on the right track. I'm concerned by the way it's being linked at compile time - by specifying the location of its makefile and depending on a bunch of macros, which I've never encountered before.

Can I assume that since I'm building a .so library (rather than a .a) that I'm in fact dynamically linking? Or is it possible for .so libs to be statically linked, in which case I need to rip apart the make/config files to better understand what's going on?

Thanks,

Andrew

答:
I'm not familiar with internal structure of executables and shared objects, so I could only give some practical hints.

Assuming you use gcc, it should have -shared option when linking object files into library - this way ld (called by gcc) makes shared object instead of executable binary.

```<code>gcc -shared -o libabc.so *.o ...
</code>```

When you link some application with this libabc.so it should link without errors and after that with ldd command you should be able to see libabc.so among its dependencies.

```<code>$ ldd app
    ...
    libabc.so => ...............
</code>```

Body:
I'm not familiar with internal structure of executables and shared objects, so I could only give some practical hints.

Assuming you use gcc, it should have -shared option when linking object files into library - this way ld (called by gcc) makes shared object instead of executable binary.

gcc -shared -o libabc.so *.o ...

When you link some application with this libabc.so it should link without errors and after that with ldd command you should be able to see libabc.so among its dependencies.

$ ldd app
    ...
    libabc.so => ...............


问:
Spoofing mysql-client connection request for demo purposes
For demo purpose, I wanted to start at least 5 MySQL-client connection to only one server. Mysql-server is running on a fixed IP.

In my script, I have added many IP's as following.

```<code>eth0     inet addr:1.2.3.4
eth0:1  inet addr:1.2.3.5
</code>```

I am the mysql client request as follows:

```<code>mysql -u test -h mysql.domain.com -p
</code>```

This request always goes with 1.2.3.4?  Can I start the mysql-client request with the IP I wanted?

答:
I'm not sure it can be defined in the mysql client.
However good'ol networking should be your friend here.

The idea here is to make sure that IP traffic from your machine to the server machine goes through the desired NIC as its gateway.
The command on *nix is 'route add' and the syntax should be something in the spirit of:
route add -host <YOUR DB SERVER IP> gw 1.2.3.5 dev <YOUR NIC DEVICE NAME>

Body:
For demo purpose, I wanted to start at least 5 MySQL-client connection to only one server. Mysql-server is running on a fixed IP.

In my script, I have added many IP's as following.

eth0     inet addr:1.2.3.4
eth0:1  inet addr:1.2.3.5

I am the mysql client request as follows:

mysql -u test -h mysql.domain.com -p

This request always goes with 1.2.3.4?  Can I start the mysql-client request with the IP I wanted?


问:
BadMethodCallException in Macroable.php line 74: Method specialization does not exist
I am getting this small issue. Below is the source code

Doctor Model:

```<code>class Doctor extends Model {
......
....
     public function specialization() {
        return $this->HasMany('App\Specialization');
    }
}
</code>```

Specialization Model:

```<code>class Specialization extends Model {
......
....
     public function doctor () {
        return $this->belongsTo('App\Doctor', 'id');
     }
}
</code>```

Specialization Model:

Here the spec_id is a foreign key

```<code>class DoctorController extends Controller
{
......
....
 //Create a Doctor
    public function createDoctor(Request $request) {
    $doctor = new Doctor();
    $doctor->doctor_id = $request->input('doctor_id');
    // $doctor->spec_id = $request->input('spec_id');
    $doctor->spec_id = $request->specialization()->id;
    $doctor->dob = $request->input('dob');
    $doctor->age = $request->input('age');
    $doctor->gender = $request->input('gender');
    $doctor->qualification = $request->input('qualification');
    $doctor->experience = $request->input('experience');
    $doctor->phone_number = $request->input('phone_number');
    // $doctor->email = $request->user()->email;
    $doctor->email = $request->input('email');
    // $doctor->user_id = $request->user()->user_id;
    $doctor->user_id = $request->input('user_id');
    $doctor->save();
    return response()->json(['doctor' => $doctor], 201);
    }
}
</code>```

Please let me know how do I fix it.

答: I think in the request does not have specialization, you to try to use Log, to find out what the request has</p>

Body:
I am getting this small issue. Below is the source code

Doctor Model:

class Doctor extends Model {
......
....
     public function specialization() {
        return $this->HasMany('App\Specialization');
    }
}

Specialization Model:

class Specialization extends Model {
......
....
     public function doctor () {
        return $this->belongsTo('App\Doctor', 'id');
     }
}

Specialization Model:

Here the spec_id is a foreign key

class DoctorController extends Controller
{
......
....
 //Create a Doctor
    public function createDoctor(Request $request) {
    $doctor = new Doctor();
    $doctor->doctor_id = $request->input('doctor_id');
    // $doctor->spec_id = $request->input('spec_id');
    $doctor->spec_id = $request->specialization()->id;
    $doctor->dob = $request->input('dob');
    $doctor->age = $request->input('age');
    $doctor->gender = $request->input('gender');
    $doctor->qualification = $request->input('qualification');
    $doctor->experience = $request->input('experience');
    $doctor->phone_number = $request->input('phone_number');
    // $doctor->email = $request->user()->email;
    $doctor->email = $request->input('email');
    // $doctor->user_id = $request->user()->user_id;
    $doctor->user_id = $request->input('user_id');
    $doctor->save();
    return response()->json(['doctor' => $doctor], 201);
    }
}

Please let me know how do I fix it.