问:
Using NSPredicate to add enable users to 'Favourite' objects, which will then appear in a separate TableView (without CoreData!)
I currently have a tableView which is parsing and displaying data from a JSON file. When a cell is pressed, then the user is taken to a detailView screen to view further information.

I am now trying to set up a Favourite button within the detailView, so that users can press a button which will add the object to a favouriteView (this will be set up exactly the same as the tableView, but only show locations which have been favourited.

My understanding is that the best way to achieve this is to use NSPredicate. I have been looking around for hours and I can't seem to find a solution that does not use CoreData (although I have found a source which says that CoreData is not necessary). I would like to achieve the Favourite function without using CoreData.

I already have a favourite button set up in the detailView, which sets a variable isFavourite from false to true. Please see all the relevant code below.

Sample JSON object:

```<code>{
        "locations": [

            {
                "id": "0001",
                "name": "Helensburgh Tunnels",
                "type": "Tunnels, Beach, Views",
                "location": "Helensburgh, South Coast",
                "image": "Helensburgh-Tunnels.jpg",
                "activity": "Walking, photography, tunnelling",
                "isVisited": false,
                "isFavourite": false,
                "latitude": -34.178985,
                "longitude": 150.992867
            }
        ]
    }
</code>```

The favourite button I have set up in the detailView:

```<code>@IBOutlet weak var favouriteButton: UIButton!
@IBAction func favouriteButtonTapped(_ sender: Any) {
    self.location.isFavourite = self.location.isFavourite ? false : true

    print(location.isFavourite)

    // Favourite button
    if location.isFavourite == false {
        favouriteButton?.setImage(UIImage(named: "starLine.png"), for: .normal)
    } else {
        favouriteButton?.setImage(UIImage(named: "starFull.png"), for: .normal)
    }

}
</code>```

How can I take all the objects which have been set to isFavourite = true and display them in a tableView?

This is a section of the FavouriteLocationsViewController class, what do I need to fix here to make it functional?

```<code>class FavouriteLocationsViewController: UITableViewController {

    var locations = [Location]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Remove the title of the back button
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)

        if let locationJson = readLocation(){
            if let locationArray = locationJson["locations"] as? [[String:Any]]{
                for location in locationArray{
                    locations.append(Location.init(locationInfo: location))
                }
                print(locations.count)
                self.tableView.reloadData()
            }
        }

    }

    // Filter to show only favourite locations
    func filterArrayOfDictonaryWithKeyValueUsingPredicate(arrOfDict: NSArray, keyOfDict: String, strSearchText: String) -> NSArray{
    let favouritePredicate = NSPredicate(format: "isFavourite == true")
    let arrResult = arrOfDict.filtered(using: favouritePredicate)
    return arrResult as NSArray
    }
}
</code>```

答:
you want to show only favourite data there?

you have array of dictonary as per you are showing above.

you can filter that array using predicate.

and you can get only object which isFavourite == "True"

use below function pass array of Location, Pass keyofDict - isFavourite

strSearchText - for your example use true

```<code>func filterArrayOfDictonaryWithKeyValueUsingPredicate(arrOfDict: NSArray, keyOfDict: String, strSearchText: String) -> NSArray{
        let searchPredicate = NSPredicate(format: "\(keyOfDict) CONTAINS[C] %@", strSearchText)
        let arrResult = arrOfDict.filtered(using: searchPredicate)
        return arrResult as NSArray
    }
</code>```

Body:
I currently have a tableView which is parsing and displaying data from a JSON file. When a cell is pressed, then the user is taken to a detailView screen to view further information.

I am now trying to set up a Favourite button within the detailView, so that users can press a button which will add the object to a favouriteView (this will be set up exactly the same as the tableView, but only show locations which have been favourited.

My understanding is that the best way to achieve this is to use NSPredicate. I have been looking around for hours and I can't seem to find a solution that does not use CoreData (although I have found a source which says that CoreData is not necessary). I would like to achieve the Favourite function without using CoreData.

I already have a favourite button set up in the detailView, which sets a variable isFavourite from false to true. Please see all the relevant code below.

Sample JSON object:

{
        "locations": [

            {
                "id": "0001",
                "name": "Helensburgh Tunnels",
                "type": "Tunnels, Beach, Views",
                "location": "Helensburgh, South Coast",
                "image": "Helensburgh-Tunnels.jpg",
                "activity": "Walking, photography, tunnelling",
                "isVisited": false,
                "isFavourite": false,
                "latitude": -34.178985,
                "longitude": 150.992867
            }
        ]
    }

The favourite button I have set up in the detailView:

@IBOutlet weak var favouriteButton: UIButton!
@IBAction func favouriteButtonTapped(_ sender: Any) {
    self.location.isFavourite = self.location.isFavourite ? false : true

    print(location.isFavourite)

    // Favourite button
    if location.isFavourite == false {
        favouriteButton?.setImage(UIImage(named: "starLine.png"), for: .normal)
    } else {
        favouriteButton?.setImage(UIImage(named: "starFull.png"), for: .normal)
    }

}

How can I take all the objects which have been set to isFavourite = true and display them in a tableView?

This is a section of the FavouriteLocationsViewController class, what do I need to fix here to make it functional?

class FavouriteLocationsViewController: UITableViewController {

    var locations = [Location]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Remove the title of the back button
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)

        if let locationJson = readLocation(){
            if let locationArray = locationJson["locations"] as? [[String:Any]]{
                for location in locationArray{
                    locations.append(Location.init(locationInfo: location))
                }
                print(locations.count)
                self.tableView.reloadData()
            }
        }

    }

    // Filter to show only favourite locations
    func filterArrayOfDictonaryWithKeyValueUsingPredicate(arrOfDict: NSArray, keyOfDict: String, strSearchText: String) -> NSArray{
    let favouritePredicate = NSPredicate(format: "isFavourite == true")
    let arrResult = arrOfDict.filtered(using: favouritePredicate)
    return arrResult as NSArray
    }
}

Body:
you want to show only favourite data there?

you have array of dictonary as per you are showing above.

you can filter that array using predicate.

and you can get only object which isFavourite == "True"

use below function pass array of Location, Pass keyofDict - isFavourite

strSearchText - for your example use true

func filterArrayOfDictonaryWithKeyValueUsingPredicate(arrOfDict: NSArray, keyOfDict: String, strSearchText: String) -> NSArray{
        let searchPredicate = NSPredicate(format: "\(keyOfDict) CONTAINS[C] %@", strSearchText)
        let arrResult = arrOfDict.filtered(using: searchPredicate)
        return arrResult as NSArray
    }


来源: stackexchange

问:
Modular menu and vector instantiation
I would like to create a modular menu system.
This is based on a contatiner class Menu and menu entries objects provided by MenuItem class.

So my classes look like this:

```<code>class Menu
{
    public:
        void addItem(MenuItem* item);
        void removeItem(unsigned int _index);
        void clear();
        MenuItem* getCurrentItem();
        void invoke();
        void display();

    private:
        vector<MenuItem*> menu_items;
        unsigned int m_current_item;
};

class MenuItem
{
    public:
        explicit MenuItem(string data);
        void onSelect();
        void invokeCallback();
        string getData() const;

    private:
        string m_data;
};
</code>```

Now i can create multiple instances of Menu for my menus (or sub-menus).

I can cast for example:

```<code>Menu home_menu;
Menu sub_menu;
</code>```

Create MenuItems:

```<code>MenuItem First("First");           //home_menu item 1
MenuItem Second("Second");         //home_menu item 2
MenuItem First_sub("First sub");   //sub_menu item 1
</code>```

And add them to the Menu (inside menu_items vector)

```<code>home_menu.addItem(&First);
home_menu.addItem(&Second);
sub_menu.addItem(&First_sub);
</code>```

If I iterate the menu_items vector I can see all MenuItems objects (both home_menu and sub_menu).

I would like it to store only pointers to its relative menu, something like the vector menu_items is instantiated.

So the output when I cast: home_menu.display() should be: First Second
and when I cast: sub_menu.display(): First_sub

Could it be done ? What am I not considering in my implementation ?

答:
If you want your Menu to take ownership of the MenuItems, you have to allocate them on the heap like so:

```<code>Menu home_menu;
Menu sub_menu;

{
    MenuItem* First = new MenuItem("First");           //home_menu item 1
    MenuItem* Second = new MenuItem("Second");         //home_menu item 2
    MenuItem* First_Sub = new MenuItem("First sub");   //sub_menu item 1

    home_menu.addItem(First);
    home_menu.addItem(Second);
    sub_menu.addItem(First_sub);
}
</code>```

But your application will leak memory this way. Every object, that is created with new, must be deleted with delete

So you want to add a destructor to your class:

```<code>~Menu() {
    for(MenuItem* item : menu_items) {
        delete item;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Modular menu and vector instantiation

Body:
I would like to create a modular menu system.
This is based on a contatiner class Menu and menu entries objects provided by MenuItem class.

So my classes look like this:

class Menu
{
    public:
        void addItem(MenuItem* item);
        void removeItem(unsigned int _index);
        void clear();
        MenuItem* getCurrentItem();
        void invoke();
        void display();

    private:
        vector<MenuItem*> menu_items;
        unsigned int m_current_item;
};

class MenuItem
{
    public:
        explicit MenuItem(string data);
        void onSelect();
        void invokeCallback();
        string getData() const;

    private:
        string m_data;
};

Now i can create multiple instances of Menu for my menus (or sub-menus).

I can cast for example:

Menu home_menu;
Menu sub_menu;

Create MenuItems:

MenuItem First("First");           //home_menu item 1
MenuItem Second("Second");         //home_menu item 2
MenuItem First_sub("First sub");   //sub_menu item 1

And add them to the Menu (inside menu_items vector)

home_menu.addItem(&First);
home_menu.addItem(&Second);
sub_menu.addItem(&First_sub);

If I iterate the menu_items vector I can see all MenuItems objects (both home_menu and sub_menu).

I would like it to store only pointers to its relative menu, something like the vector menu_items is instantiated.

So the output when I cast: home_menu.display() should be: First Second
and when I cast: sub_menu.display(): First_sub

Could it be done ? What am I not considering in my implementation ?

Body:
If you want your Menu to take ownership of the MenuItems, you have to allocate them on the heap like so:

Menu home_menu;
Menu sub_menu;

{
    MenuItem* First = new MenuItem("First");           //home_menu item 1
    MenuItem* Second = new MenuItem("Second");         //home_menu item 2
    MenuItem* First_Sub = new MenuItem("First sub");   //sub_menu item 1

    home_menu.addItem(First);
    home_menu.addItem(Second);
    sub_menu.addItem(First_sub);
}

But your application will leak memory this way. Every object, that is created with new, must be deleted with delete

So you want to add a destructor to your class:

~Menu() {
    for(MenuItem* item : menu_items) {
        delete item;
    }
}


问:
How to delete a consul service
I've created a bunch of test services in my consul cluster I wish to remove, I have tried using the /v1/agent/service/deregister/{service id} - and ensured it runs fine on each node - I can see this run on each node

[INFO] agent: Deregistered service 'ci'

Is there another way to manually clean out these old services ?

Thanks,

答:
fetch service info curl $CONSUL_AGETNT_ADDR:8500/v1/catalog/service/$SERVICE_NAME | python -mjson.tool :

{
    "Address": "10.0.1.2",
    "CreateIndex": 30242768,
    "Datacenter": "",
    "ID": "",
    "ModifyIndex": 30550079,
    "Node": "log-0",
    "NodeMeta": null,
    "ServiceAddress": "",
    "ServiceEnableTagOverride": false,
    "ServiceID": "log",
    "ServiceName": "log",
    "ServicePort": 9200,
    "ServiceTags": [
        "log"
    ],
    "TaggedAddresses": null
},
...

prepare a json file, fulfill the values with the above outputs cat > data.json :

{
  "Datacenter": "",
  "Node": "log-0",
  "ServiceID": "log-0"
}

deregister with: curl -X PUT -d @data.json $CONSUL_AGETNT_ADDR:8500/v1/catalog/deregister

Title: How to delete a consul service


问:
Scrapy CrawlSpider doesn't scrape with callback = 'parse_page'
I'm using Scrapy's CrawlSpider to scrape product info on     https://www.walmart.com/browse/makeup/lips/1085666_1007040_1001527.
This is what my rules look like:

```<code>   rules = (Rule(LinkExtractor(
            restrict_xpaths=('//*[@id="mainSearchContent"]/div[3]/div[2]/button[2]',)
        ),
                callback = 'parse_page',
                follow =True),)
</code>```

And this is the result. It doesn't scrape anything.

```<code>017-07-05 13:32:33 [scrapy] INFO: Enabled item pipelines: ImagesPipeline
2017-07-05 13:32:33 [scrapy] INFO: Spider opened
2017-07-05 13:32:33 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-07-05 13:32:33 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6026
2017-07-05 13:32:35 [scrapy] DEBUG: Crawled (200) <GET https://www.walmart.com/browse/makeup/lips/1085666_1007040_1001527> (referer: None)
2017-07-05 13:32:35 [scrapy] INFO: Closing spider (finished)
2017-07-05 13:32:35 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 322,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 157281,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 7, 5, 10, 32, 35, 320638),
 'log_count/DEBUG': 2,
 'log_count/INFO': 7,
 'log_count/WARNING': 6,
 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 7, 5, 10, 32, 33, 900621)}
</code>```

If I change callback to parse, it only scrapes the first page.
Can anyone tell me how to scrape all pages?

答:
This does not solve your issue. but there is an easy way to fetch data from that website. just request their API

This should be a comment, but the URL is too long for a comment.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Scrapy's CrawlSpider to scrape product info on     https://www.walmart.com/browse/makeup/lips/1085666_1007040_1001527.
This is what my rules look like:

   rules = (Rule(LinkExtractor(
            restrict_xpaths=('//*[@id="mainSearchContent"]/div[3]/div[2]/button[2]',)
        ),
                callback = 'parse_page',
                follow =True),)

And this is the result. It doesn't scrape anything.

017-07-05 13:32:33 [scrapy] INFO: Enabled item pipelines: ImagesPipeline
2017-07-05 13:32:33 [scrapy] INFO: Spider opened
2017-07-05 13:32:33 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-07-05 13:32:33 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6026
2017-07-05 13:32:35 [scrapy] DEBUG: Crawled (200) <GET https://www.walmart.com/browse/makeup/lips/1085666_1007040_1001527> (referer: None)
2017-07-05 13:32:35 [scrapy] INFO: Closing spider (finished)
2017-07-05 13:32:35 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 322,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 157281,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 7, 5, 10, 32, 35, 320638),
 'log_count/DEBUG': 2,
 'log_count/INFO': 7,
 'log_count/WARNING': 6,
 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 7, 5, 10, 32, 33, 900621)}

If I change callback to parse, it only scrapes the first page.
Can anyone tell me how to scrape all pages?

Body:
This does not solve your issue. but there is an easy way to fetch data from that website. just request <a href="https://www.walmart.com/search/api/wpa?el=sponsored-container-bottom-1&type=product&min=2&max=20&creative=1145x345_B-C-OG_TI_2-20_HL-BOTTOM&placementId=1145x345_B-C-OG_TI_2-20_HL-BOTTOM&theme=large&platform=desktop&bucketId=&isSpecialBrowse=false&pageType=browse&pageId=1085666_1007040_1001527&pageNumber=1&keyword=Lips&taxonomy=1085666_1007040_1001527&vtc=bXdXxb3UiKhDx6eTotCM-E&uid=75e86169-c8ab-4178-88d8-3bd0242c5069&itemsList=24520263%2C19408713%2C26775062%2C43984097%2C52664389%2C13865594%2C189016376%2C15641929%2C27419883%2C10314309&rviItems=&itemsAddedToCart=0&viewportHeight=335&viewportWidth=1439&accessModeEnabled=true" rel="nofollow noreferrer">their API

This should be a comment, but the URL is too long for a comment.


问:
NHibernate to access Oracle stored procedure REFCURSOR and output parameter
Does the current version of NHibernate (v2.1.2) support access Oracle stored procedure output REFCURSOR in addition to an output parameter?

I can access the output refcursor fine with my code. However i'm not sure i can access the additional output param in the same stored procedure.

Some sample of calling syntax would be greatly appreciated. thanks.

答:
I found a solution to call old stored procedures with NHibernate.

I don't think that is the better way, but we normally don't have time to refactor everything, so:

```<code>using (ITransaction transaction = _session.BeginTransaction()) {
    IDbCommand command = new OracleCommand();
    command.Connection = _session.Connection;

    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "pk_package.pr_procedure";

    // Set input parameters
    var param1 = new OracleParameter("@param1", OracleDbType.Decimal) {Value = someField};
    var param2 = new OracleParameter("@param2", OracleDbType.Decimal) {Value = 1};

    command.Parameters.Add(param1);
    command.Parameters.Add(param2);

    // Execute the stored procedure
    command.ExecuteNonQuery();
    transaction.Commit();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I found a solution to call old stored procedures with NHibernate.

I don't think that is the better way, but we normally don't have time to refactor everything, so:

using (ITransaction transaction = _session.BeginTransaction()) {
    IDbCommand command = new OracleCommand();
    command.Connection = _session.Connection;

    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "pk_package.pr_procedure";

    // Set input parameters
    var param1 = new OracleParameter("@param1", OracleDbType.Decimal) {Value = someField};
    var param2 = new OracleParameter("@param2", OracleDbType.Decimal) {Value = 1};

    command.Parameters.Add(param1);
    command.Parameters.Add(param2);

    // Execute the stored procedure
    command.ExecuteNonQuery();
    transaction.Commit();
}


问:
How to enable cancel button with UISearchBar?
In the contacts app on the iPhone if you enter a search term, then tap the "Search" button, the keyboard is hidden, BUT the cancel button is still enabled.  In my app the cancel button gets disabled when I call resignFirstResponder.

Anyone know how to hide the keyboard while maintaining the cancel button in an enabled state?

I use the following code:

```<code>- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}
</code>```

The keyboard slides out of view, but the "Cancel" button to the right of the search text field is disabled, so that I cannot cancel the search.  The contacts app maintains the cancel button in an enabled state.

I think maybe one solution is to dive into the searchBar object and call resignFirstResponder on the actual text field, rather than the search bar itself.

Any input appreciated.

答:
For iOS 9/10 (tested), Swift 3 (shorter):</p>

```<code>searchBar.subviews.flatMap({$0.subviews}).forEach({ ($0 as? UIButton)?.isEnabled = true })
</code>```

Body:
In the contacts app on the iPhone if you enter a search term, then tap the "Search" button, the keyboard is hidden, BUT the cancel button is still enabled.  In my app the cancel button gets disabled when I call resignFirstResponder.

Anyone know how to hide the keyboard while maintaining the cancel button in an enabled state?

I use the following code:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

The keyboard slides out of view, but the "Cancel" button to the right of the search text field is disabled, so that I cannot cancel the search.  The contacts app maintains the cancel button in an enabled state.

I think maybe one solution is to dive into the searchBar object and call resignFirstResponder on the actual text field, rather than the search bar itself.

Any input appreciated.

Body:
For iOS 9/10 (tested), Swift 3 (shorter):

searchBar.subviews.flatMap({$0.subviews}).forEach({ ($0 as? UIButton)?.isEnabled = true })


问:
Using D-Bus for multiple machines over the internet
I'm writing a server (in C) which serves different machines. I'd like to use D-Bus for remote procedure calls through Internet, but I heard that D-Bus can't be used for many machines, but for one machine. Is that right? Can I use D-Bus for this situation?</p>

答:
Even if you don’t end up using a full D-Bus bus (like the dbus-daemon) for communication between multiple machines, an interesting half-way step is to use the D-Bus wire protocol for serialising messages, and then implementing your own bus arbiter and topology.

This means you don’t have to reinvent a wire protocol (with all the potential parser bugs and exploits that entails), but can retain some flexibility over the high-level system topology and transport; potentially integrating with a separate, existing authentication system, for example.

The easiest way to do this is to use the GDBusMessage or GVariant APIs from GLib, serialising with g_dbus_message_to_blob() or g_variant_get_data(). Do not use libdbus, as it is too low level, and uses outdated API designs which are harder to use correctly from C than more modern APIs like GLib’s. Similarly, do not use dbus-glib, as its design is also awkward and outdated.


问:
Coordinates in WPF Canvas
when defining coordinates for canvas shapes in XAML files, is it possible to do something like this:

```<code><Canvas x:Name="myCanvas"
        DockPanel.Dock="Bottom"
        VerticalAlignment="Stretch">

    <Canvas.Background>
        <SolidColorBrush Color="White" Opacity="100" />
    </Canvas.Background>

    <Ellipse x:Name="ell1"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red"
                Canvas.Left="100"
                Canvas.Top="50" />

    <Ellipse x:Name="ell2"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red"
                Canvas.Right="100"
                Canvas.Top="50" />

    <Line Stroke="Black"
            StrokeThickness="1"
            X1="ell1.Canvas.Right"                              *** look here ***
            Y1="ell1.Canvas.Top + ell1.Height/2"                *** look here ***
            X2="ell2.Canvas.Left"                               *** look here ***
            Y2="ell2.Canvas.Top + ell2.Height/2" />             *** look here ***

</Canvas>
</code>```

Or the only way of doing it is through C#?

Thanks,
Massimo

答:
You can indeed bind to an attached property like this:

```<code><Line ... X2="{Binding Path=(Canvas.Left), ElementName=ell1}" />
</code>```

But there is no + or / operators defined in XAML so you will have to write some code to be able to set the Y1 property to 50 + 30 / 2.

After all XAML is a markup language and C# is a programming language.

Title: Coordinates in WPF Canvas

Body:
when defining coordinates for canvas shapes in XAML files, is it possible to do something like this:

<Canvas x:Name="myCanvas"
        DockPanel.Dock="Bottom"
        VerticalAlignment="Stretch">

    <Canvas.Background>
        <SolidColorBrush Color="White" Opacity="100" />
    </Canvas.Background>

    <Ellipse x:Name="ell1"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red"
                Canvas.Left="100"
                Canvas.Top="50" />

    <Ellipse x:Name="ell2"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red"
                Canvas.Right="100"
                Canvas.Top="50" />

    <Line Stroke="Black"
            StrokeThickness="1"
            X1="ell1.Canvas.Right"                              *** look here ***
            Y1="ell1.Canvas.Top + ell1.Height/2"                *** look here ***
            X2="ell2.Canvas.Left"                               *** look here ***
            Y2="ell2.Canvas.Top + ell2.Height/2" />             *** look here ***

</Canvas>

Or the only way of doing it is through C#?

Thanks,
Massimo

Body:
You can indeed bind to an attached property like this:

<Line ... X2="{Binding Path=(Canvas.Left), ElementName=ell1}" />

But there is no + or / operators defined in XAML so you will have to write some code to be able to set the Y1 property to 50 + 30 / 2.

After all XAML is a markup language and C# is a programming language.


问:
SQL group by with like condition
suppose there is a SQL table: testTable with columns: clientID, colA, colB, colC.

```<code>reference   clientID    colA    colB    colC
---------------------------------------------
001            1        test1   test2   test3
002            1        test1   ball2   test3
003            2        test1   ball2   test3
004            2        test1   ball2   test3
005            3        test1   test2   test3
006            4        test1   test2   test3
007            4        test1   test2   test3
009            5        test1   ball2   test3
---------------------------------------------
</code>```

i would like to select all the distinct rows where colB is like 'test' and group by the clientID. so i end up with:

```<code>reference    clientID    colA    colB    colC
----------------------------------------------
001             1        test1   test2   test3
005             3        test1   test2   test3
006             4        test1   test2   test3
----------------------------------------------
</code>```

EDIT:
reference column is unique
if i use
select distinct * .. from .. where colB like '%test%' group by clientID
then the results returned does not have clientID grouped

答:
When you use GROUP BY you have to specify all columns that you use in the query and that don't use an aggregation function.
So, for example,</p>

```<code>SELECT CLIENTID, COLA, COLB, COLC, COUNT(*) AS RC
FROM YOURTABLE
WHERE COLB LIKE '%test%'
GROUP BY CLIENTID, COLA, COLB, COLC
</code>```

Title: SQL group by with like condition

Body:
suppose there is a SQL table: testTable with columns: clientID, colA, colB, colC.

reference   clientID    colA    colB    colC
---------------------------------------------
001            1        test1   test2   test3
002            1        test1   ball2   test3
003            2        test1   ball2   test3
004            2        test1   ball2   test3
005            3        test1   test2   test3
006            4        test1   test2   test3
007            4        test1   test2   test3
009            5        test1   ball2   test3
---------------------------------------------

i would like to select all the distinct rows where colB is like 'test' and group by the clientID. so i end up with:

reference    clientID    colA    colB    colC
----------------------------------------------
001             1        test1   test2   test3
005             3        test1   test2   test3
006             4        test1   test2   test3
----------------------------------------------

EDIT:
reference column is unique
if i use
select distinct * .. from .. where colB like '%test%' group by clientID
then the results returned does not have clientID grouped

Body:
When you use GROUP BY you have to specify all columns that you use in the query and that don't use an aggregation function.
So, for example,

SELECT CLIENTID, COLA, COLB, COLC, COUNT(*) AS RC
FROM YOURTABLE
WHERE COLB LIKE '%test%'
GROUP BY CLIENTID, COLA, COLB, COLC


问:
AES 128 with CBC In IOS
```<code>+ (NSData *)doCipher:(NSData *)dataIn
                  iv:(NSData *)iv
                 key:(NSData *)symmetricKey
             context:(CCOperation)encryptOrDecrypt // kCCEncrypt or kCCDecrypt
               error:(NSError **)error
{
    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

    ccStatus = CCCrypt( encryptOrDecrypt,
                       kCCAlgorithmAES128,
                       0, //kCCOptionPKCS7Padding,
                       symmetricKey.bytes,
                       kCCKeySizeAES128,
                       iv.bytes,
                       dataIn.bytes,
                       dataIn.length,
                       dataOut.mutableBytes,
                       dataOut.length,
                       &cryptBytes);

    if (ccStatus == kCCSuccess) {
        dataOut.length = cryptBytes;
    }
    else {
        if (error) {
            *error = [NSError errorWithDomain:@"kEncryptionError"
                                         code:ccStatus
                                     userInfo:nil];
        }
        dataOut = nil;
    }

    return dataOut;
}
</code>```

I have dataIn as 154 bytes of Data, key and Iv having 16 bytes of data when i am doing encryption it is giving -4303 error.(AES128 With CBC In IOS)

答:
Error code -4303 is kCCAlignmentError. From documentation:

When decrypting, or when encrypting with a block cipher with padding
  disabled, kCCAlignmentError will be returned if the total number of
  bytes provided to CCCryptUpdate() is not an integral multiple of the
  current algorithm's block size.

You should check if your input data size is correct.

Title: AES 128 with CBC In IOS

Body:
+ (NSData *)doCipher:(NSData *)dataIn
                  iv:(NSData *)iv
                 key:(NSData *)symmetricKey
             context:(CCOperation)encryptOrDecrypt // kCCEncrypt or kCCDecrypt
               error:(NSError **)error
{
    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

    ccStatus = CCCrypt( encryptOrDecrypt,
                       kCCAlgorithmAES128,
                       0, //kCCOptionPKCS7Padding,
                       symmetricKey.bytes,
                       kCCKeySizeAES128,
                       iv.bytes,
                       dataIn.bytes,
                       dataIn.length,
                       dataOut.mutableBytes,
                       dataOut.length,
                       &cryptBytes);

    if (ccStatus == kCCSuccess) {
        dataOut.length = cryptBytes;
    }
    else {
        if (error) {
            *error = [NSError errorWithDomain:@"kEncryptionError"
                                         code:ccStatus
                                     userInfo:nil];
        }
        dataOut = nil;
    }

    return dataOut;
}

I have dataIn as 154 bytes of Data, key and Iv having 16 bytes of data when i am doing encryption it is giving -4303 error.(AES128 With CBC In IOS)


问:
What is the simplest way to achieve O(n) performance when creating the union of 3 IEnumerables?
Say a, b, c are all List<t> and I want to create an unsorted union of them. Although performance isn't super-critical, they might have 10,000 entries in each so I'm keen to avoid O(n^2) solutions.

AFAICT the MSDN documentation doesn't say anything about the performance characteristics of union as far as the different types are concerned.

My gut instinct says that if I just do a.Union(b).Union(c), this will take O(n^2) time, but new Hashset<t>(a).Union(b).Union(c) would be O(n).

Does anyone have any documentation or metrics to confirm or deny this assumption?

答:
Union is O(n).

a.Union(b).Union(c) is less efficient in most implementations than a.Union(b.Concat(c)) because it creates a hash-set for the first union operation and then another for the second, as other answers have said. Both of these also end up with a chain of IEnumerator<T> objects in use which increases cost as further sources are added.

a.Union(b).Union(c) is more efficient in .NET Core because the second .Union() operation produces a single object with knowledge of a, b and c and it will create a single hash-set for the entire operation, as well as avoiding the chain of IEnumerator<T> objects.


问:
Having issues installing nodejs/npm
I've completely uninstalled nodejs/npm both.

However they seem to be throwing same error consistently whilst installing.
I've also tried sudo-apt get update
sudo apt cache verify and apt cache search, when I search nodejs is not found or npm.

```<code>The program 'nodejs' is currently not installed. You can install it by typing:
sudo apt-get install nodejs
</code>```

And when I do sudo apt-get intall nodejs

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Package nodejs is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'nodejs' has no installation candidate
</code>```

I've made sure nodejs/npm is removed from /usr/bin etc. Still doesn't seem to be working at all.

答:
Try

This will install node version manager (nvm) by typing the following at the command line.
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash

Then activate nvm by typing the following at the command line.
. ~/.nvm/nvm.sh

Then Use nvm to install the version of Node.js you intend to use by typing the following at the command line.
nvm install 4.4.5 (you can install 6.1.0 LTS for instance)

then test it by typing
node -e "console.log('Running Node.js ' + process.version)"

Title: Having issues installing nodejs/npm

Body:
I've completely uninstalled nodejs/npm both.

However they seem to be throwing same error consistently whilst installing.
I've also tried sudo-apt get update
sudo apt cache verify and apt cache search, when I search nodejs is not found or npm.

The program 'nodejs' is currently not installed. You can install it by typing:
sudo apt-get install nodejs

And when I do sudo apt-get intall nodejs

Reading package lists... Done
Building dependency tree
Reading state information... Done
Package nodejs is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'nodejs' has no installation candidate

I've made sure nodejs/npm is removed from /usr/bin etc. Still doesn't seem to be working at all.


问:
Find pixels with given RGB colors
I would like to get all coordinates from the pixels with a given RGB color in Python. Here is the code that I'm using but it doesn't work. I want to find all pixels with a yellow color.

```<code>from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    rgb = img.convert('RGB')
    for x in range(507):
        for y in range(337):
            r, g, b, = rgb.getpixel((x, y))
            if r >= r_query and g >= g_query and b <= b_query:
                return (x,y)
</code>```

And how can you do it that Python only gives the coordinates if there are at least three pixels with the same color? (They mustn't be the exact same color, they can be for example 156,173,87 and 155,173,87.)

答:
For speed reasons I would recommend using numpy:

```<code>import numpy as np

width = 100
height = 100
channels = 3
img = np.random.rand(width, height, channels) * 255

r=0
g=1
b=2

r_query = 240
g_query = 240
b_query = 20
print(np.where((img[:,:,r] >= r_query) & (img[:,:,g] >= g_query) & (img[:,:,b] <= b_query)))
</code>```

This gives you a 2D-Array with the coordinates of the yellow pixels in your original image.

Title: Find pixels with given RGB colors

Body:
I would like to get all coordinates from the pixels with a given RGB color in Python. Here is the code that I'm using but it doesn't work. I want to find all pixels with a yellow color.

from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    rgb = img.convert('RGB')
    for x in range(507):
        for y in range(337):
            r, g, b, = rgb.getpixel((x, y))
            if r >= r_query and g >= g_query and b <= b_query:
                return (x,y)

And how can you do it that Python only gives the coordinates if there are at least three pixels with the same color? (They mustn't be the exact same color, they can be for example 156,173,87 and 155,173,87.)

Body:
For speed reasons I would recommend using numpy:

import numpy as np

width = 100
height = 100
channels = 3
img = np.random.rand(width, height, channels) * 255

r=0
g=1
b=2

r_query = 240
g_query = 240
b_query = 20
print(np.where((img[:,:,r] >= r_query) & (img[:,:,g] >= g_query) & (img[:,:,b] <= b_query)))

This gives you a 2D-Array with the coordinates of the yellow pixels in your original image.


问:
How to find matching python data frame values with other data frame
I want to update in df1['Result'] as True or False if df1['Field1'] values exist in other dataframe df2['SersName']

Please help...

df1:

```<code>Field1          Field2  Result
2020RATIO001001 A       TRUE
2020RATIO001003 B       TRUE
2020RATIO001005 C       TRUE
2020RATIO001XYZ D       FALSE
2020RATIO001123 E       FALSE
</code>```

df2:

```<code>SersName        Field2
2020RATIO001001 1
2020RATIO001003 2
2020RATIO001005 3
2020RATIO001007 4
2020RATIO001009 5
2020RATIO001011 6
2020RATIO001013 7
2020RATIO001015 8
</code>```

I tried below script:

```<code>SeriesFileNameMap = df1['Field1'].set_index('Field1')
SeriesFileNameMap.update(df2.set_index('SersName'))
df1['Result'] = SeriesFileNameMap.values
</code>```

答:
You need to use isin

```<code>import pandas as pd

df1 = pd.read_csv(StringIO("""Field1 Field2
2020RATIO001001 A
2020RATIO001003 B
2020RATIO001005 C
2020RATIO001XYZ D
2020RATIO001123 E"""),sep=" ")

df2 = pd.read_csv(StringIO("""SersName Field2
2020RATIO001001 1
2020RATIO001003 2
2020RATIO001005 3
2020RATIO001007 4
2020RATIO001009 5
2020RATIO001011 6
2020RATIO001013 7
2020RATIO001015 8"""),sep=" ")

df1['Result'] = df1['Field1'].isin(df2['SersName'])
</code>```

The resultant df1 is:

```<code>Field1  Field2  Result
0   2020RATIO001001 A   True
1   2020RATIO001003 B   True
2   2020RATIO001005 C   True
3   2020RATIO001XYZ D   False
4   2020RATIO001123 E   False
</code>```

Body:
I want to update in df1['Result'] as True or False if df1['Field1'] values exist in other dataframe df2['SersName']

Please help...

df1:

Field1          Field2  Result
2020RATIO001001 A       TRUE
2020RATIO001003 B       TRUE
2020RATIO001005 C       TRUE
2020RATIO001XYZ D       FALSE
2020RATIO001123 E       FALSE

df2:

SersName        Field2
2020RATIO001001 1
2020RATIO001003 2
2020RATIO001005 3
2020RATIO001007 4
2020RATIO001009 5
2020RATIO001011 6
2020RATIO001013 7
2020RATIO001015 8

I tried below script:

SeriesFileNameMap = df1['Field1'].set_index('Field1')
SeriesFileNameMap.update(df2.set_index('SersName'))
df1['Result'] = SeriesFileNameMap.values

Body:
You need to use isin

import pandas as pd

df1 = pd.read_csv(StringIO("""Field1 Field2
2020RATIO001001 A
2020RATIO001003 B
2020RATIO001005 C
2020RATIO001XYZ D
2020RATIO001123 E"""),sep=" ")

df2 = pd.read_csv(StringIO("""SersName Field2
2020RATIO001001 1
2020RATIO001003 2
2020RATIO001005 3
2020RATIO001007 4
2020RATIO001009 5
2020RATIO001011 6
2020RATIO001013 7
2020RATIO001015 8"""),sep=" ")

df1['Result'] = df1['Field1'].isin(df2['SersName'])

The resultant df1 is:

Field1  Field2  Result
0   2020RATIO001001 A   True
1   2020RATIO001003 B   True
2   2020RATIO001005 C   True
3   2020RATIO001XYZ D   False
4   2020RATIO001123 E   False


问:
Error while defining map in clojure
I am new clojure and am not able to understand exact issue while running this code

```<code>(def my-map {name "Srini" empid "10000"})
</code>```

Receving this error:

CompilerException java.lang.RuntimeException: Unable to resolve symbol: empid in this context, compiling:(/Users/srini/Downloads/clojureexample/my-stugg/src/my_stugg/corecomponents.clj:95:1)

```<code>(def my-map {name "Srini" :empid "10000"})
</code>```

Running successfully.

What wrong I am doing in the first line?

```<code>(def my-map {name "Srini" empid "10000"})
</code>```

答:
You probably want to change your keys to keywords. In Clojure keywords are written with a colon in front of a string, but you don't need the quotes (as long as your keyword has no spaces in it, but let's not get complicated).

I recommend starting simply:

(def my-map {:name "george"})

This will create a map with a single key and value in it.

If you want to use let, do it like so:

(let [my-map {:name "george"}] my-map)

Update: Hm you seemed to have changed your question a fair bit! I still really recommend starting simply.

name is already defined as a function in clojure (it gets the string version of a symbol or keyword), so you shoudln't use that. Use :name if you want to create a key, unless you want to shadow the name "name" in a let binding, but that's nothing to do with keys in maps.

I feel like perhaps you need to learn the basics of maps and let before you go crazy with examples. Stick to simple things, and make sure your keys are not symbols.

Title: Error while defining map in clojure

Body:
I am new clojure and am not able to understand exact issue while running this code

(def my-map {name "Srini" empid "10000"})

Receving this error:

CompilerException java.lang.RuntimeException: Unable to resolve symbol: empid in this context, compiling:(/Users/srini/Downloads/clojureexample/my-stugg/src/my_stugg/corecomponents.clj:95:1)

(def my-map {name "Srini" :empid "10000"})

Running successfully.

What wrong I am doing in the first line?

(def my-map {name "Srini" empid "10000"})


问:
Permutations with repetition without two consecutive equal elements
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

```<code>f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything
</code>```

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

```<code>from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l
</code>```

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

```<code>def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l
</code>```

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

```<code>for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())
</code>```

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

答:
How about:</p>

```<code>from itertools import product

result = [ x for x in product(iterable,repeat=r) if all(x[i-1] != x[i] for i in range(1,len(x))) ]
</code>```

Body:
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

Body:
How about:

from itertools import product

result = [ x for x in product(iterable,repeat=r) if all(x[i-1] != x[i] for i in range(1,len(x))) ]


问:
How to use the Search Method in java mail api
I am using the javamail api to make a Search option which Searches the Emails in the Gmail Folder on the Basis of a Keyword present in the Subject of the Messages
Here is the Code that i am Using

```<code>public class EGMail7 {
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    final String m10 = "abc@gmail.com";
    final String n10 = "12345";
    string host = "smtp.gmail.com";
    try
    {
    Properties pro1 = new Properties();
    pro1.put("mail.smtp.host", "smtp.gmail.com");
    pro1.put("mail.smtp.socketFactory.port", "465");
    pro1.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    pro1.put("mail.smtp.auth", "true");
    pro1.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(pro1,
        new javax.mail.Authenticator()
{
    protected PasswordAuthentication getPasswordAuthentication()
{
        return new PasswordAuthentication(m10,n10);
        }
    });
    Store store = session.getStore("imaps");
    store.connect(host, m10, n10);
    Folder folderbox = store.getFolder("INBOX");
    folderbox.open(Folder.READ_ONLY);
    SearchTerm search = new SearchTerm(){

        @Override
        public boolean match(Message message) {
            try
            {
                if(message.getSubject().contains([Keyword]))
                {
                    return true;
                }
            }
            catch(Exception e)
            {
                System.err.println(e.getMessage());
            }
            return false;
        }

    };

    Message[] found = folderbox.search(search);

    int length = found.length;
    for(int i = 0;i<found.length;i++)
    {
        Message mess1 = found[i];
        System.out.println("->Message Number > "+i);
        System.out.println("->Message Subject >"+mess1.getSubject());
    }
    folderbox.close(true);
    store.close();
}
    catch(Exception e)
    {
        System.err.println(e.getMessage());
    }
   }
  }
</code>```

I am using the Eclipse IDE and the problem i am facing is that whatever keyword I pass in the SearchTerm Method I always end up getting null Exception and an Message[] Found Array . I used Stack Trace to find out the Problem of this NullPointer Exception and it is at the line

```<code>Message[] found = folderbox.search(search);
</code>```

I cannot Seem to understand what is the Problem Here ?

Regards,
Thank you

PS - and if someone could also please post the corrected code it would be great
Thanks

Also When i Am Just Adding the Keyword Directly in the SearchTerm it give an Error like

```<code>SearchTerm searchCon = new SearchTerm([Keyword]);
</code>```

There are 2 Errors
1.Cannot Instantiate the SearchTerm
2.The Serializable class does not Declare a static final Serial Verison UID field of Type Long

So I Cannot Understand what is the Mistake here

答:
You got exception because you have mail without subject. Statement should be corrected with ; </p>

```<code>if(message.getSubject() != null && message.getSubject().contains([Keyword]))
</code>```

Body:
I am using the javamail api to make a Search option which Searches the Emails in the Gmail Folder on the Basis of a Keyword present in the Subject of the Messages
Here is the Code that i am Using

public class EGMail7 {
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    final String m10 = "abc@gmail.com";
    final String n10 = "12345";
    string host = "smtp.gmail.com";
    try
    {
    Properties pro1 = new Properties();
    pro1.put("mail.smtp.host", "smtp.gmail.com");
    pro1.put("mail.smtp.socketFactory.port", "465");
    pro1.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    pro1.put("mail.smtp.auth", "true");
    pro1.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(pro1,
        new javax.mail.Authenticator()
{
    protected PasswordAuthentication getPasswordAuthentication()
{
        return new PasswordAuthentication(m10,n10);
        }
    });
    Store store = session.getStore("imaps");
    store.connect(host, m10, n10);
    Folder folderbox = store.getFolder("INBOX");
    folderbox.open(Folder.READ_ONLY);
    SearchTerm search = new SearchTerm(){

        @Override
        public boolean match(Message message) {
            try
            {
                if(message.getSubject().contains([Keyword]))
                {
                    return true;
                }
            }
            catch(Exception e)
            {
                System.err.println(e.getMessage());
            }
            return false;
        }

    };

    Message[] found = folderbox.search(search);

    int length = found.length;
    for(int i = 0;i<found.length;i++)
    {
        Message mess1 = found[i];
        System.out.println("->Message Number > "+i);
        System.out.println("->Message Subject >"+mess1.getSubject());
    }
    folderbox.close(true);
    store.close();
}
    catch(Exception e)
    {
        System.err.println(e.getMessage());
    }
   }
  }

I am using the Eclipse IDE and the problem i am facing is that whatever keyword I pass in the SearchTerm Method I always end up getting null Exception and an Message[] Found Array . I used Stack Trace to find out the Problem of this NullPointer Exception and it is at the line

Message[] found = folderbox.search(search);

I cannot Seem to understand what is the Problem Here ?

Regards,
Thank you

PS - and if someone could also please post the corrected code it would be great
Thanks

Also When i Am Just Adding the Keyword Directly in the SearchTerm it give an Error like

SearchTerm searchCon = new SearchTerm([Keyword]);

There are 2 Errors
1.Cannot Instantiate the SearchTerm
2.The Serializable class does not Declare a static final Serial Verison UID field of Type Long

So I Cannot Understand what is the Mistake here

Body:
You got exception because you have mail without subject. Statement should be corrected with ;

if(message.getSubject() != null && message.getSubject().contains([Keyword]))


问:
File upload using ajax and JavaScript function
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

```<code><script>
   function myFunction() {
      var x = document.getElementById("up");
      $.ajax({
         type: 'GET',
         url: 'ajax.php',
         data: {},
         beforeSend: function() {},
         success: function(data) {
            alert(data);
         }
      });
   }
</script>
<input type="file" name="images" id="up" onchange="myFunction()" />
</code>```

答:
Try this, THis is my working code.</p>

```<code>function myFuction(){
        var form = $("#formId").get(0);
        e.preventDefault(); //keeps the form from behaving like a normal (non-ajax) html form

        $.ajax({
            url: ajax.php,
            type: 'POST',
            data: new FormData(form),
            dataType: 'json',
            mimeType: 'multipart/form-data',
            processData: false,
            contentType: false,
            success: function (response) {
                   alert('success');
            },
            error: function (data) {
                   alert('error');
            }
        });
}

<form id="formId" method="POST">
    <input type="file" name="images" id="up" onchange="myFunction()" />
</form>
</code>```

Body:
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

<input type="file" name="images" id="up" onchange="myFunction()" />

Body:
Try this, THis is my working code.

function myFuction(){
        var form = $("#formId").get(0);
        e.preventDefault(); //keeps the form from behaving like a normal (non-ajax) html form

        $.ajax({
            url: ajax.php,
            type: 'POST',
            data: new FormData(form),
            dataType: 'json',
            mimeType: 'multipart/form-data',
            processData: false,
            contentType: false,
            success: function (response) {
                   alert('success');
            },
            error: function (data) {
                   alert('error');
            }
        });
}

<form id="formId" method="POST">
    <input type="file" name="images" id="up" onchange="myFunction()" />
</form>


问:
TypeError: google.map is undefined (even when MapsAPILoader loaded)
I want to use google.map.XXX (e.g. google.map.LatLng) in my code.

First, to be able to build a project I added declare let google : any; before my class definition.

When I tried to run a project, TypeError: google.map is undefined error has occured.
I used google.map.XXX in ngOnInit() method, therefore i thought "Perhaps GoogleMaps still isn't loaded?"...  So, it was kind of right assumption.

Then I tried to use google.map.XXX inside of code like below

```<code>ngAfterViewInit() {
  this.mapsAPILoader.load().then(() => {
    // code that uses namespace of google.map
  });
}
</code>```

and error below has occured:

EXCEPTION: Uncaught (in promise): TypeError: google.map is undefined

Why even after MapsAPILoader fired the callback, google.map is undefined?

答:
External non-typescript libraries are always tricky and implementing them into the correct scope is just so.

There are multiple options on how you could go about this.

Using a prebuilt library such as AGM which handles pretty much everything

Implement it yourself

Load the Script in your html

Import it with declare let google : any; just like you did

Call the maps functions using new google.maps.function() inside the ngOnInit(){} environment

Body:
I want to use google.map.XXX (e.g. google.map.LatLng) in my code.

First, to be able to build a project I added declare let google : any; before my class definition.

When I tried to run a project, TypeError: google.map is undefined error has occured.
I used google.map.XXX in ngOnInit() method, therefore i thought "Perhaps GoogleMaps still isn't loaded?"...  So, it was kind of right assumption.

Then I tried to use google.map.XXX inside of code like below

ngAfterViewInit() {
  this.mapsAPILoader.load().then(() => {
    // code that uses namespace of google.map
  });
}

and error below has occured:

EXCEPTION: Uncaught (in promise): TypeError: google.map is undefined

Why even after MapsAPILoader fired the callback, google.map is undefined?

Body:
External non-typescript libraries are always tricky and implementing them into the correct scope is just so.

There are multiple options on how you could go about this.

Using a prebuilt library such as AGM which handles pretty much everything

Implement it yourself

Load the Script in your html <script src="https://maps.googleapis.com/maps/api/js?key=[YOUR-KEY]" async defer></script>

Import it with declare let google : any; just like you did

Call the maps functions using new google.maps.function() inside the ngOnInit(){} environment


问:
How to write fields dynamically to a csv file using a tJava
I'm using Talend to extract database field names from the table and write to a csv them after replacing the "_" in field names with " ". I want to have these values against the actual headers.

eg:

```<code>|First_Name|Last_Name|
|----------|---------|
|First Name|Last Name|
</code>```

My job looks similar to following.

Code in tJavaRow is as follows:

```<code>    for (java.lang.reflect.Field field:
 input_row.getClass().getDeclaredFields()) {
 String fieldName = field.getName();
 String newFieldName = null;
 newFieldName = fieldName.replaceAll("_", " ");
 context.columnName = newFieldName;
 System.out.println("Field name is " + context.columnName );
     }
</code>```

How can I get the value of this context variable for each field in csv file? If I directly use it in the tmap it will only have name of the last field as value.
tmap I had between tJava and the tFileOutputDelimited.

答:
you cannot change schema as they are treated as declared variables in java code which is generated in backend.

your schema "|First_Name|Last_Name|" is converted into as below:

String First_Name =null;

String Last_Name = null;

So you cannot change those schema column names on fly.

But you can create a record from the column names which you are retrieving from database by using the delimiter you want(lets take comma)

```<code>for (java.lang.reflect.Field field : input_row.getClass().getDeclaredFields()) {
    String fieldName = field.getName();
    context.columnName = context.columnName + "," + fieldName.replaceAll("_", " ");
}
</code>```

And now, before writing your data into a csv file, write this header record in context.columnName into that csv file.

After writing the header record, append your data to that file by checking "Append" check box in tFileOutputDelimitted.

Body:
I'm using Talend to extract database field names from the table and write to a csv them after replacing the "_" in field names with " ". I want to have these values against the actual headers.

eg:

|First_Name|Last_Name|
|----------|---------|
|First Name|Last Name|

My job looks similar to following.

Code in tJavaRow is as follows:

    for (java.lang.reflect.Field field:
 input_row.getClass().getDeclaredFields()) {
 String fieldName = field.getName();
 String newFieldName = null;
 newFieldName = fieldName.replaceAll("_", " ");
 context.columnName = newFieldName;
 System.out.println("Field name is " + context.columnName );
     }

How can I get the value of this context variable for each field in csv file? If I directly use it in the tmap it will only have name of the last field as value.
tmap I had between tJava and the tFileOutputDelimited.

Body:
you cannot change schema as they are treated as declared variables in java code which is generated in backend.

your schema "|First_Name|Last_Name|" is converted into as below:

String First_Name =null;

String Last_Name = null;

So you cannot change those schema column names on fly.

But you can create a record from the column names which you are retrieving from database by using the delimiter you want(lets take comma)

for (java.lang.reflect.Field field : input_row.getClass().getDeclaredFields()) {
    String fieldName = field.getName();
    context.columnName = context.columnName + "," + fieldName.replaceAll("_", " ");
}

And now, before writing your data into a csv file, write this header record in context.columnName into that csv file.

After writing the header record, append your data to that file by checking "Append" check box in tFileOutputDelimitted.


问:
What is the best way to specify execution time of recurring jobs or tasks?
I am looking for a way of efficiently specifying a recurring job execution time without having to write an explicit execution time to a datastore. In other words, rather than saying 'job x next runs at 13.00pm on 11.12.08' and then having to update the execution time for the following week once the job has run, I want to be able to say 'job x runs at 13.00pm every thursday'. I need to be able to specify a recurrence range of anything from a few minutes to once per month. My guess is the shorter the recurrence period, the more difficult this becomes. Any ideas?

Note: I'm not looking for advice on the scheduling mechanism. I cannot use Windows Scheduler, Cron or create a Windows Service (I have no choice but to use a background thread in ASP.NET).

答:
I implemented some unattended services (Windows Services written in c#), using cron to manage the scheduling. The pattern is powerful, and flexible. We can create schedules to any time we want, only using the cron expression. Maybe I am wrong, but the only schedule that I think cron doesn't cover is if we want the last day of the month, but this was never a requirement for all services.

I copied the cron algorithm from an article in the internet (open source by Atif Aziz), and implemented in my utility class, working beautifully for years.

See more details in my blog:
CronTab schedule parser algorithm

Cheers!

Roberto

OwnerDisplayName: TerryRoquito

LastEditorDisplayName: TerryRoquito


问:
AngularJS hiding input field
I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?

HTML:

```<code><h2>Welcome to Mail Service</h2>

<form action="/action_page.php">
  <div class="imgcontainer">
    <img src="images/img_avatar2.png" alt="Avatar" class="avatar">
  </div>

  <div class="container">
    <label><b>Username</b></label><br>
    <input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
    <label><b>Password</b></label><br>
    <input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>

    <!-- NAME INPUT FIELD -->
    <div class="textField-hidden">
        <label><b>Name</b></label><br>
        <input type="text" placeholder="Enter Name" ng-model="user.name">
    </div><br>

    <button type="submit" ng-click="login()">Login</button><br>
    <button type="submit" ng-click="register()">Register</button>
  </div>

</form>
</code>```

AngularJS Controller:

```<code>app.controller('LoginCtrl', ['$scope', '$resource', '$location',
    function($scope, $resource, $location)
    {
        $scope.login = function()
        {
            var loginRequest = $resource('/api/login');

            loginRequest.save($scope.user, function(response)
            {
            });
        };

        $scope.register = function()
        {
            var registerRequest = $resource('/api/register');

            loginRequest.save($scope.user, function(response)
            {
            });
        };
    }]);
</code>```

答:
just populate a variable as true when you click register and set that variable as false when you click login.

```<code><h2>Welcome to Mail Service</h2>

<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>

<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>

<!-- NAME INPUT FIELD -->
<div class="textField-hidden" ng-show="register">
    <label><b>Name</b></label><br>
    <input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>

<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
</code>```

now populate $scope.register as true when you click register

```<code> app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
   $scope.register=false;
   $scope.login = function()
    {
        var loginRequest = $resource('/api/login');
        $scope.register=false;
        loginRequest.save($scope.user, function(response)
        {
        });
    };

    $scope.register = function()
    {
        var registerRequest = $resource('/api/register');
            $scope.register=true;

        loginRequest.save($scope.user, function(response)
        {
        });
    };
}]);
</code>```

Title: AngularJS hiding input field

Body:
I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?

HTML:

Welcome to Mail Service

<form action="/action_page.php">

    Username

    <input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username">

    Password

    <input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password">

        Name

        <input type="text" placeholder="Enter Name" ng-model="user.name">

    <button type="submit" ng-click="login()">Login</button>

    <button type="submit" ng-click="register()">Register</button>

</form>

AngularJS Controller:

app.controller('LoginCtrl', ['$scope', '$resource', '$location',
    function($scope, $resource, $location)
    {
        $scope.login = function()
        {
            var loginRequest = $resource('/api/login');

            loginRequest.save($scope.user, function(response)
            {
            });
        };

        $scope.register = function()
        {
            var registerRequest = $resource('/api/register');

            loginRequest.save($scope.user, function(response)
            {
            });
        };
    }]);

Body:
just populate a variable as true when you click register and set that variable as false when you click login.

<h2>Welcome to Mail Service</h2>

<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>

<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>

<!-- NAME INPUT FIELD -->
<div class="textField-hidden" ng-show="register">
    <label><b>Name</b></label><br>
    <input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>

<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>

now populate $scope.register as true when you click register

 app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
   $scope.register=false;
   $scope.login = function()
    {
        var loginRequest = $resource('/api/login');
        $scope.register=false;
        loginRequest.save($scope.user, function(response)
        {
        });
    };

    $scope.register = function()
    {
        var registerRequest = $resource('/api/register');
            $scope.register=true;

        loginRequest.save($scope.user, function(response)
        {
        });
    };
}]);


问:
how to check if and else if together in javascript
/html code/
Here there are 4 textbox having minimum & maximum bugdet and area. I want to check the value that maximum value should be greater than minimum area in bugdet and area.I am checking it when the form is submited.
Currently my condtion is not working for else if.

```<code>  <div class="col-xs-12 margin-y">
         <div class="width">
            <label class="col-xs-12 col-md-2">Budget</label>
            <div class="col-xs-12 col-md-10">
               <div class="col-xs-12 col-md-6 no-padding-left no-padding-left no-padding-mobile padding-vertical">
                  <input class=" form-control"   placeholder="Minimum Budget"  id="req_min_budget" name="req_min_budget" onkeypress='return validateArea(event);'>
               </div>
               <div class="col-xs-12 col-md-6 no-padding-right no-padding-left no-padding-mobile padding-vertical">
                  <input class=" form-control"  placeholder="Maximum Budget" id="req_max_budget" name="req_max_budget" onkeypress='return validateArea(event);'><span style="color:#d9534f" id="maxBudgetError"></span>
               </div>
            </div>
         </div>
      </div>
      <div class="col-xs-12 margin-y">
         <div class="width">
            <label class="col-md-4 col-md-2">Carpet Area</label>
            <div class="col-xs-12 col-md-10 no-padding padding-vertical">
               <div class="col-md-4  padding-vertical">
                  <input class=" form-control" placeholder="Minimum Area"  onblur="return validateMaxArea1(this.value)"   id="req_min_area" name="req_min_area" onkeypress='return validateArea(event);'>
               </div>
               <div class="col-md-2  no-padding-left  padding-vertical ">
                <select onchange="return changeUnit(this.value)" id="req_carpet_area_unit" required  name="req_carpet_area_unit" class="btn btn-default dropdown-toggle">
         <!-- <option value=''>Select carpet unit</option> -->
                   <?php
         global $SQFT;

          echo $this->home_model->get_dropdown('area_unit',$SQFT)?>
      </select>
               </div>
               <div class="col-md-4 padding-vertical">
                  <input class=" form-control" onblur="return validateMaxArea(this.value)"  placeholder="Maximum Area" id="req_max_area"  name="req_max_area" onkeypress='return validateArea(event);'/><span style="color:#d9534f" id="maxAreaError"></span>
               </div>
                <div class="col-md-2">
                   <select disabled id="req_carpet_area_unit1" required  name="req_carpet_area_unit1" class="btn btn-default dropdown-toggle">
         <!-- <option value=''>Select carpet unit</option> -->
         <?php
         global $SQFT;

          echo $this->home_model->get_dropdown('area_unit',$SQFT)?>
      </select>
               </div>

            </div>
         </div>
      </div>

      <button type="submit"  class="col-xs-offset-8 col-md-offset-11 btn btn-gray" id="req_submit" name="req_submit">Submit</button>
</code>```

javascript script

```<code>$(function() {
    // Setup form validation on the #register-form element
    $("#register").validate({
        // Specify the validation rules
        // Specify the validation error messages

        submitHandler: function(form)  {
            var req_min_area = $('#req_min_area').val();
            var req_max_area = $('#req_max_area').val();
            var req_min_budget = $('#req_min_budget').val();
            var req_max_budget = $('#req_max_budget').val();

            if(req_min_area!='' && req_max_area!='') {

                if(parseFloat(req_min_area)>parseFloat(req_max_area)) {
                    $('#req_max_area').css('border-color','#d9534f');
                    document.getElementById("maxAreaError").innerHTML = "Maximum area should be greater than minimum";
                } else {
                    insertReqData();
                }
            } else if(req_min_budget!='' && req_max_budget!='') {
                alert(parseFloat(req_min_budget)>parseFloat(req_max_budget));

                if(parseFloat(req_min_budget)>parseFloat(req_max_budget)) {
                    $('#req_max_budget').css('border-color','#d9534f');
                    document.getElementById("maxBudgetError").innerHTML = "Maximum area should be greater than minimum";
                } else {
                    insertReqData();
                }
            } else {
                insertReqData();
            }
        }
    });
});
</code>```

答:
Your If statement always goes to If not elseif except If statement is False ( req_min_area or req_max_area is empty string ).
Put your elseif in If statement and change it to If should do the work.</p>

Body:
/html code/
Here there are 4 textbox having minimum & maximum bugdet and area. I want to check the value that maximum value should be greater than minimum area in bugdet and area.I am checking it when the form is submited.
Currently my condtion is not working for else if.

            Budget

                  <input class=" form-control"   placeholder="Minimum Budget"  id="req_min_budget" name="req_min_budget" onkeypress='return validateArea(event);'>

                  <input class=" form-control"  placeholder="Maximum Budget" id="req_max_budget" name="req_max_budget" onkeypress='return validateArea(event);'>

            Carpet Area

                  <input class=" form-control" placeholder="Minimum Area"  onblur="return validateMaxArea1(this.value)"   id="req_min_area" name="req_min_area" onkeypress='return validateArea(event);'>

                <select onchange="return changeUnit(this.value)" id="req_carpet_area_unit" required  name="req_carpet_area_unit" class="btn btn-default dropdown-toggle">

                   <?php
         global $SQFT;

          echo $this->home_model->get_dropdown('area_unit',$SQFT)?>
      </select>

                  <input class=" form-control" onblur="return validateMaxArea(this.value)"  placeholder="Maximum Area" id="req_max_area"  name="req_max_area" onkeypress='return validateArea(event);'/>

                   <select disabled id="req_carpet_area_unit1" required  name="req_carpet_area_unit1" class="btn btn-default dropdown-toggle">

         <?php
         global $SQFT;

          echo $this->home_model->get_dropdown('area_unit',$SQFT)?>
      </select>

      <button type="submit"  class="col-xs-offset-8 col-md-offset-11 btn btn-gray" id="req_submit" name="req_submit">Submit</button>

javascript script

$(function() {
    // Setup form validation on the #register-form element
    $("#register").validate({
        // Specify the validation rules
        // Specify the validation error messages

        submitHandler: function(form)  {
            var req_min_area = $('#req_min_area').val();
            var req_max_area = $('#req_max_area').val();
            var req_min_budget = $('#req_min_budget').val();
            var req_max_budget = $('#req_max_budget').val();

            if(req_min_area!='' && req_max_area!='') {

                if(parseFloat(req_min_area)>parseFloat(req_max_area)) {
                    $('#req_max_area').css('border-color','#d9534f');
                    document.getElementById("maxAreaError").innerHTML = "Maximum area should be greater than minimum";
                } else {
                    insertReqData();
                }
            } else if(req_min_budget!='' && req_max_budget!='') {
                alert(parseFloat(req_min_budget)>parseFloat(req_max_budget));

                if(parseFloat(req_min_budget)>parseFloat(req_max_budget)) {
                    $('#req_max_budget').css('border-color','#d9534f');
                    document.getElementById("maxBudgetError").innerHTML = "Maximum area should be greater than minimum";
                } else {
                    insertReqData();
                }
            } else {
                insertReqData();
            }
        }
    });
});


问:
Use tmx file to create map in java
I use Tiled to create tiled map.

I create tmx file but I don't know how I can use this file to create a tiled map in javafx.

I search and find I have to convert tmx file to XML file.

But I don't know how I use from the XML file.

please help me to create a tiled map from XML file.

答:
I'm not sure what exactly you want to achieve in JavaFX but there is a thread in the tiled forum that seems to address your question:

http://discourse.mapeditor.org/t/loading-tmx-map-and-displaying-with-javafx/1189

Btw tmx files actually are XML files. TMX is short for Tile Map XML.

Title: Use tmx file to create map in java


问:
Using a WSDL File instead of URL to WSDL in PHP
I have a bit of a problem understanding how the WSDL local file is working. Normally when I need to consume a WSDL file I simply use SoapClient and pass the URL (Something like https://somesite.com/something?wsdl) to it and I am able to consume it. However, now with a new webservice provider they gave me 6 files. Two of which has .wsdl extensions and the rest has .xsd extensions. I have never consumed a web service like this before and I cannot find any tutorials online or any topics regarding this with PHP. I found one where they explained it in Visual Studio, but we need to get this working on PHP. Can anyone point me in the right direction? I did not even know this method existed as normally we consume them by URL.

Any help would be greatly appreciated.

答:
generally speaking, every wsdl is one web service, so there's 2 different services. Xsd files are just xml schema definition and you don't need it while you're calling web services. Use them to validate your soap xml.

If wsdl-s are v 1.1 you can try NuSoap on php site, if not, in Visual Studio you have wsdl.exe command line tool. Use that tool to simulate those web services localy, so you'll get excellent testing environment.

I also highly recommend you to try SoapUI.

Cheers,
Siniša


问:
ng-repeat is Working perfectly with static json But fires exception with dynamic json data
I have a ng-repeat put on a list to display in table.

the script html code is like this :

```<code>`<tr ng-repeat="user in users track by $index" ng-class="{'selected':$index == selectedRow}">
                    <td>
                        {{user.FirstName}}
                    </td>
                    <td>
                        {{user.LastName}}
                    </td>
                    <td>
                        {{user.EmailId}}
                    </td>
                    <td>
                        {{user.ContactNumber}}
                    </td>
                    <td>
                        <button type="button" class="btn btn-warning">
                            <span class="glyphicon glyphicon-pencil"></span>
                        </button>
                        <button type="button" class="btn btn-danger">
                            <span class="glyphicon glyphicon-remove"></span>
                        </button>
                    </td>
                </tr>`
</code>```

and in angular script the routing is defined as bellow:

```<code>var routingApp = angular.module('App', []);
routingApp.controller("MovieController", ['$scope', '$http', function ($scope, $http) {

$scope.edit = false;
$scope.error = false;
$scope.success = false;
//TO DO : Below portion to be replaced with ajax call to get list of movies from DB
var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
console.log(users); //debugger;
    $scope.users = users;

}]);
</code>```

This part is working absolutely fine.

but when i replace the static json data ie;

```<code> var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
</code>```

with

```<code>$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
    dt = JSON.stringify(response.data);
    $scope.users = dt;
    //console.log(dt);
    //console.log(JSON.parse(dt));
})
</code>```

it will through this exception :

```<code>`[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: string:", Duplicate value`
</code>```

But the output of the api is exactly same as static json, in fact i have copied json from api output itself.

Even i have tried removing  track by $index but No luck.
are there any solutions to this issue?

答:
```<code>//dont stringify your api response and try this
$scope.users = response.data;

//html
<tr ng-repeat="user in users track by user.UserId" ng-class="{'selected':$index == selectedRow}">
</code>```

Body:
I have a ng-repeat put on a list to display in table.

the script html code is like this :

`

                        {{user.FirstName}}

                        {{user.LastName}}

                        {{user.EmailId}}

                        {{user.ContactNumber}}

                        <button type="button" class="btn btn-warning">

                        </button>
                        <button type="button" class="btn btn-danger">

                        </button>

`

and in angular script the routing is defined as bellow:

var routingApp = angular.module('App', []);
routingApp.controller("MovieController", ['$scope', '$http', function ($scope, $http) {

$scope.edit = false;
$scope.error = false;
$scope.success = false;
//TO DO : Below portion to be replaced with ajax call to get list of movies from DB
var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
console.log(users); //debugger;
    $scope.users = users;

}]);

This part is working absolutely fine.

but when i replace the static json data ie;

 var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];

with

$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
    dt = JSON.stringify(response.data);
    $scope.users = dt;
    //console.log(dt);
    //console.log(JSON.parse(dt));
})

it will through this exception :

`[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: string:", Duplicate value`

But the output of the api is exactly same as static json, in fact i have copied json from api output itself.

Even i have tried removing  track by $index but No luck.
are there any solutions to this issue?


问:
background color transition in few seconds w/o JQuery
https://codepen.io/codeispoetry/pen/dRKKEY

.back {
  margin: 20px;
  padding: 100px;
  background: yellow;
  font-size: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="back">

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

</div></code>```

I want that yellow background should change with time to yellow, but I want to do ith through CSS. there is enough solution available on StackOverflow that do it with Jquery, but can we achieve this through CSS so that it works on all the browser.

https://www.w3schools.com/css/css3_animations.asp i tried this, but it roll backs to the original color. How to make th after color permanent.

答:
You can use a keyframe animation:</p>

```<code>@keyframes background-change {
    to { background-color: hotpink; }
}

.block {
    animation: background-change 900ms forwards;
}
</code>```

Body:
https://codepen.io/codeispoetry/pen/dRKKEY

.back {
  margin: 20px;
  padding: 100px;
  background: yellow;
  font-size: 30px;
}

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

I want that yellow background should change with time to yellow, but I want to do ith through CSS. there is enough solution available on StackOverflow that do it with Jquery, but can we achieve this through CSS so that it works on all the browser.

https://www.w3schools.com/css/css3_animations.asp i tried this, but it roll backs to the original color. How to make th after color permanent.

Body:
You can use a keyframe animation:

@keyframes background-change {
    to { background-color: hotpink; }
}

.block {
    animation: background-change 900ms forwards;
}


问:
C# WebBrowser get mouse click position
I have WebBrowser class and image loaded in it. After mouse click on the browser, I need to get mouse position - what is the best way to do it?

答:
this is actually pretty simple if your just looking for the screen coordinates.

```<code>// this probably should be in your form initialization
this.MouseClick += new MouseEventHandler(MouseClickEvent);

void MouseClickEvent(object sender, MouseEventArgs e)
{
    // do whatever you need with e.Location
}
</code>```

if your strictly looking for the point in the browser, you need to consider the functions

```<code>browser.PointToClient();
browser.PointToScreen();
</code>```

Title: C# WebBrowser get mouse click position

Body:
this is actually pretty simple if your just looking for the screen coordinates.

// this probably should be in your form initialization
this.MouseClick += new MouseEventHandler(MouseClickEvent);

void MouseClickEvent(object sender, MouseEventArgs e)
{
    // do whatever you need with e.Location
}

if your strictly looking for the point in the browser, you need to consider the functions

browser.PointToClient();
browser.PointToScreen();


问:
Overlay div not showing if ng-if is true
I have a page that has a responsive menu, with a gray overlay that's triggered if the menu is active. I've been trying to show this overlay using ng-if, but without success. What am I missing?

HTML

```<code><header ng-controller="NavController">
    <div class="cover-header">
        <!-- Burger menu icon placement -->
        <div class="navbar-header">
            <button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu"
                    aria-expanded="{{showOverlay}}">
                <span class="glyphicon glyphicon-menu-hamburger"></span>
            </button>
        </div>
</header>

<div class="container-burger-menu">
    <div class="collapse container-accordion" id="main-menu">
        <!-- menu items go here -->
    </div>
</div>
<div class="overlay-nav" ng-if="showOverlay">
</code>```

CSS

```<code>.overlay-nav {
    //display:block;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 999;
}
</code>```

Controller

```<code>function NavController($scope) {
    $scope.$watch('showOverlay', function(){
        console.log("value is ", $scope.showOverlay);
        $scope.showOverlay = !$scope.showOverlay;
    });
}
</code>```

Prior to using $scope.$watch, I've tried something like this:

```<code>function NavController($scope) {
    $scope.toggleOverlay = function() {
        $scope.showOverlay = !$scope.showOverlay;
    }
}
</code>```

And then in the HTML:

```<code><button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu"
                aria-expanded="{{showOverlay}}" ng-click="toggleOverlay()>
</code>```

Any replies would be greatly appreciated. Thank you.

EDIT: My latest attempt:

HTML

```<code><button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu"
                    ng-click="toggleOverlay()">

<!-- overlay -->
<div class="overlay-nav" ng-if="nav.showOverlay">
</code>```

Controller

```<code>function NavController($scope) {

    $scope.nav = { showOverlay: '' };

    $scope.toggleOverlay = function() {
        $scope.nav.showOverlay = !$scope.nav.showOverlay;
    }
}
</code>```

$scope.nav.showOverlay changes values just fine, but is not getting picked up by ng-if.

答:
Your overlay isn't inside the scope of your controller, so it can't access showOverlay.

To fix it, move the ng-controller-directive into a container element instead. Like this:

```<code><div ng-controller="NavController">
    <header>
        <div class="cover-header">
            <!-- Burger menu icon placement -->
            <div class="navbar-header">
                <button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu"
                        aria-expanded="{{showOverlay}}">
                    <span class="glyphicon glyphicon-menu-hamburger"></span>
                </button>
            </div>
    </header>

    <div class="container-burger-menu">
        <div class="collapse container-accordion" id="main-menu">
            <!-- menu items go here -->
        </div>
    </div>
    <div class="overlay-nav" ng-if="showOverlay">
</div>
</code>```

Body:
I have a page that has a responsive menu, with a gray overlay that's triggered if the menu is active. I've been trying to show this overlay using ng-if, but without success. What am I missing?

HTML

            <button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu"
                    aria-expanded="{{showOverlay}}">

            </button>

CSS

.overlay-nav {
    //display:block;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 999;
}

Controller

function NavController($scope) {
    $scope.$watch('showOverlay', function(){
        console.log("value is ", $scope.showOverlay);
        $scope.showOverlay = !$scope.showOverlay;
    });
}

Prior to using $scope.$watch, I've tried something like this:

function NavController($scope) {
    $scope.toggleOverlay = function() {
        $scope.showOverlay = !$scope.showOverlay;
    }
}

And then in the HTML:

<button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu"
                aria-expanded="{{showOverlay}}" ng-click="toggleOverlay()>

Any replies would be greatly appreciated. Thank you.

EDIT: My latest attempt:

HTML

<button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu"
                    ng-click="toggleOverlay()">

Controller

function NavController($scope) {

    $scope.nav = { showOverlay: '' };

    $scope.toggleOverlay = function() {
        $scope.nav.showOverlay = !$scope.nav.showOverlay;
    }
}

$scope.nav.showOverlay changes values just fine, but is not getting picked up by ng-if.

Body:
Your overlay isn't inside the scope of your controller, so it can't access showOverlay.

To fix it, move the ng-controller-directive into a container element instead. Like this:

<div ng-controller="NavController">
    <header>
        <div class="cover-header">
            <!-- Burger menu icon placement -->
            <div class="navbar-header">
                <button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu"
                        aria-expanded="{{showOverlay}}">
                    <span class="glyphicon glyphicon-menu-hamburger"></span>
                </button>
            </div>
    </header>

    <div class="container-burger-menu">
        <div class="collapse container-accordion" id="main-menu">
            <!-- menu items go here -->
        </div>
    </div>
    <div class="overlay-nav" ng-if="showOverlay">
</div>