问:
NetLogo: Adding and removing items from a list
Every time an agent gets a new value for some action they're performing, I want them to add it to the end of a list. If the list has ten or more items on it, I want them to remove the first item on the list, so that the list has the ten most recent values an agent has seen, in order. How might I do that? (Edit: forgot to ask an actual question.)

I want to be able to apply mathematical operations to each item on the list, so I don't want a list of cons cell-like lists, unless there's some easy way to apply mathematical operations to each item in such a list that I don't know about.

答:
Let's build a simple example, where each turtle makes a slight right turn at a random angle at every tick, and stores the history of these angles in a list:

```<code>turtles-own [ history ]

to setup
  clear-all
  create-turtles 3 [
    set history [] ; initialize history to an empty list
  ]
  reset-ticks
end

to go
  ask turtles [
    let angle random 5
    right angle
    ; add the angle of the most recent turn
    ; at the end of the list
    set history lput angle history
    if length history > 10 [
      ; remove the first item from the list
      set history but-first history
    ]
    forward 0.1
  ]
  tick
end
</code>```

I don't want a list of cons cell-like lists, unless there's some easy way to apply mathematical operations to each item in such a list that I don't know about.

I don't know what you mean by "a list of cons cell-like lists", but a simple list like the one we built here is by far the best thing you can use if you want to do math.

To apply an operation to each item, use map. And then you can use functions like sum or mean to operate on the whole list. For example:

```<code>to do-math
  ask turtles [
    let doubled-history map [ a -> a * 2 ] history
    show history
    show doubled-history
    show mean doubled-history
  ]
end
</code>```

(Note that this uses NetLogo 6.0.1 syntax.)

Let's see a demonstration:

```<code>observer> setup repeat 5 [ go ] do-math
(turtle 2): [4 3 2 1 2]
(turtle 2): [8 6 4 2 4]
(turtle 2): 4.8
(turtle 1): [4 0 1 1 4]
(turtle 1): [8 0 2 2 8]
(turtle 1): 4
(turtle 0): [2 0 4 1 0]
(turtle 0): [4 0 8 2 0]
(turtle 0): 2.8
</code>```

Body:
Let's build a simple example, where each turtle makes a slight right turn at a random angle at every tick, and stores the history of these angles in a list:

turtles-own [ history ]

to setup
  clear-all
  create-turtles 3 [
    set history [] ; initialize history to an empty list
  ]
  reset-ticks
end

to go
  ask turtles [
    let angle random 5
    right angle
    ; add the angle of the most recent turn
    ; at the end of the list
    set history lput angle history
    if length history > 10 [
      ; remove the first item from the list
      set history but-first history
    ]
    forward 0.1
  ]
  tick
end

I don't want a list of cons cell-like lists, unless there's some easy way to apply mathematical operations to each item in such a list that I don't know about.

I don't know what you mean by "a list of cons cell-like lists", but a simple list like the one we built here is by far the best thing you can use if you want to do math.

To apply an operation to each item, use map. And then you can use functions like sum or mean to operate on the whole list. For example:

to do-math
  ask turtles [
    let doubled-history map [ a -> a * 2 ] history
    show history
    show doubled-history
    show mean doubled-history
  ]
end

(Note that this uses NetLogo 6.0.1 syntax.)

Let's see a demonstration:

observer> setup repeat 5 [ go ] do-math
(turtle 2): [4 3 2 1 2]
(turtle 2): [8 6 4 2 4]
(turtle 2): 4.8
(turtle 1): [4 0 1 1 4]
(turtle 1): [8 0 2 2 8]
(turtle 1): 4
(turtle 0): [2 0 4 1 0]
(turtle 0): [4 0 8 2 0]
(turtle 0): 2.8


来源: stackexchange

问:
how can I show news one by one horizontally?
code:

```<code><?php
   $query = "select * from latest_news limit 0,10";
   $fet = mysqli_query($link,$query);
   while ($fetch = mysqli_fetch_array($fet))
    {
      $news_title = $fetch['news_title'];
    }
?>
</code>```

html code:

```<code><marquee onmouseover="this.stop();" onmouseout="this.start();">
    <h3 id="news-h3"><?php echo $news_title; ?></h3>
</marquee>
</code>```

I am diplaying news_title using marquee but here only one data are showing. I want to display all news_title one by one. So, how can I do this.

Thank You

答:
Try rewriting your code so your query results is displayed within your marque. For example, using your code:

```<code><marquee onmouseover="this.stop();" onmouseout="this.start();">
    <?php
        $query = "select * from latest_news limit 0,10";
        $fet = mysqli_query($link,$query);
            while ($fetch = mysqli_fetch_array($fet)) {
                echo '<h3 id="news-h3">'.$fetch['news_title'].'</h3>';
            }
    ?>
</marquee>
</code>```

Hope this works for you!

ContentLicense: CC BY-SA 3.0

Body:
code:

<?php
   $query = "select * from latest_news limit 0,10";
   $fet = mysqli_query($link,$query);
   while ($fetch = mysqli_fetch_array($fet))
    {
      $news_title = $fetch['news_title'];
    }
?>

html code:

<marquee onmouseover="this.stop();" onmouseout="this.start();">

<?php echo $news_title; ?>

</marquee>

I am diplaying news_title using marquee but here only one data are showing. I want to display all news_title one by one. So, how can I do this.

Thank You

Body:
Try rewriting your code so your query results is displayed within your marque. For example, using your code:

<marquee onmouseover="this.stop();" onmouseout="this.start();">
    <?php
        $query = "select * from latest_news limit 0,10";
        $fet = mysqli_query($link,$query);
            while ($fetch = mysqli_fetch_array($fet)) {
                echo '<h3 id="news-h3">'.$fetch['news_title'].'</h3>';
            }
    ?>
</marquee>

Hope this works for you!


问:
NEON increasing run time
I am currently trying to optimize some of my image processing code to use NEON instructions.

Let's say I have to very large float arrays and I want to multiply each value of the first one with three consecutive values of the second one. (The second one is three times as large.)

```<code>float*     l_ptrGauss_pf32   = [...];
float*     l_ptrLaplace_pf32 = [...]; // Three times as large

for (uint64_t k = 0; k < l_numPixels_ui64; ++k)
{
    float l_weight_f32 = *l_ptrGauss_pf32;

    *l_ptrLaplace_pf32 *= l_weight_f32;
    ++l_ptrLaplace_pf32;
    *l_ptrLaplace_pf32 *= l_weight_f32;
    ++l_ptrLaplace_pf32;
    *l_ptrLaplace_pf32 *= l_weight_f32;
    ++l_ptrLaplace_pf32;

    ++l_ptrGauss_pf32;
}
</code>```

So when I replace the above code with NEON intrinsics, the run time is about 10% longer.

```<code>float32x4_t l_gaussElem_f32x4;
float32x4_t l_laplElem1_f32x4;
float32x4_t l_laplElem2_f32x4;
float32x4_t l_laplElem3_f32x4;

for( uint64_t k=0; k<(l_lastPixelInBlock_ui64/4); ++k)
{
    l_gaussElem_f32x4 = vld1q_f32(l_ptrGauss_pf32);
    l_laplElem1_f32x4 = vld1q_f32(l_ptrLaplace_pf32);
    l_laplElem2_f32x4 = vld1q_f32(l_ptrLaplace_pf32+4);
    l_laplElem3_f32x4 = vld1q_f32(l_ptrLaplace_pf32+8);

    l_laplElem1_f32x4 = vmulq_f32(l_gaussElem_f32x4, l_laplElem1_f32x4);
    l_laplElem2_f32x4 = vmulq_f32(l_gaussElem_f32x4, l_laplElem2_f32x4);
    l_laplElem3_f32x4 = vmulq_f32(l_gaussElem_f32x4, l_laplElem3_f32x4);

    vst1q_f32(l_ptrLaplace_pf32,   l_laplElem1_f32x4);
    vst1q_f32(l_ptrLaplace_pf32+4, l_laplElem2_f32x4);
    vst1q_f32(l_ptrLaplace_pf32+8, l_laplElem3_f32x4);

    l_ptrLaplace_pf32 += 12;
    l_ptrGauss_pf32   += 4;
}
</code>```

Both versions are compiled with -Ofast using Apple LLVM 8.0. Is the compiler really so good at optimizing this code even without NEON intrinsics?

答:
You code contains relatively many operations of vector loading and a few operations of multiplication. So I would recommend to optimize loading of vectors. There are two steps:

Use aligned memory in your arrays.

Use prefetch.

In order to do this I would recommend to use next function:

```<code>inline float32x4_t Load(const float * p)
{
    // use prefetch:
    __builtin_prefetch(p + 256);
    // tell compiler that address is aligned:
    float * _p = (float *)__builtin_assume_aligned(p, 16);
    return vld1q_f32(_p);
}
</code>```

Title: NEON increasing run time

Body:
I am currently trying to optimize some of my image processing code to use NEON instructions.

Let's say I have to very large float arrays and I want to multiply each value of the first one with three consecutive values of the second one. (The second one is three times as large.)

float*     l_ptrGauss_pf32   = [...];
float*     l_ptrLaplace_pf32 = [...]; // Three times as large

for (uint64_t k = 0; k < l_numPixels_ui64; ++k)
{
    float l_weight_f32 = *l_ptrGauss_pf32;

    *l_ptrLaplace_pf32 *= l_weight_f32;
    ++l_ptrLaplace_pf32;
    *l_ptrLaplace_pf32 *= l_weight_f32;
    ++l_ptrLaplace_pf32;
    *l_ptrLaplace_pf32 *= l_weight_f32;
    ++l_ptrLaplace_pf32;

    ++l_ptrGauss_pf32;
}

So when I replace the above code with NEON intrinsics, the run time is about 10% longer.

float32x4_t l_gaussElem_f32x4;
float32x4_t l_laplElem1_f32x4;
float32x4_t l_laplElem2_f32x4;
float32x4_t l_laplElem3_f32x4;

for( uint64_t k=0; k<(l_lastPixelInBlock_ui64/4); ++k)
{
    l_gaussElem_f32x4 = vld1q_f32(l_ptrGauss_pf32);
    l_laplElem1_f32x4 = vld1q_f32(l_ptrLaplace_pf32);
    l_laplElem2_f32x4 = vld1q_f32(l_ptrLaplace_pf32+4);
    l_laplElem3_f32x4 = vld1q_f32(l_ptrLaplace_pf32+8);

    l_laplElem1_f32x4 = vmulq_f32(l_gaussElem_f32x4, l_laplElem1_f32x4);
    l_laplElem2_f32x4 = vmulq_f32(l_gaussElem_f32x4, l_laplElem2_f32x4);
    l_laplElem3_f32x4 = vmulq_f32(l_gaussElem_f32x4, l_laplElem3_f32x4);

    vst1q_f32(l_ptrLaplace_pf32,   l_laplElem1_f32x4);
    vst1q_f32(l_ptrLaplace_pf32+4, l_laplElem2_f32x4);
    vst1q_f32(l_ptrLaplace_pf32+8, l_laplElem3_f32x4);

    l_ptrLaplace_pf32 += 12;
    l_ptrGauss_pf32   += 4;
}

Both versions are compiled with -Ofast using Apple LLVM 8.0. Is the compiler really so good at optimizing this code even without NEON intrinsics?

Body:
You code contains relatively many operations of vector loading and a few operations of multiplication. So I would recommend to optimize loading of vectors. There are two steps:

Use aligned memory in your arrays.

Use prefetch.

In order to do this I would recommend to use next function:

inline float32x4_t Load(const float * p)
{
    // use prefetch:
    __builtin_prefetch(p + 256);
    // tell compiler that address is aligned:
    float * _p = (float *)__builtin_assume_aligned(p, 16);
    return vld1q_f32(_p);
}


问:
converting unicode to datetime in python 2.7
This should be an easy one but I am new to using datetime ...

I want to convert the following unicode to any usable datetime format:
u'Tuesday, March 28, 2017'

So I have:

```<code>>> from datetime import datetime
>> test = u'Tuesday, March 28, 2017'
>> date_time = datetime.strptime(test, '????')
</code>```

I have tried a bunch of combinations for '????' but I keep getting an error saying that the format does not match.  I am looking for one working example of '????' to get the unicode date into datetime type and then I can mess with the format to get it that way I want it in datetime.

答:
If you have trouble figuring out what datetime.strptime() specifications work for your date, break down the date into components. It is much easier to puzzle out a single specification per component.

So for your date, start perhaps with the March 28 component (just Tuesday is very ambiguous, nor is it very unique to a date):

```<code>>>> from datetime import datetime
>>> datetime.strptime('March 28', '%B %d')  # Full month and numeric day
datetime.datetime(1900, 3, 28, 0, 0)
>>> datetime.strptime('March 28, ', '%B %d, ')  # add in the comma and space
datetime.datetime(1900, 3, 28, 0, 0)
>>> datetime.strptime('March 28, 2017', '%B %d, %Y')  # add in the year
datetime.datetime(2017, 3, 28, 0, 0)
>>> datetime.strptime(', March 28, 2017', ', %B %d, %Y')  # another comma and space
datetime.datetime(2017, 3, 28, 0, 0)
>>> datetime.strptime('Tuesday, March 28, 2017', '%A, %B %d, %Y')  # Full weekday name
datetime.datetime(2017, 3, 28, 0, 0)
</code>```

So '%A, %B %d, %Y' matches the string you tried to parse.

Body:
This should be an easy one but I am new to using datetime ...

I want to convert the following unicode to any usable datetime format:
u'Tuesday, March 28, 2017'

So I have:

>> from datetime import datetime
>> test = u'Tuesday, March 28, 2017'
>> date_time = datetime.strptime(test, '????')

I have tried a bunch of combinations for '????' but I keep getting an error saying that the format does not match.  I am looking for one working example of '????' to get the unicode date into datetime type and then I can mess with the format to get it that way I want it in datetime.

Body:
If you have trouble figuring out what datetime.strptime() specifications work for your date, break down the date into components. It is much easier to puzzle out a single specification per component.

So for your date, start perhaps with the March 28 component (just Tuesday is very ambiguous, nor is it very unique to a date):

>>> from datetime import datetime
>>> datetime.strptime('March 28', '%B %d')  # Full month and numeric day
datetime.datetime(1900, 3, 28, 0, 0)
>>> datetime.strptime('March 28, ', '%B %d, ')  # add in the comma and space
datetime.datetime(1900, 3, 28, 0, 0)
>>> datetime.strptime('March 28, 2017', '%B %d, %Y')  # add in the year
datetime.datetime(2017, 3, 28, 0, 0)
>>> datetime.strptime(', March 28, 2017', ', %B %d, %Y')  # another comma and space
datetime.datetime(2017, 3, 28, 0, 0)
>>> datetime.strptime('Tuesday, March 28, 2017', '%A, %B %d, %Y')  # Full weekday name
datetime.datetime(2017, 3, 28, 0, 0)

So '%A, %B %d, %Y' matches the string you tried to parse.


问:
load content of pdf in Webview
I want to display the content of a pdf file in a WebView.

The problem:
When I start the WebView a new dialog is opening, whether I want load the pdf in Browser or in the pdf Viewer. But I want to load the content directly in the WebView. I tried it also with a prefix url to embed the content, but then it shows: no preview available.

My Code:

```<code>public class Changelog_View extends ActionBarActivity {

@Override
protected void onCreate ( Bundle savedInstanceState ) {

    super.onCreate(savedInstanceState);

    String myPdfUrl = "https://onedrive.live.com/download?cid=DB700463EBEC6BC9&resid=DB700463EBEC6BC9%2120693&authkey=ALJ-NvyQqMdACpA&em=2";
    String url = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;

    WebView webview = new WebView(this);

    webview.getSettings().setJavaScriptEnabled(true);
    webview.loadUrl(url);

    setContentView(webview);
}
}
</code>```

I tried it now with the android-pdfView library with this code:

```<code> @Override
protected void onCreate ( Bundle savedInstanceState ) {

    super.onCreate ( savedInstanceState );

   com.joanzapata.pdfview.PDFView pdfView = new com.joanzapata.pdfview.PDFView ( getApplicationContext (), null );
    String myPdfUrl = "https://onedrive.live.com/download?cid=DB700463EBEC6BC9&resid=DB700463EBEC6BC9%2120693&authkey=ALJ-NvyQqMdACpA&em=2";

    pdfView.fromAsset(myPdfUrl)
            .defaultPage(1)
            .showMinimap(false)
            .enableSwipe(true)
            .onLoad(this)
            .onPageChange ( new OnPageChangeListener () {
                @Override
                public void onPageChanged ( int i, int i1 ) {

                }
            } )
            .load();
</code>```

But then a FileNotFoundExceptionappears at adress: https://onedrive.live.com/download?cid=DB700463EBEC6BC9&resid=DB700463EBEC6BC9%2120693&authkey=ALJ-NvyQqMdACpA&em=2. The adress refers directly to a pdf file from my onedrive account. So when I type in this link into a browser, the pdf file is downloading.

So how to display the pdf file from the adress: https://onedrive.live.com/download?cid=DB700463EBEC6BC9&resid=DB700463EBEC6BC9%2120693&authkey=ALJ-NvyQqMdACpA&em=2 with the android-pdfView library in my application?

Thanks.

答:
To open pdf in Webview , it better to show pdf via google doc service

```<code>WebView webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + REPLACE_WITH_YOUR_LINK);
</code>```

Title: load content of pdf in Webview

Body:
I want to display the content of a pdf file in a WebView.

The problem:
When I start the WebView a new dialog is opening, whether I want load the pdf in Browser or in the pdf Viewer. But I want to load the content directly in the WebView. I tried it also with a prefix url to embed the content, but then it shows: no preview available.

My Code:

public class Changelog_View extends ActionBarActivity {

@Override
protected void onCreate ( Bundle savedInstanceState ) {

    super.onCreate(savedInstanceState);

    String myPdfUrl = "https://onedrive.live.com/download?cid=DB700463EBEC6BC9&resid=DB700463EBEC6BC9%2120693&authkey=ALJ-NvyQqMdACpA&em=2";
    String url = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;

    WebView webview = new WebView(this);

    webview.getSettings().setJavaScriptEnabled(true);
    webview.loadUrl(url);

    setContentView(webview);
}
}

I tried it now with the android-pdfView library with this code:

 @Override
protected void onCreate ( Bundle savedInstanceState ) {

    super.onCreate ( savedInstanceState );

   com.joanzapata.pdfview.PDFView pdfView = new com.joanzapata.pdfview.PDFView ( getApplicationContext (), null );
    String myPdfUrl = "https://onedrive.live.com/download?cid=DB700463EBEC6BC9&resid=DB700463EBEC6BC9%2120693&authkey=ALJ-NvyQqMdACpA&em=2";

    pdfView.fromAsset(myPdfUrl)
            .defaultPage(1)
            .showMinimap(false)
            .enableSwipe(true)
            .onLoad(this)
            .onPageChange ( new OnPageChangeListener () {
                @Override
                public void onPageChanged ( int i, int i1 ) {

                }
            } )
            .load();

But then a FileNotFoundExceptionappears at adress: https://onedrive.live.com/download?cid=DB700463EBEC6BC9&resid=DB700463EBEC6BC9%2120693&authkey=ALJ-NvyQqMdACpA&em=2. The adress refers directly to a pdf file from my onedrive account. So when I type in this link into a browser, the pdf file is downloading.

So how to display the pdf file from the adress: https://onedrive.live.com/download?cid=DB700463EBEC6BC9&resid=DB700463EBEC6BC9%2120693&authkey=ALJ-NvyQqMdACpA&em=2 with the android-pdfView library in my application?

Thanks.

Body:
To open pdf in Webview , it better to show pdf via google doc service

WebView webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + REPLACE_WITH_YOUR_LINK);


问:
iOS Loading Custom Annotations
I've built an app that displays facilities and users on the map. Both, facility and users are custom annotations (I've extended MKPointAnnotation). I've also enabled callouts, left and right callout accessory views for both the types of annotations. The geo and other meta data for these objects are loaded from my Parse database in background. I have seen a recommendation in many places that says you should load all the annotations in viewDidLoad(). While that seems reasonable, I am wondering if that's the right approach where I want to quickly load and display what's in user's current region.

My current approach is this: load a set of annotations in viewDidLoad()based on user's current location. In my regionDidChange method for the MapView delegate, I perform search, remove all annotations and add them again. This largely works but occasionally I get facility's accessory views assigned to user's annotation. I've checked everything several times it seems to be related to timing and happens when user pans the map while annotations are being added/displayed. It doesn't happen in the debugger. I suspect that's to do with I'm reloading the annotations when user changes his/her region.

I would like to get some feedback on if I'm fundamentally loading the annotations incorrectly and how should I model it to dynamically load/display annotation as user moves the location, or pans on the map. I've seen Redfin loading properties as user pans the map, though I don't know if they have multiple types of custom annotations.

Thank you for all the help!

Rajesh

答:
step 1: Create class like below </p>

```<code>  class custumAnnotation : MKPointAnnotation
    {
        var imgName : String?

    }
</code>```

<p>step 2 : go to your Viewcontroller.swift and write code as a following </p>

```<code>import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController,MKMapViewDelegate {

    @IBOutlet var mapView : MKMapView!
    var CLManager = CLLocationManager()
    var flag : Int = 0
     var tag : Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()

        CLManager.requestWhenInUseAuthorization()
        mapView.mapType = .hybridFlyover
        mapView.showsUserLocation = true

        let center = CLLocationCoordinate2D(latitude: 18.4575
            , longitude: 73.8677)

        let center1 = CLLocationCoordinate2D(latitude: 18.5597
            , longitude: 73.7799)
        let point1 = custumAnnotation()
        point1.coordinate = center
        point1.imgName = "1.png"
        point1.title = "First"
        point1.subtitle = "Subtitle1"

        let point2  = custumAnnotation()
        point2.coordinate = center1
        point2.imgName = "2.png"
        point2.title = "Second"
        point2.subtitle = "Subtitle2"

        mapView.addAnnotation(point1)
        mapView.addAnnotation(point2)
        mapView.delegate = self
    }

    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {

        if(flag == 0)
        {
            flag=1
            let userLocation  = userLocation.location?.coordinate

            let center = CLLocationCoordinate2D(latitude: (userLocation?.latitude)!
                , longitude: (userLocation?.longitude)!)

            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

            mapView.setRegion(region, animated: true)
            mapView.showsUserLocation = false

            let annotation = MKPointAnnotation()
            annotation.coordinate = center
            annotation.title = "ME"
            annotation.subtitle = "CD"
            mapView.addAnnotation(annotation)
        }
    }

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

        if !(annotation is custumAnnotation) {
            return nil
        }

        let reuseId = "test"

        var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
        if anView == nil
        {
            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView?.canShowCallout = true
        }
        else
        {
            anView?.annotation = annotation

        }

        let cpa = annotation as! custumAnnotation
        anView?.image = UIImage(named:cpa.imgName!)
        anView?.tag = tag
        tag = tag + 1
        return anView
    }
    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

        print(view.tag)

    }
}
</code>```

Title: iOS Loading Custom Annotations

Body:
step 1: Create class like below

  class custumAnnotation : MKPointAnnotation
    {
        var imgName : String?

    }

step 2 : go to your Viewcontroller.swift and write code as a following

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController,MKMapViewDelegate {

    @IBOutlet var mapView : MKMapView!
    var CLManager = CLLocationManager()
    var flag : Int = 0
     var tag : Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()

        CLManager.requestWhenInUseAuthorization()
        mapView.mapType = .hybridFlyover
        mapView.showsUserLocation = true

        let center = CLLocationCoordinate2D(latitude: 18.4575
            , longitude: 73.8677)

        let center1 = CLLocationCoordinate2D(latitude: 18.5597
            , longitude: 73.7799)
        let point1 = custumAnnotation()
        point1.coordinate = center
        point1.imgName = "1.png"
        point1.title = "First"
        point1.subtitle = "Subtitle1"

        let point2  = custumAnnotation()
        point2.coordinate = center1
        point2.imgName = "2.png"
        point2.title = "Second"
        point2.subtitle = "Subtitle2"

        mapView.addAnnotation(point1)
        mapView.addAnnotation(point2)
        mapView.delegate = self
    }

    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {

        if(flag == 0)
        {
            flag=1
            let userLocation  = userLocation.location?.coordinate

            let center = CLLocationCoordinate2D(latitude: (userLocation?.latitude)!
                , longitude: (userLocation?.longitude)!)

            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

            mapView.setRegion(region, animated: true)
            mapView.showsUserLocation = false

            let annotation = MKPointAnnotation()
            annotation.coordinate = center
            annotation.title = "ME"
            annotation.subtitle = "CD"
            mapView.addAnnotation(annotation)
        }
    }

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

        if !(annotation is custumAnnotation) {
            return nil
        }

        let reuseId = "test"

        var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
        if anView == nil
        {
            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView?.canShowCallout = true
        }
        else
        {
            anView?.annotation = annotation

        }

        let cpa = annotation as! custumAnnotation
        anView?.image = UIImage(named:cpa.imgName!)
        anView?.tag = tag
        tag = tag + 1
        return anView
    }
    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

        print(view.tag)

    }
}


问:
XtraReport not showing any data
I have followed the instructions from this documentation link.
The xtrareport shows the box toolbar but it doesnot shows any data. What am I doing wrong?

In my HomeController.cs

```<code> public ActionResult Index()
        {
            ViewBag.Message = "Welcome to DevExpress Extensions for ASP.NET MVC!";
            ViewData["Report"] = new DXApplication.Reports.XtraReport1();

            return View();
        }

       public ActionResult DocumentViewerPartial()
       {
        ViewData["Report"] = new DXApplication.Reports.XtraReport1();
        return PartialView("DocumentViewerPartial");
        }

        public ActionResult ExportDocumentViewer()
        {
            return DevExpress.Web.Mvc.DocumentViewerExtension.ExportTo(new DXApplication.Reports.XtraReport1());
        }
</code>```

DocumentViewerPartial.cs

```<code>**@Html.DevExpress().DocumentViewer(settings =>
{
    settings.Name = "DocumentViewer";
    settings.Report = (DXApplication.Reports.XtraReport1)ViewData["Reports"];

    settings.CallbackRouteValues = new { Controller = "Home", Action = "DocumentViewerPartial" };
    settings.ExportRouteValues = new { Controller = "Home", Action = "ExportDocumentViewer" };
}).GetHtml()**
</code>```

And Index.cshtml

```<code>{
    ViewBag.Title = "Home Page";

}
@ViewBag.Message

@Html.Action("DocumentViewerPartial")
</code>```

答:
In XtraReport1 how do you write? it would be great if you provide your code XtraReport1 or provide us with a simple demonstrating with case.
I saw in your Controller, if you write that, it will get data 3rd:
ViewData["Report"] = new DXApplication.Reports.XtraReport1();

The first in Index ()

The second in DocumentViewerPartial()

The third in ExportDocumentViewer()

Ready you only need get data 1st, you can write:

```<code>public ActionResult Index()
    {
        ViewBag.Message = "Welcome to DevExpress Extensions for ASP.NET MVC!";
        return View();
    }

   public ActionResult DocumentViewerPartial()
   {
    Session["Report"] = new DXApplication.Reports.XtraReport1();
    return PartialView("DocumentViewerPartial");
    }

    public ActionResult ExportDocumentViewer()
    {
        return DevExpress.Web.Mvc.DocumentViewerExtension.ExportTo(Session["Report"] as XtraReport1());
    }
</code>```

And in DocumentViewerPartial.cs you edit:

```<code>@Html.DevExpress().DocumentViewer(settings =>{
settings.Name = "DocumentViewer";
settings.Report = (DXApplication.Reports.XtraReport1)Session["Reports"];

settings.CallbackRouteValues = new { Controller = "Home", Action = "DocumentViewerPartial" };
settings.ExportRouteValues = new { Controller = "Home", Action = "ExportDocumentViewer" };}).GetHtml()
</code>```

Then final in file Index.cshtml you call:

```<code>@Html.Partial("ExportDocumentViewer")
@Html.Partial("DocumentViewerPartial")
</code>```

Please perform the corresponding modifications and let me know your results.

Title: XtraReport not showing any data

Body:
I have followed the instructions from this documentation link.
The xtrareport shows the box toolbar but it doesnot shows any data. What am I doing wrong?

In my HomeController.cs

 public ActionResult Index()
        {
            ViewBag.Message = "Welcome to DevExpress Extensions for ASP.NET MVC!";
            ViewData["Report"] = new DXApplication.Reports.XtraReport1();

            return View();
        }

       public ActionResult DocumentViewerPartial()
       {
        ViewData["Report"] = new DXApplication.Reports.XtraReport1();
        return PartialView("DocumentViewerPartial");
        }

        public ActionResult ExportDocumentViewer()
        {
            return DevExpress.Web.Mvc.DocumentViewerExtension.ExportTo(new DXApplication.Reports.XtraReport1());
        }

DocumentViewerPartial.cs

**@Html.DevExpress().DocumentViewer(settings =>
{
    settings.Name = "DocumentViewer";
    settings.Report = (DXApplication.Reports.XtraReport1)ViewData["Reports"];

    settings.CallbackRouteValues = new { Controller = "Home", Action = "DocumentViewerPartial" };
    settings.ExportRouteValues = new { Controller = "Home", Action = "ExportDocumentViewer" };
}).GetHtml()**

And Index.cshtml

{
    ViewBag.Title = "Home Page";

}
@ViewBag.Message

@Html.Action("DocumentViewerPartial")

Body:
In XtraReport1 how do you write? it would be great if you provide your code XtraReport1 or provide us with a simple demonstrating with case.
I saw in your Controller, if you write that, it will get data 3rd:
ViewData["Report"] = new DXApplication.Reports.XtraReport1();

The first in Index ()

The second in DocumentViewerPartial()

The third in ExportDocumentViewer()

Ready you only need get data 1st, you can write:

public ActionResult Index()
    {
        ViewBag.Message = "Welcome to DevExpress Extensions for ASP.NET MVC!";
        return View();
    }

   public ActionResult DocumentViewerPartial()
   {
    Session["Report"] = new DXApplication.Reports.XtraReport1();
    return PartialView("DocumentViewerPartial");
    }

    public ActionResult ExportDocumentViewer()
    {
        return DevExpress.Web.Mvc.DocumentViewerExtension.ExportTo(Session["Report"] as XtraReport1());
    }

And in DocumentViewerPartial.cs you edit:

@Html.DevExpress().DocumentViewer(settings =>{
settings.Name = "DocumentViewer";
settings.Report = (DXApplication.Reports.XtraReport1)Session["Reports"];

settings.CallbackRouteValues = new { Controller = "Home", Action = "DocumentViewerPartial" };
settings.ExportRouteValues = new { Controller = "Home", Action = "ExportDocumentViewer" };}).GetHtml()

Then final in file Index.cshtml you call:

@Html.Partial("ExportDocumentViewer")
@Html.Partial("DocumentViewerPartial")

Please perform the corresponding modifications and let me know your results.


问:
Regular Expressions for file name matching
In Bash, how does one match a regular expression with multiple criteria against a file name?
For example, I'd like to match against all the files with .txt or .log endings.

I know how to match one type of criteria:

```<code>for file in *.log
do
        echo "${file}"
done
</code>```

What's the syntax for a logical or to match two or more types of criteria?

答:
You can also do this:

```<code>shopt -s extglob
for file in *.+(log|txt)
</code>```

which could be easily extended to more alternatives:

```<code>for file in *.+(log|txt|mp3|gif|foo)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In Bash, how does one match a regular expression with multiple criteria against a file name?
For example, I'd like to match against all the files with .txt or .log endings.

I know how to match one type of criteria:

for file in *.log
do
        echo "${file}"
done

What's the syntax for a logical or to match two or more types of criteria?

Body:
You can also do this:

shopt -s extglob
for file in *.+(log|txt)

which could be easily extended to more alternatives:

for file in *.+(log|txt|mp3|gif|foo)


问:
Enable local network access to sites on WAMP Server
I have Windows 10 64 bit,  WampServer Version 3.0.6 64bit,  Apache/2.4.23 (Win64),  PHP/5.6.25.

I have downloaded a fresh version of it today so it is the latest version.

I am trying to make my sites available on the local network.

I have created a virtual host for my site and i am able to access my site properly on my pc (where the server is also located).
I have tried all below solutions but none of them works

Here is my Httpd.conf

```<code>Require all granted
    Order Allow,Deny
    Allow from all
</Directory>
</code>```

Here is my Httpd-vhosts.conf

```<code><VirtualHost *:80>
    ServerName testsite
    DocumentRoot "c:/wamp64/www/simple-php-website-master"
    <Directory  "c:/wamp64/www/simple-php-website-master/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
</code>```

I have put my server online by enabling the options by Right click Wampmanager -> WAMPSetting -> Menu Item: Online/Offline

Both antivirus and windows firewall is turned off. I am running it as administrator. Also reinstalling didn't work.

I am using pc ip address to access the site and i have tried all below formats but none of them worked

192.168.0.36/testsite/index.php

192.168.0.36/testsite/

192.168.0.36/

Already looked into following solutions.

why wamp server put online/ offline option is missing?

How to enable local network users to access my WAMP sites?

Cannot access wamp server on local network

How to enable local network users to access my WAMP sites?

I am using this simple site to test. it doesn't have any database or anything.

I am getting below error when I try to access the site from mobile or any other pc

```<code>Forbidden

You don't have permission to access /testsite on this server.

Apache/2.4.23 (Win64) PHP/5.6.25 Server at 192.168.0.36 Port 80
</code>```

答:
You need to edit the hosts file in every computer on lan you want access from.

path C:\Windows\System32\drivers\etc\hosts

I recommend using Notepad++ in administrator mode

you will need to add something like this
192.168.0.16    testsite.dev
where the Ip is the local ip address of the computer that is the server
and yes, i would recommend to add a ".dev" to your virtual host, after you modify your virtual host remember to restart the services.

Body:
I have Windows 10 64 bit,  WampServer Version 3.0.6 64bit,  Apache/2.4.23 (Win64),  PHP/5.6.25.

I have downloaded a fresh version of it today so it is the latest version.

I am trying to make my sites available on the local network.

I have created a virtual host for my site and i am able to access my site properly on my pc (where the server is also located).
I have tried all below solutions but none of them works

Here is my Httpd.conf

Require all granted
    Order Allow,Deny
    Allow from all
</Directory>

Here is my Httpd-vhosts.conf

<VirtualHost *:80>
    ServerName testsite
    DocumentRoot "c:/wamp64/www/simple-php-website-master"
    <Directory  "c:/wamp64/www/simple-php-website-master/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

I have put my server online by enabling the options by Right click Wampmanager -> WAMPSetting -> Menu Item: Online/Offline

Both antivirus and windows firewall is turned off. I am running it as administrator. Also reinstalling didn't work.

I am using pc ip address to access the site and i have tried all below formats but none of them worked

192.168.0.36/testsite/index.php

192.168.0.36/testsite/

192.168.0.36/

Already looked into following solutions.

why wamp server put online/ offline option is missing?

How to enable local network users to access my WAMP sites?

Cannot access wamp server on local network

How to enable local network users to access my WAMP sites?

I am using this simple site to test. it doesn't have any database or anything.

I am getting below error when I try to access the site from mobile or any other pc

Forbidden

You don't have permission to access /testsite on this server.

Apache/2.4.23 (Win64) PHP/5.6.25 Server at 192.168.0.36 Port 80


问:
if condition is not working properly it is not checking properly
I have created a function to create automatic username on the bassis of name if name already exist then username will be creted on the basis of user id but when I created a user and tested if the name is already not present into the database it is creating username alongwith user id as it shouldn't be because test name is not already in the database. here is my code</p>

```<code>// $user_id is the last inserted id
$check_username = $this->db->where('name', $name);
        $check_username = $this->db->where('id !=', $user_id);
        $check_username = $this->db->get('users');

        if($check_username >= 1) {
            $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
        } else {
            $username = strtolower(str_replace(" ", ".", $name));
        }

        $this->db->where('id', $user_id);
        $this->db->update('users', array("username" => $username));
</code>```

答:
Use $this->db->num_rows() to check whether name is already present in database or not like belw:

```<code>$this->db->where('name', $name);
$this->db->where('id !=', $user_id);
$check_username = $this->db->get('users');

if($this->db->num_rows($check_username) >= 1) {
    $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
} else {
    $username = strtolower(str_replace(" ", ".", $name));
}

$this->db->where('id', $user_id);
$this->db->update('users', array("username" => $username));
</code>```

Body:
I have created a function to create automatic username on the bassis of name if name already exist then username will be creted on the basis of user id but when I created a user and tested if the name is already not present into the database it is creating username alongwith user id as it shouldn't be because test name is not already in the database. here is my code

// $user_id is the last inserted id
$check_username = $this->db->where('name', $name);
        $check_username = $this->db->where('id !=', $user_id);
        $check_username = $this->db->get('users');

        if($check_username >= 1) {
            $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
        } else {
            $username = strtolower(str_replace(" ", ".", $name));
        }

        $this->db->where('id', $user_id);
        $this->db->update('users', array("username" => $username));

Body:
Use $this->db->num_rows() to check whether name is already present in database or not like belw:

$this->db->where('name', $name);
$this->db->where('id !=', $user_id);
$check_username = $this->db->get('users');

if($this->db->num_rows($check_username) >= 1) {
    $username = strtolower(str_replace(" ", ".", $name)) . $user_id;
} else {
    $username = strtolower(str_replace(" ", ".", $name));
}

$this->db->where('id', $user_id);
$this->db->update('users', array("username" => $username));


问:
Absolute bottom positioning not working as expected in Edge and IE
I have an icon that is absolute positioned at bottom: 50px, while this works fine in every browser, Edge and IE are the exceptions.  I understand there are a lot of problems with Microsoft's browsers and how they render differently. Here I see that the browser is treating the mid-way point of the 100vh div as the bottom. What I need help with is to position the icon in IE & Edge the same way it is in Chrome, Opera and Firefox. Thanks.

IE & Edge

Chrome, Firefox, Opera

HTML

.content1 {
  height: 100vh;
  width: 100%;
  position: relative;
  top: 0;
  z-index: 99;
}

/* this is the icon I was talking about */

.dropdown_blue1 {
  width: 25px;
  padding: 20px;
  position: absolute;
  margin: auto;
  z-index: 99;
  left: 0;
  right: 0;
  bottom: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content1"><img class="dropup_blue1" src="../assets/dropup_blue.png" alt=""><img class="dropdown_blue1" src="../assets/dropdown_blue.png" alt=""></div></code>```

答: I fixed it! Simply use margin-left: auto; and margin-right: auto; instead of margin: auto;


问:
How to change date from DD.MM.YYYY to YYYY.MM.DD in EXCEL?
Pls help me with this!
I have a sheet with some columns (some products), one of the colums is with expire date of products and the format of column is "20/3/2017 (DD.MM.YY)". I want to sort entire sheet by this column but i can't because excel make short after first number "DD".
I tried with format cells, and changed format day on custom field with "YYYY.MM.DD", but nothing happened. :(
I tried with text to columns, but some dates are changing, others won't and i don't understand why is not changing all...
I tried to export my data with computer date changed to English(South Africa) because the format date there is YYYY.MM.DD but nothing happened.
Is there a formula to help me? I tried all ideas on google, but nothing.... </p>

答:
Print Screen of my column

an example...

Body:
Print Screen of my column

an example...


问:
" where in " mysql clause
i used a mysql query where there is "where id in ("22,20,21") "
but when i get the result its like array ordered in asecending order ie  20,21,20

but i need it in the same order as i gave the clause

答:
SQL results are unordered unless given an explicit ordering; the order won't be picked up from the in clause.

Since the IDs are neither ASC nor DESC either, you'd have to ORDER BY something else; how are you determining the 22,20,21 order in the first place?

Title: " where in " mysql clause


问:
HTTP GET to generate Excel workbook, respond with Express, and then auto-download file?
I'm building my first custom NodeJS server and I'd like some guidance and advice on how to implement the following procedure:

Client sends an HTTP GET request to server with some query parameters

Query MongoDB based on query parameters (using Mongoose)

An Excel workbook is generated from the resulting MongoDB data

The file is sent to the client as an HTTP response (using Express)

Upon receiving the response, the client browser automatically starts downloading the Excel workbook file.

I'm particularly lost on parts 3-5. I'm not sure what tools I should use to generate an Excel workbook on the server with Node, which way is best to send an Excel file as an HTTP response, or how to make the client browser start downloading the received file.

Thanks!

答:
For 3. point use any package of npm like this

Js code

```<code>  /* Read Excel */
  mongoXlsx.xlsx2MongoData("./file.xlsx", model, function(err, mongoData) {
    console.log('Mongo data:', mongoData);
  });
</code>```

refer linkmongo-xlsx

For point 5 use following

```<code>    var http = require('http');
    var fs = require('fs');

    var file = fs.createWriteStream("file.jpg");
    var request = http.get("./file.xlsx", function(response) {
      response.pipe(file);
    });
</code>```

You have to keep this code under your api callback function

Body:
For 3. point use any package of npm like this

Js code

  /* Read Excel */
  mongoXlsx.xlsx2MongoData("./file.xlsx", model, function(err, mongoData) {
    console.log('Mongo data:', mongoData);
  });

refer linkmongo-xlsx

For point 5 use following

    var http = require('http');
    var fs = require('fs');

    var file = fs.createWriteStream("file.jpg");
    var request = http.get("./file.xlsx", function(response) {
      response.pipe(file);
    });

You have to keep this code under your api callback function


问:
Propublica API authenticate key with javascript
Sorry if this is a simple question, but I'm trying to send a GET request to the ProPublica API. They gave me a key, but the documentation does not say how to authenticate with this key when I try and hit the endpoints of the API. If anyone can make sense of this, I'd appreciate it!

I would like to hit this route:

```<code>GET https://api.propublica.org/congress/v1/members/{chamber}/{state}/current.json
</code>```

The documentation only mentions curl:

```<code>curl "https://api.propublica.org/congress/v1/members/senate/RI/current.json"
  -H "X-API-Key: PROPUBLICA_API_KEY"
</code>```

答:
try to used this</p>

```<code>$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         type: "GET",
         dataType: 'json',
         headers: {'X-API-Key', 'PROPUBLICA_API_KEY'}
       });
</code>```

Body:
Sorry if this is a simple question, but I'm trying to send a GET request to the ProPublica API. They gave me a key, but the documentation does not say how to authenticate with this key when I try and hit the endpoints of the API. If anyone can make sense of this, I'd appreciate it!

I would like to hit this route:

GET https://api.propublica.org/congress/v1/members/{chamber}/{state}/current.json

The documentation only mentions curl:

curl "https://api.propublica.org/congress/v1/members/senate/RI/current.json"
  -H "X-API-Key: PROPUBLICA_API_KEY"

Body:
try to used this

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         type: "GET",
         dataType: 'json',
         headers: {'X-API-Key', 'PROPUBLICA_API_KEY'}
       });


问:
How to put a border-radius on a specific corner of a button
I have a modal that looks like this

As you can see, the modal has border-radius but the buttons at the footer dont. I want to put a border-radius at the bottom left of the purple button and a border-radius at the bottom right of the gray button. Ive tried border-bottom-left-radius and border-bottom-right-radius but it didnt work. Here`s my codes

Modal:

```<code><!--Notifier Modal-->
<div id="notifier-modal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
   <div class="modal-dialog modal-md" role="document">
       <div class="modal-content">
           <div class="modal-body">
               <div class="row">
                   <div class="col-md-12">
                       <div class="confirm-purchase-label">
                           Only {{size}} out of {{totalsize}} transactions have been loaded <br>
                           <h5>The complete list of transactions will be sent to your email after the process.</h5>
                       </div>
                   </div>
               </div>
           </div>

           <div class="modal-footer g-nopadding">
               <div class="col-md-6 g-nopadding">
                   <button type="button" class="btn btn-purple btn-block col-md-6" ng-click="proceedAction();">PROCEED</button>
               </div>
               <div class="col-md-6 g-nopadding">
                   <button type="button" class="btn btn-gray btn-block col-md-6" data-dismiss="modal">CANCEL</button>
               </div>
           </div>
       </div>
   </div>
</code>```

CSS:

```<code>#notifier-modal .btn,
{
    border: none!important;
    border-radius: 0px!important;
    font-family: 'AvenirMedium';
    height: 50px!important;
}

#notifier-modal .modal-md{
    width: 500px;
}

.modal-footer {
   padding: 15px;
   text-align: right;
   border-top: 1px solid #e5e5e5;
}

.modal-content{
   background:#f0f0f0;
   box-shadow:0px 0px 30px 0px rgba(101,101,101,0.50);
   border: none;
}

.btn-gray {
   color: #797979!important;
   background:#e0e0e0!important;
   font-size:14px!important;
   border: none!important;
}

.btn-purple {
   color: #f0f0f0!important;
   background-color: #9c82cd!important;
   font-size:14px!important;
   border: none!important;
}
</code>```

答:
To put a border-radius at the bottom left of the purple button You can use below CSS

```<code>.btn-purple {
color: #f0f0f0!important;
background-color: #9c82cd!important;
font-size: 14px!important;
border: none!important;
border-radius: 0 0 0 20px; /*20px is example you can use how much radius you want*/
}
</code>```

To put a border-radius at the bottom right of the gray button. You can use below CSS

```<code>.btn-gray {
color: #797979!important;
background: #e0e0e0!important;
font-size: 14px!important;
border: none!important;
border-radius: 0 0 20px 0;
}
</code>```

Body:
I have a modal that looks like this

As you can see, the modal has border-radius but the buttons at the footer dont. I want to put a border-radius at the bottom left of the purple button and a border-radius at the bottom right of the gray button. Ive tried border-bottom-left-radius and border-bottom-right-radius but it didnt work. Here`s my codes

Modal:

                           Only {{size}} out of {{totalsize}} transactions have been loaded

The complete list of transactions will be sent to your email after the process.

                   <button type="button" class="btn btn-purple btn-block col-md-6" ng-click="proceedAction();">PROCEED</button>

                   <button type="button" class="btn btn-gray btn-block col-md-6" data-dismiss="modal">CANCEL</button>

CSS:

#notifier-modal .btn,
{
    border: none!important;
    border-radius: 0px!important;
    font-family: 'AvenirMedium';
    height: 50px!important;
}

#notifier-modal .modal-md{
    width: 500px;
}

.modal-footer {
   padding: 15px;
   text-align: right;
   border-top: 1px solid #e5e5e5;
}

.modal-content{
   background:#f0f0f0;
   box-shadow:0px 0px 30px 0px rgba(101,101,101,0.50);
   border: none;
}

.btn-gray {
   color: #797979!important;
   background:#e0e0e0!important;
   font-size:14px!important;
   border: none!important;
}

.btn-purple {
   color: #f0f0f0!important;
   background-color: #9c82cd!important;
   font-size:14px!important;
   border: none!important;
}

Body:
To put a border-radius at the bottom left of the purple button You can use below CSS

.btn-purple {
color: #f0f0f0!important;
background-color: #9c82cd!important;
font-size: 14px!important;
border: none!important;
border-radius: 0 0 0 20px; /*20px is example you can use how much radius you want*/
}

To put a border-radius at the bottom right of the gray button. You can use below CSS

.btn-gray {
color: #797979!important;
background: #e0e0e0!important;
font-size: 14px!important;
border: none!important;
border-radius: 0 0 20px 0;
}


问:
Edittext password is always showing the password
I have an EditText to enter the password and i set inputType as "textPassword". But when i run it in app or emulator the password is visible. Why it is showing password instead of dots?

```<code><EditText
 android:id="@+id/etPassword"
 android:layout_width="match_parent"
 android:inputType="textPassword"
 android:layout_height="wrap_content"
 android:hint="@string/Password"
 android:layout_marginBottom="10dp"
 android:maxLength="15"
 android:background="@drawable/ss"/>
</code>```

drawable file ss:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#ffffffff"/>
<stroke android:width="1dp" android:color="#CCCCCC" />
</code>```

Complete Layout:

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:background="#ffffffff"
        android:gravity="center_vertical" >

        <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/foodstall"
         android:layout_gravity="center"
         android:layout_marginBottom="10dp"/>

        <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:background="#ffffffff">

        <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/Username"
        android:maxLength="15"
        android:background="@drawable/ss"
        android:layout_marginBottom="10dp"/>

        <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_height="wrap_content"                                                     android:hint="@string/Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15"
        android:background="@drawable/ss"
                android:text="askdjhkashdjasdksakdkaskdhkashkdhkashdkjhakshdkjhaskhdkj"/>

        <Button
        android:id="@+id/bLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_login"
        android:background="@color/button"
        android:textColor="#ffffffff"
        android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:background="@drawable/ss"
        android:layout_marginTop="10dp">

        <TextView
        android:id="@+id/tvRegisterLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/Newuser"
        android:gravity="center"
        android:layout_weight="1"
        android:textStyle="bold"/>

        <TextView
        android:id="@+id/fpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/title_activity_forgotpass"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"/>

        </LinearLayout>

        </LinearLayout>
</code>```

答:
1) Remove android:inputType="textPassword" from your xml file and instead, in set it in java:

```<code>  EditText password = (EditText) findViewById(R.id.password_text);
  password.setTransformationMethod(new PasswordTransformationMethod());
</code>```

With this approach, the hint font looks good but as you're typing in that edit field, you don't see each character in plain text before it turns into a password dot. Also when making input in fullscreen, the dots will not appear, but the passoword in clear text.

2) Leave android:inputType="textPassword" in your xml. In Java,passwordMethod:

```<code>  EditText password = (EditText) findViewById(R.id.register_password_text);
  password.setTransformationMethod(new PasswordTransformationMethod());
</code>```

This approach gave password dots.

Body:
I have an EditText to enter the password and i set inputType as "textPassword". But when i run it in app or emulator the password is visible. Why it is showing password instead of dots?

<EditText
 android:id="@+id/etPassword"
 android:layout_width="match_parent"
 android:inputType="textPassword"
 android:layout_height="wrap_content"
 android:hint="@string/Password"
 android:layout_marginBottom="10dp"
 android:maxLength="15"
 android:background="@drawable/ss"/>

drawable file ss:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#ffffffff"/>
<stroke android:width="1dp" android:color="#CCCCCC" />

Complete Layout:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:background="#ffffffff"
        android:gravity="center_vertical" >

        <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/foodstall"
         android:layout_gravity="center"
         android:layout_marginBottom="10dp"/>

        <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:background="#ffffffff">

        <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/Username"
        android:maxLength="15"
        android:background="@drawable/ss"
        android:layout_marginBottom="10dp"/>

        <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_height="wrap_content"                                                     android:hint="@string/Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15"
        android:background="@drawable/ss"
                android:text="askdjhkashdjasdksakdkaskdhkashkdhkashdkjhakshdkjhaskhdkj"/>

        <Button
        android:id="@+id/bLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_login"
        android:background="@color/button"
        android:textColor="#ffffffff"
        android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:background="@drawable/ss"
        android:layout_marginTop="10dp">

        <TextView
        android:id="@+id/tvRegisterLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/Newuser"
        android:gravity="center"
        android:layout_weight="1"
        android:textStyle="bold"/>

        <TextView
        android:id="@+id/fpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/title_activity_forgotpass"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"/>

        </LinearLayout>

        </LinearLayout>

Body:
1) Remove android:inputType="textPassword" from your xml file and instead, in set it in java:

  EditText password = (EditText) findViewById(R.id.password_text);
  password.setTransformationMethod(new PasswordTransformationMethod());

With this approach, the hint font looks good but as you're typing in that edit field, you don't see each character in plain text before it turns into a password dot. Also when making input in fullscreen, the dots will not appear, but the passoword in clear text.

2) Leave android:inputType="textPassword" in your xml. In Java,passwordMethod:

  EditText password = (EditText) findViewById(R.id.register_password_text);
  password.setTransformationMethod(new PasswordTransformationMethod());

This approach gave password dots.


问:
Min vs max in linq.
Please help me understand why second line returns exception if  my runs are empty.
I can take maxDate even if some of my schedules haven't runs

```<code>var maxDate = schedulingList.Max(p => p.Runs.Max(x => x.StartDate));
var minDate = schedulingList.Min(s => s.Runs.Min(r => r.StartDate));
</code>```

what is the best way to get minDate ( null is posible ) ?
Great thanks in advance

答:
You can select all your dates, do a DefaultIfEmpty on it, then get the min and max.

DefaultIfEmpty method will ensure that you have at least 1 item https://msdn.microsoft.com/en-us/library/bb360179(v=vs.110).aspx

```<code>var dates = schedulingList.SelectMany(p=>p.Runs.Select(t=>t.startDate)).DefaultIfEmpty();
var maxDate = dates.Max();
var minDate = dates.Min();
</code>```

Title: Min vs max in linq.

Body:
Please help me understand why second line returns exception if  my runs are empty.
I can take maxDate even if some of my schedules haven't runs

var maxDate = schedulingList.Max(p => p.Runs.Max(x => x.StartDate));
var minDate = schedulingList.Min(s => s.Runs.Min(r => r.StartDate));

what is the best way to get minDate ( null is posible ) ?
Great thanks in advance

Body:
You can select all your dates, do a DefaultIfEmpty on it, then get the min and max.

DefaultIfEmpty method will ensure that you have at least 1 item https://msdn.microsoft.com/en-us/library/bb360179(v=vs.110).aspx

var dates = schedulingList.SelectMany(p=>p.Runs.Select(t=>t.startDate)).DefaultIfEmpty();
var maxDate = dates.Max();
var minDate = dates.Min();


答:
Please check: https://www.npmjs.com/package/excel-export

In this module introduction page, there is a very good example on how to:

Generate excel file content with excel-export.

Send excel file content to browser via Express.

Make browser download the excel file automatically via Content-Disposition

Here is the example code on the page:

```<code>var express = require('express');
var nodeExcel = require('excel-export');
var app = express();

app.get('/Excel', function(req, res){
    var conf ={};
    conf.stylesXmlFile = "styles.xml";
    conf.name = "mysheet";
    conf.cols = [{
        caption:'string',
        type:'string',
        beforeCellWrite:function(row, cellData){
             return cellData.toUpperCase();
        },
        width:28.7109375
    },{
        caption:'date',
        type:'date',
        beforeCellWrite:function(){
            var originDate = new Date(Date.UTC(1899,11,30));
            return function(row, cellData, eOpt){
                if (eOpt.rowNum%2){
                    eOpt.styleIndex = 1;
                }
                else{
                    eOpt.styleIndex = 2;
                }
                if (cellData === null){
                  eOpt.cellType = 'string';
                  return 'N/A';
                } else
                  return (cellData - originDate) / (24 * 60 * 60 * 1000);
            }
        }()
    },{
        caption:'bool',
        type:'bool'
    },{
        caption:'number',
        type:'number'
    }];
    conf.rows = [
        ['pi', new Date(Date.UTC(2013, 4, 1)), true, 3.14],
        ["e", new Date(2012, 4, 1), false, 2.7182],
        ["M&M<>'", new Date(Date.UTC(2013, 6, 9)), false, 1.61803],
        ["null date", null, true, 1.414]
    ];
    var result = nodeExcel.execute(conf);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
    res.end(result, 'binary');
});

app.listen(3000);
console.log('Listening on port 3000');
</code>```

Title: HTTP GET to generate Excel workbook, respond with Express, and then auto-download file?

Body:
I'm building my first custom NodeJS server and I'd like some guidance and advice on how to implement the following procedure:

Client sends an HTTP GET request to server with some query parameters

Query MongoDB based on query parameters (using Mongoose)

An Excel workbook is generated from the resulting MongoDB data

The file is sent to the client as an HTTP response (using Express)

Upon receiving the response, the client browser automatically starts downloading the Excel workbook file.

I'm particularly lost on parts 3-5. I'm not sure what tools I should use to generate an Excel workbook on the server with Node, which way is best to send an Excel file as an HTTP response, or how to make the client browser start downloading the received file.

Thanks!

Body:
Please check: https://www.npmjs.com/package/excel-export

In this module introduction page, there is a very good example on how to:

Generate excel file content with excel-export.

Send excel file content to browser via Express.

Make browser download the excel file automatically via Content-Disposition

Here is the example code on the page:

var express = require('express');
var nodeExcel = require('excel-export');
var app = express();

app.get('/Excel', function(req, res){
    var conf ={};
    conf.stylesXmlFile = "styles.xml";
    conf.name = "mysheet";
    conf.cols = [{
        caption:'string',
        type:'string',
        beforeCellWrite:function(row, cellData){
             return cellData.toUpperCase();
        },
        width:28.7109375
    },{
        caption:'date',
        type:'date',
        beforeCellWrite:function(){
            var originDate = new Date(Date.UTC(1899,11,30));
            return function(row, cellData, eOpt){
                if (eOpt.rowNum%2){
                    eOpt.styleIndex = 1;
                }
                else{
                    eOpt.styleIndex = 2;
                }
                if (cellData === null){
                  eOpt.cellType = 'string';
                  return 'N/A';
                } else
                  return (cellData - originDate) / (24 * 60 * 60 * 1000);
            }
        }()
    },{
        caption:'bool',
        type:'bool'
    },{
        caption:'number',
        type:'number'
    }];
    conf.rows = [
        ['pi', new Date(Date.UTC(2013, 4, 1)), true, 3.14],
        ["e", new Date(2012, 4, 1), false, 2.7182],
        ["M&M<>'", new Date(Date.UTC(2013, 6, 9)), false, 1.61803],
        ["null date", null, true, 1.414]
    ];
    var result = nodeExcel.execute(conf);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
    res.end(result, 'binary');
});

app.listen(3000);
console.log('Listening on port 3000');


问:
Is md5 value language dependent?
If I generate md5 of a file in java and javascript -Will both the values be same?
I have to generate md5 in javascript and send it to the server and the server matches it. I am getting a hash mismatch error.

Actually, I need 'base64 encoded 128-bit MD5 digest' to send to S3 using javascript.

Thanks

答: md5 is the hashing algorithm, It is language independent. as long as the input to the algorithm is same it will generate same hash

Title: Is md5 value language dependent?


问:
Symfony Form Validation: UniqueEntity - multiple fields - including one nullable field
Situation: I have an form based on an entity. This entity has two properties country and staticRank and the tuple of both these both properties should be unique... BUT: the staticRank could isn't required and due to that, it can be null. I tried solving that problem using the UniqueEntity annotation:

```<code>@UniqueEntity(fields={"country", "staticRank"})
</code>```

This isn't working like expected, because if the staticRank is null it should be a valid combination according to my definition. However, there are several tuples given with the same country and null (for the staticRank), so the constraint notes a violation.

Actual Question: Is there a way to archieve this behaviour without inheriting the "UniqueEntityValidator"?

EDIT: As far as I've experienced, the ignoreNull-property of the constraint would just allow both values to be null (or if the constraint is only set to a single field)

答:
Solved that problem by passing a service into my Type (inherited from "AbstractType") and adding a constraint option:

```<code>public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setRequired('myService');
    $resolver->setDefaults([
        // ...
        'constraints' => [
            new Callback([
                'callback' => [$this, 'checkCountryRankUniqueness']
            ])
        ]
    ]);
}
</code>```

In that constraint method, I checked whether the staticRank is null. If it isn't null, it will iterate over all objects and check whether the combination is unique.

Body:
Situation: I have an form based on an entity. This entity has two properties country and staticRank and the tuple of both these both properties should be unique... BUT: the staticRank could isn't required and due to that, it can be null. I tried solving that problem using the UniqueEntity annotation:

@UniqueEntity(fields={"country", "staticRank"})

This isn't working like expected, because if the staticRank is null it should be a valid combination according to my definition. However, there are several tuples given with the same country and null (for the staticRank), so the constraint notes a violation.

Actual Question: Is there a way to archieve this behaviour without inheriting the "UniqueEntityValidator"?

EDIT: As far as I've experienced, the ignoreNull-property of the constraint would just allow both values to be null (or if the constraint is only set to a single field)

Body:
Solved that problem by passing a service into my Type (inherited from "AbstractType") and adding a constraint option:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setRequired('myService');
    $resolver->setDefaults([
        // ...
        'constraints' => [
            new Callback([
                'callback' => [$this, 'checkCountryRankUniqueness']
            ])
        ]
    ]);
}

In that constraint method, I checked whether the staticRank is null. If it isn't null, it will iterate over all objects and check whether the combination is unique.


问:
Random port number appended to URL when browsing Web App in Azure
Whenever I browse to an Azure Web App I've published, a random port number (e.g. 44893) is appended to the URL, resulting in a Page cannot be displayed error. The web app uses HTTPS.

What causes this?

答: According to your description, I assumed that this issue comes from your web application project. Since you have located the specific page which could encounter this issue, I suggest that you could debug your project and make sure it could work as expected on your development environment. For Azure Web App, you could follow this tutorial for remoting debug. Also, you could leverage Fiddler to capture the network packages when you troubleshoot this issue. Additionally, if you could not find the cause, you could provide us with a sample project to reproduce this issue, then we could help you to locate and fix this issue.</p>


问:
Replace consecutive repeated characters with one - Column-wise operation - `pandas.DataFrame`
How do I remove repeated characters in string and just leave one of them.

e.g:-

```<code>"Bertuggggg Mete"
</code>```

to

```<code>"Bertug Mete"
</code>```

I've just read data like this:

```<code>dataFrame = pd.read_excel("C:\\Users\\Bertug\\Desktop\\example.xlsx")
</code>```

Name
0 Bertuggggg Mete

Input is read from .xlsx file. I have tried split and strip functions but they don't work seem to work as expected.

How I can solve this problem ?

答:
python code :

```<code>if __name__ == '__main__':
    s = 'Bertuggggg Mete'
    if len(s) == 0:
        print('wrong!')
        exit()
    r = s[0]
    for c in s:
        if r[len(r) - 1] != c:
            r += c
    print(r)
</code>```

java code :

```<code>public class Test {

public static void main(String[] args) {
    String s = "Bertuggggg Mete";
    StringBuffer sb = new StringBuffer();
    for (int i = 0, j = s.length(); i < j; i++) {
        if (i == 0) {
            sb.append(s.charAt(0));
        }
        if (s.charAt(i) != sb.charAt(sb.length() - 1)) {
            sb.append(s.charAt(i));
        }
    }
    System.out.println(sb);
}

}
</code>```

Body:
How do I remove repeated characters in string and just leave one of them.

e.g:-

"Bertuggggg Mete"

to

"Bertug Mete"

I've just read data like this:

dataFrame = pd.read_excel("C:\\Users\\Bertug\\Desktop\\example.xlsx")

Name
0 Bertuggggg Mete

Input is read from .xlsx file. I have tried split and strip functions but they don't work seem to work as expected.

How I can solve this problem ?

Body:
python code :

if __name__ == '__main__':
    s = 'Bertuggggg Mete'
    if len(s) == 0:
        print('wrong!')
        exit()
    r = s[0]
    for c in s:
        if r[len(r) - 1] != c:
            r += c
    print(r)

java code :

public class Test {

public static void main(String[] args) {
    String s = "Bertuggggg Mete";
    StringBuffer sb = new StringBuffer();
    for (int i = 0, j = s.length(); i < j; i++) {
        if (i == 0) {
            sb.append(s.charAt(0));
        }
        if (s.charAt(i) != sb.charAt(sb.length() - 1)) {
            sb.append(s.charAt(i));
        }
    }
    System.out.println(sb);
}

}


问:
Error Loading Excel FIle Kindly Check Worksheet Name
I am working on a C# Application and needs to get data from Excel Sheet named SMS. I tried the below code but it gives me the subjected error that is "Error Loading Excel File Kindly Check Worksheet Name".

Here is the code:

```<code>private void button3_Click_1(object sender, EventArgs e)
{

    int rows_counting, column_counting1 = 0;

    OpenFileDialog dialog = new OpenFileDialog { };

    dialog.Filter = "SMS Sending File(*.xlsx;*.xls)|*.xlsx;*.xls";

    dialog.Title = "Select Excel File For SMS";

    DialogResult dlgresult = dialog.ShowDialog();

    if (dlgresult == DialogResult.Cancel)
    {
        MessageBox.Show("You Press Cancelled :-) !!!");
    }
    else
    {
        string sms_filename = dialog.FileName;

        if (System.IO.File.Exists(sms_filename))
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", sms_filename);

                string query = String.Format("select * from [{0}$]", "SMS");

                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);

                dataSet = new DataSet();

                dataAdapter.Fill(dataSet);

                dataGridView1.DataSource = dataSet.Tables[0];

                dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

                rows_counting = dataGridView1.RowCount - 1;

                column_counting1 = dataGridView1.ColumnCount;

                if (column_counting1 < 2 || column_counting1 > 2)
                {
                    MessageBox.Show("Kindly Check Column Count in Excel Sheet !!!\r\n\nThere Should Be Only Two Columns in Sheet Like Below\r\n\nCELL NUMBER | MESSAGE", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (    dataGridView1.Columns[0].Name.ToString().ToUpper() == "CELL NUMBER" &&
                        dataGridView1.Columns[1].Name.ToString().ToUpper() == "MESSAGES")

                {
                    label25.Text = "Total SMS In Excel File " + rows_counting;
                    MessageBox.Show("Data Imported Successfully...!!!\r\n\nCheck Imported Values & SEND SMS.....!!!!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    button7.Enabled = true;
                    button4.Enabled = true;

                    Cursor.Current = Cursors.Default;
                }
                else
                {
                    MessageBox.Show("Column Names Are Not In Specified Format !!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

            }
            catch (Exception E6)
            {
                MessageBox.Show("Error Loading Excel File\r\n\nKindly Check Worksheet Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

        }
    }

}
</code>```

答:
Please confirm your worksheet name is SMS.
Also check there is no blank spaces in the worksheet name.</p>

Body:
I am working on a C# Application and needs to get data from Excel Sheet named SMS. I tried the below code but it gives me the subjected error that is "Error Loading Excel File Kindly Check Worksheet Name".

Here is the code:

private void button3_Click_1(object sender, EventArgs e)
{

    int rows_counting, column_counting1 = 0;

    OpenFileDialog dialog = new OpenFileDialog { };

    dialog.Filter = "SMS Sending File(*.xlsx;*.xls)|*.xlsx;*.xls";

    dialog.Title = "Select Excel File For SMS";

    DialogResult dlgresult = dialog.ShowDialog();

    if (dlgresult == DialogResult.Cancel)
    {
        MessageBox.Show("You Press Cancelled :-) !!!");
    }
    else
    {
        string sms_filename = dialog.FileName;

        if (System.IO.File.Exists(sms_filename))
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", sms_filename);

                string query = String.Format("select * from [{0}$]", "SMS");

                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);

                dataSet = new DataSet();

                dataAdapter.Fill(dataSet);

                dataGridView1.DataSource = dataSet.Tables[0];

                dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

                rows_counting = dataGridView1.RowCount - 1;

                column_counting1 = dataGridView1.ColumnCount;

                if (column_counting1 < 2 || column_counting1 > 2)
                {
                    MessageBox.Show("Kindly Check Column Count in Excel Sheet !!!\r\n\nThere Should Be Only Two Columns in Sheet Like Below\r\n\nCELL NUMBER | MESSAGE", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (    dataGridView1.Columns[0].Name.ToString().ToUpper() == "CELL NUMBER" &&
                        dataGridView1.Columns[1].Name.ToString().ToUpper() == "MESSAGES")

                {
                    label25.Text = "Total SMS In Excel File " + rows_counting;
                    MessageBox.Show("Data Imported Successfully...!!!\r\n\nCheck Imported Values & SEND SMS.....!!!!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    button7.Enabled = true;
                    button4.Enabled = true;

                    Cursor.Current = Cursors.Default;
                }
                else
                {
                    MessageBox.Show("Column Names Are Not In Specified Format !!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

            }
            catch (Exception E6)
            {
                MessageBox.Show("Error Loading Excel File\r\n\nKindly Check Worksheet Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

        }
    }

}


问:
File Locking (Read/Write) in ASP.NET Application
I have two ASP.NET web application. One is responsible for processing some info and writing to a log file, and the other application is reponsible for reading the log file and displays the information based on user request.

Here's my code for the Writer

```<code>public static void WriteLog(String PathToLogFile, String Message)
{
    Mutex FileLock = new Mutex(false, "LogFileMutex");
    try
    {
        FileLock.WaitOne();
        using (StreamWriter sw = File.AppendText(FilePath))
        {
            sw.WriteLine(Message);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        LogUtil.WriteToSystemLog(ex);
    }
    finally
    {
        FileLock.ReleaseMutex();
    }
}
</code>```

And here's my code for the Reader :

```<code>private String ReadLog(String PathToLogFile)
{
    FileStream fs = new FileStream(
          PathToLogFile, FileMode.Open,
          FileAccess.Read, FileShare.ReadWrite);
    StreamReader Reader = new StreamReader(fs);
    return Reader.ReadToEnd();
}
</code>```

My question, is the above code enough to prevent locking in a web garden environemnt?

EDIT 1 : Dirty read is okay.
EDIT 2 : Creating Mutex with new Mutex(false, "LogFileMutex"), closing StreamWriter

答:
Sounds like your trying to implement a basic queue. Why not use a queue that gives you guarenteed availability. You could drop the messages into an MSMQ, then implement a windows service which will read from the queue and push the messages to the DB. If the writting to the DB fails you simply leave the message on the queue (Although you will want to handle posion messages so if it fails cause the data is bad you don't end up in an infinite loop)

This will get rid of all locking concerns and give you guarenteed delivery to your reader...

Body:
I have two ASP.NET web application. One is responsible for processing some info and writing to a log file, and the other application is reponsible for reading the log file and displays the information based on user request.

Here's my code for the Writer

public static void WriteLog(String PathToLogFile, String Message)
{
    Mutex FileLock = new Mutex(false, "LogFileMutex");
    try
    {
        FileLock.WaitOne();
        using (StreamWriter sw = File.AppendText(FilePath))
        {
            sw.WriteLine(Message);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        LogUtil.WriteToSystemLog(ex);
    }
    finally
    {
        FileLock.ReleaseMutex();
    }
}

And here's my code for the Reader :

private String ReadLog(String PathToLogFile)
{
    FileStream fs = new FileStream(
          PathToLogFile, FileMode.Open,
          FileAccess.Read, FileShare.ReadWrite);
    StreamReader Reader = new StreamReader(fs);
    return Reader.ReadToEnd();
}

My question, is the above code enough to prevent locking in a web garden environemnt?

EDIT 1 : Dirty read is okay.
EDIT 2 : Creating Mutex with new Mutex(false, "LogFileMutex"), closing StreamWriter

OwnerDisplayName: Josh


问:
What is the meaning of erb?
Why is the view of Rails application in the format *.erb.html? What does "erb" mean?

答:
As @Chowlett mentioned before, erb stands for Embedded Ruby. When you define any file as ".html.erb" that means it's an HTML file with ruby code embedded in it and it is similar to ".rhtml" extension of rails file.

You can see a detailed and nice difference between ".html.erb" and ".rhtml" Click Here

Same as ".rhtml", you can also rename ".rjs" extension to ".js.erb" or ".rxml" to ".xml.erb"

This format separates out content type from template engine which is "erb" in this case.

Title: What is the meaning of erb?


问:
Combobox SelectedItem is not retrieved properly
I have saved all combobox values which are added dynmaically to a collection.
No i want to retrieve the info. When I retrieve it my combobox values are not displayed in it.

We use Telerik component here

```<code><tele:RadComboBox HorizontalAlignment="Stretch" DisplayMemberPath="content" ItemsSource="{Binding ManyValue,Mode=TwoWay}" SelectedItem="{Binding MyValue, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}">
</code>```

ManyValue is a dropdown of values which has id,content
Myvalue is  selected value what I have selected in combobox

ManyValue is a collection of viewmodel to combobox.
MyValue is a property of ViewModel i.e. selected item of comboobox.

This is happening correctly when I select, But when I retrieve the data,In collection Items are present but something wrong in Binding so that am not able to display it.

I do the save properly. But when I retrieve unable to load the already selected item in combobox.

Can anyone help?

答: Set the SelectedItem,SelectedValue and SelectedValuePath did the trick for me </p>

Body:
I have saved all combobox values which are added dynmaically to a collection.
No i want to retrieve the info. When I retrieve it my combobox values are not displayed in it.

We use Telerik component here

<tele:RadComboBox HorizontalAlignment="Stretch" DisplayMemberPath="content" ItemsSource="{Binding ManyValue,Mode=TwoWay}" SelectedItem="{Binding MyValue, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}">

ManyValue is a dropdown of values which has id,content
Myvalue is  selected value what I have selected in combobox

ManyValue is a collection of viewmodel to combobox.
MyValue is a property of ViewModel i.e. selected item of comboobox.

This is happening correctly when I select, But when I retrieve the data,In collection Items are present but something wrong in Binding so that am not able to display it.

I do the save properly. But when I retrieve unable to load the already selected item in combobox.

Can anyone help?


问:
replace underscores at end of name and numbers at beginning of name
i am still struggling with Matlab and regex.

This is what i got so far but it will just not work for me, no matter what i am trying..

set_param(blocks(i), 'Name', regexprep(get_param(blocks(i), 'Name'), '(_|[0-9])+', ''));

set_param(blocks(i), 'Name', regexprep(get_param(blocks(i), 'Name'), '_\w*', ''));

Any help is much appreciated!!

Error: You cannot set the name of '5Product' to an empty string

答:
You need to use alternation and anchors:

```<code>regexprep(str, '^[0-9]+|_+$', '')
</code>```

The ^[0-9]+|_+$ pattern will match one of the two alternatives:

^[0-9]+ - 1 or more digits ([0-9]+) at the start of the string (^)

| - or

_+$ - 1 or more _ symbols (_+) at the end of the string ($)

Body:
You need to use alternation and anchors:

regexprep(str, '^[0-9]+|_+$', '')

The ^[0-9]+|_+$ pattern will match one of the two alternatives:

^[0-9]+ - 1 or more digits ([0-9]+) at the start of the string (^)

| - or

_+$ - 1 or more _ symbols (_+) at the end of the string ($)


问:
Camunda: Configure/setup MS SQL server database for rest api
By default, camunda rest api uses H2 database.
I'm unable to locate the file where I can configure the rest api to use Microsoft SQL Server.

Apologies for not being much clear as I am new to camunda.

答:
You can find information's about configure the JDBC connections in the Camunda installation Guide.

For Example for Tomcat (you have to simply edit the driverClassName, url and the credentials).

To configure a JDBC Resource you have to edit the file
  $TOMCAT_HOME/conf/server.xml. This could look like the following
  example for an H2 database:

```<code><Server>
  ...
  <GlobalNamingResources>
    ...
    <Resource name="jdbc/ProcessEngine"
              auth="Container"
              type="javax.sql.DataSource"
              factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
              uniqueResourceName="process-engine"
              driverClassName="org.h2.Driver"
              url="jdbc:h2:./camunda-h2-dbs/process-engine;MVCC=TRUE;TRACE_LEVEL_FILE=0"
              username="sa"
              password=""
              maxActive="20"
              minIdle="5" />
  </GlobalNamingResources>
</Server>
</code>```

For JBoss or Wildfly you have to edit the standalone/configuration/standalone.xml:

Add a datasource and driver tag, which could like the following, to the datasources.

```<code><datasource jta="true" enabled="true" use-java-context="true" use-ccm="true"
                jndi-name="java:jboss/datasources/ProcessEngine"
                pool-name="ProcessEngine">
    <connection-url>jdbc:sqlserver://SERVER_NAME:SERVER_PORT;databaseName=DB_NAME</connection-url>
    <driver>sqlserver2008</driver>
    <security>
        <user-name>USERNAME</user-name>
        <password>PASSWORD</password>
    </security>
    <pool>
        <min-pool-size>5</min-pool-size>
        <max-pool-size>50</max-pool-size>
        <prefill>false</prefill>
        <use-strict-min>false</use-strict-min>
        <flush-strategy>FailingConnectionOnly</flush-strategy>
    </pool>
    <validation>
        <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mssql.MSSQLValidConnectionChecker"></valid-connection-checker>
    </validation>
</datasource>
<drivers>
    <driver name="sqlserver2008" module="com.microsoft">
        <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
    </driver>
</drivers>
</code>```

Body:
You can find information's about configure the JDBC connections in the Camunda installation Guide.

For Example for Tomcat (you have to simply edit the driverClassName, url and the credentials).

To configure a JDBC Resource you have to edit the file
  $TOMCAT_HOME/conf/server.xml. This could look like the following
  example for an H2 database:

<Server>
  ...
  <GlobalNamingResources>
    ...
    <Resource name="jdbc/ProcessEngine"
              auth="Container"
              type="javax.sql.DataSource"
              factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
              uniqueResourceName="process-engine"
              driverClassName="org.h2.Driver"
              url="jdbc:h2:./camunda-h2-dbs/process-engine;MVCC=TRUE;TRACE_LEVEL_FILE=0"
              username="sa"
              password=""
              maxActive="20"
              minIdle="5" />
  </GlobalNamingResources>
</Server>

For JBoss or Wildfly you have to edit the standalone/configuration/standalone.xml:

Add a datasource and driver tag, which could like the following, to the datasources.

<datasource jta="true" enabled="true" use-java-context="true" use-ccm="true"
                jndi-name="java:jboss/datasources/ProcessEngine"
                pool-name="ProcessEngine">
    <connection-url>jdbc:sqlserver://SERVER_NAME:SERVER_PORT;databaseName=DB_NAME</connection-url>
    <driver>sqlserver2008</driver>
    <security>
        <user-name>USERNAME</user-name>
        <password>PASSWORD</password>
    </security>
    <pool>
        <min-pool-size>5</min-pool-size>
        <max-pool-size>50</max-pool-size>
        <prefill>false</prefill>
        <use-strict-min>false</use-strict-min>
        <flush-strategy>FailingConnectionOnly</flush-strategy>
    </pool>
    <validation>
        <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mssql.MSSQLValidConnectionChecker"></valid-connection-checker>
    </validation>
</datasource>
<drivers>
    <driver name="sqlserver2008" module="com.microsoft">
        <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
    </driver>
</drivers>


问:
Instead method for Priority.DEBUG in log4j
I want to upgrade log4j 1.2 version to log4j 2.7 version with slf4j. in my code having.

```<code>if (logger.isEnabledFor(Priority.DEBUG)){
            logger.debug("Exit checkAccess()");
        }
</code>```

this function but the Priority.DEBUG method is deprecated so instead of that i am using Level.DEBUG and import "org.slf4j.event.Level"  but still it shows following error "The method isEnabledFor(Level) is undefined for the type Logger"

答:
I find the solution for this problam..

```<code>if (logger.isDebugEnabled(){
        logger.debug("Exit checkAccess()");
    }
</code>```

this is implemented method in log4j 2.7

Body:
I want to upgrade log4j 1.2 version to log4j 2.7 version with slf4j. in my code having.

if (logger.isEnabledFor(Priority.DEBUG)){
            logger.debug("Exit checkAccess()");
        }

this function but the Priority.DEBUG method is deprecated so instead of that i am using Level.DEBUG and import "org.slf4j.event.Level"  but still it shows following error "The method isEnabledFor(Level) is undefined for the type Logger"

Body:
I find the solution for this problam..

if (logger.isDebugEnabled(){
        logger.debug("Exit checkAccess()");
    }

this is implemented method in log4j 2.7


问:
explicit conversion operator vs get< T >() function for std::variant
What are the downsides to make a part of std::variant class an explicit conversion (to alternative) operator overloadings set in addition to (or even instead of) get< T >() free functions (p.568 of the draft)?

```<code>template<class... Types>
class variant
{
    template<class T>
    explicit operator const T& () const&;
    template<class T>
    explicit operator T& () &;
    template<class T>
    explicit operator const T&& () const &&;
    template<class T>
    explicit operator T&& () &&;
};
</code>```

Is it unsafe in some contexts? Why do we need free get() function (namely, "type" version, not "index" one), when variant exposes a value semantic (cite from the draft):

A variant object holds and manages the lifetime of a value.

Isn't it enough to make a variant explicitly convertible to alternative, but still implicitly constructible from an alternative?

I know, the uniformity of the interface is good thing (I remember we need get() along with get< T >()), but I think it is more natural way to get containing alternative value simply by converting to it, rather then applying some function specialization to variant instance.

答:
My main reason not to propose it was the following:

optional doesn't have it

optional has an explicit operator bool() (has_value() or not?)

variant and optional should remain as consistent as possible.

But given the right arguments this could certainly be changed in a future revision.

Body:
What are the downsides to make a part of std::variant class an explicit conversion (to alternative) operator overloadings set in addition to (or even instead of) get< T >() free functions (p.568 of the draft)?

template<class... Types>
class variant
{
    template<class T>
    explicit operator const T& () const&;
    template<class T>
    explicit operator T& () &;
    template<class T>
    explicit operator const T&& () const &&;
    template<class T>
    explicit operator T&& () &&;
};

Is it unsafe in some contexts? Why do we need free get() function (namely, "type" version, not "index" one), when variant exposes a value semantic (cite from the draft):

A variant object holds and manages the lifetime of a value.

Isn't it enough to make a variant explicitly convertible to alternative, but still implicitly constructible from an alternative?

I know, the uniformity of the interface is good thing (I remember we need get() along with get< T >()), but I think it is more natural way to get containing alternative value simply by converting to it, rather then applying some function specialization to variant instance.


问:
Avoid visible window using IEAction
I'm having difficulty to hide the new window that _IEAction($oIE_Input, "click") creates. The code:

```<code>$oIE = _IECreate("mypage")
Sleep(20000)
$oIE_Input= _IEGetObjById($oIE, "the button")
_IEAction($oIE_Input, "click")
Sleep(20000)
_IEQuit($oIE)
</code>```

When it presses the button Internet Explorer opens a new visible window. How can I avoid or hide opening new windows?

答:
Maybe you can start the whole IE session in the background. Have a look at _IECreate parameters.

Browser Window is hidden

```<code>$sUrl [optional] specifies the Url to navigate to upon creation
$iTryAttach [optional] specifies whether to try to attach to an existing window
    0 = (Default) do not try to attach
    1 = Try to attach to an existing window
$iVisible [optional] specifies whether the browser window will be visible
    0 = Browser Window is hidden
    1 = (Default) Browser Window is visible
$iWait [optional] specifies whether to wait for page to load before returning
    0 = Return immediately, not waiting for page to load
    1 = (Default) Wait for page load to complete before returning
$iTakeFocus [optional] specifies whether to bring the attached window to focus
    0 = Do not bring window into focus
    1 = (Default) bring window into focus
</code>```

Title: Avoid visible window using IEAction

Body:
I'm having difficulty to hide the new window that _IEAction($oIE_Input, "click") creates. The code:

$oIE = _IECreate("mypage")
Sleep(20000)
$oIE_Input= _IEGetObjById($oIE, "the button")
_IEAction($oIE_Input, "click")
Sleep(20000)
_IEQuit($oIE)

When it presses the button Internet Explorer opens a new visible window. How can I avoid or hide opening new windows?

Body:
Maybe you can start the whole IE session in the background. Have a look at _IECreate parameters.

Browser Window is hidden

$sUrl [optional] specifies the Url to navigate to upon creation
$iTryAttach [optional] specifies whether to try to attach to an existing window
    0 = (Default) do not try to attach
    1 = Try to attach to an existing window
$iVisible [optional] specifies whether the browser window will be visible
    0 = Browser Window is hidden
    1 = (Default) Browser Window is visible
$iWait [optional] specifies whether to wait for page to load before returning
    0 = Return immediately, not waiting for page to load
    1 = (Default) Wait for page load to complete before returning
$iTakeFocus [optional] specifies whether to bring the attached window to focus
    0 = Do not bring window into focus
    1 = (Default) bring window into focus