问:
installation error for elasticsearch on windows7
I have been trying to setup elasticsearch in windows7 machine by following https://www.elastic.co/guide/en/elasticsearch/reference/current/_installation.html
I was able to download, unzip but when running ./elasticsearch, I get the below error,

```<code>Error: Could not find or load main class
org.elasticsearch.tools.JavaVersionChecker
Elasticsearch requires at least Java 8 but your Java version from C:\Program
Files\Java\jdk1.8.0_131/bin/java does not meet this requirement
</code>```

I have verified Java versions installed and they look fine,

$ java -version

```<code>java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
</code>```

$ javac -version
    javac 1.8.0_131

Can someone point out where I am wrong ?

答:
In run Elasticsearch in Windows, you should run with elasticsearch.bat not ./elasticsearch directly:

And now we are ready to start our node and single cluster (Windows users should run the elasticsearch.bat file):

Body:
I have been trying to setup elasticsearch in windows7 machine by following https://www.elastic.co/guide/en/elasticsearch/reference/current/_installation.html
I was able to download, unzip but when running ./elasticsearch, I get the below error,

Error: Could not find or load main class
org.elasticsearch.tools.JavaVersionChecker
Elasticsearch requires at least Java 8 but your Java version from C:\Program
Files\Java\jdk1.8.0_131/bin/java does not meet this requirement

I have verified Java versions installed and they look fine,

$ java -version

java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

$ javac -version
    javac 1.8.0_131

Can someone point out where I am wrong ?


来源: stackexchange

问:
how to pass route params in [routerLink] angular 2
I'm trying to create an application with angular 2,And Want pass params to tag a in [routerLink],i want craete a link like this :

```<code><a href="/auth/signup?cell=1654654654"></a>
</code>```

i dont know how to pass cell in template...

答:
The accepted answer is outdated and IMHO doesn't answer the question.

However the question is not clear: "route params" are in the path part of the URL but the question was about "query params" which are after the '?' (question mark).

So the answer to the question is in the answer of @Akash: you have to use

```<code>[queryParams]="{name: value}"
</code>```

in the template.

So this anchor will reference to /path/with/myparam?cell=1654654654:

```<code><a [routerLink]="['/path/with/:paramName', {paramName: "myparam"}]"
   [queryParams]="{cell: 1654654654}"
></a>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create an application with angular 2,And Want pass params to tag a in [routerLink],i want craete a link like this :

i dont know how to pass cell in template...

Body:
The accepted answer is outdated and IMHO doesn't answer the question.

However the question is not clear: "route params" are in the path part of the URL but the question was about "query params" which are after the '?' (question mark).

So the answer to the question is in the answer of @Akash: you have to use

[queryParams]="{name: value}"

in the template.

So this anchor will reference to /path/with/myparam?cell=1654654654:

<a [routerLink]="['/path/with/:paramName', {paramName: "myparam"}]"
   [queryParams]="{cell: 1654654654}"
></a>


问:
How to set to an instance of an object as below code?
I want your help to my problem, Please:
From my test class, I try run my test code:

```<code>[setUp]
public void setup()
{
BrowserFactory.InitBrowser("Chrome");
}
</code>```

But, it failed, because it didn’t initialized the “driver” variable.

(I got msg: system.nullReferenceException: The WebDriver browser instance was not initialized. You should first call the method InitBrowser)

Below code of InitBrowser() function as I copied from  http://toolsqa.com/selenium-webdriver/c-sharp/browser-factory-or-webdriver-factory/

```<code>using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using System;
using System.Collections.Generic;

namespace _AutomationTests.WrapperFactory
{
   public class BrowserFactory
   {
       private static readonly IDictionary<string, IWebDriver> Drivers = new Dictionary<string, IWebDriver>();
        private static IWebDriver driver;

    public static IWebDriver Driver
    {
        get
        {
            if (driver == null)
                throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
            return driver;
        }
        private set
        {
            driver = value;
        }
    }

    public static void InitBrowser(string browserName)
    {
        switch (browserName)
        {
            case "Firefox":
                if (Driver == null)
                {
                    driver = new FirefoxDriver();
                    Drivers.Add("Firefox", Driver);
                }
                break;

            case "IE":
                if (Driver == null)
                {
                    driver = new InternetExplorerDriver(@"C:\PathTo\IEDriverServer");
                    Drivers.Add("IE", Driver);
                }
                break;

            case "Chrome":
                if (Driver == null)
                {
                    driver = new ChromeDriver();//@"C:\PathTo\CHDriverServer"
                    Drivers.Add("Chrome", Driver);
                }
                break;
        }
    }

    public static void LoadApplication(string url)
    {
        Driver.Url = url;
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("javascript:document.getElementById('overridelink').click()");
    }

    public static void CloseAllDrivers()
    {
        foreach (var key in Drivers.Keys)
        {
            Drivers[key].Close();
            Drivers[key].Quit();
        }
    }
}
</code>```

}

thank alot!

答:
There is a bug in your code.

You should change each of these lines:

if (Driver == null)

to this:

if (driver == null)

Another option is to change the get from:

```<code>    get
    {
        if (driver == null)
            throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
        return driver;
    }
</code>```

to:

```<code>    get
    {
        return driver;
    }
</code>```

Body:
I want your help to my problem, Please:
From my test class, I try run my test code:

[setUp]
public void setup()
{
BrowserFactory.InitBrowser("Chrome");
}

But, it failed, because it didn’t initialized the “driver” variable.

(I got msg: system.nullReferenceException: The WebDriver browser instance was not initialized. You should first call the method InitBrowser)

Below code of InitBrowser() function as I copied from  http://toolsqa.com/selenium-webdriver/c-sharp/browser-factory-or-webdriver-factory/

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using System;
using System.Collections.Generic;

namespace _AutomationTests.WrapperFactory
{
   public class BrowserFactory
   {
       private static readonly IDictionary<string, IWebDriver> Drivers = new Dictionary<string, IWebDriver>();
        private static IWebDriver driver;

    public static IWebDriver Driver
    {
        get
        {
            if (driver == null)
                throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
            return driver;
        }
        private set
        {
            driver = value;
        }
    }

    public static void InitBrowser(string browserName)
    {
        switch (browserName)
        {
            case "Firefox":
                if (Driver == null)
                {
                    driver = new FirefoxDriver();
                    Drivers.Add("Firefox", Driver);
                }
                break;

            case "IE":
                if (Driver == null)
                {
                    driver = new InternetExplorerDriver(@"C:\PathTo\IEDriverServer");
                    Drivers.Add("IE", Driver);
                }
                break;

            case "Chrome":
                if (Driver == null)
                {
                    driver = new ChromeDriver();//@"C:\PathTo\CHDriverServer"
                    Drivers.Add("Chrome", Driver);
                }
                break;
        }
    }

    public static void LoadApplication(string url)
    {
        Driver.Url = url;
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("javascript:document.getElementById('overridelink').click()");
    }

    public static void CloseAllDrivers()
    {
        foreach (var key in Drivers.Keys)
        {
            Drivers[key].Close();
            Drivers[key].Quit();
        }
    }
}

}

thank alot!

Body:
There is a bug in your code.

You should change each of these lines:

if (Driver == null)

to this:

if (driver == null)

Another option is to change the get from:

    get
    {
        if (driver == null)
            throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
        return driver;
    }

to:

    get
    {
        return driver;
    }


问:
iPhone app icon showing up as blank after a project rename
I'm working on an app using the 4.2 iOS SDK and recently changed the name of the project to something else. It compiles and runs fine, but now the icon file defined in the info plist is no longer working. When I build and run, the app icon shows up at blank on both the simulator and my iPhone 4 device.

I've tried swapping out different image files but to no avail. I also cleaned my build and targets. Any ideas why this is happening and how to fix it?

Thanks!

答:
I actually saw this answer and it worked!

iPhone Icon@2x.png not showing in Retina display

ContentLicense: CC BY-SA 2.5


问:
Ionic2 google maps image layer
I am building an Ionic2 app where I am using google maps as an orientation map and I need to put an image layer on top of the map. I am trying to put building layout image over the building complex in Google maps.
I found this solution for javascript here, which is exactly what I need: Google maps js API

I am quite new to Ionic2 and Anglular2 and having no luck figuring it out so far.

Any advice appreciated

My code :

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';

declare var google;

@Component({
  selector: 'map',
  templateUrl: 'map.html'
})
export class MapPage {

 @ViewChild('map') mapElement: ElementRef;
 map: any;

 lat : any ;
 lng : any ;

 constructor(public navCtrl: NavController,  public geolocation: Geolocation) {
    this.getGeoLocation();

  }

 initializeMap() {
    var minZoomLevel = 17;

      let mapOptions =
      {
        zoom: minZoomLevel,
        center: new google.maps.LatLng(lat, lng),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
      }
    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
  }

  getGeoLocation(){
   this.geolocation.getCurrentPosition().then((position) => {
      this.lat = position.coords.latitude;
      this.lng = position.coords.longitude;
      this.initializeMap();

    }, (err) => {
      console.log(err);
    });

  }```

答:
Well, apparently it was easier than I thought. You just define image boundaries and create an instance of an overlay and then add it to the map like this...

```<code>var oldBuilding = {
      north: 53.27959,
      west: -9.01287,
      south: 53.278038,
      east: -9.00876
    };
this.oldBuildingOverLay = new google.maps.GroundOverlay('../assets/Map.png', oldBuilding);
this.oldBuildingOverLay.setMap(this.map);
</code>```

Declare oldBuildingOverlay: any; and you're up and running.

Title: Ionic2 google maps image layer

Body:
Well, apparently it was easier than I thought. You just define image boundaries and create an instance of an overlay and then add it to the map like this...

var oldBuilding = {
      north: 53.27959,
      west: -9.01287,
      south: 53.278038,
      east: -9.00876
    };
this.oldBuildingOverLay = new google.maps.GroundOverlay('../assets/Map.png', oldBuilding);
this.oldBuildingOverLay.setMap(this.map);

Declare oldBuildingOverlay: any; and you're up and running.


问:
MySQL - Retrieving the record with the maximum value
I've a table like below on my MySQL database:

```<code>employee
-------------------------
id    name    num
1     Jack    1
2     John    1
3     Jack    2
4     Steve   1
5     Jack    3
6     Steve   2
7     Carol   1
</code>```

The thing I want to do is to retrieve names with the highest "num" value.

For example:

```<code>5     Jack    3
</code>```

There more than one records named Jack but I want to get the one with the maximum "num" value.

I've tried to use the query below:

```<code>SELECT MAX(num),id,name FROM `employee`
</code>```

But it returns the id and name of first record (first "Jack") but the num of the latest.

```<code>MAX(num)    id     num
-----------------------
3           1      Jack
</code>```

Of course I can try to use "Order by" but I also want to retrieve the only record with the highest value.

```<code>SELECT num,id,name FROM `employee` order by num desc
</code>```

This query will also return all the records including the smaller ones.

```<code>id    name    num
-------------------------
3     5       Jack
2     3       Jack
2     6       Steve
1     1       Jack
1     2       John
1     4       Steve
1     7       Carol
</code>```

When I try to group by name, it returns the records grouped by name but again only the small records.

The both of the queries below give the same result:

```<code>SELECT num,id,name FROM `employee` group by name order by num desc

SELECT * FROM
(
select * from `employee` order by num desc
) as employee_tmp
group by name
order by num desc
</code>```

Again, it groups with only the first and smallest records.

```<code>id  name    num
1   Jack    1
2   John    1
4   Steve   1
7   Carol   1
</code>```

答:
MAX(column_name) will return max of all records,

```<code>SELECT emp.* FROM `employee` emp INNER JOIN
(SELECT name,MAX(num) as num FROM `employee` GROUP BY name) tbl
ON emp.`name` = tbl.`name` AND emp.`num` = tbl.`num`
</code>```

We have used inner query to find out the name and max num of that name and then joined with the main table on name col and num col.
We need to mention group by so that it gives the name and max of each num for that name

I think, this should solve your purpose

Body:
I've a table like below on my MySQL database:

employee
-------------------------
id    name    num
1     Jack    1
2     John    1
3     Jack    2
4     Steve   1
5     Jack    3
6     Steve   2
7     Carol   1

The thing I want to do is to retrieve names with the highest "num" value.

For example:

5     Jack    3

There more than one records named Jack but I want to get the one with the maximum "num" value.

I've tried to use the query below:

SELECT MAX(num),id,name FROM `employee`

But it returns the id and name of first record (first "Jack") but the num of the latest.

MAX(num)    id     num
-----------------------
3           1      Jack

Of course I can try to use "Order by" but I also want to retrieve the only record with the highest value.

SELECT num,id,name FROM `employee` order by num desc

This query will also return all the records including the smaller ones.

id    name    num
-------------------------
3     5       Jack
2     3       Jack
2     6       Steve
1     1       Jack
1     2       John
1     4       Steve
1     7       Carol

When I try to group by name, it returns the records grouped by name but again only the small records.

The both of the queries below give the same result:

SELECT num,id,name FROM `employee` group by name order by num desc

SELECT * FROM
(
select * from `employee` order by num desc
) as employee_tmp
group by name
order by num desc

Again, it groups with only the first and smallest records.

id  name    num
1   Jack    1
2   John    1
4   Steve   1
7   Carol   1

Body:
MAX(column_name) will return max of all records,

SELECT emp.* FROM `employee` emp INNER JOIN
(SELECT name,MAX(num) as num FROM `employee` GROUP BY name) tbl
ON emp.`name` = tbl.`name` AND emp.`num` = tbl.`num`

We have used inner query to find out the name and max num of that name and then joined with the main table on name col and num col.
We need to mention group by so that it gives the name and max of each num for that name

I think, this should solve your purpose


问:
How to remove object from array in local storage?
I have array like this:

```<code>var myMovie = [];
</code>```

And object like this:

```<code>var first = {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}
</code>```

I added object into local storage array via OnClick() on button.

```<code>$(document).ready(function() {
   $(".btn.btn-outline-success").click(function () {

    myMovie.push(first);

    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));
</code>```

After adding object into local storage, local storage looks like this:

```<code>[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}]
</code>```

My question here is, how could I remove whole object via variable name? I want to remove object first from myMovie. Index position of object may be different each time.

```<code>[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}, [{id:"tt9574821", title:"Ghost Protocol", year:"2012", type:"Action, Adventure"}]
</code>```

答:
you need to get the object and set new one:</p>

```<code>myMovie = JSON.parse(localStorage.getItem("myMovie"));
myMovie.splice(0,1);
localStorage.setItem("myMovie",JSON.stringify(myMovie));
</code>```

Body:
I have array like this:

var myMovie = [];

And object like this:

var first = {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}

I added object into local storage array via OnClick() on button.

$(document).ready(function() {
   $(".btn.btn-outline-success").click(function () {

    myMovie.push(first);

    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));

After adding object into local storage, local storage looks like this:

[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}]

My question here is, how could I remove whole object via variable name? I want to remove object first from myMovie. Index position of object may be different each time.

[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}, [{id:"tt9574821", title:"Ghost Protocol", year:"2012", type:"Action, Adventure"}]

Body:
you need to get the object and set new one:

myMovie = JSON.parse(localStorage.getItem("myMovie"));
myMovie.splice(0,1);
localStorage.setItem("myMovie",JSON.stringify(myMovie));


问:
ASP.NET Core 1.1 Web API not working on Web Application
I created an ASP.NET CORE web application using Visual Studio 2017 Community. On it I have the usual controllers (Manage, Home, Account) plus a few of my own.

My API TestController has so far only two methods:

```<code>[HttpGet]
public IActionResult GetSitemap()
{
    Request.Headers.Clear();
    Request.Headers.Add("Accept", "text/xml");
    System.Xml.Linq.XDocument gsmXML = GoogleSitemap.AutoSeek(Domain);
    return new ContentResult()
        {
            StatusCode = 200,
            ContentType = "application/xml",
            Content = gsmXML.ToString()
        };
}

[HttpGet]
public IActionResult GetSiteName()
{
    return new OkObjectResult( "Test API");
}
</code>```

Now, I wanted to also add a Web API to my web application, somebody suggests using an AREA for the API which is just fine. So I created an area named API for all API controllers.

```<code>   ~/Areas/
        API/
           Controllers/
               TestController.cs
           _ViewImports.cshtml
           _ViewStart.cshtml
</code>```

And my route definition in Startup.cs looks like this:

```<code>app.UseMvc(routes =>
    routes.MapRoute(
                name: "areaRoute",
                template: "{area:exists}/{controller=Dashboard}/{action=Index}/{id?}");
    routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
});
</code>```

The problem is when I make a request to my API method I get an empty page:

```<code>      localhost:1234/api/Test/GetSitemap
</code>```

and for what I see the breakpoint does not trigger on the GetSitemap API method.
But when I change the request to:

```<code>      localhost:1234/api/Test/
</code>```

Then I get an exception saying something about ambitguous because two methods matched. They both start with Get but the route specified Get (and Get alone) as the default so I do not see why GetSitemap and GetSiteName match.

If I remove the GetSiteName API method then the ambiguous exception does not happen but I am shown a page with the results of GetSitemap which is wrong because the default action is Get and not GetSitemap.

答:
Method names are not related to the api routes. You currently have two calls that are on the same route, which is the default controller route:

```<code>localhost:1234/api/Test/
</code>```

You can define the routes of methods by editing your HttpGet tags to the following:

```<code>[HttpGet("GetSitemap")]
public IActionResult GetSitemap()
{
    ...
}

[HttpGet("GetSiteName")]
public IActionResult GetSiteName()
{
    ...
}
</code>```

Body:
I created an ASP.NET CORE web application using Visual Studio 2017 Community. On it I have the usual controllers (Manage, Home, Account) plus a few of my own.

My API TestController has so far only two methods:

[HttpGet]
public IActionResult GetSitemap()
{
    Request.Headers.Clear();
    Request.Headers.Add("Accept", "text/xml");
    System.Xml.Linq.XDocument gsmXML = GoogleSitemap.AutoSeek(Domain);
    return new ContentResult()
        {
            StatusCode = 200,
            ContentType = "application/xml",
            Content = gsmXML.ToString()
        };
}

[HttpGet]
public IActionResult GetSiteName()
{
    return new OkObjectResult( "Test API");
}

Now, I wanted to also add a Web API to my web application, somebody suggests using an AREA for the API which is just fine. So I created an area named API for all API controllers.

   ~/Areas/
        API/
           Controllers/
               TestController.cs
           _ViewImports.cshtml
           _ViewStart.cshtml

And my route definition in Startup.cs looks like this:

app.UseMvc(routes =>
    routes.MapRoute(
                name: "areaRoute",
                template: "{area:exists}/{controller=Dashboard}/{action=Index}/{id?}");
    routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
});

The problem is when I make a request to my API method I get an empty page:

      localhost:1234/api/Test/GetSitemap

and for what I see the breakpoint does not trigger on the GetSitemap API method.
But when I change the request to:

      localhost:1234/api/Test/

Then I get an exception saying something about ambitguous because two methods matched. They both start with Get but the route specified Get (and Get alone) as the default so I do not see why GetSitemap and GetSiteName match.

If I remove the GetSiteName API method then the ambiguous exception does not happen but I am shown a page with the results of GetSitemap which is wrong because the default action is Get and not GetSitemap.

Body:
Method names are not related to the api routes. You currently have two calls that are on the same route, which is the default controller route:

localhost:1234/api/Test/

You can define the routes of methods by editing your HttpGet tags to the following:

[HttpGet("GetSitemap")]
public IActionResult GetSitemap()
{
    ...
}

[HttpGet("GetSiteName")]
public IActionResult GetSiteName()
{
    ...
}


问:
Access Microsoft dynamics online CRM through web api
I am new to microsoft & dynamics CRM online API... I am really getting confused how to access CRM online API's. I just implemented based on this and I see this works.

But is there any proper documentation to connect all the modules of dynamics online CRM through API... In the image, I have marked the things I need to have

答:
Here's a link to Microsoft's documentation on how to use the Web API.

From the docs, this is how you retrieve an entity:

```<code>GET [Organization URI]/api/data/v8.2/accounts(00000000-0000-0000-0000-000000000001)
</code>```

Replace accounts with the schema name of the entity you're trying to retrieve. The guid represents the id of the record you're retrieving. Replace 8.2 with your CRM's API version.

I'm assuming you want to retrieve an entity from your text: Need to have these things through API

Body:
Here's a link to Microsoft's documentation on how to use the Web API.

From the docs, this is how you retrieve an entity:

GET [Organization URI]/api/data/v8.2/accounts(00000000-0000-0000-0000-000000000001)

Replace accounts with the schema name of the entity you're trying to retrieve. The guid represents the id of the record you're retrieving. Replace 8.2 with your CRM's API version.

I'm assuming you want to retrieve an entity from your text: Need to have these things through API


问:
Creating security groups for a custom module in odoo 10
I have created a custom module on odoo 10. Now I wanted to create security groups with users where each group have a particular menu of my custom module. I've already asked this question and I followed the answers that I got but I did not get the results (I definitely messed up at some point but I can't see where, this is my first time working with odoo) so I ask again the question. Here's what I did:

I created a file security.xml in my security folder with contain the following

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="0">
   <!-- Creating a Group Category -->
   <record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>
   <!-- Adding a Group to the Group Category -->
   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="evaluation_subj" ref="evaluation subjective"/>
       <!-- Adding Rights of existing Groups -->
       <field name="implied_ids"
              eval="[(4, ref('base.group_system')),
     (4,ref('base.group_sale_manager'))]"/>
   </record>
  </data>
 </odoo>
</code>```

Then in the file pnc_menus.xml (I have a file called pnc_menus.xml where I created all of my menus) I added the groups field to this menu:

```<code><menuitem name="Parties Prenantes" id="pnc_evaluation_stakeholders"
         action="pncevaluation_partieprenante" parent="pnc_documents" sequence="40" groups="base.group_system"/>
</code>```

Then in csv file of my security folder I added this :

```<code>id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
eval_group,groupe_evaluation,pnc_evaluation_stakeholders,group_eval_subj,1,1,1,1
</code>```

When I updated my module I have an error saying "csv file could not be proccessed"

```<code>In the log file I have this:
`Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
 File "D:\Odoo 10.0\server\odoo\tools\convert.py", line 898, in convert_csv_import
    raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
</code>```

The link to my previous question.

答:
The logs are clear and mentioning the issue, there's problem with your csv file.

file pncevaluation\security\ir.model.access.csv could not be processed:

```<code>No records found for external id 'group_eval_subj' in the 'Group' field
</code>```

Here are some tips that may can help and solve your issue.

In your __openerp__.py file, make sure that security.xml is loading before the csv file containing the reference of records in it.

Double check ids in the CSV file, they must exactly same as defined in your xml files.

Check your CSV for any error. You can take help of spreadsheet viewer and see whether all columns are properly aligned or not.

Hope this will solve your problem.

PS:

Here's the updated code. With the fix in group record definition. Update your security.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="0">
   <!-- Creating a Group Category -->
   <record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>

   <!-- Adding a Group to the Group Category -->
   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="category_id" ref="evaluation_subj"/>
       <!-- Adding Rights of existing Groups -->
       <field name="implied_ids" eval="[(4, ref('base.group_system')), (4,ref('base.group_sale_manager'))]"/>
   </record>

  </data>
 </odoo>
</code>```

Following the answer of sfx,
The group sale manager is moved to module sale_team in odoo 10, so you need to change respective line as:

```<code><field name="implied_ids" eval="[(4, ref('base.group_system')), (4,ref('sales_team.group_sale_manager'))]"/>
</code>```

Thanks to sfx

Body:
I have created a custom module on odoo 10. Now I wanted to create security groups with users where each group have a particular menu of my custom module. I've already asked this question and I followed the answers that I got but I did not get the results (I definitely messed up at some point but I can't see where, this is my first time working with odoo) so I ask again the question. Here's what I did:

I created a file security.xml in my security folder with contain the following

<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="0">

   <record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>

   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="evaluation_subj" ref="evaluation subjective"/>

       <field name="implied_ids"
              eval="[(4, ref('base.group_system')),
     (4,ref('base.group_sale_manager'))]"/>
   </record>
  </data>
 </odoo>

Then in the file pnc_menus.xml (I have a file called pnc_menus.xml where I created all of my menus) I added the groups field to this menu:

<menuitem name="Parties Prenantes" id="pnc_evaluation_stakeholders"
         action="pncevaluation_partieprenante" parent="pnc_documents" sequence="40" groups="base.group_system"/>

Then in csv file of my security folder I added this :

id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
eval_group,groupe_evaluation,pnc_evaluation_stakeholders,group_eval_subj,1,1,1,1

When I updated my module I have an error saying "csv file could not be proccessed"

In the log file I have this:
`Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
 File "D:\Odoo 10.0\server\odoo\tools\convert.py", line 898, in convert_csv_import
    raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.

The link to my previous question.

Body:
The logs are clear and mentioning the issue, there's problem with your csv file.

file pncevaluation\security\ir.model.access.csv could not be processed:

No records found for external id 'group_eval_subj' in the 'Group' field

Here are some tips that may can help and solve your issue.

In your __openerp__.py file, make sure that security.xml is loading before the csv file containing the reference of records in it.

Double check ids in the CSV file, they must exactly same as defined in your xml files.

Check your CSV for any error. You can take help of spreadsheet viewer and see whether all columns are properly aligned or not.

Hope this will solve your problem.

PS:

Here's the updated code. With the fix in group record definition. Update your security.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="0">
   <!-- Creating a Group Category -->
   <record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>

   <!-- Adding a Group to the Group Category -->
   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="category_id" ref="evaluation_subj"/>
       <!-- Adding Rights of existing Groups -->
       <field name="implied_ids" eval="[(4, ref('base.group_system')), (4,ref('base.group_sale_manager'))]"/>
   </record>

  </data>
 </odoo>

Following the answer of sfx,
The group sale manager is moved to module sale_team in odoo 10, so you need to change respective line as:

<field name="implied_ids" eval="[(4, ref('base.group_system')), (4,ref('sales_team.group_sale_manager'))]"/>

Thanks to sfx


问:
Why is this C++ code execution so slow compared to java?
I recently wrote a computation-intensive algorithm in Java, and then translated it to C++. To my surprise the C++ executed considerably slower. I have now written a much shorter Java test program, and a corresponding C++ program - see below. My original code featured a lot of array access, as does the test code. The C++ takes 5.5 times longer to execute (see comment at end of each program).

Conclusions after 1st 21 comments below ...

Test code:

g++ -o ... Java 5.5 times faster

g++ -O3 -o ... Java 2.9 times faster

g++ -fprofile-generate -march=native -O3 -o ... (run, then g++ -fprofile-use etc) Java 1.07 times faster.

My original project (much more complex than test code):

Java 1.8 times faster

C++ 1.9 times faster

C++ 2 times faster

```<code>Software environment:
    Ubuntu 16.04 (64 bit).
    Netbeans 8.2 / jdk 8u121 (java code executed inside netbeans)
    g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
    Compilation: g++ -o cpp_test cpp_test.cpp
</code>```

Java code:

public class JavaTest {
    public static void main(String[] args) {
        final int ARRAY_LENGTH = 100;
        final int FINISH_TRIGGER = 100000000;
        int[] intArray = new int[ARRAY_LENGTH];
        for (int i = 0; i < ARRAY_LENGTH; i++) intArray[i] = 1;
        int i = 0;
        boolean finished = false;
        long loopCount = 0;
        System.out.println("Start");
        long startTime = System.nanoTime();
        while (!finished) {
            loopCount++;
            intArray[i]++;
            if (intArray[i] >= FINISH_TRIGGER) finished = true;
            else if (i <(ARRAY_LENGTH - 1)) i++;
            else i = 0;
        }
        System.out.println("Finish: " + loopCount + " loops; " +
            ((System.nanoTime() - startTime)/1e9) + " secs");
        // 5 executions in range 5.98 - 6.17 secs (each 9999999801 loops)
    }
}
```

<p>C++ code:</p>

<pre class="lang-cpp prettyprint-override"><code>//cpp_test.cpp:
#include <iostream>
#include <sys/time.h>
int main() {
    const int ARRAY_LENGTH = 100;
    const int FINISH_TRIGGER = 100000000;
    int *intArray = new int[ARRAY_LENGTH];
    for (int i = 0; i < ARRAY_LENGTH; i++) intArray[i] = 1;
    int i = 0;
    bool finished = false;
    long long loopCount = 0;
    std::cout << "Start\n";
    timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    long long startTime = (1000000000*ts.tv_sec) + ts.tv_nsec;
    while (!finished) {
        loopCount++;
        intArray[i]++;
        if (intArray[i] >= FINISH_TRIGGER) finished = true;
        else if (i < (ARRAY_LENGTH - 1)) i++;
        else i = 0;
    }
    clock_gettime(CLOCK_REALTIME, &ts);
    double elapsedTime =
        ((1000000000*ts.tv_sec) + ts.tv_nsec - startTime)/1e9;
    std::cout << "Finish: " << loopCount << " loops; ";
    std::cout << elapsedTime << " secs\n";
    // 5 executions in range 33.07 - 33.45 secs (each 9999999801 loops)
}
</code>```

答:
The only time I could get the C++ program to outperform Java was when using profiling information. This shows that there's something in the runtime information (that Java gets by default) that allows for faster execution.

There's not much going on in your program apart from a non-trivial if statement. That is, without analysing the entire program, it's hard to predict which branch is most likely. This leads me to believe that this is a branch misprediction issue. Modern CPUs do instruction pipelining which allows for higher CPU throughput. However, this requires a prediction of what the next instructions to execute are. If the guess is wrong, the instruction pipeline must be cleared out, and the correct instructions loaded in (which takes time).

At compile time, the compiler doesn't have enough information to predict which branch is most likely. CPUs do a bit of branch prediction as well, but this is generally along the lines of loops loop and ifs if (rather than else).

Java, however, has the advantage of being able to use information at runtime as well as compile time. This allows Java to identify the middle branch as the one that occurs most frequently and so have this branch predicted for the pipeline.

Body:
I recently wrote a computation-intensive algorithm in Java, and then translated it to C++. To my surprise the C++ executed considerably slower. I have now written a much shorter Java test program, and a corresponding C++ program - see below. My original code featured a lot of array access, as does the test code. The C++ takes 5.5 times longer to execute (see comment at end of each program).

Conclusions after 1st 21 comments below ...

Test code:

g++ -o ... Java 5.5 times faster

g++ -O3 -o ... Java 2.9 times faster

g++ -fprofile-generate -march=native -O3 -o ... (run, then g++ -fprofile-use etc) Java 1.07 times faster.

My original project (much more complex than test code):

Java 1.8 times faster

C++ 1.9 times faster

C++ 2 times faster

Software environment:
    Ubuntu 16.04 (64 bit).
    Netbeans 8.2 / jdk 8u121 (java code executed inside netbeans)
    g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
    Compilation: g++ -o cpp_test cpp_test.cpp

Java code:

public class JavaTest {
    public static void main(String[] args) {
        final int ARRAY_LENGTH = 100;
        final int FINISH_TRIGGER = 100000000;
        int[] intArray = new int[ARRAY_LENGTH];
        for (int i = 0; i < ARRAY_LENGTH; i++) intArray[i] = 1;
        int i = 0;
        boolean finished = false;
        long loopCount = 0;
        System.out.println("Start");
        long startTime = System.nanoTime();
        while (!finished) {
            loopCount++;
            intArray[i]++;
            if (intArray[i] >= FINISH_TRIGGER) finished = true;
            else if (i <(ARRAY_LENGTH - 1)) i++;
            else i = 0;
        }
        System.out.println("Finish: " + loopCount + " loops; " +
            ((System.nanoTime() - startTime)/1e9) + " secs");
        // 5 executions in range 5.98 - 6.17 secs (each 9999999801 loops)
    }
}

C++ code:

//cpp_test.cpp:
#include <iostream>
#include <sys/time.h>
int main() {
    const int ARRAY_LENGTH = 100;
    const int FINISH_TRIGGER = 100000000;
    int *intArray = new int[ARRAY_LENGTH];
    for (int i = 0; i < ARRAY_LENGTH; i++) intArray[i] = 1;
    int i = 0;
    bool finished = false;
    long long loopCount = 0;
    std::cout << "Start\n";
    timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    long long startTime = (1000000000*ts.tv_sec) + ts.tv_nsec;
    while (!finished) {
        loopCount++;
        intArray[i]++;
        if (intArray[i] >= FINISH_TRIGGER) finished = true;
        else if (i < (ARRAY_LENGTH - 1)) i++;
        else i = 0;
    }
    clock_gettime(CLOCK_REALTIME, &ts);
    double elapsedTime =
        ((1000000000*ts.tv_sec) + ts.tv_nsec - startTime)/1e9;
    std::cout << "Finish: " << loopCount << " loops; ";
    std::cout << elapsedTime << " secs\n";
    // 5 executions in range 33.07 - 33.45 secs (each 9999999801 loops)
}


问:
JS decrement existing array values- NaN error
I have some troubles with NaN values in my array.
I can display that table, but after decrement opration(code at the bottom) when I want display actualized values I get all NaN. I don't have any idea how to fix that. I appreciate any help.

script.js

```<code>[![var result = "<table border=1>";
    for (var i = 0; i < wymiar; i++)
    {
        result += "<tr>";
        for (var j = 0; j < wymiar; j++)
        {
            tablica\[i, j\] = Math.floor((Math.random() * 10) + 1);
            result += "<td>"+tablica\[i,j\]+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";
    document.getElementById("macierzLosowa").innerHTML = result;][1]][1]

var result1 = "<table border=1>";
    for (var i = 0; i < wymiar; i++)
    {
        result1 += "<tr>";
        for (var j = 0; j < wymiar; j++)
        {
            if (tablica[i, j] < minWWierszu[i])
            {
                minWWierszu[i] = tablica[i, j];
            }
        }
        for (var j = 0; j < wymiar; j++)
        {
            tablica[i, j] -= minWWierszu[i];
            result1 += "<td>"+tablica[i,j]+"</td>";
        }
        result1 += "</tr>";
    }
    result1 += "</table>";
    document.getElementById("NajmniejszeWiersz").innerHTML = result1;
</code>```

index.html

```<code><div id="NajmniejszeWiersz"></div>
</code>```

Live example: https://jsfiddle.net/RadoszSzymon/aydr6bcm/2/

答:
You need to initialize the minWWierszu array with numeric values.
Hope this help.</p>

Body:
I have some troubles with NaN values in my array.
I can display that table, but after decrement opration(code at the bottom) when I want display actualized values I get all NaN. I don't have any idea how to fix that. I appreciate any help.

script.js

[![var result = "
";
    for (var i = 0; i < wymiar; i++)
    {
        result += "
";
        for (var j = 0; j < wymiar; j++)
        {
            tablica\[i, j\] = Math.floor((Math.random() * 10) + 1);
            result += ""+tablica\[i,j\]+"	";
        }
        result += "
";
    }
    result += "
";
    document.getElementById("macierzLosowa").innerHTML = result;][1]][1]

var result1 = "
";
    for (var i = 0; i < wymiar; i++)
    {
        result1 += "
";
        for (var j = 0; j < wymiar; j++)
        {
            if (tablica[i, j] < minWWierszu[i])
            {
                minWWierszu[i] = tablica[i, j];
            }
        }
        for (var j = 0; j < wymiar; j++)
        {
            tablica[i, j] -= minWWierszu[i];
            result1 += ""+tablica[i,j]+"	";
        }
        result1 += "
";
    }
    result1 += "
";
    document.getElementById("NajmniejszeWiersz").innerHTML = result1;

index.html

Live example: https://jsfiddle.net/RadoszSzymon/aydr6bcm/2/


问:
Anchor link to another specfic tab's content from another page
Question. I have some tabs and I would like to be able to link back to a specific tab from another page and make it the active tab. How should I do it?

HTML:

```<code><div id="tabs-container">
            <ul class="tabs-menu">
                <li class="current"><a href="#tab-1"><strong>Tab 1</strong></a></li>
                <li><a href="#tab-2"><strong>Tab 2</strong></a></li>
                <li><a href="#tab-3"><strong>Tab 3</strong></a></li>
                <li><a href="#tab-4"><strong>Tab 4</strong></a></li>
            </ul>

            <div class="tab">
                <div id="tab-1" class="tab-content">Content1</div>
                <div id="tab-2" class="tab-content">Content2</div>
                <div id="tab-3" class="tab-content">Content3</div>
                <div id="tab-4" class="tab-content">Content4</div>
            </div>

</div>
</code>```

JavaScript

```<code>$(document).ready(function() {
    $(".tabs-menu a").click(function(event) {
        event.preventDefault();
        $(this).parent().addClass("current");
        $(this).parent().siblings().removeClass("current");
        var tab = $(this).attr("href");
        $(".tab-content").not(tab).css("display", "none");
        $(tab).fadeIn();
    });
});
</code>```

Thanks in advance :)

答:
You can use URL parameters for that :

```<code>function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

$(function(){
    var toGet = getUrlParameter('tab');
    $(".tab-content").not('#'+toGet).css("display", "none");
    $("#"+toGet).fadeIn();
});
</code>```

With a URL like http://....?tab=tab-1

Body:
Question. I have some tabs and I would like to be able to link back to a specific tab from another page and make it the active tab. How should I do it?

HTML:

Tab 1

Tab 2

Tab 3

Tab 4

Content1

Content2

Content3

Content4

JavaScript

$(document).ready(function() {
    $(".tabs-menu a").click(function(event) {
        event.preventDefault();
        $(this).parent().addClass("current");
        $(this).parent().siblings().removeClass("current");
        var tab = $(this).attr("href");
        $(".tab-content").not(tab).css("display", "none");
        $(tab).fadeIn();
    });
});

Thanks in advance :)

Body:
You can use URL parameters for that :

function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

$(function(){
    var toGet = getUrlParameter('tab');
    $(".tab-content").not('#'+toGet).css("display", "none");
    $("#"+toGet).fadeIn();
});

With a URL like http://....?tab=tab-1


问:
How to use python-request to post a file on a Rails App
I have a Rails app server. I want to build a Python client that uploads an image.

I want to do something like this:

```<code>def add_photo(entry_id, image_path):

    return requests.post(
        url     = URL,
        headers = HEADER,
        json    = {
            'entry': {
                'entry_id': entry_id,
            }
        },
        files   = {
            "entry['photo']": (
                os.path.basename(image_path),
                open(image_path, 'rb'),
                'image/jpg',
                {'Expires': '0'}
            )
        }
    )
</code>```

I need the image nested into the 'entry' key. The above code does not work because the key "entry['photo']" isn't valid.

How do I do this?

Thank you so much for your help!

答:
Comment: I need the key of the image to be entry['photo'].

What you want to do results in invalid dict. The following is from docs.python-requests.org

```<code>files = {'photo': ('test.jpg', open('test.jpg', 'rb'), 'image/jpg', {'entry_id': entry_id, 'Expires': '0'})}
</code>```

From SO Answer Upload Image using POST form data in Python-requests

```<code>files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
</code>```

Body:
I have a Rails app server. I want to build a Python client that uploads an image.

I want to do something like this:

def add_photo(entry_id, image_path):

    return requests.post(
        url     = URL,
        headers = HEADER,
        json    = {
            'entry': {
                'entry_id': entry_id,
            }
        },
        files   = {
            "entry['photo']": (
                os.path.basename(image_path),
                open(image_path, 'rb'),
                'image/jpg',
                {'Expires': '0'}
            )
        }
    )

I need the image nested into the 'entry' key. The above code does not work because the key "entry['photo']" isn't valid.

How do I do this?

Thank you so much for your help!

Body:
Comment: I need the key of the image to be entry['photo'].

What you want to do results in invalid dict. The following is from docs.python-requests.org

files = {'photo': ('test.jpg', open('test.jpg', 'rb'), 'image/jpg', {'entry_id': entry_id, 'Expires': '0'})}

From SO Answer Upload Image using POST form data in Python-requests

files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)


问:
Find object by id in an array of JSON objects with Twig
I am being passed an array that unfortunately I cannot restructure:

```<code>"options": [
            {"name":"namea","text":"valuea"},
            {"name":"nameb","text":"valueb"},
            {"name":"namec","text":"valuec"},
            {"name":"named","text":"valued"}
           ]
</code>```

I need to be able to find the object with the name equal to namea, nameb, namec, etc. and then produce the appropriate text. I tried the following and few other variations of that but could not get it to work:

```<code>{% for item in event.options %}
    {% if item.name == "nameb" %}
        {{ item.text|capitalize }}
    {% endif %}
{% endfor %}
</code>```

Thanks in advance for any help.

Edit:  I basically only have access to a text box to input HTML and Twig. I do not have access to framework, custom extensions, etc.

Edit: JSON with exact formatting:

```<code>{
"source": "TEST.COM",
"trigger": "test",
"options": [{
            "name":"test_date",
            "value":"31-05-2017"
            },
            {
            "name":"test_number",
            "value":"9081003"
            },
            {
            "name":"test_test",
            "value":"9asd003"
            },
            {
            "name":"Name",
            "value":"Todd"
            },
            {
            "name":"test_other",
            "value":"kslkjsfd"
            },
            {
            "name":"test_help",
            "value":"908sdf3"
            }]
}
</code>```

答:
This is going to be very hacky either way (I feel the javascript way as mentioned in the comments would still be less hacky).

However as its multilined we could write a basic parser like thing (this is by no means bullet proof and fails if the content has a ", or the structure changes or whatever changes to be honest):

```<code>{# create an array of lines #}
{% set event = event|split('\n') %}

{# an array to hold our options #}
{% set options = [] %}

{# using a bool to track if we are inside the options part #}
{% set inOptions = false %}

{# this holds the name of the last name value we have passed #}
{% set currentKey = '' %}

{# go through each line #}
{% for line in event %}

    {# if we are inside the options tag do our magic #}
    {% if inOptions %}
        {# check if the line starts with "name": and track the current key name #}
        {# or check if it starts with "value": and set the current key to that value #}
        {% if line matches '/"name":/' %}
            {# split line on the double quotes and get the last bit #}
            {% set currentKey = line|split('"') %}
            {# cant get the array index piped in one go idk.. #}
            {% set currentKey = currentKey[3] %}
        {% elseif line matches '/"value":/i' %}
            {% set currentValue = line|split('"') %}
            {% set options = options|merge({(currentKey): currentValue[3]}) %}
        {% elseif line matches '/\s*}]/' %}
            {% set inOptions = false %}
        {% endif %}
    {% endif %}

    {# check for the options sectioning start #}
    {% if line matches '/^"options/' %}
        {% set inOptions = true %}
    {% endif %}
{% endfor %}

{{ dump(options) }}
</code>```

This returns in my dump (which you didn't have so you cant see):

```<code>array:6 [▼
  "test_date" => "31-05-2017"
  "test_number" => "9081003"
  "test_test" => "9asd003"
  "Name" => "Todd"
  "test_other" => "kslkjsfd"
  "test_help" => "908sdf3"
]
</code>```

As an actual array where you can then call options.test_date but all this is super hacky, it still can be improved but twig is not made for it and the syntax gets so clunky its hard to maintain.

Body:
I am being passed an array that unfortunately I cannot restructure:

"options": [
            {"name":"namea","text":"valuea"},
            {"name":"nameb","text":"valueb"},
            {"name":"namec","text":"valuec"},
            {"name":"named","text":"valued"}
           ]

I need to be able to find the object with the name equal to namea, nameb, namec, etc. and then produce the appropriate text. I tried the following and few other variations of that but could not get it to work:

{% for item in event.options %}
    {% if item.name == "nameb" %}
        {{ item.text|capitalize }}
    {% endif %}
{% endfor %}

Thanks in advance for any help.

Edit:  I basically only have access to a text box to input HTML and Twig. I do not have access to framework, custom extensions, etc.

Edit: JSON with exact formatting:

{
"source": "TEST.COM",
"trigger": "test",
"options": [{
            "name":"test_date",
            "value":"31-05-2017"
            },
            {
            "name":"test_number",
            "value":"9081003"
            },
            {
            "name":"test_test",
            "value":"9asd003"
            },
            {
            "name":"Name",
            "value":"Todd"
            },
            {
            "name":"test_other",
            "value":"kslkjsfd"
            },
            {
            "name":"test_help",
            "value":"908sdf3"
            }]
}

Body:
This is going to be very hacky either way (I feel the javascript way as mentioned in the comments would still be less hacky).

However as its multilined we could write a basic parser like thing (this is by no means bullet proof and fails if the content has a ", or the structure changes or whatever changes to be honest):

{# create an array of lines #}
{% set event = event|split('\n') %}

{# an array to hold our options #}
{% set options = [] %}

{# using a bool to track if we are inside the options part #}
{% set inOptions = false %}

{# this holds the name of the last name value we have passed #}
{% set currentKey = '' %}

{# go through each line #}
{% for line in event %}

    {# if we are inside the options tag do our magic #}
    {% if inOptions %}
        {# check if the line starts with "name": and track the current key name #}
        {# or check if it starts with "value": and set the current key to that value #}
        {% if line matches '/"name":/' %}
            {# split line on the double quotes and get the last bit #}
            {% set currentKey = line|split('"') %}
            {# cant get the array index piped in one go idk.. #}
            {% set currentKey = currentKey[3] %}
        {% elseif line matches '/"value":/i' %}
            {% set currentValue = line|split('"') %}
            {% set options = options|merge({(currentKey): currentValue[3]}) %}
        {% elseif line matches '/\s*}]/' %}
            {% set inOptions = false %}
        {% endif %}
    {% endif %}

    {# check for the options sectioning start #}
    {% if line matches '/^"options/' %}
        {% set inOptions = true %}
    {% endif %}
{% endfor %}

{{ dump(options) }}

This returns in my dump (which you didn't have so you cant see):

array:6 [▼
  "test_date" => "31-05-2017"
  "test_number" => "9081003"
  "test_test" => "9asd003"
  "Name" => "Todd"
  "test_other" => "kslkjsfd"
  "test_help" => "908sdf3"
]

As an actual array where you can then call options.test_date but all this is super hacky, it still can be improved but twig is not made for it and the syntax gets so clunky its hard to maintain.


问:
Layering objects in Android Studio
I'm quite new to this whole Android Studio and all, but I'm quickly getting used to it all.

Now here's my problem:

I have my main Activity with two screen-filling buttons and I want a checkbox on top of the first button.

I've looked all around the Internet, but I couldn't find a single clue.

EDIT: Messing with the order of the objects doesn't work.

This is my XML code (I haven't filled in the functionality, yet):

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ggblbl.example.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/button_one"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="8dp"
        android:text="@string/button_two"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline"
        app:layout_constraintVertical_bias="0.0" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/checkbox"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginRight="150dp"
        android:layout_marginLeft="150dp"
        android:layout_marginBottom="20dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline" />
</android.support.constraint.ConstraintLayout>
</code>```

PS: I don't know if this helps, but I use API 15 and Android Studio 2.3.2.

EDIT: I've got this

But I want this

答:
I finally chose to abandon the use of a checkbox, as I guess it's hard-coded in that checkboxes are behind buttons.

I've found that the toggleButton does what I need too.
This one is in front of the button.

Title: Layering objects in Android Studio

Body:
I'm quite new to this whole Android Studio and all, but I'm quickly getting used to it all.

Now here's my problem:

I have my main Activity with two screen-filling buttons and I want a checkbox on top of the first button.

I've looked all around the Internet, but I couldn't find a single clue.

EDIT: Messing with the order of the objects doesn't work.

This is my XML code (I haven't filled in the functionality, yet):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ggblbl.example.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/button_one"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="8dp"
        android:text="@string/button_two"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline"
        app:layout_constraintVertical_bias="0.0" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/checkbox"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginRight="150dp"
        android:layout_marginLeft="150dp"
        android:layout_marginBottom="20dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline" />
</android.support.constraint.ConstraintLayout>

PS: I don't know if this helps, but I use API 15 and Android Studio 2.3.2.

EDIT: I've got this

But I want this


问:
How to get multiple inputs of String when the number of input string is n
I am working with a question for that we need to get n string inputs how to store then in n string variables.

I tried with array storing the string in each elements

Is there any other way in java ?

答:
Well it depends on how you are getting that N, if N is first input then you can take that input and make array of that size like:

```<code>int n = scanner.nextInt();
String[] array = new String[n];
</code>```

Or if you just want to add until X input which will stop it then you can use arraylist like this:

```<code>List<String> array = new ArrayList<>();
</code>```

Collections are dynamic so you don't need to specify number of elements in advance. You simple add elements:

array.add("somestring"); or array.add(stringVariableName);

Body:
Well it depends on how you are getting that N, if N is first input then you can take that input and make array of that size like:

int n = scanner.nextInt();
String[] array = new String[n];

Or if you just want to add until X input which will stop it then you can use arraylist like this:

List<String> array = new ArrayList<>();

Collections are dynamic so you don't need to specify number of elements in advance. You simple add elements:

array.add("somestring"); or array.add(stringVariableName);


问:
Eclipse IDE: How to zoom in on text?
I want the same behaviour Firefox has, when you use the scroll button in the mouse to zoom in and out on the current view.
Is there something like it for eclipse?</p>

答: To zoom on Eclipse you can use : CTRL SHIFT + OR -

Title: Eclipse IDE: How to zoom in on text?


问:
Add event to fullCalendar integrated with spring MVC by ajax request
I want to add new event to fullCalendar and send this event as a json object to the server side which is springMVC by ajax request and every time the request is send ,the response is "400 bad request"

the ajax request

$.ajax({
      type: "POST",
      url: "insertSession",
      contentType: 'application/json',
      data: dataObject,
      success: function (result) {
      $('#modal').modal('toggle');
      },
      error: function (request, error) {
        console.log(arguments);
        alert(" Can't Save your Event: " + error);
      }});

the dataObject = { id: null, start: "05/29/2017 12:00:00 am", durationInMinutes: "159", room: "1", sessionType: "2", course: "2", event: null }

the business logic

@RequestMapping(value = "/insertSession", method = RequestMethod.POST)
    public String addSession(@RequestBody SessionDTO session, BindingResult result) {
// do some code
}

SessionDTO

```<code>`class SessionDTO {
    private Integer id;
    private String start;
   private int durationInMinutes;
private int course;
private int room;
private int event;
private int sessionType;
// setter and getter method}`
</code>```

答:
HTTP 400 bad request is usually seen when browser/clients sent some data to server and servers couldn't understand it. Clients shouldn't repeat the request without modifications.

In your case,

dataObject = { id: null, start: "05/29/2017 12:00:00 am",
  durationInMinutes: "159", room: "1", sessionType: "2", course: "2",
  event: null }

is being sent to server and it had problems understanding the data.

Javascript has a utility function to exchange data to/from the server.
JSON.stringify(dataObject) will convert the javascript object to a string in JSON notion.

Hope this helps..!!!

Body:
I want to add new event to fullCalendar and send this event as a json object to the server side which is springMVC by ajax request and every time the request is send ,the response is "400 bad request"

the ajax request

$.ajax({
      type: "POST",
      url: "insertSession",
      contentType: 'application/json',
      data: dataObject,
      success: function (result) {
      $('#modal').modal('toggle');
      },
      error: function (request, error) {
        console.log(arguments);
        alert(" Can't Save your Event: " + error);
      }});

the dataObject = { id: null, start: "05/29/2017 12:00:00 am", durationInMinutes: "159", room: "1", sessionType: "2", course: "2", event: null }

the business logic

@RequestMapping(value = "/insertSession", method = RequestMethod.POST)
    public String addSession(@RequestBody SessionDTO session, BindingResult result) {
// do some code
}

SessionDTO

`class SessionDTO {
    private Integer id;
    private String start;
   private int durationInMinutes;
private int course;
private int room;
private int event;
private int sessionType;
// setter and getter method}`


问:
Read POST form in Angular submitted by external websites
I am developing a website with Java for the backend and Angular for frontend. There is a situation when some external websites may send data to my website using POST form. For instance,

▼ General

        Request URL: https://myangularwebsite/

        Request Method: POST

        ...

▼ Request Headers

        Content-Type: application/x-www-form-urlencoded

        Host: myangularwebsite

        Origin: https://externalwebsite

        Referer: https://externalwebsite/send.form?id=0

        ...

▼ Form data

        ID: 0000000

        TIME: 2017.06.04 11:53:58

        SIGNATURE: ...geirgmGKFGJWR...

        ...

Now, I need to capture the form in Angular somehow, send/redirect it to the backend to validate the signature and return the answer back to Angular to proceed working with this website.
I tried posting to my website to test how it might work using Postman, but get Cannot POST /.

I know how to work with GET and URL query parameters in Angular but I think I need to process a POST request based on headers I see with Chrome DevTools 'Network' section when coming from externalwebsite to myangularwebsite.

Should I dedicate a route in the backend and expose it, for example, .../api/external in my backend and tell these websites to use this link instead of directly posting to my Angular website's homepage?

I have already read another question ( How to read form post data in Angular 2 typescript? ) which is somewhat similar but I do not think using PHP is the right way for me as the website I am developing already has an older version written in PHP.

答:
The answer at the link you provided is correct: you cannot do it in just Javascript, you have to use some server-side code. They mention PHP as an example, but any server-side component will do, and as you have Java at your backend, let it be Java.

So, when an HTTP request comes from an external site, you have to use a server-side component to handle it. But there are some options.

If this request is made using your user browser (so it is something like a redirect, but using a POST method), then you can do the following: catch that request at your backend, output some javascript with some data to the user's browser and process that data in your Angular code. Or this could be a redirection to your main Angular entry point, it is up to you.

If this request is made by some other means (for example, this is a server-to-server request made with with curl like a notification from a Credit Card processing), with no browser involved, then you don't need to have any Javascript (Angular or whatever it could be) as they are needed for browser only. In this case you just handle the request at your server-side.

In both cases, it seems plausible to dedicate some special endpoint for handling (or landing) such externally-originated requests.


问:
How to clone the panel control to the same form dynamically in vb.net
My need is to generate the copy of existing panel under the same panel in my form

I have written some code that would do my desired work but it's not going to work according to my needs, but It destroy the main panel and generate a copy, but I don't want to destroy first one, I want to keep all the panels...

This is the function that I've called at button "+" click event

```<code>Friend Function AddNewPanel() As System.Windows.Forms.Panel
        Dim Pnl As New System.Windows.Forms.Panel
        Pnl = MediPanel  'This is the main panel that I want to copy
        Pnl.Top = 500
        'Pnl.Left = 100
        ParentPanel.Controls.Add(Pnl)  'ParentPanel in which I want to generate a copy
        Return Pnl
    End Function
</code>```

This is what I exactly want but This is actually happened

So, I want to generate copy of panel as I press "+" button and also earlier panels should not be destroyed..

答:
Generate a new control dynamically. When your form loads, set a tag to your button indicating the bottom position of the original panel.

```<code>button1.tag = Medipanel.Bottom
</code>```

When you click the + button

```<code>Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click

   Dim new_panel As New Panel
   With new_panel
     .Location = New Point(Medipanel.Left, Cint(button1.tag) + 5)
     .Size = New Size (Medipanel.Width, Medipanel.Height)
     ....
   End With

   Dim some_label = New Label
   With some_label
    .AutoSize = True
    .Name = "label"
    .Location = New Point(0, 0)  ''' Position in the new panel
    .Text = "Some Text"
   End With
   new_panel.Controls.Add(some_label)

   Dim some_button as New Button
   With some_button
        .Tag = "some value" '''' A way to Identify the button if clicked
        ....
        ....
        AddHandler some_button.click, AddressOf some_button_click
        '''' The Sub that determines what happens when that button is clicked.
   End With

   ....
   ....

   ParentPanel.Controls.Add(new_panel)

   button1.tag = new_panel.bottom '''' Set the bottom position of the last panel added.

End Sub
</code>```

When the new button is clicked:

```<code>Private Sub some_button_click(sender As Object, e As EventArgs)

   Dim sending_button As Button = DirectCast(sender, Button)
   Dim ref As String = DirectCast(sending_button.Tag, String)

   ''''Perform your stuff here

End Sub
</code>```

This will only add a new control and not destroy old ones.

Body:
My need is to generate the copy of existing panel under the same panel in my form

I have written some code that would do my desired work but it's not going to work according to my needs, but It destroy the main panel and generate a copy, but I don't want to destroy first one, I want to keep all the panels...

This is the function that I've called at button "+" click event

Friend Function AddNewPanel() As System.Windows.Forms.Panel
        Dim Pnl As New System.Windows.Forms.Panel
        Pnl = MediPanel  'This is the main panel that I want to copy
        Pnl.Top = 500
        'Pnl.Left = 100
        ParentPanel.Controls.Add(Pnl)  'ParentPanel in which I want to generate a copy
        Return Pnl
    End Function

This is what I exactly want but This is actually happened

So, I want to generate copy of panel as I press "+" button and also earlier panels should not be destroyed..

Body:
Generate a new control dynamically. When your form loads, set a tag to your button indicating the bottom position of the original panel.

button1.tag = Medipanel.Bottom

When you click the + button

Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click

   Dim new_panel As New Panel
   With new_panel
     .Location = New Point(Medipanel.Left, Cint(button1.tag) + 5)
     .Size = New Size (Medipanel.Width, Medipanel.Height)
     ....
   End With

   Dim some_label = New Label
   With some_label
    .AutoSize = True
    .Name = "label"
    .Location = New Point(0, 0)  ''' Position in the new panel
    .Text = "Some Text"
   End With
   new_panel.Controls.Add(some_label)

   Dim some_button as New Button
   With some_button
        .Tag = "some value" '''' A way to Identify the button if clicked
        ....
        ....
        AddHandler some_button.click, AddressOf some_button_click
        '''' The Sub that determines what happens when that button is clicked.
   End With

   ....
   ....

   ParentPanel.Controls.Add(new_panel)

   button1.tag = new_panel.bottom '''' Set the bottom position of the last panel added.

End Sub

When the new button is clicked:

Private Sub some_button_click(sender As Object, e As EventArgs)

   Dim sending_button As Button = DirectCast(sender, Button)
   Dim ref As String = DirectCast(sending_button.Tag, String)

   ''''Perform your stuff here

End Sub

This will only add a new control and not destroy old ones.


问:
GridView: ImageViews/ImageButtons not shown after inflating layout
I try to display tiles within a GridView using a custom item layout. Each has a TextView as well as three image buttons below.
The XML item layout looks like this. Within the Android Studio designer, the layout looks exactly the way I want it.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <LinearLayout
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_edit" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_play" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_remove" />
    </LinearLayout>
</LinearLayout>
</code>```

However, after inflating within my GridView adapter, the TextView is visible but the three image views are not shown. Same happens when I use image button. Curiously, when I replace the three images by a normal button, it works.

Adapter code:

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(R.layout.layout_subject, parent, false);
    float scale = context.getResources().getDisplayMetrics().density;
    v.setLayoutParams(new ConstraintLayout.LayoutParams((int)(180 * scale + .5f), (int)(180 * scale + .5f)));

    return v;
}
</code>```

The defined tile size 180 x 180 is indeed large enough, at runtime, there's plenty of empty space where the images should be.

Any idea what could be wrong?

Thank you in advance

答:
The image assets you are using are vectors and you need to make some changes in your build.gradle file. add

```<code> vectorDrawables.useSupportLibrary = true
</code>```

under defaultConfig  in your build.gradle file.

```<code>android {
  defaultConfig {
     ...
     ...
     vectorDrawables.useSupportLibrary = true  //add this
   }
}
</code>```

In your Activity add this line of code

```<code> AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
</code>```

now you can set vector using app:srcCompat instead of android:src.

Body:
I try to display tiles within a GridView using a custom item layout. Each has a TextView as well as three image buttons below.
The XML item layout looks like this. Within the Android Studio designer, the layout looks exactly the way I want it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <LinearLayout
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_edit" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_play" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_remove" />
    </LinearLayout>
</LinearLayout>

However, after inflating within my GridView adapter, the TextView is visible but the three image views are not shown. Same happens when I use image button. Curiously, when I replace the three images by a normal button, it works.

Adapter code:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(R.layout.layout_subject, parent, false);
    float scale = context.getResources().getDisplayMetrics().density;
    v.setLayoutParams(new ConstraintLayout.LayoutParams((int)(180 * scale + .5f), (int)(180 * scale + .5f)));

    return v;
}

The defined tile size 180 x 180 is indeed large enough, at runtime, there's plenty of empty space where the images should be.

Any idea what could be wrong?

Thank you in advance

Body:
The image assets you are using are vectors and you need to make some changes in your build.gradle file. add

 vectorDrawables.useSupportLibrary = true

under defaultConfig  in your build.gradle file.

android {
  defaultConfig {
     ...
     ...
     vectorDrawables.useSupportLibrary = true  //add this
   }
}

In your Activity add this line of code

 AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

now you can set vector using app:srcCompat instead of android:src.


问:
Snom 7xx devices bulk setup through FreePBX with custom template
Can someone teach me how to deploy multilple Snom 7xx series desktop mobiles in bulk (like 150) at once using FreePBX system with custom device settings (templates). As I am very new to this. Specially setting templates and where to place in Centos 6.2 FreePBX SYSTEM to auto provission...etc.
I asked so much in one question

Yes here is the updated question detail:
I have created one extension for snom710 model, I want to make a template settings using that test extension but after clicking on edit template it shows some files, don't know which one to edit and which one serve for what purpose. And also if I want to control some of the settings using PBX then how to make that working, say for example <user_host idx="1" perm="">{$server.ip.1}</user_host>  what is this {$server.ip.1} I have seen this in my other snom model configured by freelancer for testing purpose.
attached is the screen shot.

Thanks.

答:
You can use the End Point Manager (EPM) to bulk configure your devices. It is a commercial modules.

Alternatively, if you want to do it yourself, you can build an auto provisioning server and configure your devices to download the config from the server. All Snom devices support auto provisioning out of the box. You can also put the auto provisioning server IP into DHCP option 66 so that your device can pick up the config automatically as soon as you connects it into your network.

A complete user guide can be found from the following. https://wiki.freepbx.org/display/FPG/EPM-Admin+User+Guide

Snom devices auto provisioning user guide. http://wiki.snom.com/Category:Auto_Provisioning

------------------------------------------------------------EDIT----------------------------------------------------------------

Definition of User host

Specify the IP or DNS address of the registrar/proxy where you want to register this account. After a successful registration, the registrar knows how to reach this speciﬁc identity and can route requests (e.g., incoming calls) from other registered parties to this phone.

http://wiki.snom.com/Settings/user_host

Definitions of all other settings can be found from their wiki.


问:
Page system in back end or front end
I want make a page system to a data base values, what is correct?

1-) Get all values of backend and create a page system with front end.

2-) Get only values that will be show in select page on back end?

My concern is with website performance

I'm using Angular in front, php on back end, and MySql database.

答:
I would use the option 2 because:

You won´t have in your front end data that you don´t need

Your front end will use less memory (as you have less data)

You will have less data to comunicate

You will have less security problems

Your front end will be faster

......

Well, i think that if you don´t need the data in your front end, just don´t send it

Title: Page system in back end or front end


问:
Getting a simple Spring JMS client acknowledge to work
Just starting to get my head around getting JMS ActiveMQ Acknowledgements working in Spring. So far I have a consumer working perfectly, with the exception that when I don't acknowledge the message, it's still taken from the queue (I expect it to stay there or end in a dead letter queue).

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd">

    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"
    p:brokerURL="failover://(tcp://jms1:61616,tcp://jms2:61616)?randomize=false&jms.redeliveryPolicy.maximumRedeliveries=5" />

    <bean id="simpleMessageListener" class="com.company.ConsumerClass" />

    <jms:listener-container
            container-type="default"
            connection-factory="connectionFactory"
            acknowledge="client"
            concurrency="10-50"
            cache="consumer">
        <jms:listener destination="someQueue" ref="simpleMessageListener" method="onMessage" />
    </jms:listener-container>
</beans>
```

<p>In the ConsumerClass, my simple consumer looks something like this:</p>

<pre class="lang-cs prettyprint-override"><code>@Override public final void onMessage(Message message) {
    Object postedMessage = null;
    try {
        postedMessage = ((ObjectMessage) message).getObject();

        if (postedMessage.getClass() == SomeMessageType.class) {
            try {
                //Some logic here

                message.acknowledge();
                return; //Success Here
            } catch (MyException e) {
                logger.error("Could not process message, but as I didn't call acknowledge I expect it to end up in the dead message queue");
            }
        }
    } catch (JMSException e) {
        logger.error("Error occurred pulling Message from Queue", e);
    }

    //Also worth noting, if I throw new RuntimeException("Aww Noos"); here then it won't take it from the queue, but it won't get consumed (or end up as dead letter)...
}
</code>```

答:
Call acknowledge() method on message in your consumer.

Consider the following scenario: An application receives but does not acknowledge a message. The application receives a subsequent message and acknowledges it. What happens to the former message? The former message is also considered acknowledged. Generally, acknowledging a particular message acknowledges all prior messages the session receives. In the above output, only message 5 is explicitly acknowledged. All the messages before message 5 are implicitly acknowledged. Messages after message 5 are not acknowledged.

For more details refer this article

Also Check this article Sun Java System Message Queue 4.3 Developer's Guide for Java Clients

Body:
Just starting to get my head around getting JMS ActiveMQ Acknowledgements working in Spring. So far I have a consumer working perfectly, with the exception that when I don't acknowledge the message, it's still taken from the queue (I expect it to stay there or end in a dead letter queue).

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd">

    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"
    p:brokerURL="failover://(tcp://jms1:61616,tcp://jms2:61616)?randomize=false&jms.redeliveryPolicy.maximumRedeliveries=5" />

    <bean id="simpleMessageListener" class="com.company.ConsumerClass" />

    <jms:listener-container
            container-type="default"
            connection-factory="connectionFactory"
            acknowledge="client"
            concurrency="10-50"
            cache="consumer">
        <jms:listener destination="someQueue" ref="simpleMessageListener" method="onMessage" />
    </jms:listener-container>
</beans>

In the ConsumerClass, my simple consumer looks something like this:

@Override public final void onMessage(Message message) {
    Object postedMessage = null;
    try {
        postedMessage = ((ObjectMessage) message).getObject();

        if (postedMessage.getClass() == SomeMessageType.class) {
            try {
                //Some logic here

                message.acknowledge();
                return; //Success Here
            } catch (MyException e) {
                logger.error("Could not process message, but as I didn't call acknowledge I expect it to end up in the dead message queue");
            }
        }
    } catch (JMSException e) {
        logger.error("Error occurred pulling Message from Queue", e);
    }

    //Also worth noting, if I throw new RuntimeException("Aww Noos"); here then it won't take it from the queue, but it won't get consumed (or end up as dead letter)...
}


问:
Spirit X3 : Can't compile any example on Ubuntu 16.04
Can't compile any example
on Ubuntu 16.04

```<code>$ g++ -std=c++14  main.cpp
In file included from /usr/include/boost/spirit/home/x3/nonterminal.hpp:14:0,
                 from /usr/include/boost/spirit/home/x3.hpp:20,
                 from main.cpp:23:
main.cpp:226:9: error: ‘client::calculator_grammar::parse_rule’ declared as an ‘inline’ variable
         BOOST_SPIRIT_DEFINE(
         ^
main.cpp:226:9: error: expected ‘)’ before ‘rule_’
         BOOST_SPIRIT_DEFINE(
         ^
main.cpp:226:9: error: expected primary-expression before ‘&’ token
         BOOST_SPIRIT_DEFINE(
         ^
main.cpp:226:9: error: ‘first’ was not declared in this scope
         BOOST_SPIRIT_DEFINE(
         ^
</code>```

this is a spirit::x3 bug?

答:
Two changes:

add the missing include

```<code>#include <boost/foreach.hpp>
</code>```

choose "new style" macro usage:

```<code>BOOST_SPIRIT_DEFINE(expression , term , factor);
</code>```

To be honest, I didn't know the p = p_def style initialization was possible. I suspect it was the required syntax before X3 was released.

Body:
Can't compile any example
on Ubuntu 16.04

$ g++ -std=c++14  main.cpp
In file included from /usr/include/boost/spirit/home/x3/nonterminal.hpp:14:0,
                 from /usr/include/boost/spirit/home/x3.hpp:20,
                 from main.cpp:23:
main.cpp:226:9: error: ‘client::calculator_grammar::parse_rule’ declared as an ‘inline’ variable
         BOOST_SPIRIT_DEFINE(
         ^
main.cpp:226:9: error: expected ‘)’ before ‘rule_’
         BOOST_SPIRIT_DEFINE(
         ^
main.cpp:226:9: error: expected primary-expression before ‘&’ token
         BOOST_SPIRIT_DEFINE(
         ^
main.cpp:226:9: error: ‘first’ was not declared in this scope
         BOOST_SPIRIT_DEFINE(
         ^

this is a spirit::x3 bug?

Body:
Two changes:

add the missing include

#include <boost/foreach.hpp>

choose "new style" macro usage:

BOOST_SPIRIT_DEFINE(expression , term , factor);

To be honest, I didn't know the p = p_def style initialization was possible. I suspect it was the required syntax before X3 was released.