问:
Volley ImageRequest won't always replace progress spinner with image inside ViewPagerAdapter
I would like to be able to load images into a ViewPager with volley and a progress spinner.

My issue is sometimes the image shows and sometimes the progress spinner goes on forever. Generally if it takes less than a second to load the image, it loads properly and the image shows, otherwise the progress spinner goes on forever if it takes any longer.

Here is my PagerAdapter code in the instantiateItem method:

```<code>    @Override
public Object instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    viewGroup = container;

    view = inflater.inflate(R.layout.photo_pager_layout, container, false);
    progressLayout = (LinearLayout) view.findViewById(R.id.photoProgress);

    imageView  = (TouchImageView) view.findViewById(R.id.photo);
    RequestQueue queue = Volley.newRequestQueue(activity);
    Display display = activity.getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    String url = photos.get(position).getPhotoUrl();
    url = url.replaceAll(activity.getString(R.string.flickr_photo_link_fifth), activity.getString(R.string.flickr_photo_link_sixth));

    progressLayout.setVisibility(View.VISIBLE);
    imageView.setVisibility(View.GONE);

    ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            progressLayout.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
            imageView.setImageBitmap(response);

        }
    }, 1600, 1600, ImageView.ScaleType.FIT_XY, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            progressLayout.setVisibility(View.GONE);
        }
    });
    queue.add(imageRequest);
    container.addView(view);

    return view;
}
</code>```

any help is appreciated, thanks.

答:
So, I went looking hard for a while, and this worked really well!

I used Universal Image Loader for loading the image. You can find this here: https://github.com/nostra13/Android-Universal-Image-Loader, and to add it to your project you need to add this line to your Build.Gradle file:

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

I used an extension of Fresco's (by Facebook) ZoomableDraweeView to hold the image, found that zooming still didn't work, so I looked more in depth. It's still really useful for holding loaded photos without fail, so I'll post it here: https://github.com/ibosong/CommentGallery/tree/master/frescozoomablelib/, and you can add this to your Build.Gradle dependencies to use it:

compile 'com.github.ibosong.CommentGallery:frescozoomablelib:1.0.1'

I found a PhotoViewAttacher that works really well for zooming in and out of the photos here: https://github.com/chrisbanes/PhotoView, and you can add this to you Build.Gradle dependencies to use it:

compile 'com.commit451:PhotoView:1.2.4'

You also need to add this to your Build.Gradle repositories:

maven { url 'https://jitpack.io' }

I can confirm that this works really well with a ViewPager, implementation is posted below:

PhotoPagerActivity:

```<code>private PhotoPagerAdapter mAdapter;
private ViewPager mPager;
private Activity activity;
private DisplayImageOptions options;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photo_pager_activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Show the Up button in the action bar.
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    activity = this;

    options = new DisplayImageOptions.Builder()
            .resetViewBeforeLoading(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .considerExifParams(true)
            .displayer(new FadeInBitmapDisplayer(300))
            .build();

    Bundle extras = getIntent().getExtras();
    int position = extras.getInt("pos");
    String title = extras.getString("AlbumTitle");
    setTitle(title);

    ArrayList<Photo> photos = PhotoAlbumActivity.getPhotos();
    mPager = (ViewPager) findViewById(R.id.photoPager);
    mAdapter = new PhotoPagerAdapter(photos, activity, options);
    mPager.setAdapter(mAdapter);
    mPager.setCurrentItem(position);
}
</code>```

PhotoPagerAdapter:

```<code>private ArrayList<Photo> images;
private View v;
private LayoutInflater inflater;
private ZoomableDraweeView mImageView;
private Activity activity;
private ImageLoader imageLoader;
private DisplayImageOptions options;

PhotoPagerAdapter(ArrayList<Photo> images, Activity activity, DisplayImageOptions options) {
    super();
    this.images = images;
    this.activity = activity;
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(activity).build();
    ImageLoader.getInstance().init(configuration);
    imageLoader = ImageLoader.getInstance();
    this.options = options;
}

@Override
public Object instantiateItem(final ViewGroup container, int position) {
    inflater = LayoutInflater.from(activity);
    v = inflater.inflate(R.layout.photo_pager_layout, container, false);

    String url = images.get(position).getPhotoUrl().replaceAll(activity.getString(R.string.flickr_photo_link_fifth), activity.getString(R.string.flickr_photo_link_sixth));
    mImageView = (ZoomableDraweeView) v.findViewById(R.id.photo);
    PhotoViewAttacher pAttacher;
    pAttacher = new PhotoViewAttacher(mImageView);
    pAttacher.update();

    imageLoader.displayImage(url, mImageView, options, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {

        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            String message = null;
            switch (failReason.getType()) {
                case IO_ERROR:
                    message = "Input/Output error";
                    break;
                case DECODING_ERROR:
                    message = "Image can't be downloaded";
                    break;
                case NETWORK_DENIED:
                    message = "Downloads are denied";
                    break;
                case OUT_OF_MEMORY:
                    message = "Out Of Memory error";
                    break;
                case UNKNOWN:
                    message = "Unknown error";
                    break;
            }

            Toast.makeText(v.getContext(), message, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        }
    });

    container.addView(v, 0);
    return v;
}
</code>```

and photo_pager_layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="1dp">

    <ProgressBar
        android:id="@+id/pbHeaderProgress"
        style="@style/SpinnerAsEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

    <com.bosong.frescozoomablelib.zoomable.ZoomableDraweeView
        android:id="@+id/photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:layout_gravity="center"/>

</FrameLayout>
</code>```

The layout for the activity just contains a viewpager and some other stuff that are unimportant. Hope this helps someone!

Body:
I would like to be able to load images into a ViewPager with volley and a progress spinner.

My issue is sometimes the image shows and sometimes the progress spinner goes on forever. Generally if it takes less than a second to load the image, it loads properly and the image shows, otherwise the progress spinner goes on forever if it takes any longer.

Here is my PagerAdapter code in the instantiateItem method:

    @Override
public Object instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    viewGroup = container;

    view = inflater.inflate(R.layout.photo_pager_layout, container, false);
    progressLayout = (LinearLayout) view.findViewById(R.id.photoProgress);

    imageView  = (TouchImageView) view.findViewById(R.id.photo);
    RequestQueue queue = Volley.newRequestQueue(activity);
    Display display = activity.getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    String url = photos.get(position).getPhotoUrl();
    url = url.replaceAll(activity.getString(R.string.flickr_photo_link_fifth), activity.getString(R.string.flickr_photo_link_sixth));

    progressLayout.setVisibility(View.VISIBLE);
    imageView.setVisibility(View.GONE);

    ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            progressLayout.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
            imageView.setImageBitmap(response);

        }
    }, 1600, 1600, ImageView.ScaleType.FIT_XY, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            progressLayout.setVisibility(View.GONE);
        }
    });
    queue.add(imageRequest);
    container.addView(view);

    return view;
}

any help is appreciated, thanks.

Body:
So, I went looking hard for a while, and this worked really well!

I used Universal Image Loader for loading the image. You can find this here: https://github.com/nostra13/Android-Universal-Image-Loader, and to add it to your project you need to add this line to your Build.Gradle file:

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

I used an extension of Fresco's (by Facebook) ZoomableDraweeView to hold the image, found that zooming still didn't work, so I looked more in depth. It's still really useful for holding loaded photos without fail, so I'll post it here: https://github.com/ibosong/CommentGallery/tree/master/frescozoomablelib/, and you can add this to your Build.Gradle dependencies to use it:

compile 'com.github.ibosong.CommentGallery:frescozoomablelib:1.0.1'

I found a PhotoViewAttacher that works really well for zooming in and out of the photos here: https://github.com/chrisbanes/PhotoView, and you can add this to you Build.Gradle dependencies to use it:

compile 'com.commit451:PhotoView:1.2.4'

You also need to add this to your Build.Gradle repositories:

maven { url 'https://jitpack.io' }

I can confirm that this works really well with a ViewPager, implementation is posted below:

PhotoPagerActivity:

private PhotoPagerAdapter mAdapter;
private ViewPager mPager;
private Activity activity;
private DisplayImageOptions options;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photo_pager_activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Show the Up button in the action bar.
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    activity = this;

    options = new DisplayImageOptions.Builder()
            .resetViewBeforeLoading(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .considerExifParams(true)
            .displayer(new FadeInBitmapDisplayer(300))
            .build();

    Bundle extras = getIntent().getExtras();
    int position = extras.getInt("pos");
    String title = extras.getString("AlbumTitle");
    setTitle(title);

    ArrayList<Photo> photos = PhotoAlbumActivity.getPhotos();
    mPager = (ViewPager) findViewById(R.id.photoPager);
    mAdapter = new PhotoPagerAdapter(photos, activity, options);
    mPager.setAdapter(mAdapter);
    mPager.setCurrentItem(position);
}

PhotoPagerAdapter:

private ArrayList<Photo> images;
private View v;
private LayoutInflater inflater;
private ZoomableDraweeView mImageView;
private Activity activity;
private ImageLoader imageLoader;
private DisplayImageOptions options;

PhotoPagerAdapter(ArrayList<Photo> images, Activity activity, DisplayImageOptions options) {
    super();
    this.images = images;
    this.activity = activity;
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(activity).build();
    ImageLoader.getInstance().init(configuration);
    imageLoader = ImageLoader.getInstance();
    this.options = options;
}

@Override
public Object instantiateItem(final ViewGroup container, int position) {
    inflater = LayoutInflater.from(activity);
    v = inflater.inflate(R.layout.photo_pager_layout, container, false);

    String url = images.get(position).getPhotoUrl().replaceAll(activity.getString(R.string.flickr_photo_link_fifth), activity.getString(R.string.flickr_photo_link_sixth));
    mImageView = (ZoomableDraweeView) v.findViewById(R.id.photo);
    PhotoViewAttacher pAttacher;
    pAttacher = new PhotoViewAttacher(mImageView);
    pAttacher.update();

    imageLoader.displayImage(url, mImageView, options, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {

        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            String message = null;
            switch (failReason.getType()) {
                case IO_ERROR:
                    message = "Input/Output error";
                    break;
                case DECODING_ERROR:
                    message = "Image can't be downloaded";
                    break;
                case NETWORK_DENIED:
                    message = "Downloads are denied";
                    break;
                case OUT_OF_MEMORY:
                    message = "Out Of Memory error";
                    break;
                case UNKNOWN:
                    message = "Unknown error";
                    break;
            }

            Toast.makeText(v.getContext(), message, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        }
    });

    container.addView(v, 0);
    return v;
}

and photo_pager_layout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="1dp">

    <ProgressBar
        android:id="@+id/pbHeaderProgress"
        style="@style/SpinnerAsEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

    <com.bosong.frescozoomablelib.zoomable.ZoomableDraweeView
        android:id="@+id/photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:layout_gravity="center"/>

</FrameLayout>

The layout for the activity just contains a viewpager and some other stuff that are unimportant. Hope this helps someone!


来源: stackexchange

问:
Why variables start out with random values in C
I think this is wrong, it should start as NULL and not with a random value. In the case that you have a pointer with a random memory address as its default value it could be a very dangerous thing, no?</p>

答: Variables start out with a random value because you are just handed a block of memory and told to deal with it yourself. It has whatever value that block of memory had before hand. Why should the program waste time setting the value to some arbitrary default when you are likely going to set it yourself later?</p>

ContentLicense: CC BY-SA 2.5


问:
Kubernetes update changes static+reserved external IPs for nodes in Google Cloud
I have three nodes in my google container cluster.

Everytime i perform a kubernetes update through the web-ui on the cluster in Google Container Engine.

My external IP's change, and i have to manually assign the previous IP on all three instances in Google Cloud Console.

These are reserved static external IP set up using the following guide.

Reserving a static external IP

Has anyone run into the same problem? Starting to think this is a bug.

Perhaps you can set up the same static outbound external IP for all the instances to use, but i cannot find any information on how to do so, that would be a solution as long as it persists through updates, otherwise we've got the same issue.

It's only updates that cause this, not restarts.

答:
You should not rely on the IP addresses of each individual node. Instances can come and go (especially when you use Cluster Autoscaler), and their IP addresses can change.

You should always be exposing your applications with Service or Ingress and IP addresses of the load balancers created with these resources do not change between upgrades. Further you can convert IP address on a load balancer to a static (reserved) IP address.

I see that you're assigning static IP addresses to your nodes. I don't see any reason to do that. When you expose your services with Service/Ingress resources, you can associate a static external IP to them.

See this tutorial: https://cloud.google.com/container-engine/docs/tutorials/http-balancer#step_5_optional_configuring_a_static_ip_address

ContentLicense: CC BY-SA 3.0


问:
How to make UIImage round
I am trying to make the annotation.image round. But I don't know how. How would i go about making a UIImage round.

```<code> //Customize Annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationIdentifier = "Identifier"

    var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView != nil {
        annotationView.annotation = annotation
    } else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

        annotationView.image = profileImage.image

        annotationView.canShowCallout = true
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.autoresizesSubviews = true
        annotationView.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIView
    }

      return annotationView
}
</code>```

}

Currently looks like this on a map

答:
How about adding imageView?</p>

```<code>let imageView = UIImageView(frame: CGRectMake(0, 0, 25, 25))
imageView.image = UIImage(named: "image.png");
imageView.layer.cornerRadius = imageView.layer.bounds.size.width / 2
imageView.layer.masksToBounds = true
annotationView.addSubview(imageView)
</code>```

Title: How to make UIImage round

Body:
I am trying to make the annotation.image round. But I don't know how. How would i go about making a UIImage round.

 //Customize Annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationIdentifier = "Identifier"

    var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView != nil {
        annotationView.annotation = annotation
    } else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

        annotationView.image = profileImage.image

        annotationView.canShowCallout = true
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.autoresizesSubviews = true
        annotationView.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIView
    }

      return annotationView
}

}

Currently looks like this on a map

Body:
How about adding imageView?

let imageView = UIImageView(frame: CGRectMake(0, 0, 25, 25))
imageView.image = UIImage(named: "image.png");
imageView.layer.cornerRadius = imageView.layer.bounds.size.width / 2
imageView.layer.masksToBounds = true
annotationView.addSubview(imageView)


问:
Rails merge multiple json response
Can anyone help me with this problem?

So, here is the problem, I want to merge this query response:

```<code> @energy = Alert.where(["alert_type = ?", "Energy"]).last.as_json

 @cost = Alert.where(["alert_type = ?", "Cost"]).last.as_json
</code>```

Then I merge those object with:

```<code>@current_notif = @energy.merge(@cost)
</code>```

But those just give me @cost object like this:

```<code>{
  "alert_type": "Cost",
  "value": 30000000,
  "status": "Cost exceeds limit",
  "created_at": "2017-06-03T15:31:21.156+07:00",
  "updated_at": "2017-06-03T15:31:21.156+07:00",
  "home_id": 2
}
</code>```

Rather than a merged @energy + @cost like this:

```<code>    { {"alert_type": "Energy",
       "value": 384455.813978742,
       "status": "Energy too high",
       "created_at": "2017-05-31T11:31:12.907+07:00",
       "updated_at": "2017-05-31T11:31:12.907+07:00",
       "home_id": 2 },
     {
       "alert_type": "Cost",
       "value": 30000000,
       "status": "Cost exceeds limit",
       "created_at": "2017-06-03T15:31:21.156+07:00",
       "updated_at": "2017-06-03T15:31:21.156+07:00",
       "home_id": 2
     }
}
</code>```

答:
This is happening because that's how merge works.

```<code>hash = {:name => "Ade", :gender => "Male"}.merge(:name => "Bob")
puts hash # {:name=>"Bob", :gender=>"Male"}
</code>```

Solution:

```<code>results = [ @energy, @cost ]
results.each do |result|
  puts result['alert_type'] # Energy, Cost
end
</code>```

Title: Rails merge multiple json response

Body:
Can anyone help me with this problem?

So, here is the problem, I want to merge this query response:

 @energy = Alert.where(["alert_type = ?", "Energy"]).last.as_json

 @cost = Alert.where(["alert_type = ?", "Cost"]).last.as_json

Then I merge those object with:

@current_notif = @energy.merge(@cost)

But those just give me @cost object like this:

{
  "alert_type": "Cost",
  "value": 30000000,
  "status": "Cost exceeds limit",
  "created_at": "2017-06-03T15:31:21.156+07:00",
  "updated_at": "2017-06-03T15:31:21.156+07:00",
  "home_id": 2
}

Rather than a merged @energy + @cost like this:

    { {"alert_type": "Energy",
       "value": 384455.813978742,
       "status": "Energy too high",
       "created_at": "2017-05-31T11:31:12.907+07:00",
       "updated_at": "2017-05-31T11:31:12.907+07:00",
       "home_id": 2 },
     {
       "alert_type": "Cost",
       "value": 30000000,
       "status": "Cost exceeds limit",
       "created_at": "2017-06-03T15:31:21.156+07:00",
       "updated_at": "2017-06-03T15:31:21.156+07:00",
       "home_id": 2
     }
}

Body:
This is happening because that's how merge works.

hash = {:name => "Ade", :gender => "Male"}.merge(:name => "Bob")
puts hash # {:name=>"Bob", :gender=>"Male"}

Solution:

results = [ @energy, @cost ]
results.each do |result|
  puts result['alert_type'] # Energy, Cost
end


问:
Is there a better way to write this navigation statement?
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!</p>

```<code>$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});
</code>```

答:
I'm making some assumptions about what your document looks like, but this is what I might do:</p>

```<code>$('.nav li a').click(function() {
    $('.nav li a').removeClass('active');
    $(this).addClass('active');
});
</code>```

Body:
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!

$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});

Body:
I'm making some assumptions about what your document looks like, but this is what I might do:

$('.nav li a').click(function() {
    $('.nav li a').removeClass('active');
    $(this).addClass('active');
});


问:
Could not find INI file in $ANDROID_AVD_HOME nor in $HOME/.android/avd
I cannot start a virtual devices on android SDK when I press the start button on AVD manager, this error shows on my screen:

```<code>Starting emulator for AVD 'AVD_for_Galaxy_Nexus_by_Google'
PANIC: Could not find AVD_for_Galaxy_Nexus_by_Google.ini file in
  $ANDROID_AVD_HOME nor in $HOME/.android/avd"!
</code>```

Here is the screen shot:

答: because android SDK environment ANDROID_SDK_HOME, wrong path. /usr/local/opt/android-sdk or /Users/[userName]/Library/Android/sdk TRUE</p>

Body:
I cannot start a virtual devices on android SDK when I press the start button on AVD manager, this error shows on my screen:

Starting emulator for AVD 'AVD_for_Galaxy_Nexus_by_Google'
PANIC: Could not find AVD_for_Galaxy_Nexus_by_Google.ini file in
  $ANDROID_AVD_HOME nor in $HOME/.android/avd"!

Here is the screen shot:


问:
Can't run d3js to a website (jupyter notebook)
I don't really know much about html, d3js or javascript but according to some course in Udacity I could load d3js to any website inputting this code in the web developer console:

```<code>var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://d3js.org/d3.v4.min.js';
document.head.appendChild(script);
</code>```

Looks pretty straightforward, and it has worked with every page I've tried except my jupyter notebook. The script gets appended in the  tag but it has really low opacity and when I try to run some d3js code it doesn't work (running d3.select("p"); gives ReferenceError: d3 is not defined). Is there any other workaround?

答:
It's because you need to make d3 global.  What I do in a cell is this.  Jupyter already has require loaded.</p>

```<code>%%javascript
require.config({
    paths: {
        d3: "https://d3js.org/d3.v4.min"
     }
});

require(["d3"], function(d3) {
    window.d3 = d3;
});
</code>```

Body:
I don't really know much about html, d3js or javascript but according to some course in Udacity I could load d3js to any website inputting this code in the web developer console:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://d3js.org/d3.v4.min.js';
document.head.appendChild(script);

Looks pretty straightforward, and it has worked with every page I've tried except my jupyter notebook. The script gets appended in the  tag but it has really low opacity and when I try to run some d3js code it doesn't work (running d3.select("p"); gives ReferenceError: d3 is not defined). Is there any other workaround?

Body:
It's because you need to make d3 global.  What I do in a cell is this.  Jupyter already has require loaded.

%%javascript
require.config({
    paths: {
        d3: "https://d3js.org/d3.v4.min"
     }
});

require(["d3"], function(d3) {
    window.d3 = d3;
});


问:
How to have myname.github.io as url of a personal website on GitHub?
I want to set up a personal website on Github. I followed this video to create a repository containing a file index.html.

I read online that in order to obtain an url <myname>.github.io for this html page, you need to name the respository <myname>.github.io. But when I do this, the html page gets published to <accountname>.github.io/<myname>.github.io. Did I do something wrong?

答:
From https://pages.github.com:

Head over to GitHub and create a new repository named
  username.github.io, where username is your username (or organization
  name) on GitHub.

If the first part of the repository doesn’t exactly match your
  username, it won’t work, so make sure to get it right.


问:
Ensure SSL all the way to the pod using Google Container Engine Ingress
I have a pod that serves HTTPS traffic on 443 using a self-signed certificate with a CN of app that matches the service name, app. It also serves HTTP on 80.

I also have an Ingress object that exposes the pod externally on foo.com and I use kube-lego to dynamically fetch and configure a LetsEncrypt certificate for foo.com:

```<code>spec:
  rules:
  - host: foo.com
    http:
      paths:
      - backend:
          serviceName: kube-lego-gce
          servicePort: 8080
        path: /.well-known/acme-challenge/*
      - backend:
          serviceName: app
          servicePort: 80
        path: /*
  tls:
  - hosts:
    - foo.com
    secretName: app-tls-staging
</code>```

This means there are two levels of SSL. If I set the servicePort of the Ingress to 443 to ensure traffic between Google's LB and my pod is encrypted, the endpoint returns 502 Server Error. Is this because it doesn't know to trust my self-signed cert? Is there a way to specify a CA?

Once I set it back to 80 the Ingress starts working normally again after a few minutes.

答:
What you're looking for is "re-encryption" for Load Balancer <=> cluster traffic. If you see here, re-encryption is listed as "Future Work".

But I see this feature is merged: https://github.com/kubernetes/ingress/pull/519/commits

It looks like you can find an example here and it's described as "Backend HTTPS" in this document: https://github.com/kubernetes/ingress/tree/master/controllers/gce#backend-https

However today this feature seems to be in alpha, so it may be subject to change and you may need to create an alpha GKE cluster (which is short-lived) to use it.

Body:
I have a pod that serves HTTPS traffic on 443 using a self-signed certificate with a CN of app that matches the service name, app. It also serves HTTP on 80.

I also have an Ingress object that exposes the pod externally on foo.com and I use kube-lego to dynamically fetch and configure a LetsEncrypt certificate for foo.com:

spec:
  rules:
  - host: foo.com
    http:
      paths:
      - backend:
          serviceName: kube-lego-gce
          servicePort: 8080
        path: /.well-known/acme-challenge/*
      - backend:
          serviceName: app
          servicePort: 80
        path: /*
  tls:
  - hosts:
    - foo.com
    secretName: app-tls-staging

This means there are two levels of SSL. If I set the servicePort of the Ingress to 443 to ensure traffic between Google's LB and my pod is encrypted, the endpoint returns 502 Server Error. Is this because it doesn't know to trust my self-signed cert? Is there a way to specify a CA?

Once I set it back to 80 the Ingress starts working normally again after a few minutes.


答:
If you want you could "join" both values, and then over that use as_json:

```<code>[@energy, @cost].as_json
# [{"alert_type": "Energy", ... }, {"alert_type": "Cost", ... }]
</code>```

Or if you want you could use the IN expression, in order to deal with ActiveRecord instead having to customize the result this gives you:

```<code>Alert.where(alert_type: ['Energy', 'Cost']).as_json
# [{"alert_type": "Energy", ... }, {"alert_type": "Cost", ... }]
</code>```

Title: Rails merge multiple json response

Body:
If you want you could "join" both values, and then over that use as_json:

[@energy, @cost].as_json
# [{"alert_type": "Energy", ... }, {"alert_type": "Cost", ... }]

Or if you want you could use the IN expression, in order to deal with ActiveRecord instead having to customize the result this gives you:

Alert.where(alert_type: ['Energy', 'Cost']).as_json
# [{"alert_type": "Energy", ... }, {"alert_type": "Cost", ... }]


问:
More efficient algorithm to find OR of two sets
Given a matrix of n rows and m columns of 1's and 0's, it is required to find out the number of pairs of rows that can be selected so that their OR is 11111....m times.

Example:

```<code>1 0 1 0 1
0 1 0 0 1
1 1 1 1 0
</code>```

Answer:

```<code>2 ---> OR of row number [1,3] and [2,3]
</code>```

Given n and m can be an order upto <= 3000, how efficiently can this problem be solved?

PS: I already tried with a naive O(n*n*m) method. I was thinking of a better solution.

答:
Expanding on TheGreatContini's idea:

First try

Let's look at it as finding combinations that belong to AxB, with A and B sets of rows. These combinations must satisfy the or condition, but we'll also assume the hamming weight of a is at least as large as b (to avoid some duplicates).

Now split A into A0 (rows that start with 0) and A1 (rows that start with 1). Do the same for B. We have now reduced the problem into three smaller problems: A0xB1, A1xB1 and A1xB0. If A and B were the same, A0xB1 and A1xB0 are the same, so we only need to do one. Not only are these three subproblems combined smaller than the first, we've also fully checked the first column and can ignore it from now on.

To solve these subproblems, we can use the same approach, but now with column 2, 3, ... At some point, either we will have checked all the columns or #A and #B will be 1.

Depending on the implementation, stopping sooner might be more efficient. At that point we can do an exhaustive check of the remaining combinations. Remember though that if we have already checked k columns, that this will only cost m-k per combination.

Better column selection

As TheGreatContini suggested, instead of selecting the first column, we can select the column that would lead to the smallest subproblems. The cost of finding this column at each step is rather high, but the weights could be calculated once in the beginning and then used as an estimate for the best column. We can then rearrange the columns use the algorithm as normal, after it is done, rearrange them again.

The exact best column would be the column for which the amount of zeros in A times the amount of zeros in B is maximal.

Hamming weight pruning

We know that the sum of the hamming weights of a and b must be at least m. And since we assumed a to be the highest hamming weight, we can remove all the values of a that have a hamming weight less than m/2. (the speedup this gives might be negligable, i'm not sure). Calculating all the hamming weights costs O(m*n).

Efficient Splitting

If we sort the rows, the splitting in groups can be done much faster using the bisection algorithm. This can also lead to an efficient representation of the sets in memory. We can just specify the minimum and maximum row. Sorting can be done in O(n*m*log(n)). Splitting can then be done in about log(n).

Here's some code that won't compile, but should give the right idea.

```<code>private List<Row> rows;
public int findFirstOne(int column, int start, int end){
    if(rows.get(start).get(column) == 1) return start;
    if(rows.get(end).get(column) == 0) return -1;
    while(start < end){
        int mid = (start+end)/2;
        if(rows.get(mid).get(column) == 0){
            start = mid+1;
        }else{
            end = mid;
        }
    }
    return start;
}
</code>```

Complexity

In the following calculations the effect of the better column selection is ignored as it will give little improvement on worst case efficienty. However, in average cases it can give a massive improvement by reducing the search space as soon as possible and thereby making the other checks faster.

The algorithms run time is bounded by n²m.
However, the worst examples i have found are all O(n*log(n)*m).

First, the sorting of the matrix will be O(n*log(n)*m) for the rows and optionally, sorting the columns will be O(n*m + m*log(m)).

Then, the creating of the subproblems. Let's make an overestimate first. We need to subdivise at most m times and the cost for a full level of of subdivisions at depth i can be overestimated as log(n)*3^i (cost per subdivision times number of subdivisions). This leads to O(log(n)*3^m) in total.

It must also hold that 3^i <= n²/2, because this is the maximum number of combinations possible, so for large m it caps at O(n²*log(n)*m). I struggle to find an example that actually behaves like this though.

I think it is reasonable to assume many of the subproblems become trivial very early. Leading to O(log(n)*m*n) (if someone wants to check this, i'm not really sure about it).

Body:
Given a matrix of n rows and m columns of 1's and 0's, it is required to find out the number of pairs of rows that can be selected so that their OR is 11111....m times.

Example:

1 0 1 0 1
0 1 0 0 1
1 1 1 1 0

Answer:

2 ---> OR of row number [1,3] and [2,3]

Given n and m can be an order upto <= 3000, how efficiently can this problem be solved?

PS: I already tried with a naive O(n*n*m) method. I was thinking of a better solution.

Body:
Expanding on TheGreatContini's idea:

First try

Let's look at it as finding combinations that belong to AxB, with A and B sets of rows. These combinations must satisfy the or condition, but we'll also assume the hamming weight of a is at least as large as b (to avoid some duplicates).

Now split A into A0 (rows that start with 0) and A1 (rows that start with 1). Do the same for B. We have now reduced the problem into three smaller problems: A0xB1, A1xB1 and A1xB0. If A and B were the same, A0xB1 and A1xB0 are the same, so we only need to do one. Not only are these three subproblems combined smaller than the first, we've also fully checked the first column and can ignore it from now on.

To solve these subproblems, we can use the same approach, but now with column 2, 3, ... At some point, either we will have checked all the columns or #A and #B will be 1.

Depending on the implementation, stopping sooner might be more efficient. At that point we can do an exhaustive check of the remaining combinations. Remember though that if we have already checked k columns, that this will only cost m-k per combination.

Better column selection

As TheGreatContini suggested, instead of selecting the first column, we can select the column that would lead to the smallest subproblems. The cost of finding this column at each step is rather high, but the weights could be calculated once in the beginning and then used as an estimate for the best column. We can then rearrange the columns use the algorithm as normal, after it is done, rearrange them again.

The exact best column would be the column for which the amount of zeros in A times the amount of zeros in B is maximal.

Hamming weight pruning

We know that the sum of the hamming weights of a and b must be at least m. And since we assumed a to be the highest hamming weight, we can remove all the values of a that have a hamming weight less than m/2. (the speedup this gives might be negligable, i'm not sure). Calculating all the hamming weights costs O(m*n).

Efficient Splitting

If we sort the rows, the splitting in groups can be done much faster using the bisection algorithm. This can also lead to an efficient representation of the sets in memory. We can just specify the minimum and maximum row. Sorting can be done in O(n*m*log(n)). Splitting can then be done in about log(n).

Here's some code that won't compile, but should give the right idea.

private List<Row> rows;
public int findFirstOne(int column, int start, int end){
    if(rows.get(start).get(column) == 1) return start;
    if(rows.get(end).get(column) == 0) return -1;
    while(start < end){
        int mid = (start+end)/2;
        if(rows.get(mid).get(column) == 0){
            start = mid+1;
        }else{
            end = mid;
        }
    }
    return start;
}

Complexity

In the following calculations the effect of the better column selection is ignored as it will give little improvement on worst case efficienty. However, in average cases it can give a massive improvement by reducing the search space as soon as possible and thereby making the other checks faster.

The algorithms run time is bounded by n²m.
However, the worst examples i have found are all O(n*log(n)*m).

First, the sorting of the matrix will be O(n*log(n)*m) for the rows and optionally, sorting the columns will be O(n*m + m*log(m)).

Then, the creating of the subproblems. Let's make an overestimate first. We need to subdivise at most m times and the cost for a full level of of subdivisions at depth i can be overestimated as log(n)*3^i (cost per subdivision times number of subdivisions). This leads to O(log(n)*3^m) in total.

It must also hold that 3^i <= n²/2, because this is the maximum number of combinations possible, so for large m it caps at O(n²*log(n)*m). I struggle to find an example that actually behaves like this though.

I think it is reasonable to assume many of the subproblems become trivial very early. Leading to O(log(n)*m*n) (if someone wants to check this, i'm not really sure about it).


问:
double free or corruption (!prev)

I get the following error when running a c program: * Error in `./final': double free or corruption (!prev): 0x0000000000c2f010 *

I believe this is due to free() being called at the end of the
  program, but I can't figure out where the malloc'd memory is being
  freed prior to this. Here is the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include <time.h>
#include <stdlib.h>

static int DIM = 1000; // Golbal variable for Matrices Dimentions
int isPrime(unsigned int number);
int countPrimes(int **matrix);

int main() {

    time_t tic = clock();
    int **matrixA;//
    int **matrixB;
    int **mult;
    int k = 0, sum=0;
    time_t t;
    int i =0,j;

    // Allocate dynamic memory for Matrices A,B && mult first (rows) dimension
    matrixA = (int **) malloc (DIM * sizeof (int *));
    matrixB = (int **) malloc (DIM * sizeof (int *));
    mult = (int **) malloc (DIM * sizeof (int *));
    // Allocate dynamic memory for Matrices A,B && mult second (rows) dimension, && Initialize elements to "0" For Matrices B && Mult
    for (k = 0; k < DIM; k++) {
        matrixA[k] = (int *) calloc (DIM, sizeof (int *));
        matrixB[k] = (int *) calloc (DIM, sizeof (int *));
        mult[k] = (int *) calloc (DIM, sizeof (int *));
    }

    // Generate random numbers for matrix A elements
    for (i = 0; i < DIM; i++)
    {
        for (j = 0; j < DIM; j++)
        {
            matrixA[i][j] = (rand() % 100)+1 ;
            printf("%d  ",matrixA[i][j]);
        }
    }

    // Do the matrix multiplication
    for (i = 0; i < DIM; i++) {
        for (j = 0; j < DIM; j++) {
            for (k = 0; k < j; k++) {
                sum += matrixA[i][k] * matrixB[k][j];
            }
            mult[i][j] = sum;
        sum = 0;
        }
    }

    int total = countPrimes(matrixA);
    printf("\n\nnumber of primes in a : %d\n\n", total);

  // Delete the dynamic memory of Matrix A
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixA+i));
    }
    free(matrixA);

    // Delete the dynamic memory of Matrix B
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixB+i));
    }
    free(matrixA);

    // Delete the dynamic memory of Matrix B
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixB+i));
    }
    free(matrixA);

    // Compute SpeedUp
    time_t toc = clock();
    double time = (double) (toc - tic) / CLOCKS_PER_SEC;
    printf("The amount of time the OS has spent running your process is : %lf seconds\n\n\n", time);

    return 0;
}

// Check elements of Matrix A if its a Prime number or not
int isPrime(unsigned int number) { // Psitive numbers could be Prime numbers only
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
    }

// Count number of prime numbers in Matrix A
int countPrimes(int **matrix) {
    int row, col;
    int flag = 0;
    int total = 0;
    for (row = 0; row < DIM; row++) {
        for (col = 0; col < DIM; col++) {
            flag = isPrime(matrix[row][col]);
            if(flag == 1)
                total++;
        }
    }
    return total;
}
</code>```

答:
Your error is here:

```<code>  // Delete the dynamic memory of Matrix A
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixA+i));
    }
    free(matrixA);

    // Delete the dynamic memory of Matrix B
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixB+i));
    }
    free(matrixA);

    // Delete the dynamic memory of Matrix B
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixB+i));
    }
    free(matrixA);
</code>```

Notice that you free(matrixA) three times, even though you intend to free matrixB and matrixC.  You also mistakenly use free(*(matrixB+i)); in two different loops.

Title: double free or corruption (!prev)

Body:
I get the following error when running a c program: * Error in `./final': double free or corruption (!prev): 0x0000000000c2f010 *

I believe this is due to free() being called at the end of the
  program, but I can't figure out where the malloc'd memory is being
  freed prior to this. Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include <time.h>
#include <stdlib.h>

static int DIM = 1000; // Golbal variable for Matrices Dimentions
int isPrime(unsigned int number);
int countPrimes(int **matrix);

int main() {

    time_t tic = clock();
    int **matrixA;//
    int **matrixB;
    int **mult;
    int k = 0, sum=0;
    time_t t;
    int i =0,j;

    // Allocate dynamic memory for Matrices A,B && mult first (rows) dimension
    matrixA = (int **) malloc (DIM * sizeof (int *));
    matrixB = (int **) malloc (DIM * sizeof (int *));
    mult = (int **) malloc (DIM * sizeof (int *));
    // Allocate dynamic memory for Matrices A,B && mult second (rows) dimension, && Initialize elements to "0" For Matrices B && Mult
    for (k = 0; k < DIM; k++) {
        matrixA[k] = (int *) calloc (DIM, sizeof (int *));
        matrixB[k] = (int *) calloc (DIM, sizeof (int *));
        mult[k] = (int *) calloc (DIM, sizeof (int *));
    }

    // Generate random numbers for matrix A elements
    for (i = 0; i < DIM; i++)
    {
        for (j = 0; j < DIM; j++)
        {
            matrixA[i][j] = (rand() % 100)+1 ;
            printf("%d  ",matrixA[i][j]);
        }
    }

    // Do the matrix multiplication
    for (i = 0; i < DIM; i++) {
        for (j = 0; j < DIM; j++) {
            for (k = 0; k < j; k++) {
                sum += matrixA[i][k] * matrixB[k][j];
            }
            mult[i][j] = sum;
        sum = 0;
        }
    }

    int total = countPrimes(matrixA);
    printf("\n\nnumber of primes in a : %d\n\n", total);

  // Delete the dynamic memory of Matrix A
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixA+i));
    }
    free(matrixA);

    // Delete the dynamic memory of Matrix B
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixB+i));
    }
    free(matrixA);

    // Delete the dynamic memory of Matrix B
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixB+i));
    }
    free(matrixA);

    // Compute SpeedUp
    time_t toc = clock();
    double time = (double) (toc - tic) / CLOCKS_PER_SEC;
    printf("The amount of time the OS has spent running your process is : %lf seconds\n\n\n", time);

    return 0;
}

// Check elements of Matrix A if its a Prime number or not
int isPrime(unsigned int number) { // Psitive numbers could be Prime numbers only
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
    }

// Count number of prime numbers in Matrix A
int countPrimes(int **matrix) {
    int row, col;
    int flag = 0;
    int total = 0;
    for (row = 0; row < DIM; row++) {
        for (col = 0; col < DIM; col++) {
            flag = isPrime(matrix[row][col]);
            if(flag == 1)
                total++;
        }
    }
    return total;
}

Body:
Your error is here:

  // Delete the dynamic memory of Matrix A
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixA+i));
    }
    free(matrixA);

    // Delete the dynamic memory of Matrix B
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixB+i));
    }
    free(matrixA);

    // Delete the dynamic memory of Matrix B
    for (i = 0; i < DIM; i++) {          // free first matrix
        free(*(matrixB+i));
    }
    free(matrixA);

Notice that you free(matrixA) three times, even though you intend to free matrixB and matrixC.  You also mistakenly use free(*(matrixB+i)); in two different loops.


问:
$not operator is not working inside an $and operator in query
I want to query my database with the following restrictions, for all records where all these conditions are true:

property is propertyID

active is true

startDate is NOT greater than Y

endDate is NOT less than X

I am having a hard time getting MongoDB to accept my $match:

```<code>$match:{
    $and:[
        { property : propertyID },
        { active   : true },
        { $not: { start : {$gte: 1498780800 } } },
        { $not: { end   : {$lte: 1497052800 } } }
    ]
}
</code>```

Right now I am getting the error: MongoError: unknown top level operator: $not. You might say just do startDate less than X and endDate less than Y, but this won't work because startDate might be greater than X and endDate less than Y which is a record I want etc.. which is why that won't work. How can I fix this?

UPDATE:

My logic is not correct, this is what I am trying to do...

答:
The problem is that you've got $not in the wrong place. Per the documentation:

Syntax: { field: { $not: { <operator-expression> } } }

Thus, $not should be used not as a top level operator, the field should be at the top level.

On to the logical side of this problem. You want to select records where start is in between the restricted dates or end is in between the restricted dates, there's no reason to use $not here. Also, make sure you are checking for greater than the minimum and less than the maximum, not the other way around. Try the following query:

```<code>$match: {
  $and: [
    { property: propertyID },
    { active: true },
    { $or: [
      { start: { $lte: 1498780800, $gte: 1497052800 } },
      { end: { $lte: 1498780800, $gte: 1497052800 } }
    ] }
  ]
}
</code>```

This will check if either start or end is in between the restricted dates.

Body:
I want to query my database with the following restrictions, for all records where all these conditions are true:

property is propertyID

active is true

startDate is NOT greater than Y

endDate is NOT less than X

I am having a hard time getting MongoDB to accept my $match:

$match:{
    $and:[
        { property : propertyID },
        { active   : true },
        { $not: { start : {$gte: 1498780800 } } },
        { $not: { end   : {$lte: 1497052800 } } }
    ]
}

Right now I am getting the error: MongoError: unknown top level operator: $not. You might say just do startDate less than X and endDate less than Y, but this won't work because startDate might be greater than X and endDate less than Y which is a record I want etc.. which is why that won't work. How can I fix this?

UPDATE:

My logic is not correct, this is what I am trying to do...

Body:
The problem is that you've got $not in the wrong place. Per the documentation:

Syntax: { field: { $not: { <operator-expression> } } }

Thus, $not should be used not as a top level operator, the field should be at the top level.

On to the logical side of this problem. You want to select records where start is in between the restricted dates or end is in between the restricted dates, there's no reason to use $not here. Also, make sure you are checking for greater than the minimum and less than the maximum, not the other way around. Try the following query:

$match: {
  $and: [
    { property: propertyID },
    { active: true },
    { $or: [
      { start: { $lte: 1498780800, $gte: 1497052800 } },
      { end: { $lte: 1498780800, $gte: 1497052800 } }
    ] }
  ]
}

This will check if either start or end is in between the restricted dates.


问:
How to use column/row index as range in VBA
Like using Cells(1, 1) instead of Range("A1"), what's the best way to use column/Row index as range in VBA?

I came up with 2 solutions to denote Range("A:A"):

Range(Cells(1, 1), Cells(Columns(1).Rows.count, 1))

Union(Columns(1), Columns(1))

Is there a better and more concise solution?

Edit: noted response from Tehscript and thanks for the same. I already tried that but it's giving below error:

Run-time error '13': Type mismatch.

Here's the code:

```<code>Sub tfind()
    Dim r1 As Range
    Set r1 = Columns(1)
    MsgBox mCount("Test:", r1)
End Sub
Function mCount(find As String, lookin As Range) As Long
   Dim cell As Range
   For Each cell In lookin
       If (Left(cell.Value, Len(find)) = find) Then mCount = mCount + 1
   Next
End Function
</code>```

Although it works fine if the 3rd line:

```<code>Set r1 = Columns(1)
</code>```

is changed to:

```<code>Set r1 = Union(Columns(1), Columns(1))
</code>```

答:
There is no best way to do this, but there are ways that you can use according to your needs. For example if you want to loop through both rows and columns you should better use Cells():

```<code>Sub RowTimesColumn()
Dim i As Long, j As Long
For i = 1 To 10
    For j = 1 To 5
        Cells(i, j) = i * j
    Next j
Next i
End Sub
</code>```

On the other hand you can reference a range like Range("A1:B3") in either way depending on your needs. If you simply need the reference, you should use Range("A1:B3"). If you need to play with the rows and columns, you should better use Range(Cells(1, 1), Cells(3, 2)).

It is all about readability and functionality.

For your question, you might want to use the following:

Range("A:A") --> Columns(1)

Range("A:C") --> Range(Columns(1), Columns(3))

Edit: You are looping through the cells within Column A, in that case you need to use:

Columns("A").Cells or Columns(1).Cells

Body:
Like using Cells(1, 1) instead of Range("A1"), what's the best way to use column/Row index as range in VBA?

I came up with 2 solutions to denote Range("A:A"):

Range(Cells(1, 1), Cells(Columns(1).Rows.count, 1))

Union(Columns(1), Columns(1))

Is there a better and more concise solution?

Edit: noted response from Tehscript and thanks for the same. I already tried that but it's giving below error:

Run-time error '13': Type mismatch.

Here's the code:

Sub tfind()
    Dim r1 As Range
    Set r1 = Columns(1)
    MsgBox mCount("Test:", r1)
End Sub
Function mCount(find As String, lookin As Range) As Long
   Dim cell As Range
   For Each cell In lookin
       If (Left(cell.Value, Len(find)) = find) Then mCount = mCount + 1
   Next
End Function

Although it works fine if the 3rd line:

Set r1 = Columns(1)

is changed to:

Set r1 = Union(Columns(1), Columns(1))

Body:
There is no best way to do this, but there are ways that you can use according to your needs. For example if you want to loop through both rows and columns you should better use Cells():

Sub RowTimesColumn()
Dim i As Long, j As Long
For i = 1 To 10
    For j = 1 To 5
        Cells(i, j) = i * j
    Next j
Next i
End Sub

On the other hand you can reference a range like Range("A1:B3") in either way depending on your needs. If you simply need the reference, you should use Range("A1:B3"). If you need to play with the rows and columns, you should better use Range(Cells(1, 1), Cells(3, 2)).

It is all about readability and functionality.

For your question, you might want to use the following:

Range("A:A") --> Columns(1)

Range("A:C") --> Range(Columns(1), Columns(3))

Edit: You are looping through the cells within Column A, in that case you need to use:

Columns("A").Cells or Columns(1).Cells


问:
Optimizing LINQ Query to avoid multiple enumerations
I have written a code like this in my .NET project:

```<code>var v = ctx.Items
        .Where(x => x.userid== user.userid)
        .Select(e => new MyViewModel
        {
          Title = e.Title,
          CurrentPrice = e.CurrenctPrice.Value,
          ItemID = e.ItemID.ToString(),
          Sales = e.Transactions.Where(p => p.TransactionDate >= intoPast && p.TransactionDate <= endDate).Sum(x => x.QuantityPurchased)
         })
         .Where(x => x.Sales > 0 && ((filterWord == "") || (filterWord != "" && x.Title.ToLower().Contains(filterWord.ToLower()))));
</code>```

where "ctx" is my object context variable...

And this is the ViewModelClass that I use:

```<code>  public class MyViewModel
    {
        public string Title { get; set; }
        public int Sales { get; set; }
        public string ItemID { get; set; }
        public double CurrentPrice { get; set; }
    }
</code>```

The thing that most bugs me here is the sales property... As you can see i set its value in select statement. This way all my data gets  enumerated every time...

What I was thinking here is to create a method called "getsales()"... And then to just simply call the GetSales method in my where statement like this:

```<code>.Where(x=>X.GetSales(/*neccesary parameters here*/)...)
</code>```

In order to avoid having multiple enumerations...

But I'm not really sure how to do it...

Can someone help me out here?

答:
I think this is what you're looking for:</p>

```<code>var v = ctx.Items
    .Where(x =>
        x.userid == user.userid &&
        (filterWord == "" || x.Title.ToLower().Contains(filterWord.ToLower())))
    .Select(e => new MyViewModel
    {
        Title = e.Title,
        CurrentPrice = e.CurrentPrice.Value,
        ItemID = e.ItemID.ToString(),
        Sales = e.Transactions
            .Where(p =>
                p.TransactionDate >= intoPast &&
                p.TransactionDate <= endDate)
            .Sum(x => x.QuantityPurchased)
    })
    .Where(x => x.Sales > 0);
</code>```

Body:
I have written a code like this in my .NET project:

var v = ctx.Items
        .Where(x => x.userid== user.userid)
        .Select(e => new MyViewModel
        {
          Title = e.Title,
          CurrentPrice = e.CurrenctPrice.Value,
          ItemID = e.ItemID.ToString(),
          Sales = e.Transactions.Where(p => p.TransactionDate >= intoPast && p.TransactionDate <= endDate).Sum(x => x.QuantityPurchased)
         })
         .Where(x => x.Sales > 0 && ((filterWord == "") || (filterWord != "" && x.Title.ToLower().Contains(filterWord.ToLower()))));

where "ctx" is my object context variable...

And this is the ViewModelClass that I use:

  public class MyViewModel
    {
        public string Title { get; set; }
        public int Sales { get; set; }
        public string ItemID { get; set; }
        public double CurrentPrice { get; set; }
    }

The thing that most bugs me here is the sales property... As you can see i set its value in select statement. This way all my data gets  enumerated every time...

What I was thinking here is to create a method called "getsales()"... And then to just simply call the GetSales method in my where statement like this:

.Where(x=>X.GetSales(/*neccesary parameters here*/)...)

In order to avoid having multiple enumerations...

But I'm not really sure how to do it...

Can someone help me out here?

Body:
I think this is what you're looking for:

var v = ctx.Items
    .Where(x =>
        x.userid == user.userid &&
        (filterWord == "" || x.Title.ToLower().Contains(filterWord.ToLower())))
    .Select(e => new MyViewModel
    {
        Title = e.Title,
        CurrentPrice = e.CurrentPrice.Value,
        ItemID = e.ItemID.ToString(),
        Sales = e.Transactions
            .Where(p =>
                p.TransactionDate >= intoPast &&
                p.TransactionDate <= endDate)
            .Sum(x => x.QuantityPurchased)
    })
    .Where(x => x.Sales > 0);


问:
Use of uninitialized value $site in string
'm trying to execute this code but it's already give me the following error :

Use of uninitialized value $site in string at C:\Users\USER\Desktop\script.pl line 35.

```<code>#!/usr/bin/perl

use LWP::UserAgent;
use File::Slurp;
use warnings;
use strict;
use HTTP::Request;

open (THETARGET, "<list.txt") || die "[-] Can't open the file";
my @TARGETS = <THETARGET>;
close THETARGET;
my $link=$#TARGETS + 1;

OUTER: foreach my $site(@TARGETS){
    chomp($site);
}

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $url = my $site;
my $picture = "teest.png";
my %args;
my $field_name = "file[]";
my $buf ;
my $buf_ref = $args{'buf'} || \$buf ;

my $value = read_file( $picture , binmode => ':raw' , scalar_ref => 1 );

my $response = $ua->post( $url,
            Content_Type => 'form-data',
            Content => [ $field_name => ["$picture"] ]
            );
print "$site";
</code>```

答:
I think what you are expecting is the value of $site to carry over from the for loop, but because it is defined in the for loop, its scope is limited to that loop.  Perhaps what you intended is for all of the following code to also be inside that loop.  Otherwise, that value for $site ceases to exist at the closing-brace two lines after it was created.  Your line

```<code>my $url = my $site;
</code>```

then creates a new variable $site (which is undef), and that undef value is used to set $url, so it is also undef.  I suspect you initially had

```<code>my $url = $site;
</code>```

then added the extra "my" to resolve an earlier error.

I hope this helps you.

Body:
'm trying to execute this code but it's already give me the following error :

Use of uninitialized value $site in string at C:\Users\USER\Desktop\script.pl line 35.

#!/usr/bin/perl

use LWP::UserAgent;
use File::Slurp;
use warnings;
use strict;
use HTTP::Request;

open (THETARGET, "<list.txt") || die "[-] Can't open the file";
my @TARGETS = <THETARGET>;
close THETARGET;
my $link=$#TARGETS + 1;

OUTER: foreach my $site(@TARGETS){
    chomp($site);
}

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $url = my $site;
my $picture = "teest.png";
my %args;
my $field_name = "file[]";
my $buf ;
my $buf_ref = $args{'buf'} || \$buf ;

my $value = read_file( $picture , binmode => ':raw' , scalar_ref => 1 );

my $response = $ua->post( $url,
            Content_Type => 'form-data',
            Content => [ $field_name => ["$picture"] ]
            );
print "$site";

Body:
I think what you are expecting is the value of $site to carry over from the for loop, but because it is defined in the for loop, its scope is limited to that loop.  Perhaps what you intended is for all of the following code to also be inside that loop.  Otherwise, that value for $site ceases to exist at the closing-brace two lines after it was created.  Your line

my $url = my $site;

then creates a new variable $site (which is undef), and that undef value is used to set $url, so it is also undef.  I suspect you initially had

my $url = $site;

then added the extra "my" to resolve an earlier error.

I hope this helps you.


问:
How to remove button shadow (android)
I want to remove the shadow from the button to make it seem more flat.

I have this right now:

But I want this:

答:
Instead of a Button, you can use a TextView and add a click listener in the java code.

I.e.

in the activity layout xml:

```<code><TextView
    android:id="@+id/btn_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:text="@string/btn_text"
    android:gravity="center"
    android:textColor="@color/colorAccent"
    android:fontFamily="sans-serif-medium"
    android:textAllCaps="true" />
</code>```

in the activity java file:

```<code>TextView btnTextView = (TextView) findViewById(R.id.btn_text_view);
btnTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // handler code
            }
        });
</code>```

Title: How to remove button shadow (android)

Body:
Instead of a Button, you can use a TextView and add a click listener in the java code.

I.e.

in the activity layout xml:

<TextView
    android:id="@+id/btn_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:text="@string/btn_text"
    android:gravity="center"
    android:textColor="@color/colorAccent"
    android:fontFamily="sans-serif-medium"
    android:textAllCaps="true" />

in the activity java file:

TextView btnTextView = (TextView) findViewById(R.id.btn_text_view);
btnTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // handler code
            }
        });


问:
Looping or repeatedly running a bunch of JQuery functions
I was learning JQuery on my own and yesterday night I stumbled upon a doubt and am stuck since then.
simple: I need the animation to repeat on loop. but it is not working, can you please help me out? I have tried setInterval, it is not working.
The fiddle is: https://jsfiddle.net/8v5feL9u/

```<code>            $(document).ready(function(){

//window.setInterval(function(){

            $(".img1").css({display:''});
            $(".img1").animate({bottom: '300px', opacity: '1'}, 2000, function(){
                $(".img1").fadeOut(700);
                $(".img1").css({display:'none', bottom: '', opacity:'0'});
                $(".img2").css({display:''});
                $(".img2").animate({top: '300px', opacity: '1'}, 2000, function(){
                    $(".img2").fadeOut(700);
                    $(".img2").css({display:'none', top: '', opacity:'0'});
                    $(".img3").css({display:''});
                    $(".img3").animate({bottom: '300px', opacity: '1'}, 2000, function(){
                        $(".img3").fadeOut(700);
                        $(".img3").css({display:'none', bottom: '', opacity:'0'})
                        $(".img4").css({display:''});
                        $(".img4").animate({top: '300px', opacity: '1'}, 2000, function(){
                            $(".img4").fadeOut(700);
                            $(".img4").css({display:'none', top: '', opacity:'0'});

                        });
                    });
                });
            });

//});

        });
</code>```

thank you so much.

答:
Without re-writing entire piece, you can provide a name for and call the function passed to .ready() within last nested .animate() callback function

$(function fn() {
  $(".img1").css({
    display: ''
  });
  $(".img1").animate({
    bottom: '300px',
    opacity: '1'
  }, 2000, function() {
    $(".img1").fadeOut(700);
    $(".img1").css({
      display: 'none',
      bottom: '',
      opacity: '0'
    });
    $(".img2").css({
      display: ''
    });
    $(".img2").animate({
      top: '300px',
      opacity: '1'
    }, 2000, function() {
      $(".img2").fadeOut(700);
      $(".img2").css({
        display: 'none',
        top: '',
        opacity: '0'
      });
      $(".img3").css({
        display: ''
      });
      $(".img3").animate({
        bottom: '300px',
        opacity: '1'
      }, 2000, function() {
        $(".img3").fadeOut(700);
        $(".img3").css({
          display: 'none',
          bottom: '',
          opacity: '0'
        })
        $(".img4").css({
          display: ''
        });
        $(".img4").animate({
          top: '300px',
          opacity: '1'
        }, 2000, function() {
          $(".img4").fadeOut(700);
          $(".img4").css({
            display: 'none',
            top: '',
            opacity: '0'
          });
          // call `fn` again here
          fn()
        });
      });
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bckgrnd {
  width: 100vw;
  height: 100vh;
  position: relative;
}</code>```

Hi how are you

```

Body:
I was learning JQuery on my own and yesterday night I stumbled upon a doubt and am stuck since then.
simple: I need the animation to repeat on loop. but it is not working, can you please help me out? I have tried setInterval, it is not working.
The fiddle is: https://jsfiddle.net/8v5feL9u/

            $(document).ready(function(){

//window.setInterval(function(){

            $(".img1").css({display:''});
            $(".img1").animate({bottom: '300px', opacity: '1'}, 2000, function(){
                $(".img1").fadeOut(700);
                $(".img1").css({display:'none', bottom: '', opacity:'0'});
                $(".img2").css({display:''});
                $(".img2").animate({top: '300px', opacity: '1'}, 2000, function(){
                    $(".img2").fadeOut(700);
                    $(".img2").css({display:'none', top: '', opacity:'0'});
                    $(".img3").css({display:''});
                    $(".img3").animate({bottom: '300px', opacity: '1'}, 2000, function(){
                        $(".img3").fadeOut(700);
                        $(".img3").css({display:'none', bottom: '', opacity:'0'})
                        $(".img4").css({display:''});
                        $(".img4").animate({top: '300px', opacity: '1'}, 2000, function(){
                            $(".img4").fadeOut(700);
                            $(".img4").css({display:'none', top: '', opacity:'0'});

                        });
                    });
                });
            });

//});

        });

thank you so much.

Body:
Without re-writing entire piece, you can provide a name for and call the function passed to .ready() within last nested .animate() callback function

$(function fn() {
  $(".img1").css({
    display: ''
  });
  $(".img1").animate({
    bottom: '300px',
    opacity: '1'
  }, 2000, function() {
    $(".img1").fadeOut(700);
    $(".img1").css({
      display: 'none',
      bottom: '',
      opacity: '0'
    });
    $(".img2").css({
      display: ''
    });
    $(".img2").animate({
      top: '300px',
      opacity: '1'
    }, 2000, function() {
      $(".img2").fadeOut(700);
      $(".img2").css({
        display: 'none',
        top: '',
        opacity: '0'
      });
      $(".img3").css({
        display: ''
      });
      $(".img3").animate({
        bottom: '300px',
        opacity: '1'
      }, 2000, function() {
        $(".img3").fadeOut(700);
        $(".img3").css({
          display: 'none',
          bottom: '',
          opacity: '0'
        })
        $(".img4").css({
          display: ''
        });
        $(".img4").animate({
          top: '300px',
          opacity: '1'
        }, 2000, function() {
          $(".img4").fadeOut(700);
          $(".img4").css({
            display: 'none',
            top: '',
            opacity: '0'
          });
          // call `fn` again here
          fn()
        });
      });
    });
  });
});

.bckgrnd {
  width: 100vw;
  height: 100vh;
  position: relative;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- this is the end of the head tag-->

<!--this is the start of the body tag-->

<body>
  <div class="bckgrnd w3-center w3-grey" style="position:absolute; z-index:-1">
    <img src="https://s1.postimg.org/a51sj109n/image1.jpg" class="w3-image img1" style="width:100vw; height:148vh; margin-bottom: -48vh; position: fixed; left: 0px; opacity: 0;">
    <img src="https://s1.postimg.org/57o7xwyaj/image2.jpg" class="w3-image img2" style="width:100vw; height:148vh; margin-top: -48vh; left: 0px; display:none; position:fixed; opacity: 0">
    <img src="https://s1.postimg.org/k4woyxbiz/image3.jpg" class="w3-image img3" style="width:100vw; height:148vh; margin-bottom: -48vh; left:0px; position:fixed; display:none; opacity: 0">
    <img src="https://s1.postimg.org/a8vlza5qz/image4.jpg" class="w3-image img4" style="width:100vw; height:148vh; margin-top: -48vh; left:0px; display:none;  position: fixed; opacity: 0">
  </div>
  <div class="w3-container w3-black w3-center" style="z-index:1000 !important">
    <h1>Hi how are you</h1>
  </div>


问:
get a list of the shortest path from one node to another on neo4j?
I need to find the short way between two nodes, getting a list of all the relations (with the properties) of the path.

If I have something like this:

```<code>MERGE (p1:Person{name: 'jim'})
MERGE (p2:Person{name: 'rob'})
MERGE (p3:Person{name: 'tom'})
MERGE (p4:Person{name: 'bob'})

MERGE (p1)-[:FRIEND{age: '20'}]->(p2)
MERGE (p2)-[:NO_FRIEND{age: '35'}]->(p3)
MERGE (p3)-[:FRIEND{age: '20'}]->(p4)
MERGE (p2)-[:FOO{age: '40'}]->(p4)
</code>```

Assuming that I need to go from p1 to p4, the resulting list should be a list with:  FRIEND{age: '20'} and FOO{age: '40'}

If I need to go from p1 to p3, the result should be FRIEND{age: '20'} and NO_FRIEND{age: '35'}

So I have this two requirements, the short way, and the list with relationships. How can I do it?

答:
It sounds like you just need to use the shortestPath function and return the resulting path (which will give you the nodes and relationships along the path, along with their properties). For example, to get the shortest path from your p1 to p4 nodes:

```<code>MATCH path=shortestPath((p1:Person {name: 'jim'})-[*]-(p4:Person {name: 'bob'}))
RETURN path;
</code>```

You can use allShortestPaths function if you want to find all paths that have the same shortest path length.

Body:
I need to find the short way between two nodes, getting a list of all the relations (with the properties) of the path.

If I have something like this:

MERGE (p1:Person{name: 'jim'})
MERGE (p2:Person{name: 'rob'})
MERGE (p3:Person{name: 'tom'})
MERGE (p4:Person{name: 'bob'})

MERGE (p1)-[:FRIEND{age: '20'}]->(p2)
MERGE (p2)-[:NO_FRIEND{age: '35'}]->(p3)
MERGE (p3)-[:FRIEND{age: '20'}]->(p4)
MERGE (p2)-[:FOO{age: '40'}]->(p4)

Assuming that I need to go from p1 to p4, the resulting list should be a list with:  FRIEND{age: '20'} and FOO{age: '40'}

If I need to go from p1 to p3, the result should be FRIEND{age: '20'} and NO_FRIEND{age: '35'}

So I have this two requirements, the short way, and the list with relationships. How can I do it?

Body:
It sounds like you just need to use the shortestPath function and return the resulting path (which will give you the nodes and relationships along the path, along with their properties). For example, to get the shortest path from your p1 to p4 nodes:

MATCH path=shortestPath((p1:Person {name: 'jim'})-[*]-(p4:Person {name: 'bob'}))
RETURN path;

You can use allShortestPaths function if you want to find all paths that have the same shortest path length.


问:
Join to a table only when column value is true
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

```<code>select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'
</code>```

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

答:
Perhaps I have misunderstood your question, but here's my guess.

I think you can use a case in the WHERE.

```<code>select * from T1
join T2 on T1.value = T2.value
where T2.value2 = case T1.useT2 when 'yes' then 'variable2' else T2.value2 END
and T2.value3 = case T1.useT2 when 'yes' then 'variable3' else T2.value3 END
</code>```

OwnerDisplayName: Arni Gunnar Ragnarsson

Body:
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

Body:
Perhaps I have misunderstood your question, but here's my guess.

I think you can use a case in the WHERE.

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = case T1.useT2 when 'yes' then 'variable2' else T2.value2 END
and T2.value3 = case T1.useT2 when 'yes' then 'variable3' else T2.value3 END

OwnerDisplayName: Sam


问:
inputting decimals in ipad calc with objective c
I'm a complete novice to objective C/ipad development, but I am trying to build a simple four function calculator on the iPad.

My problem is trying to display a number with a decimal in it: i.e. 5.273 or .0021

My entire calculator is float, but when doing

```<code>[resultfield setText: NSString stringWithFormat:@"%lf", display]]
</code>```

the output (say the one button was pressed) would be: 1.00000. I know that if you change the format to @".0lf" all the extra zeroes will disappear and the output would be 1

However, that doesn't help me when doing trying to input a decimal number, or when doing division. If I divide 10/3 the result would be displayed as 3 rather than 3.333333333

Any ideas on how to keep my numbers as float but not display trailing zeroes?

答: Check out the NSNumberFormatter class. It will let you set rounding and truncation of your decimals.</p>

Body:
I'm a complete novice to objective C/ipad development, but I am trying to build a simple four function calculator on the iPad.

My problem is trying to display a number with a decimal in it: i.e. 5.273 or .0021

My entire calculator is float, but when doing

[resultfield setText: NSString stringWithFormat:@"%lf", display]]

the output (say the one button was pressed) would be: 1.00000. I know that if you change the format to @".0lf" all the extra zeroes will disappear and the output would be 1

However, that doesn't help me when doing trying to input a decimal number, or when doing division. If I divide 10/3 the result would be displayed as 3 rather than 3.333333333

Any ideas on how to keep my numbers as float but not display trailing zeroes?


问:
What is the right choice between canvas and svg for circular daily planner
I am a pretty new programmer (wannabe programmer technically) and I would like to ask you guys a question about graphic tools in html5 for my project.
I plan to make a planner app by using electron and the planner form should be round. this is the planner I am talking about. And I want to add event handlers for each circular sector to add new or edit existing lists.
So My question is, Which is the proper method between canvas and svg in this case? What I mean is, which method is easy to implement (or needs shorter codes) and which one has faster rendering speed and better performance?</p>

答: You should start with SVG if you're a beginner. Rendering will be easier and so will event management. Don't worry too much about performance, they'll both do the trick for you.</p>


答:
You can wrap your animation in a function and then call that function recursively in the last "animation complete" callback on the most nested part of the animation.

function doAnimation() {
  $('.animate')
  .hide()
  .fadeIn(1000, function() {
    $(this).fadeOut(1000, function() {
      // recursively call our function in the inner-most animation callback
      doAnimation();
    });
  })
}

// start out initial loop
doAnimation();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.animate {
  padding: 30px;

  background: cornflowerblue;
}</code>```

animate me
```

Title: Looping or repeatedly running a bunch of JQuery functions

Body:
You can wrap your animation in a function and then call that function recursively in the last "animation complete" callback on the most nested part of the animation.

function doAnimation() {
  $('.animate')
  .hide()
  .fadeIn(1000, function() {
    $(this).fadeOut(1000, function() {
      // recursively call our function in the inner-most animation callback
      doAnimation();
    });
  })
}

// start out initial loop
doAnimation();

.animate {
  padding: 30px;

  background: cornflowerblue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animate">animate me</div>


问:
Add an additional label control to an <ItemTemplate> dynamically in certain cases
How can I add an extra label control dynamically (should be added only on certain conditions).
I am trying to do something like this:

```<code> <asp:DataGrid id="dg" runat="server" AutoGenerateColumns="false">
 <Columns>
    <asp:TemplateColumn SortExpression="Column1">
        <HeaderTemplate>
         <asp:LinkButton Runat="server" text="Column1 Hdr" ID="col1Hdr">
         </asp:LinkButton>
        </HeaderTemplate>
      <ItemTemplate>
        <asp:Label ID="col1Label" runat="server" Text='<%# Method1(DataBinder.Eval(Container.DataItem, "Column1").ToString(), DataBinder.Eval(Container.DataItem, "Column2").ToString())  %>' >
           <asp:PlaceHolder ID="col2Holder" runat="server"></asp:PlaceHolder>
       </asp:Label>
      </ItemTemplate>
   </asp:TemplateColumn>
 </Columns>
</asp:DataGrid>
</code>```

Alternatively, I tried putting the placeholder in a seperate template:

```<code> <EditItemTemplate>
        <asp:PlaceHolder ID="col2Holder" runat="server"></asp:PlaceHolder>
  </EditItemTemplate>
</code>```

but to no avail.
Any tips on  how I can create the Placeholder only in some cases (like for some values of Column1/Column2), rather than opt for a repeater approach...
I get a null reference exception but that was solved when I had to explicitly mention:

```<code>protected PlaceHolder col2Holder = new Placeholder();
</code>```

instead of

```<code>protected PlaceHolder col2Holder;
</code>```

But though method1 is able to set the 'Column1's text value correctly, it does nothing for the Column2's value...
Is there something I'm missing or is there a different way to do this?

Here's method1's defn:

```<code>public string Method1(string col1, string col2)
{
    col1 += "Called method1";
     Label col2label= new Label();

     col2label.Visible = true;
     col2label.Text = col2;

     col2Holder.Controls.Add(col2label);
     col2Holder.DataBind();

return col1;
</code>```

}

答:
Where and when do you need the extra control to be inserted?

You should most likely hookup a method to the OnItemDataBound event and in there decide whether to add a control or not. The event gives you a reference to the item being bound so you can say e.Item.Controls.Add(your_control)

Update

Ah, now i get it what you're asking for. You need to add another argument to your Method1 that takes a DataGridItem. When you call Method1 you add it like this Method1(Container) where Container refers to the DataGridItem in question. Then you can say in the Method1

```<code>public string Method1(DataGridItem item)
{
    string col1 = DataBinder.Eval(item.DataItem, "Column1").ToString();
    string col2 = DataBinder.Eval(item.DataItem, "Column2").ToString();

    var col2label = new Label() { Visible = true, Text = col2 };
    var col2Holder = item.FindControl("col2Holder");

    col2Holder.Controls.Add(col2label);

    return col1 + "Called method1";
}
</code>```

Btw, you can't add any controls to a Label, your ItemTemplate should look like this

```<code><ItemTemplate>
   <asp:Label ID="col1Label" runat="server" Text="<%# Method1(Container) %>" />
   <asp:PlaceHolder ID="col2Holder" runat="server" />
</ItemTemplate>
</code>```

If you want the new Label to be nested inside the first label, you should do that explicit in the method, and leave out the placeholder:

```<code><ItemTemplate>
   <asp:Label ID="label" runat="server" Text="<%# Method1(Container) %>" />
</ItemTemplate>

public string Method1(DataGridItem item)
{
    string col1 = DataBinder.Eval(item.DataItem, "Column1").ToString();
    string col2 = DataBinder.Eval(item.DataItem, "Column2").ToString();

    var label = item.FindControl("label");
    var col2label = new Label() { Visible = true, Text = col2 };

    col1Holder.Controls.Add(col2label);

    return col1 + "Called method1";
}
</code>```

Body:
How can I add an extra label control dynamically (should be added only on certain conditions).
I am trying to do something like this:

 <asp:DataGrid id="dg" runat="server" AutoGenerateColumns="false">
 <Columns>
    <asp:TemplateColumn SortExpression="Column1">
        <HeaderTemplate>
         <asp:LinkButton Runat="server" text="Column1 Hdr" ID="col1Hdr">
         </asp:LinkButton>
        </HeaderTemplate>
      <ItemTemplate>
        <asp:Label ID="col1Label" runat="server" Text='<%# Method1(DataBinder.Eval(Container.DataItem, "Column1").ToString(), DataBinder.Eval(Container.DataItem, "Column2").ToString())  %>' >
           <asp:PlaceHolder ID="col2Holder" runat="server"></asp:PlaceHolder>
       </asp:Label>
      </ItemTemplate>
   </asp:TemplateColumn>
 </Columns>
</asp:DataGrid>

Alternatively, I tried putting the placeholder in a seperate template:

 <EditItemTemplate>
        <asp:PlaceHolder ID="col2Holder" runat="server"></asp:PlaceHolder>
  </EditItemTemplate>

but to no avail.
Any tips on  how I can create the Placeholder only in some cases (like for some values of Column1/Column2), rather than opt for a repeater approach...
I get a null reference exception but that was solved when I had to explicitly mention:

protected PlaceHolder col2Holder = new Placeholder();

instead of

protected PlaceHolder col2Holder;

But though method1 is able to set the 'Column1's text value correctly, it does nothing for the Column2's value...
Is there something I'm missing or is there a different way to do this?

Here's method1's defn:

public string Method1(string col1, string col2)
{
    col1 += "Called method1";
     Label col2label= new Label();

     col2label.Visible = true;
     col2label.Text = col2;

     col2Holder.Controls.Add(col2label);
     col2Holder.DataBind();

return col1;

}

Body:
Where and when do you need the extra control to be inserted?

You should most likely hookup a method to the OnItemDataBound event and in there decide whether to add a control or not. The event gives you a reference to the item being bound so you can say e.Item.Controls.Add(your_control)

Update

Ah, now i get it what you're asking for. You need to add another argument to your Method1 that takes a DataGridItem. When you call Method1 you add it like this Method1(Container) where Container refers to the DataGridItem in question. Then you can say in the Method1

public string Method1(DataGridItem item)
{
    string col1 = DataBinder.Eval(item.DataItem, "Column1").ToString();
    string col2 = DataBinder.Eval(item.DataItem, "Column2").ToString();

    var col2label = new Label() { Visible = true, Text = col2 };
    var col2Holder = item.FindControl("col2Holder");

    col2Holder.Controls.Add(col2label);

    return col1 + "Called method1";
}

Btw, you can't add any controls to a Label, your ItemTemplate should look like this

<ItemTemplate>
   <asp:Label ID="col1Label" runat="server" Text="<%# Method1(Container) %>" />
   <asp:PlaceHolder ID="col2Holder" runat="server" />
</ItemTemplate>

If you want the new Label to be nested inside the first label, you should do that explicit in the method, and leave out the placeholder:

<ItemTemplate>
   <asp:Label ID="label" runat="server" Text="<%# Method1(Container) %>" />
</ItemTemplate>

public string Method1(DataGridItem item)
{
    string col1 = DataBinder.Eval(item.DataItem, "Column1").ToString();
    string col2 = DataBinder.Eval(item.DataItem, "Column2").ToString();

    var label = item.FindControl("label");
    var col2label = new Label() { Visible = true, Text = col2 };

    col1Holder.Controls.Add(col2label);

    return col1 + "Called method1";
}


问:
Scipy Import Error; cannot import name NUMPY_MKL
I used python xy recently with an old lib of scipy (0.15). Because I wanted to use Spherical Voronoi, I had to install a more recent version of scipy. For this I used pip and the unofficial distributions for python modules with wheel. The install worked without error messages. But now, if I try to import scipy by code, I get this error message below. I already unistalled whole python packages so far and instead installed anaconda. But the error message is still the same. I checked my registry (Windows 10) - can't find anything suspicious.

Any idea? Thank you!

```<code>test.py
1.12.1
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    import scipy
  File "C:\Users\Boss\AppData\Roaming\Python\Python27\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name NUMPY_MKL
</code>```

答: Your scipy is built with mkl support and requires mkl support in numpy too. Download numpy from the same site you downloaded scipy (probably Christoph Gohlke's builds). Or if you are using Anaconda use Anaconda packages for both.</p>

Body:
I used python xy recently with an old lib of scipy (0.15). Because I wanted to use Spherical Voronoi, I had to install a more recent version of scipy. For this I used pip and the unofficial distributions for python modules with wheel. The install worked without error messages. But now, if I try to import scipy by code, I get this error message below. I already unistalled whole python packages so far and instead installed anaconda. But the error message is still the same. I checked my registry (Windows 10) - can't find anything suspicious.

Any idea? Thank you!

test.py
1.12.1
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    import scipy
  File "C:\Users\Boss\AppData\Roaming\Python\Python27\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name NUMPY_MKL


问:
Import python module in package adjacent to sibling directory of program
Given the following python project structure:

example_dir

alpha.py

beta.py

chi/__init__.py

chi/delta.py

epsilon/__init__.py

epsilon/fudge.py

Where alpha.py contains:

```<code>from beta import beta_var
print(beta_var)

from chi.delta import delta_var
print(delta_var)

from epsilon.fudge import fudge_var
print(fudge_var)
</code>```

beta.py contains:

```<code>from chi.delta import delta_func

beta_var = delta_func()
</code>```

chi.py contains:

```<code>delta_var = 42

def delta_func():
    return 69
</code>```

And fudge.py contains:

```<code>from chi.delta import delta_func

fudge_var = delta_func()
</code>```

I can run alpha.py directly as expected.

I can run beta.py too.

But when I run fudge.py, whether via python epsilon/fudge.py or cd epsilon && python fudge.py, Python displays the error:

ImportError: No module named chi.delta

How can I run fudge.py directly, and successfully access delta_func defined in delta.py, while still being able to run alpha.py? Ideally, I'd like to invoke python fudge.py from within the epsilon subdirectory.

I thought I understood the fundamentals of Python modules and packages, but perhaps I do not, as this seems to be far more difficult than it needs to be!

答:
You can run it directly like this:

```<code>python -m epsilon.fudge
</code>```

...provided your current working directory is example_dir. (Unfortunately, I don't know of any way to run the script inside of the epsilon directory.)

Simple Explanation: In short, this will force Python to run your script as part of a package.

This allows you to do:

```<code>from chi.delta import delta_func
</code>```

in your fudge.py, even though delta.py is in the separate chi directory. It works because (in this case) doing python -m runs your script as a part of a package, which contains all of the directories in example_dir.

Body:
Given the following python project structure:

example_dir

alpha.py

beta.py

chi/__init__.py

chi/delta.py

epsilon/__init__.py

epsilon/fudge.py

Where alpha.py contains:

from beta import beta_var
print(beta_var)

from chi.delta import delta_var
print(delta_var)

from epsilon.fudge import fudge_var
print(fudge_var)

beta.py contains:

from chi.delta import delta_func

beta_var = delta_func()

chi.py contains:

delta_var = 42

def delta_func():
    return 69

And fudge.py contains:

from chi.delta import delta_func

fudge_var = delta_func()

I can run alpha.py directly as expected.

I can run beta.py too.

But when I run fudge.py, whether via python epsilon/fudge.py or cd epsilon && python fudge.py, Python displays the error:

ImportError: No module named chi.delta

How can I run fudge.py directly, and successfully access delta_func defined in delta.py, while still being able to run alpha.py? Ideally, I'd like to invoke python fudge.py from within the epsilon subdirectory.

I thought I understood the fundamentals of Python modules and packages, but perhaps I do not, as this seems to be far more difficult than it needs to be!

Body:
You can run it directly like this:

python -m epsilon.fudge

...provided your current working directory is example_dir. (Unfortunately, I don't know of any way to run the script inside of the epsilon directory.)

Simple Explanation: In short, this will force Python to run your script as part of a package.

This allows you to do:

from chi.delta import delta_func

in your fudge.py, even though delta.py is in the separate chi directory. It works because (in this case) doing python -m runs your script as a part of a package, which contains all of the directories in example_dir.