问:
Karaf : Recommended way to uninstall/install API's bundle, and how to avoid ghost bundle resolution
I'm using Karaf (2.4.* & 4.0.*) for the past two years, in different missions, and each time I faced caching problem with API bundles when it comes to uninstall/install them.

Let's imagine the following scenario :

I install (1) service-api/1.0.0, exporting com.service.api

I install (2) service-core/1.0.0, which imports com.service.api

I uninstall service-api/1.0.0.

I install (3) service-api/1.1.0, which adds new interfaces.

The different behaviour occurs when I use bundle:install -s to install bundles, uninstall  to uninstall them :

The -core is not always stopped. In fact, he use a cached version of service-api. I can even see the bundle id (1) when I do a imports -i (2). Doing a "resolve (2)" doesn't solve the problem, only the fact to "stop (2)" then start it again.

When I install service-api/1.1.0, the bug in 3 still occurs and my service-core uses again the old -api. The big problem is if I install a new service-soap, it will use the bundle (3), while the (2) uses the (1), and thus it creates clash between classloader.

I can't find any resource on that matter on the internet, and I've tried Equinox & Felix and I do not see any solution for that problem. Is bundle:install the good way to install bundle ? Does using deploy is a better solution ?

Bonus : In OSGI spec, a bundle should not be uninstalled until all the reference are released, but in Karaf, the bundle is uninstalling itself directly.. Could it be the cause of the problem described above ?

答:
What you see is conforming to the OSGi specs. When you uninstall an API then all bundles using it will still use it until they are resolved again.
This behavior was introduced to avoid cascading changes in the runtime.

To make a bundle pick up or loose an API you need to resolve the bundle. The easiest way to do this is to use the resolve command. Which resolves a given bundle or all bundles.

Another way to auto resolve bundles is to always install them using Apache Karaf features. When you install / uninstall features Karaf will always make sure to re resolve all bundles that could be affected.


来源: stackexchange

问:
To print the boundary of Binary Tree
I have been asked in an interviews to print the boundary of the Binary Tree. For example.

```<code>      1
   /    \
  2      3
 /  \   /  \
4    5 6    7
    /   \     \
   8     9     10
</code>```

Answer will be : 1, 2, 4, 8, 9, 10, 7, 3

I have given the following answer.

First Method :

I have used a  Bool  variable to solve the above problem.

```<code>void printLeftEdges(BinaryTree *p, bool print) {
   if (!p) return;
   if (print || (!p->left && !p->right))
       cout << p->data << " ";
   printLeftEdges(p->left, print);
   printLeftEdges(p->right, false);
}

void printRightEdges(BinaryTree *p, bool print) {
   if (!p) return;
   printRightEdges(p->left, false);
   printRightEdges(p->right, print);
   if (print || (!p->left && !p->right))
   cout << p->data << " ";
}

void printOuterEdges(BinaryTree *root) {
   if (!root) return;
   cout << root->data << " ";
   printLeftEdges(root->left, true);
   printRightEdges(root->right, true);
}
</code>```

His Response : You have used  Bool  variable so many times. Can you solve this without using that.

Second Method :

I simply used tree traversal to solve this problem.

```<code>1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
     2.1 Print all leaf nodes of left sub-tree from left to right.
     2.2 Print all leaf nodes of right subtree from left to right.
3. Print the right boundary in bottom-up manner.
</code>```

His Response : He was not happy with this method too. He told that you are traversing the tree 3 times. That is too much. Give another solution if you have any.

Third Method :
This time i have went for Level Order traversal (BFS).

```<code> 1: Print starting and ending node of each level
 2: For each other node check if its both the children are <b>NULL</b> then print that node too.
</code>```

His Response : He was not seems happy with this method too because this method takes extra memory of order O(n).

My question is that Tell me a method which traverse tree single times, do not use any Bool variable and do not use any extra memory. Is it possible?

答:
Method O(n) No extra space and single traversal of tree.

I divided the Tree Nodes into four types of nodes

Type 1 ->  Nodes which form the left boundary(eg 8)

Type 0 -> Nodes which do not form the boundar(eg 12)

Type 3    -> Nodes which form the right boundary(eg 22)

Leaf Nodes(eg 4,10,14)

In my method i am just doing recurrsion method of tree traversal (just modified) where my function is of this form

```<code>  void recFunc(btNode *temp,int type)
   {
      //Leaf Nodes
     if((temp->left == NULL)&&(temp->right == NULL))
                 cout << temp->data <<  " ";
     // type -1 Nodes must be printed before their children
   else if(type == 1)cout << temp->data << " ";
   else {;}

   if(type == 3)
   {
    if(temp->left)recFunc(temp->left,0);
    if(temp->right)recFunc(temp->right,3);
     //type 3 nodes must be printed after their children
    cout << temp->data << " ";
   }
   else if(type == 1)
   {
    if(temp->left)recFunc(temp->left,1);
    if(temp->right)recFunc(temp->right,0);
   }
   else if(type == 0)
   {
    if(temp->left)recFunc(temp->left,0);
    if(temp->right)recFunc(temp->right,0);
   }
   else {;}
    }
</code>```

where i have modofied the

In my recurrsive function Nodes of type 1 must make their left nodes
as type 1 and must be printed before calling their children(if they
exist)

Nodes Of Type 3 must be printed in reverse order .So they must be
printed after call to their children.They must also assign their
right children as Type 3 Nodes

Nodes Of Type 0 must not be printed and they assign their children as
type 0 Nodes

Leaf Nodes must be directly printed only and return

Link to Code

ContentLicense: CC BY-SA 3.0

Title: To print the boundary of Binary Tree

Body:
I have been asked in an interviews to print the boundary of the Binary Tree. For example.

      1
   /    \
  2      3
 /  \   /  \
4    5 6    7
    /   \     \
   8     9     10

Answer will be : 1, 2, 4, 8, 9, 10, 7, 3

I have given the following answer.

First Method :

I have used a  Bool  variable to solve the above problem.

void printLeftEdges(BinaryTree *p, bool print) {
   if (!p) return;
   if (print || (!p->left && !p->right))
       cout <
data << " ";
   printLeftEdges(p->left, print);
   printLeftEdges(p->right, false);
}

void printRightEdges(BinaryTree *p, bool print) {
   if (!p) return;
   printRightEdges(p->left, false);
   printRightEdges(p->right, print);
   if (print || (!p->left && !p->right))
   cout <
data << " ";
}

void printOuterEdges(BinaryTree *root) {
   if (!root) return;
   cout << root->data << " ";
   printLeftEdges(root->left, true);
   printRightEdges(root->right, true);
}

His Response : You have used  Bool  variable so many times. Can you solve this without using that.

Second Method :

I simply used tree traversal to solve this problem.

1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
     2.1 Print all leaf nodes of left sub-tree from left to right.
     2.2 Print all leaf nodes of right subtree from left to right.
3. Print the right boundary in bottom-up manner.

His Response : He was not happy with this method too. He told that you are traversing the tree 3 times. That is too much. Give another solution if you have any.

Third Method :
This time i have went for Level Order traversal (BFS).

 1: Print starting and ending node of each level
 2: For each other node check if its both the children are NULL then print that node too.

His Response : He was not seems happy with this method too because this method takes extra memory of order O(n).

My question is that Tell me a method which traverse tree single times, do not use any Bool variable and do not use any extra memory. Is it possible?

Body:
Method O(n) No extra space and single traversal of tree.

I divided the Tree Nodes into four types of nodes

Type 1 ->  Nodes which form the left boundary(eg 8)

Type 0 -> Nodes which do not form the boundar(eg 12)

Type 3    -> Nodes which form the right boundary(eg 22)

Leaf Nodes(eg 4,10,14)

In my method i am just doing recurrsion method of tree traversal (just modified) where my function is of this form

  void recFunc(btNode *temp,int type)
   {
      //Leaf Nodes
     if((temp->left == NULL)&&(temp->right == NULL))
                 cout << temp->data <<  " ";
     // type -1 Nodes must be printed before their children
   else if(type == 1)cout << temp->data << " ";
   else {;}

   if(type == 3)
   {
    if(temp->left)recFunc(temp->left,0);
    if(temp->right)recFunc(temp->right,3);
     //type 3 nodes must be printed after their children
    cout << temp->data << " ";
   }
   else if(type == 1)
   {
    if(temp->left)recFunc(temp->left,1);
    if(temp->right)recFunc(temp->right,0);
   }
   else if(type == 0)
   {
    if(temp->left)recFunc(temp->left,0);
    if(temp->right)recFunc(temp->right,0);
   }
   else {;}
    }

where i have modofied the

In my recurrsive function Nodes of type 1 must make their left nodes
as type 1 and must be printed before calling their children(if they
exist)

Nodes Of Type 3 must be printed in reverse order .So they must be
printed after call to their children.They must also assign their
right children as Type 3 Nodes

Nodes Of Type 0 must not be printed and they assign their children as
type 0 Nodes

Leaf Nodes must be directly printed only and return

Link to Code


问:
good in training and bad in prediction
I've written a code for prediction in neural network...

the error in training is good ( below 1 %) but for prediction the error is high ( about 20 %)...I think my network is over trained but i don't know a way to solve this problem...I've changed number of layers,number of neurons and training function but the result has not changed...

so I put my code in this forum and hope to get an answer for it:
link text

this zip file contains 2 files:

1-an Excel file for datas : lines 1-4 for training input, line 5 for training output (line 6 is output but didn't use in this code), line 7-10 for testing input, line 11 for testing output.

2-matlab code

after running the program 4 chart appear: first row is for trained data and second row for tested datas.

if somebody knows the answer, please change my code and put it again.

thanks a lot.

EDIT:

more description:

I have 2 output and two code for each...for line 6 ( second output) this code has acceptable results but for line 5 no good result...

please change my code and apply your suggestions on it and put it here if you think that your suggestion is useful...I have received some suggestions in other forums that are general solutions with no influence on results...

答:
As people have mentioned you are likely overfitting the ANN to the training data. Depending on the dataset you might get an arbitrarily good fit of the training data if you train long enough.. Another problem could be that the training data does not properly represent the problem space. I.e. there are inputs in the test data that are very dissimilar to the data you used for training. If that is the case there is no way the ANN can function adequately.

In order to overcome the overfitting, try this. Split the data into 3 sets; training, validation and testing. While training the ANN also calculate the error on the validation set. If the validation set does not improve for, let's say, 5 epochs (you can always configure this) then stop training.

Also, as a general point. I did not have a chance to look at your data and source code, but remember that you will need a significant amount of data in order to get good results. If you only have a few datapoints then it will be very hard/impossible to achieve good results.

I recommend reading the guide here for a good overview of many aspects of ANNs.

Good luck!

Title: good in training and bad in prediction

ContentLicense: CC BY-SA 2.5


问:
Stale Element reference error on finding the element -> when navigates back to previous page
My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.

It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.

Code is :

```<code>public class EcommerceSearchResult {

public static WebDriver driver ;

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow
    = driver.findElements
    (By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count);
        for(int i = 0 ; i<count ; i++)
        {
            List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
            System.out.println(gridrow.get(i).getText());
            listingelementinloop.get(i).click();
            driver.navigate().back();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        }

    }
}
</code>```

答:
Below is the solution code for your problem.Tested it in my machine and attached console screenshot.

```<code>import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class EcommerceSearchResult {

   public static WebDriver driver ;

   public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow = driver.findElements(By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count+"\n");
    for(int i = 0 ; i<count ; i++)
    {
        WebElement listingelementinloop = driver.findElement(By.xpath(".//*[@id='grid_view_products_page_container']/div/div["+(i+1)+"]"));
        System.out.println(listingelementinloop.getText());
        listingelementinloop.findElement(By.xpath(".//div/a")).click();
        wait.until(ExpectedConditions.urlContains("products-page/product-category"));
        driver.navigate().back();
        wait.until(ExpectedConditions.titleIs("iphone | Search Results | ONLINE STORE"));
    }
    }
    }
</code>```

Body:
My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.

It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.

Code is :

public class EcommerceSearchResult {

public static WebDriver driver ;

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow
    = driver.findElements
    (By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count);
        for(int i = 0 ; i<count ; i++)
        {
            List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
            System.out.println(gridrow.get(i).getText());
            listingelementinloop.get(i).click();
            driver.navigate().back();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        }

    }
}

Body:
Below is the solution code for your problem.Tested it in my machine and attached console screenshot.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class EcommerceSearchResult {

   public static WebDriver driver ;

   public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow = driver.findElements(By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count+"\n");
    for(int i = 0 ; i<count ; i++)
    {
        WebElement listingelementinloop = driver.findElement(By.xpath(".//*[@id='grid_view_products_page_container']/div/div["+(i+1)+"]"));
        System.out.println(listingelementinloop.getText());
        listingelementinloop.findElement(By.xpath(".//div/a")).click();
        wait.until(ExpectedConditions.urlContains("products-page/product-category"));
        driver.navigate().back();
        wait.until(ExpectedConditions.titleIs("iphone | Search Results | ONLINE STORE"));
    }
    }
    }


问:
Getting price from JSON
I'm trying to get the JSON key and value called price. I can get the key but the price is just undefined.

```<code>    for(var item in prices.response){
        console.log(item);
        console.log(prices.response.price)
    }
</code>```

Snippet of JSON

```<code>"response": {
    "AK-47 | Aquamarine Revenge (Battle-Scarred)": {
        "price": 962,
        "quantity": 192
    }
</code>```

答:
You can stick with your current code but you need to use item as your key like:

```<code>for(let item in prices.response){ // consider using let instead of var as well
    console.log(item);
    console.log(prices.response[item].price)
}
</code>```

or you could go using directly the value as :

```<code>for(let item of prices.response){ // of keyword instead of in keyword
    console.log(item);
    console.log(item.price)
}
</code>```

Title: Getting price from JSON

Body:
I'm trying to get the JSON key and value called price. I can get the key but the price is just undefined.

    for(var item in prices.response){
        console.log(item);
        console.log(prices.response.price)
    }

Snippet of JSON

"response": {
    "AK-47 | Aquamarine Revenge (Battle-Scarred)": {
        "price": 962,
        "quantity": 192
    }

Body:
You can stick with your current code but you need to use item as your key like:

for(let item in prices.response){ // consider using let instead of var as well
    console.log(item);
    console.log(prices.response[item].price)
}

or you could go using directly the value as :

for(let item of prices.response){ // of keyword instead of in keyword
    console.log(item);
    console.log(item.price)
}


问:
Show all multidimensional array keys without their values?
I am working with multidimensional arrays and i need dumping they keys. But their values are wery huge. Is there some easy and quick way dump keys like print_r or var_dump but without values? Or truncated values?

Own function or 'helper' i can write by myself i want know whether exist some default function which one knows...

答:
Use array_keys</p>

```<code> print_r(array_keys($array));
</code>```

Body:
Use array_keys

 print_r(array_keys($array));


问:
how to pass array of model from one actvtiy to another in android
```<code>public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}
</code>```

this is my Datamodel:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}
</code>```

main activtiy

```<code>public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}
</code>```

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

答:
you create Datamodel in this way :

```<code> DataModel _modeDataModel=new DataModel(MainActivity.this);
</code>```

but DataModel class does not have constructor that accept an Activity !

add this constructor to your DataModelClass

```<code>public DataModel(Activity activity){

}
</code>```

Or Change That line to this :

```<code> DataModel _modeDataModel=new DataModel();
</code>```

after all send Arrays of Datamodel to another Activity Like this :

```<code>ArrayList<DataModel> array = new ArrayList<>;

 DataModel _modeDataModel=new DataModel();
 _modeDataModel.setCid("1");
 _modeDataModel.setName("Anil");
array.add(_modeDataModel);
//Add any number you want

 Intent intent = new Intent(MainActivity.this,SecondActivity.class);
 intent.putParcelableArrayListExtra("Key",array);
 startActivity(intent);
</code>```

and in SecondActivity :

```<code>ArrayList<DataModel> array2 = getIntent().getParcelableArrayListExtra("Key");
</code>```

I hope to be useful.

Body:
public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}

this is my Datamodel:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}

main activtiy

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

Body:
you create Datamodel in this way :

 DataModel _modeDataModel=new DataModel(MainActivity.this);

but DataModel class does not have constructor that accept an Activity !

add this constructor to your DataModelClass

public DataModel(Activity activity){

}

Or Change That line to this :

 DataModel _modeDataModel=new DataModel();

after all send Arrays of Datamodel to another Activity Like this :

ArrayList<DataModel> array = new ArrayList<>;

 DataModel _modeDataModel=new DataModel();
 _modeDataModel.setCid("1");
 _modeDataModel.setName("Anil");
array.add(_modeDataModel);
//Add any number you want

 Intent intent = new Intent(MainActivity.this,SecondActivity.class);
 intent.putParcelableArrayListExtra("Key",array);
 startActivity(intent);

and in SecondActivity :

ArrayList<DataModel> array2 = getIntent().getParcelableArrayListExtra("Key");

I hope to be useful.


问:
What is the purpose of EventMention in Stanford-NLP?
When using the pipeline annotator, relation, I get back appropriate RelationMention objects for each sentence.  These are binary type objects with two entity mentions and a corresponding relation type.

However, in the code, I also see EventMention objects which can be obtained from the sentence in much the same way.  In the class MachineReadingProperties, I see that extraction of relations and extraction of events both default to true.  However, I am only seeing generated relations and not generated events.

I can find no mention of events in the Stanford documentation, nor does the page describing the relation annotator or how to train a custom relation model describe it.  There are no links to research papers on the event portion, just the link to the Roth and Yih paper on relations.

So do events work with the relation annotator and if so are there any more documents describing them?

答: From tracing the code, I see that EventMention is only used in conjunction with the ACE2005 code.  It does not appear to be connected with any of the pipeline annotators and cannot be directly created in that manner.</p>


问:
Unindexed remote maven resitories in intellij IDEA 15.0.1
While creating new Gradle project in Intellij Idea 15.0.1,

I get the following error :

And when I try to update the repository in Repositories List, I get the following exception :

When I searched for this problem, I came across some posts stating that it was a known issues which was to be fixed in the previous versions (14. something) but apparently it isn't fixed, or it is not a bug.
Some also advised to uncheck "use maven3 to import project" in File -> Settings -> maven -> importing, but can't find that option:

Seems like the problem is with the internet connection, when I use my mobile hotspot sharing phone's cellular data, the updating start, but since it has to sync around 260MB data, it was too slow. But when I use the LAN provided by the school which uses proxy it gives the aforementioned error right away.

I've configured the http proxy in settings and connection seems okay.

Is this error (Unindexed remote maven repositories found) something to worry about, if I am able to download the dependencies? Any way to fix this?

答:
In build.gradle, substitute:

```<code>repositories {
    jcenter()
}
</code>```

or perhaps:

```<code>repositories {
    maven {
        url "http://repo1.maven.org/maven2/"
    }
}
</code>```

instead of:

```<code>repositories {
    mavenCentral()
}
</code>```

Close and reopen your IDEA project.

Body:
In build.gradle, substitute:

repositories {
    jcenter()
}

or perhaps:

repositories {
    maven {
        url "http://repo1.maven.org/maven2/"
    }
}

instead of:

repositories {
    mavenCentral()
}

Close and reopen your IDEA project.


问:
Using Arabic fonts with the extension .otf
I'm working on a small project, where the client sent me a font that he wants me to use for the Arabic language. The file extension for the file is .otf

I embedded the file, and tried to use it, and the results were:

IE8: Didn't recognize the font.

Chrome: Didn't recognize the font.

Firefox: Recognized the font, but when viewing it the letters were separated (in Arabic language the letters of the word is connected to each other)

Any idea on how to fix it on Firefox and make IE and Chrome recognize the font type ??

Here is the code is used:

CSS

```<code>@font-face {
font-family: Dinar;
src: url("GEDinarTwo-Light.otf") format("opentype");
}

@font-face {
font-family: Dinar;
font-weight: bold;
src: url("GEDinarTwo-Light.otf") format("opentype");
}

#ss {
font-family: Dinar, Arial, Helvetica, Sans-Serif;
}
</code>```

Many thanks ...

答:
IE doesn't support OTF fonts.

http://webfonts.info/wiki/index.php?title=@font-face_support_in_Internet_Explorer

Body:
I'm working on a small project, where the client sent me a font that he wants me to use for the Arabic language. The file extension for the file is .otf

I embedded the file, and tried to use it, and the results were:

IE8: Didn't recognize the font.

Chrome: Didn't recognize the font.

Firefox: Recognized the font, but when viewing it the letters were separated (in Arabic language the letters of the word is connected to each other)

Any idea on how to fix it on Firefox and make IE and Chrome recognize the font type ??

Here is the code is used:

CSS

@font-face {
font-family: Dinar;
src: url("GEDinarTwo-Light.otf") format("opentype");
}

@font-face {
font-family: Dinar;
font-weight: bold;
src: url("GEDinarTwo-Light.otf") format("opentype");
}

#ss {
font-family: Dinar, Arial, Helvetica, Sans-Serif;
}

Many thanks ...


问:
TFS Properties of an Activity Workflow, how can I put a path to the VB Expression
I'm following this tuto: http://blog.justtfs.co.uk/2014/09/movedeployfiles-copy-file-activity-for.html

But how can I put the path in the VB expression:

For example if I put in the argument RepositoryPath: C:\agent, it doesn't work
So, how is the syntax?

Thank you for helping me.

答:
The syntax is a VB expression.
Some Examples.

A constant string: "C:\agent"

Value of SourcesDirectory variable: SourcesDirectory

Compose variable with string SourcesDirectory + "\subdir"

As per the accepted values, they depend on the specific activity's property.


问:
Best way to implement nodejs "service"
So, I have this application where I hold insurance expiration dates. My client wants to be notified when an expiration date is seven days from the present day. How do I implement this "service"?
I'm using MongoDb and Heroku.</p>

答:
You will need to make your process run at certain intervals and see if there are any new items that matches your criteria.

To see how to make your code run at certain intervals, read Scheduled Jobs and Custom Clock Processes in the Heroku documentation:

https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes

Title: Best way to implement nodejs "service"


问:
Some elements are not showing in openstreetmap
I added a point on openstreetmap several months ago, and that point is not showing in the standard layer (or any other layer).

When I click on the interrogation mark, I can see that the point exist in the database, but no icon is showing for that point :

If someone can tell me why this is happening (because it is not the first time), I will really appreciate it.

Here are also the point link https://www.openstreetmap.org/node/4541228705 to verify by yourself if you want to.

答:
Not all POIs are shown on the standard layer. This can have several reasons:

The POI is too unimportant to display it.

The POI hasn't been added to the renderer stylesheet yet.

The POI is in the stylesheet but not in the renderer database and a re-import of the database would be necessary.

The POI is in the stylesheet and the database but there is not enough space to show it.

Your POI is tagged as office=association. Currently the office key is not rendered on the standard style. There is already a [corresponding issue for openstreetmap-carto (the current default rendering style).

In other words: You did everything right. The reason for the office not being rendered is not your fault. Unfortunately you have to wait until the rendering stylesheet gets updated (you might participate in the mentioned issue to speed things up). Do not change the tagging just to make it appear on the map (also called tagging for the renderer). The good news is: Geocoders / routing engines will find your office nevertheless (e.g. Nominatim)! There might even exist other OSM-based maps with a different stylesheet that already show your POI.


问:
SQL Exclude Zero from Case Column
I have a query inserting values into a table and am using CASE to determine the value for each row. I was wondering if it is possible at the end of it to then exclude null or zero from the calculated column?

```<code>   CASE
       WHEN Value = 0 THEN Value2
       WHEN Value2 < Value1 THEN Value3
       WHEN Value2 > Value1 THEN Value4
   END AS Final_Value
</code>```

This produces a few hundred thousand rows, of which a good few thousand are now zero or null. Can I exclude these in the same piece of code?

Thanks

答:
0 or null values can be avoided in the end of query like </p>

```<code>SELECT
ACCGRPID,
LOCID,
USERID4,
LOBNAME,
REINSTYPE,
INCEPTDATE,
EXPIREDATE,
Latitude,
Longitude,
CountryRMSCode,
StreetAddress,
CityName,
ACCGRPNUM,
ACCGRPNAME,
CASE
   WHEN Value = 0 THEN Value2
   WHEN Value2 < Value1 THEN Value3
   WHEN Value2 > Value1 THEN Value4
END AS Final_Value
FROM  <table_name>
WHERE Final_Value <> 0
</code>```

Title: SQL Exclude Zero from Case Column

Body:
I have a query inserting values into a table and am using CASE to determine the value for each row. I was wondering if it is possible at the end of it to then exclude null or zero from the calculated column?

   CASE
       WHEN Value = 0 THEN Value2
       WHEN Value2 < Value1 THEN Value3
       WHEN Value2 > Value1 THEN Value4
   END AS Final_Value

This produces a few hundred thousand rows, of which a good few thousand are now zero or null. Can I exclude these in the same piece of code?

Thanks

Body:
0 or null values can be avoided in the end of query like

SELECT
ACCGRPID,
LOCID,
USERID4,
LOBNAME,
REINSTYPE,
INCEPTDATE,
EXPIREDATE,
Latitude,
Longitude,
CountryRMSCode,
StreetAddress,
CityName,
ACCGRPNUM,
ACCGRPNAME,
CASE
   WHEN Value = 0 THEN Value2
   WHEN Value2 < Value1 THEN Value3
   WHEN Value2 > Value1 THEN Value4
END AS Final_Value
FROM  <table_name>
WHERE Final_Value <> 0


答:
```<code>   ;WITH CTE AS (
       select
          ACCGRPID,
          LOCID,
          USERID4,
          LOBNAME,
          REINSTYPE,
          INCEPTDATE,
          EXPIREDATE,
          Latitude,
          Longitude,
          CountryRMSCode,
          StreetAddress,
          CityName,
          ACCGRPNUM,
          ACCGRPNAME,
          CASE
                 WHEN Value = 0 THEN Value2
                WHEN Value2 < Value1 THEN Value3
                 WHEN Value2 > Value1 THEN Value4
          END AS Final_Value
   )
   select * from CTE
   where  Final_Value <> 0
          and Final_Value is not null
</code>```

Title: SQL Exclude Zero from Case Column


问:
How to keep header the same size as the window
I am a total beginner and i have a problem with a header width (i am also not so great English speaker so i hope that i will manage to explain this good as i need to).
Header is marked in css as 100% but when i change size of the firefox or chrome window it stays with width of the monitor and i get that drag line down on the browser window.
Everything else on site follows the size of the window, only that stays big.
Also they all have position:relative.
This is the html code:</p>

```<code><header>
        <div id="adresa">
            <ul>
              <li><img name="telefon" src="Prvisajt/Rounded-16-128.png" width="20"; height="18"; align="bottom";> 011/2762-124 </li>
              <li>  <img name="adresa" src="Prvisajt/location-square-social-media-128.png" width="20"; height="18"; align="bottom";> Ruzveltova 45, 11000 Beograd, Frizerski salon Marko</li>
              <li id="mail"><a href="mailto:kontakt@frizerskisalonmarko.com"> <img src="Prvisajt/mail-square-social-media-128.png" width="20"; height="18"; align="bottom"> </a></li>
              <li id="face"><a href="https://www.facebook.com/FSM.Beograd/"> <img src="Prvisajt/Facebook_social_media_logo-128.png" width="20"; height="18"; align="bottom"> </a></li>
            </ul>
        </div>

       <div id="navbar">
        <ul>
            <li><img id="logo" src="Prvisajt/logo-alternate.png" alt="Logo"></li>
            <li><a href="galerija.html">GALERIJA</a></li>
            <li><a href="cenovnik.html">CENOVNIK</a></li>
            <li><a href="kontakt.html">KONTAKT</a></li>
        </ul>
      </div>
    </header>

and this is css:

body {
    margin: 0;
    padding: 0;
    background: black;
}

header {
    width: 100%;
    max-width: 100%;
    height: 120px;
    position: relative;
}

#navbar {
    width:100%;
    height:92px;
    float: right;
    background-color: black;
    position: relative;
    top: 0px;
    border-bottom: 1px solid white;

}

#navbar ul li {
    width:100px;
    float: left;
    list-style: none;
    display: inline;
    position: relative;
    left: 970px;
}

#navbar li a {
    color: white;
    line-height: 80px;
    text-align: center;
    font-size: 12px;
    font-family: sans-serif;
    font-weight: 600;
    text-decoration: none;
}

#logo {
    position: relative;
    top: -16px;
    right: 620px;
}

#adresa {
    float: left;
    display:inline;
    background-color: black;
    border-bottom: 1px solid white;
    width: 100%;
    height: 25px;
    text-align: center;
    font-size: 11px;
    font-weight: 600;
    font-family: sans-serif;
    list-style-type: none;
    text-decoration: none;
    text-align: left;
    position: relative;
    top: 0px;
}

#adresa ul li {
    list-style-type: none;
    background-color: black;
    text-align: center;
    display: inline;
    text-decoration: none;
    color: white;
    position: relative;
    top: -10px;
    left: 350px;
}

#mail img {
    position: relative;
    top: 4px;
    right: -600px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}

#face img {
    position: relative;
    top: 4px;
    right: -610px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}
</code>```

答:
You will need to change the width and height of the images to 100%

```<code>#adresa ul li img {
width: 100%;
height: 100%;
}
</code>```

This should fix it.

Body:
I am a total beginner and i have a problem with a header width (i am also not so great English speaker so i hope that i will manage to explain this good as i need to).
Header is marked in css as 100% but when i change size of the firefox or chrome window it stays with width of the monitor and i get that drag line down on the browser window.
Everything else on site follows the size of the window, only that stays big.
Also they all have position:relative.
This is the html code:

 011/2762-124

   Ruzveltova 45, 11000 Beograd, Frizerski salon Marko

GALERIJA

CENOVNIK

KONTAKT

and this is css:

body {
    margin: 0;
    padding: 0;
    background: black;
}

header {
    width: 100%;
    max-width: 100%;
    height: 120px;
    position: relative;
}

#navbar {
    width:100%;
    height:92px;
    float: right;
    background-color: black;
    position: relative;
    top: 0px;
    border-bottom: 1px solid white;

}

#navbar ul li {
    width:100px;
    float: left;
    list-style: none;
    display: inline;
    position: relative;
    left: 970px;
}

#navbar li a {
    color: white;
    line-height: 80px;
    text-align: center;
    font-size: 12px;
    font-family: sans-serif;
    font-weight: 600;
    text-decoration: none;
}

#logo {
    position: relative;
    top: -16px;
    right: 620px;
}

#adresa {
    float: left;
    display:inline;
    background-color: black;
    border-bottom: 1px solid white;
    width: 100%;
    height: 25px;
    text-align: center;
    font-size: 11px;
    font-weight: 600;
    font-family: sans-serif;
    list-style-type: none;
    text-decoration: none;
    text-align: left;
    position: relative;
    top: 0px;
}

#adresa ul li {
    list-style-type: none;
    background-color: black;
    text-align: center;
    display: inline;
    text-decoration: none;
    color: white;
    position: relative;
    top: -10px;
    left: 350px;
}

#mail img {
    position: relative;
    top: 4px;
    right: -600px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}

#face img {
    position: relative;
    top: 4px;
    right: -610px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}

Body:
You will need to change the width and height of the images to 100%

#adresa ul li img {
width: 100%;
height: 100%;
}

This should fix it.


问:
How can I choose Swift compiler version
I'm using Xcode 7.3 but my project is in Swift 2.1. I don't want to update my codes right now. So how can I choose or download older version of Swift compiler? Many thanks in advance!</p>

答:
The following example is tested on Xcode 8.3 with swift 3.1

If you are using Xcode 8 you can download toolchains with needed Swift versions

1) Open this link:
https://swift.org/download/#releases

2) Download Toolchain with swift version that you need. For example I have 3.1 version of swift and downloaded swift 3.0.2

3) Open .pkg file and install it.

4) Open Xcode and select in menu:

Xcode -> Toolchains -> Select Swift Version you need.

That is all folks

Title: How can I choose Swift compiler version


问:
ionic IBM MobileFirst platform 8.0 sqladapter ReferenceError: WL is not defined
this is my service.js,using Wl.Client.invoke,dont know which files i am missing ,do i need wlinit.js or initoptions.js or do i need to install any plugin</p>

```<code>    .factory('loginservice', function(){
    var user;
    return{
           checkvalue:function(settings){
                    user=settings;
                    console.log(user);
                    var invocationData = {
                            adapter : 'sqltest2',
                            procedure : 'checkvalue',
                            parameters : [user.username,user.password]
                                            };
                    WL.Client.invokeProcedure(invocationData,{
                        onSuccess : loginSuccess,
                        onFailure : loginFailure
                                                             });

                    function loginSuccess(result){
                        console.log("Retrieve success" +  JSON.stringify(result));
                        //displayFeeds(result.invocationResult.resultSet);
                                                }

                    function loginFailure(result){
                        console.log("Retrieve failure");
                                                    }

                }

                }
              })
</code>```

答:
IBM MobileFirst platform 8.0 sqladapter ReferenceError: WL is not defined

I assume you are using IBM MobileFirst platform 8.0,  You have to install mfpdev-cli & cordova-plugin-mfp then use WLResourceRequest. see the sample:

```<code>var resourceRequest = new WLResourceRequest(
    "/adapters/JavaAdapter/users",
    WLResourceRequest.GET
);
var formParams = {"param1": "value1", "param2": "value2"};
resourceRequest.sendFormParameters(formParams);

resourceRequest.send().then(
    onSuccess,
    onFailure
)
</code>```

WL.Client.invokeProcedure is no longer in use in IBM MobileFirst 8.0.

I suggest that you will take a tour of the MobileFirst Foundation development in Cordova applications  . See here:

Integrating MobileFirst Foundation 8.0 in Ionic-based apps: https://mobilefirstplatform.ibmcloud.com/blog/2016/07/19/integrating-mobilefirst-foundation-8-in-ionic-based-apps/

Adding the MobileFirst Foundation SDK to Cordova Applications: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/sdk/cordova/

Resource request from JavaScript (Cordova, Web) applications: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/resource-request/javascript/

Body:
this is my service.js,using Wl.Client.invoke,dont know which files i am missing ,do i need wlinit.js or initoptions.js or do i need to install any plugin

    .factory('loginservice', function(){
    var user;
    return{
           checkvalue:function(settings){
                    user=settings;
                    console.log(user);
                    var invocationData = {
                            adapter : 'sqltest2',
                            procedure : 'checkvalue',
                            parameters : [user.username,user.password]
                                            };
                    WL.Client.invokeProcedure(invocationData,{
                        onSuccess : loginSuccess,
                        onFailure : loginFailure
                                                             });

                    function loginSuccess(result){
                        console.log("Retrieve success" +  JSON.stringify(result));
                        //displayFeeds(result.invocationResult.resultSet);
                                                }

                    function loginFailure(result){
                        console.log("Retrieve failure");
                                                    }

                }

                }
              })

Body:
IBM MobileFirst platform 8.0 sqladapter ReferenceError: WL is not defined

I assume you are using IBM MobileFirst platform 8.0,  You have to install mfpdev-cli & cordova-plugin-mfp then use WLResourceRequest. see the sample:

var resourceRequest = new WLResourceRequest(
    "/adapters/JavaAdapter/users",
    WLResourceRequest.GET
);
var formParams = {"param1": "value1", "param2": "value2"};
resourceRequest.sendFormParameters(formParams);

resourceRequest.send().then(
    onSuccess,
    onFailure
)

WL.Client.invokeProcedure is no longer in use in IBM MobileFirst 8.0.

I suggest that you will take a tour of the MobileFirst Foundation development in Cordova applications  . See here:

Integrating MobileFirst Foundation 8.0 in Ionic-based apps: https://mobilefirstplatform.ibmcloud.com/blog/2016/07/19/integrating-mobilefirst-foundation-8-in-ionic-based-apps/

Adding the MobileFirst Foundation SDK to Cordova Applications: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/sdk/cordova/

Resource request from JavaScript (Cordova, Web) applications: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/resource-request/javascript/


问:
403 error on XAMPP change document root
I have installed XAMPP on Linux Mint. Got it running OK, then I wanted to change the htdocs folder location to another partition.

I made these changes to httpd.conf:

```<code>DocumentRoot "/media/alex/776FAD4B34B3CF0A/XAMPP htdocs"
<Directory "/media/alex/776FAD4B34B3CF0A/XAMPP htdocs">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>
</code>```

and also did:

```<code>cd /media/alex/776FAD4B34B3CF0A
sudo chmod -R 777 "XAMPP htdocs"
</code>```

but I keep getting a 403 error, despite restarting Apache.

Any suggestions please!
Thanks

答:
This looks pretty much exactly like your problem, doesn't it? :)

What's probably missing is this (assumung that your Apache is running under www-data):

```<code>sudo adduser <username> www-data
sudo chown -R www-data:www-data /media/alex/776FAD4B34B3CF0A
sudo chmod -R g+rw /media/alex/776FAD4B34B3CF0A
</code>```

Eventually that won't be enough though and you gotta go with

```<code>chown -R www-data:www-data
</code>```

But that's more like your last resort...

Title: 403 error on XAMPP change document root

Body:
I have installed XAMPP on Linux Mint. Got it running OK, then I wanted to change the htdocs folder location to another partition.

I made these changes to httpd.conf:

DocumentRoot "/media/alex/776FAD4B34B3CF0A/XAMPP htdocs"
<Directory "/media/alex/776FAD4B34B3CF0A/XAMPP htdocs">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

and also did:

cd /media/alex/776FAD4B34B3CF0A
sudo chmod -R 777 "XAMPP htdocs"

but I keep getting a 403 error, despite restarting Apache.

Any suggestions please!
Thanks

Body:
This looks pretty much exactly like your problem, doesn't it? :)

What's probably missing is this (assumung that your Apache is running under www-data):

sudo adduser <username> www-data
sudo chown -R www-data:www-data /media/alex/776FAD4B34B3CF0A
sudo chmod -R g+rw /media/alex/776FAD4B34B3CF0A

Eventually that won't be enough though and you gotta go with

chown -R www-data:www-data

But that's more like your last resort...


问:
AngularJS - Organizing large services & functions
I honestly can't think of the one way when it comes to the organization of my services.

I have a large service that defines a lot of methods, including one whose purpose it is to validate a large object. The functionality is quite complex, so I'd like to split the method up in bite-sized ones.

How should I do that? I can think of multiple ways to achieve this:

Creating a helper service whose only purpose it is to provide validation functionality

This could be the most elegant way, however it would bloat my application with another service

Keeping it in the current service, just split up the methods

This would lead to a very large validation method that lives amongst other ones, creating a vast service:

```<code>app.service('serv',function(){

    return{

        someFunc: function(){
            // ...
        },

        // some more functions

        _validate: function(options){

            // call each function defined below

            function a(){
                // ...
            }

             function b(){
                // ...
            }

             function c(){
                // ...
            }
        }

});
</code>```

Defining private methods directly on the current service

Considering the above example, i could also define functions a - c directly on the service. Not quite elegant, too

So what is the best practice here?

答:
Please forgive my syntax or compialtion errors, as i am directly typing it here.

First things first i hope you meant factory and not service, as you don't return the object in a service.

Also, hope i understood your question correctly, so you dont want to inject helper services, but just organize the code in the same service, is that right?

One way i can think of is, wrap it under a IIFE, this would help in making all the variables and functions private

few tips, as a best practice, please avoid creating var app in window or global scope and referencing it everywhere else, it pollutes the global scope and secondly, it can create conflicts when your app gets bigger and you lose track of the variables created. if you need to get a module, use angular.module('yourAppName'), shown below.

```<code>(function(){

// define your variables or functions here,
// All of them will be in the scope of the above function and
// outside functions cannot excess it or you can do the same inside the MyFactory function

angular.module('yourAppName').factory('myFactory', MyFactory);

function MyFactory(){
  var factory = {};

  // some local variables
   var a, b, c;

 // some local functions,

    someFunc: function(){
            // ...
        },

    // some more functions

        _validate: function(options){

            // call each function defined below

            function a(){
                // ...
            }

             function b(){
                // ...
            }

             function c(){
                // ...
            }
    }

  // add the functions you want to expose to be called by the controllers or any objects where you have injected the factory.
    factory.funcA = function(){   }

   return factory;
  }
})();
</code>```

Body:
I honestly can't think of the one way when it comes to the organization of my services.

I have a large service that defines a lot of methods, including one whose purpose it is to validate a large object. The functionality is quite complex, so I'd like to split the method up in bite-sized ones.

How should I do that? I can think of multiple ways to achieve this:

Creating a helper service whose only purpose it is to provide validation functionality

This could be the most elegant way, however it would bloat my application with another service

Keeping it in the current service, just split up the methods

This would lead to a very large validation method that lives amongst other ones, creating a vast service:

app.service('serv',function(){

    return{

        someFunc: function(){
            // ...
        },

        // some more functions

        _validate: function(options){

            // call each function defined below

            function a(){
                // ...
            }

             function b(){
                // ...
            }

             function c(){
                // ...
            }
        }

});

Defining private methods directly on the current service

Considering the above example, i could also define functions a - c directly on the service. Not quite elegant, too

So what is the best practice here?

Body:
Please forgive my syntax or compialtion errors, as i am directly typing it here.

First things first i hope you meant factory and not service, as you don't return the object in a service.

Also, hope i understood your question correctly, so you dont want to inject helper services, but just organize the code in the same service, is that right?

One way i can think of is, wrap it under a IIFE, this would help in making all the variables and functions private

few tips, as a best practice, please avoid creating var app in window or global scope and referencing it everywhere else, it pollutes the global scope and secondly, it can create conflicts when your app gets bigger and you lose track of the variables created. if you need to get a module, use angular.module('yourAppName'), shown below.

(function(){

// define your variables or functions here,
// All of them will be in the scope of the above function and
// outside functions cannot excess it or you can do the same inside the MyFactory function

angular.module('yourAppName').factory('myFactory', MyFactory);

function MyFactory(){
  var factory = {};

  // some local variables
   var a, b, c;

 // some local functions,

    someFunc: function(){
            // ...
        },

    // some more functions

        _validate: function(options){

            // call each function defined below

            function a(){
                // ...
            }

             function b(){
                // ...
            }

             function c(){
                // ...
            }
    }

  // add the functions you want to expose to be called by the controllers or any objects where you have injected the factory.
    factory.funcA = function(){   }

   return factory;
  }
})();


问:
Make query on null field Appengine search document?
In a appengine search document, can I make a request on only null value something like ?

```<code>myfield = ""
</code>```

I looked at the documentation  and i don't found how to make this kind of request.

Do you have any suggestion

Thanks

答:
I have solved this with a field fieldNull who takes a boolean true or false and i make a query </p>

```<code>fieldNull = true
</code>```

Body:
In a appengine search document, can I make a request on only null value something like ?

myfield = ""

I looked at the documentation  and i don't found how to make this kind of request.

Do you have any suggestion

Thanks

Body:
I have solved this with a field fieldNull who takes a boolean true or false and i make a query

fieldNull = true


问:
XML schema error with Jetty
I got a problem with my spring configuration when I run it in jetty. I used the exact same file in tomcat without any problems. The error i get is the following.

```<code>org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 6 in XML document from ServletContext resource [/WEB-INF/web-application-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'SpringSource.org | '.
Caused by: org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'SpringSource.org | '.
</code>```

My schema looks like this.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.5.xsd">
</code>```

I have no idea what can be wrong. Have tested it with 2 different configurations and both gave this error.

答:
Obviously you can not have a newline character inside XML attribute.

Put xsi:schemaLocation attribute value all inside one line.

Title: XML schema error with Jetty

Body:
I got a problem with my spring configuration when I run it in jetty. I used the exact same file in tomcat without any problems. The error i get is the following.

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 6 in XML document from ServletContext resource [/WEB-INF/web-application-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'SpringSource.org | '.
Caused by: org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'SpringSource.org | '.

My schema looks like this.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.5.xsd">

I have no idea what can be wrong. Have tested it with 2 different configurations and both gave this error.


问:
Use of foreignKey between app models in Django 1.10
I have a website built in Django 1.10. The site has 3 different apps: teams, members and news.

The first app, called teams has one model called Team.

This is the Team/models.py:

```<code>from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

class Team(models.Model):
        name = models.CharField(max_length=255)
        description = models.TextField()
        slug = models.CharField(max_length=255, default='team', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

The second app, called members has one model called Member.

This is the Member/models.py:

```<code>from django.db import models

class Piloto(models.Model):
        name = models.CharField(max_length=255)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

What I want is include the name of the team inside the member profile, so I know it should be something like:

```<code>team_of_member = models.ForeignKey();
</code>```

But I don't know what to put in the parenthesis or how to import the model of the team to the model of the member. I was following the documentation of Django 1.10 but it wasn't working, also I've tried this link but it doesn't work. Could you give a hand?  Thanks

Edit:
I tried to do as @Bulva was suggesting, so my code is now like this:

```<code>from django.db import models
from equipos.models import Team

class Member(models.Model):
        name = models.CharField(max_length=255)
        team = models.ForeignKey('teams.Team', null=True)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

答:
Try this:</p>

```<code>from teams.models import Team

# in the member model field
team_of_member = models.ForeignKey(Team);
</code>```

Body:
I have a website built in Django 1.10. The site has 3 different apps: teams, members and news.

The first app, called teams has one model called Team.

This is the Team/models.py:

from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

class Team(models.Model):
        name = models.CharField(max_length=255)
        description = models.TextField()
        slug = models.CharField(max_length=255, default='team', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

The second app, called members has one model called Member.

This is the Member/models.py:

from django.db import models

class Piloto(models.Model):
        name = models.CharField(max_length=255)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

What I want is include the name of the team inside the member profile, so I know it should be something like:

team_of_member = models.ForeignKey();

But I don't know what to put in the parenthesis or how to import the model of the team to the model of the member. I was following the documentation of Django 1.10 but it wasn't working, also I've tried this link but it doesn't work. Could you give a hand?  Thanks

Edit:
I tried to do as @Bulva was suggesting, so my code is now like this:

from django.db import models
from equipos.models import Team

class Member(models.Model):
        name = models.CharField(max_length=255)
        team = models.ForeignKey('teams.Team', null=True)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

Body:
Try this:

from teams.models import Team

# in the member model field
team_of_member = models.ForeignKey(Team);


问:
Opening VS 2012 C++ Project in VS 2015 gives Build error
We have a C++ Project built in VS 2012 (To generate .arx files to work with AutoCad 2014). Now we need to recompile it in VS 2015. we have not installed VS 2012. I opened the project in VS 2015. Properties -> General -> Platform toolset is set to Visual Studio 2015 (v140). Still we are getting "The build tools for v140 (Platform Toolset = 'v140') cannot be found. To build using the v140 build tools, please install v140 build tools."

we created a simple C++ Console application and ran it. Works fine no build error there.

Need to recompile the files for building .arx files to work in AutoCad 2018.

Initial Project Load :->

In the initial project load itself for Nimcad and planact we are getting build tools error. But not for engr.

Build on engr Project getting errors this might be the changes in ObjectARX 2018 I don't know. If you have a solution for this error please let us know:->

Buid on Nimcad Project :->

Build on Planact Project :->

For both Nimcad and planact all we get is build tools error.

Property Pages :

Any help please.

答:
To build AutoCAD 2018 ObjectARX app you'll need Visual Studio 2015 Update 3 configured (by default) with VC14.0. As you are migrating a project, make sure to adjust all libraries (.lib files) to version 22. Did you download the ObjectARX 2018 SDK?

Update

This seems a problem with your Visual Studio installation. If you create a new C++ project, VS should also ask you to install the missing parts.

In Visual Studio 2015 (...) the C++ compiler, libraries, and project templates have been moved into an optional feature. (...) To install the various components needed for desktop and mobile development in C++, you must choose “Custom” and manually select those items (Visual C++ Team Blog)

You may need to re-run VS setup and select the C++ related parts (as already mentioned on the question comments).

Finally, check your VisualStudioVersion using the VS2015 Command Prompt:


问:
Which Operating Systems support native (inotify-like) file watching in Java
The JavaDoc for java.nio.file.WatchService states;

The implementation ... is
  intended to map directly on to the native file event notification
  facility where available, or to use a primitive mechanism, such as
  polling, when a native facility is not available.

I assume this means it will try a lightweight, native mechanism when it can (something like inotify on Linux) and poll if it can not.

Is that correct?

What operating systems are likely or unlikely to provide such a facility? Distro level for Linux would be really useful or can I assume that if the JVM runs on *unix, it will be supported?

答:
I think that you can find some information in this post Watchservice in windows 7 does not work. There is some note about file system watchers on Windows and MacOSX (author of post says that they are using polling).
On Linux file system monitoring is part of a Linux kernel and it's implemented using quite nice notifications mechanism (more info about some of them can be found here)</p>


问:
How to Avoid Clearing Glide's Caches from Internal Storage?
I'm making an app that load abundant of images from internet, then store caches for offline use where Internet is not accessible. A lot of apps nowadays also loads images from Internet such as Instagram and Facebook but their caches not being removed/cleared after Internal caches is cleared.

How to avoid Glide's caches being cleared when performing Clear Cached Data in Internal Storage?

答:
Starting in Glide 3.5, you can use the GlideModule interface to lazily configure Glide and register components like ModelLoaders automatically when the first Glide request is made.

You can set the location of cache in public directory which will not be deleted:

```<code>package com.mypackage;

public class MyGlideModule implements GlideModule {
    @Override public void applyOptions(Context context, GlideBuilder builder) {
        builder.setDiskCache(
      new ExternalCacheDiskCacheFactory(context, cacheDirectoryName, yourSizeInBytes));
    }

    @Override public void registerComponents(Context context, Glide glide) {
        // register ModelLoaders here.
    }
}
</code>```

look more at wiki.

Body:
Starting in Glide 3.5, you can use the GlideModule interface to lazily configure Glide and register components like ModelLoaders automatically when the first Glide request is made.

You can set the location of cache in public directory which will not be deleted:

package com.mypackage;

public class MyGlideModule implements GlideModule {
    @Override public void applyOptions(Context context, GlideBuilder builder) {
        builder.setDiskCache(
      new ExternalCacheDiskCacheFactory(context, cacheDirectoryName, yourSizeInBytes));
    }

    @Override public void registerComponents(Context context, Glide glide) {
        // register ModelLoaders here.
    }
}

look more at wiki.


问:
Where to initiate a side effect action in an ngrx app?
In this ngrx example, the START action is initiated in the search method of the container smart component.

If I want to list all the books from a category without the user typing in any string or selecting any category (a default category of 'technical' can be used), where should I dispatch the SEARCH action? I'm looking for an initial effect without the user taking any action.

答:
I'd do it like this:

set up a SearchByCategory effect and its reducer.

in collection-page.ts, in a ngOnInit function, something like

this.book$ = store.dispatch( {
                   type: DISPLAY_CATEGORY,
                   payload: { category: 'technical' }
             });```

Take this as a hint since I have not tested it (for some reason, vscode throws plenty of declaration errors and no time correct them today). However, I do exactly that in my current project, so it should work.

Body:
I'd do it like this:

set up a SearchByCategory effect and its reducer.

in collection-page.ts, in a ngOnInit function, something like

this.book$ = store.dispatch( {
                   type: DISPLAY_CATEGORY,
                   payload: { category: 'technical' }
             });

Take this as a hint since I have not tested it (for some reason, vscode throws plenty of declaration errors and no time correct them today). However, I do exactly that in my current project, so it should work.


答:
If it's not possible to filter in the where clause, so there is a simple solution i use in some cases, with a subselect.

Example:

```<code>select X.* from (
SELECT
     ACCGRPID,
     LOCID,
     USERID4,
     LOBNAME,
     REINSTYPE,
     INCEPTDATE,
     EXPIREDATE,
     Latitude,
     Longitude,
     CountryRMSCode,
     StreetAddress,
     CityName,
     ACCGRPNUM,
     ACCGRPNAME,
     CASE
        WHEN Value = 0 THEN Value2
        WHEN Value2 < Value1 THEN Value3
        WHEN Value2 > Value1 THEN Value4
     END AS Final_Value
    from <table_name>) X
where X.Final_Value != 0 and X.Final_Value is not null
</code>```

Title: SQL Exclude Zero from Case Column

Body:
I have a query inserting values into a table and am using CASE to determine the value for each row. I was wondering if it is possible at the end of it to then exclude null or zero from the calculated column?

   CASE
       WHEN Value = 0 THEN Value2
       WHEN Value2 < Value1 THEN Value3
       WHEN Value2 > Value1 THEN Value4
   END AS Final_Value

This produces a few hundred thousand rows, of which a good few thousand are now zero or null. Can I exclude these in the same piece of code?

Thanks

Body:
If it's not possible to filter in the where clause, so there is a simple solution i use in some cases, with a subselect.

Example:

select X.* from (
SELECT
     ACCGRPID,
     LOCID,
     USERID4,
     LOBNAME,
     REINSTYPE,
     INCEPTDATE,
     EXPIREDATE,
     Latitude,
     Longitude,
     CountryRMSCode,
     StreetAddress,
     CityName,
     ACCGRPNUM,
     ACCGRPNAME,
     CASE
        WHEN Value = 0 THEN Value2
        WHEN Value2 < Value1 THEN Value3
        WHEN Value2 > Value1 THEN Value4
     END AS Final_Value
    from <table_name>) X
where X.Final_Value != 0 and X.Final_Value is not null


问:
Reversing single linked list
I tried to revert single linkied list as follows:

```<code>public class MutableLst<T> {
    public T current;
    public MutableLst<T> next;

    private MutableLst(T current){
        this.current = current;
    }

    public static <T> MutableLst<T> create(T current){
        return new MutableLst<T>(current);
    }

    public void reverse(){
        MutableLst<T> newNext = null;
        MutableLst<T> nxt = next;
        next = newNext;
        while(nxt != null) {
            newNext = this;  //<------- cycle is here
            current = nxt.current;
            next = newNext;
            nxt = nxt.next;
        }
    }
</code>```

But this implementation does not work. When I assign to this I got a cycle. How to fix it?

答:
Your code's problem is that you never assign a value to next. Here's my iterative solution to your problem. Also, to make it easier on yourself I would suggested having a head that references the beginning of your linked list.</p>

```<code>public void reverse() {
    MutableLst<T> prev = null;
    MutableLst<T> curr = head;
    MutableLst<T> next = null;
       while (curr != null) {
           next = curr.next;
           curr.next = prev;
           prev = curr;
           curr = next;
       }
    }
    head = prev;
</code>```

Title: Reversing single linked list

Body:
I tried to revert single linkied list as follows:

public class MutableLst<T> {
    public T current;
    public MutableLst<T> next;

    private MutableLst(T current){
        this.current = current;
    }

    public static <T> MutableLst<T> create(T current){
        return new MutableLst<T>(current);
    }

    public void reverse(){
        MutableLst<T> newNext = null;
        MutableLst<T> nxt = next;
        next = newNext;
        while(nxt != null) {
            newNext = this;  //<------- cycle is here
            current = nxt.current;
            next = newNext;
            nxt = nxt.next;
        }
    }

But this implementation does not work. When I assign to this I got a cycle. How to fix it?

Body:
Your code's problem is that you never assign a value to next. Here's my iterative solution to your problem. Also, to make it easier on yourself I would suggested having a head that references the beginning of your linked list.

public void reverse() {
    MutableLst<T> prev = null;
    MutableLst<T> curr = head;
    MutableLst<T> next = null;
       while (curr != null) {
           next = curr.next;
           curr.next = prev;
           prev = curr;
           curr = next;
       }
    }
    head = prev;


问:
Error message from filter array
So I have tried to get the error message from a filter array in a logic app workflow, this is what i have tried:

```<code>@body('Filter_array')['error']

@actions('Filter_array')['outputs']['body']['error']
</code>```

Am I missing something or doing something wrong here?

Thanks.

UPDATE:

It says: "cannot be evaluated because property 'error' cannot be selected. ".

But i can clearly see the "error" in the body object in the output.

答:
Ok so i managed to figure it out, i missed the fact that the array doesnt give me a single object as i thought i set it up to. so the solution was this:

```<code>@string(actions('Filter_array')['outputs']['body'][0]['error'])
</code>```

Thanks for the help! :)

Title: Error message from filter array

Body:
So I have tried to get the error message from a filter array in a logic app workflow, this is what i have tried:

@body('Filter_array')['error']

@actions('Filter_array')['outputs']['body']['error']

Am I missing something or doing something wrong here?

Thanks.

UPDATE:

It says: "cannot be evaluated because property 'error' cannot be selected. ".

But i can clearly see the "error" in the body object in the output.

Body:
Ok so i managed to figure it out, i missed the fact that the array doesnt give me a single object as i thought i set it up to. so the solution was this:

@string(actions('Filter_array')['outputs']['body'][0]['error'])

Thanks for the help! :)


问:
Get length of json array in SQL Server 2016
You know about the new JSON_ support in SQL Server 2016 so
let's say I have this data in a row

```<code>{
  "BaseBoarding": 1,
  "PriceLineStrategy": "PerPersonPerNight",
  "Currency": "EUR",
  "BasePriceLineList": [
    {
      "RoomTypeId": 1,
      "PeriodId": 1,
      "Price": 10.0
    },
    {
      "RoomTypeId": 1,
      "PeriodId": 2,
      "Price": 100.0
    },
    {
      "RoomTypeId": 1,
      "PeriodId": 3,
      "Price": 190.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 1,
      "Price": 280.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 2,
      "Price": 310.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 3,
      "Price": 340.0
    }
  ]
}
</code>```

How do I get the number of items of "BasePriceLineList" in the most performant way, preferably using the built-in JSON support?

Need to write something like this:

```<code>SELECT JSON_ARRLEN(JsonDataCol, '$.BasePriceline') FROM MyTable
WHERE Id = 1
</code>```

and get 6 as the result.

答:
You can convert it to a data set and then count the rows: </p>

```<code>DECLARE @JSON NVARCHAR(4000) = N'{
  "BaseBoarding": 1,
  "PriceLineStrategy": "PerPersonPerNight",
  "Currency": "EUR",
  "BasePriceLineList": [
    {
      "RoomTypeId": 1,
      "PeriodId": 1,
      "Price": 10.0
    },
    {
      "RoomTypeId": 1,
      "PeriodId": 2,
      "Price": 100.0
    },
    {
      "RoomTypeId": 1,
      "PeriodId": 3,
      "Price": 190.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 1,
      "Price": 280.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 2,
      "Price": 310.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 3,
      "Price": 340.0
    }
  ]
}'

select COUNT(*)
FROM OPENJSON(@json, N'$.BasePriceLineList')
WITH (RoomTypeID varchar(100) '$.RoomTypeId')
</code>```

Body:
You know about the new JSON_ support in SQL Server 2016 so
let's say I have this data in a row

{
  "BaseBoarding": 1,
  "PriceLineStrategy": "PerPersonPerNight",
  "Currency": "EUR",
  "BasePriceLineList": [
    {
      "RoomTypeId": 1,
      "PeriodId": 1,
      "Price": 10.0
    },
    {
      "RoomTypeId": 1,
      "PeriodId": 2,
      "Price": 100.0
    },
    {
      "RoomTypeId": 1,
      "PeriodId": 3,
      "Price": 190.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 1,
      "Price": 280.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 2,
      "Price": 310.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 3,
      "Price": 340.0
    }
  ]
}

How do I get the number of items of "BasePriceLineList" in the most performant way, preferably using the built-in JSON support?

Need to write something like this:

SELECT JSON_ARRLEN(JsonDataCol, '$.BasePriceline') FROM MyTable
WHERE Id = 1

and get 6 as the result.

Body:
You can convert it to a data set and then count the rows:

DECLARE @JSON NVARCHAR(4000) = N'{
  "BaseBoarding": 1,
  "PriceLineStrategy": "PerPersonPerNight",
  "Currency": "EUR",
  "BasePriceLineList": [
    {
      "RoomTypeId": 1,
      "PeriodId": 1,
      "Price": 10.0
    },
    {
      "RoomTypeId": 1,
      "PeriodId": 2,
      "Price": 100.0
    },
    {
      "RoomTypeId": 1,
      "PeriodId": 3,
      "Price": 190.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 1,
      "Price": 280.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 2,
      "Price": 310.0
    },
    {
      "RoomTypeId": 2,
      "PeriodId": 3,
      "Price": 340.0
    }
  ]
}'

select COUNT(*)
FROM OPENJSON(@json, N'$.BasePriceLineList')
WITH (RoomTypeID varchar(100) '$.RoomTypeId')


问:
WPF toolkit DateTimePicker giving incorrectly formated value
I am trying to get DateTimePicker value in dd/MM/yyyy hh:mm:ss tt format.DateTimePicker code is

```<code><xctk:DateTimePicker x:Name="startDateTimePicker" Value="{Binding SelectedDate}"
FormatString="dd/MM/yyyy hh:mm:ss tt" Width="280" Height="30" Watermark="Select DateTime"/>
</code>```

I have mentioned the Format string as I want but it's giving me output as MM/dd/yyyy hh:mm:ss tt. Not getting why this is happening. My system date time is MM/dd/yyyy will that affect the result. If yes, how can I nullify that.

答:
You should set the Format property to Custom for the FormatString to be applied.

Try this:

```<code><xctk:DateTimePicker x:Name="startDateTimePicker" Value="{Binding SelectedDate}"
                     Format="Custom"
                     FormatString="dd\/MM\/yyyy hh:mm:ss tt" Width="280" Height="30" Watermark="Select DateTime"/>
</code>```

Body:
I am trying to get DateTimePicker value in dd/MM/yyyy hh:mm:ss tt format.DateTimePicker code is

<xctk:DateTimePicker x:Name="startDateTimePicker" Value="{Binding SelectedDate}"
FormatString="dd/MM/yyyy hh:mm:ss tt" Width="280" Height="30" Watermark="Select DateTime"/>

I have mentioned the Format string as I want but it's giving me output as MM/dd/yyyy hh:mm:ss tt. Not getting why this is happening. My system date time is MM/dd/yyyy will that affect the result. If yes, how can I nullify that.

Body:
You should set the Format property to Custom for the FormatString to be applied.

Try this:

<xctk:DateTimePicker x:Name="startDateTimePicker" Value="{Binding SelectedDate}"
                     Format="Custom"
                     FormatString="dd\/MM\/yyyy hh:mm:ss tt" Width="280" Height="30" Watermark="Select DateTime"/>


问:
Generating string in code when one of a group of properties change
I am seeking advice on how to be notified when one of many properties change.

For example, lets say I want to bind a control's text to a FullAddress property in my WPF ViewModel that I can calculate on the fly whenever one of a set of properties changes, such as StreetNumber, StreetName, Suburb, PostCode etc.

I am thinking that I need to bind my displaying control to the FullAddress property, but how do I have it automatically update whenever one of the dependent properties changes? Can I bind the property's codebehind to multiple other properties on the same ViewModel? If so how? Is there a better way?

答:
You can use MultiBinding and do not use FullAddress property at all

EDIT:

If you only need to show the full address you can use StringFormat

```<code><TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}, {1}">
            <Binding Path="City"/>
            <Binding Path="Street"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>
</code>```

If you wish to allow users edit the whole address string and then split it into parts then you need to implement IMultiValueConverter interface

Body:
You can use MultiBinding and do not use FullAddress property at all

EDIT:

If you only need to show the full address you can use StringFormat

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}, {1}">
            <Binding Path="City"/>
            <Binding Path="Street"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

If you wish to allow users edit the whole address string and then split it into parts then you need to implement IMultiValueConverter interface


问:
'_Screen' object has no attribute 'onTimer'
For some reason my code that was working perfectly fine suddenly stopped working when I opened up my project today, here is my snippet of code that is not working.

```<code>import turtle
running = True
wn = turtle.Screen()
TimeTurtle = turtle.Turtle()

def setTime():
    global Time
    global running
    if running:
        Time = Time + 1
        TimeTurtle.clear()
    TimeTurtle.write("Time: " + str(Time), align="center", font=("Arial", 15, "bold"))
    wn.onTimer(setTime, 1000)
</code>```

I get the error: '_Screen' object has no attribute 'onTimer'
Any help?

答:
```<code>wn.onTimer(setTime, 1000)
</code>```

I don't see an onTimer method listed anywhere in the turtle documentation. Perhaps you want ontimer, with a lowercase T?

```<code>wn.ontimer(setTime, 1000)
</code>```

Body:
For some reason my code that was working perfectly fine suddenly stopped working when I opened up my project today, here is my snippet of code that is not working.

import turtle
running = True
wn = turtle.Screen()
TimeTurtle = turtle.Turtle()

def setTime():
    global Time
    global running
    if running:
        Time = Time + 1
        TimeTurtle.clear()
    TimeTurtle.write("Time: " + str(Time), align="center", font=("Arial", 15, "bold"))
    wn.onTimer(setTime, 1000)

I get the error: '_Screen' object has no attribute 'onTimer'
Any help?

Body:
wn.onTimer(setTime, 1000)

I don't see an onTimer method listed anywhere in the turtle documentation. Perhaps you want ontimer, with a lowercase T?

wn.ontimer(setTime, 1000)


问:
SImulate Chrome custom tabs fall back
I have successfully implemented Chrome Custom Tabs for my app and it works fine across my devices.

```<code>CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
... customizing it here ...
CustomTabActivityHelper.openCustomTab(adapter.main, builder.build(), Uri.parse(url), new WebviewFallback());
</code>```

I now want to simluate and test the failure in case the browser is not supported and it should fall back to my custom WebView as specified in the WebviewFallback class above.

What would be the best way to do that?

答: You can just uninstall you Chrome app on your device, or if it is installed as a system app, you just have to disable it (Settings > Applications > Chrome > Tap Disable).</p>

Title: SImulate Chrome custom tabs fall back

Body:
I have successfully implemented Chrome Custom Tabs for my app and it works fine across my devices.

CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
... customizing it here ...
CustomTabActivityHelper.openCustomTab(adapter.main, builder.build(), Uri.parse(url), new WebviewFallback());

I now want to simluate and test the failure in case the browser is not supported and it should fall back to my custom WebView as specified in the WebviewFallback class above.

What would be the best way to do that?


问:
configure max pool size hikaricp hibernate JPA
I'm trying to use hibernate jpa and hikaricp for the CP.
But I have an issue that I dont understand, so either my config is bad ... or I do have something else.

this is the config In have in my persistence.xml file :

```<code><properties>
    <!-- SQL -->
        <property name="hibernate.dialect" value="org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect" />
        <property name="hibernate.show_sql" value="false" />
        <property name="hibernate.format_sql" value="false" />
        <!-- HikariCP -->
        <property name="hibernate.connection.provider_class" value="com.zaxxer.hikari.hibernate.HikariConnectionProvider"/>
        <property name="hibernate.hikari.driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="hibernate.hikari.minimumIdle" value="5"/>
        <property name="hibernate.hikari.maximumPoolSize" value="30"/>
        <property name="hibernate.hikari.maxLifetime" value="150000"/>
        <property name="hibernate.hikari.dataSource.user" value="user" />
        <property name="hibernate.hikari.dataSource.password" value="password" />
        <property name="hibernate.hikari.jdbcUrl"
            value="jdbc:mysql://server:3306" />
    </properties>
</code>```

Still I'm having 100+ connections on the database. I thought that using maximumPoolSize it would have limit my number of connections. Is my configuration OK, based on my research it seems ok to me, but before trying to debug elsewhere I want to make sure it is.

Thanks

答:
You must be missing the hibernate-hikari module jar on your classpath. This module is necessary to integrate hibernate with HikariCP

Here is the official documentation

Body:
I'm trying to use hibernate jpa and hikaricp for the CP.
But I have an issue that I dont understand, so either my config is bad ... or I do have something else.

this is the config In have in my persistence.xml file :

<properties>

        <property name="hibernate.dialect" value="org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect" />
        <property name="hibernate.show_sql" value="false" />
        <property name="hibernate.format_sql" value="false" />

        <property name="hibernate.connection.provider_class" value="com.zaxxer.hikari.hibernate.HikariConnectionProvider"/>
        <property name="hibernate.hikari.driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="hibernate.hikari.minimumIdle" value="5"/>
        <property name="hibernate.hikari.maximumPoolSize" value="30"/>
        <property name="hibernate.hikari.maxLifetime" value="150000"/>
        <property name="hibernate.hikari.dataSource.user" value="user" />
        <property name="hibernate.hikari.dataSource.password" value="password" />
        <property name="hibernate.hikari.jdbcUrl"
            value="jdbc:mysql://server:3306" />
    </properties>

Still I'm having 100+ connections on the database. I thought that using maximumPoolSize it would have limit my number of connections. Is my configuration OK, based on my research it seems ok to me, but before trying to debug elsewhere I want to make sure it is.

Thanks


问:
How to jointly learn two tasks at prediction level?
I have trained a network on two different modals of the same image. I pass the data together in one layer but after that, it is pretty much two networks in parallel, they don't share a layer and the two tasks have different set of labels, therefore I have two different loss and accuracy layers (I use caffe btw). I would like to learn these tasks jointly. For example, the prediction of a class of task 1 should be higher in presence of the task 2 predicting a certain class label. I don't want to join them at feature level but at prediction level. How do I get to do this?</p>

答:
Why don't you want to join the prediction at feature level?

If you really want to stick to your idea of not joining any layers of the network, you can apply a CRF or SVM on top of the overall prediction pipeline to learn cross-correlations between the predictions. For any other method you will need to combine features inside the network, one way or another. However I would strongly recommend, that you consider doing this. It is a general theme in deep learning, that doing stuff inside the network works better then doing it outside.

From what I have learned by experimenting with joint prediction, you will get the most performance gain, if you share weights between all convolutional layers of the network. You can then apply independent fc-layers, followed by a softmax regression and separate loss functions on top of the jointly predicted features. This will allow the network to learn cross-correlation between features while it is still able to make separate predictions.

Have a look at my MultiNet paper as a good starting point. All our training code is on github.

ContentLicense: CC BY-SA 4.0


问:
Ruby OpenSSL RSA decryption failing due to padding check failed
I'm trying to replicate the following python code in ruby.  The python code works fine, the ruby code fails due to "padding check failed".  I can encrypt a string and decrypt it with the private key in Ruby, but the encrypted data I need to work with is being retrieved from elsewhere.  I'm unsure of the library and even language used to encrypt it, but the Python code works.

Working Python code:

```<code>def decrypt_secret(encrypted_base64, private_key):
  key = RSA.importKey(open(private_key, "r").read())
  pkey = PKCS1_OAEP.new(key, hashAlgo=SHA256)
  encrypted_blob = base64.urlsafe_b64decode(encrypted_base64)
  decrypted_string = pkey.decrypt(encrypted_blob)
  return decrypted_string
</code>```

Ruby Code fails "padding check failed"

```<code>def decrypt_secret(encrypted_base64, private_key)
  key = File.read(private_key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted_blob = Base64.urlsafe_decode64(encrypted_base64)
  decrypted_string = pkey.private_decrypt(encrypted_blob, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
  return decrypted_string
end
</code>```

答:
I found the needed functions contained in the JOSE gem to support SHA256 OAEP.  The following code does the job:</p>

```<code>require 'jose'
def decrypt_secret(encrypted_base64, private_key)
  key = File.read(private_key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted_blob = Base64.urlsafe_decode64(encrypted_base64)
  decrypted_string = JOSE::JWA::PKCS1::rsaes_oaep_decrypt(OpenSSL::Digest::SHA256, encrypted_blob, pkey)
  return decrypted_string
end
</code>```

Body:
I'm trying to replicate the following python code in ruby.  The python code works fine, the ruby code fails due to "padding check failed".  I can encrypt a string and decrypt it with the private key in Ruby, but the encrypted data I need to work with is being retrieved from elsewhere.  I'm unsure of the library and even language used to encrypt it, but the Python code works.

Working Python code:

def decrypt_secret(encrypted_base64, private_key):
  key = RSA.importKey(open(private_key, "r").read())
  pkey = PKCS1_OAEP.new(key, hashAlgo=SHA256)
  encrypted_blob = base64.urlsafe_b64decode(encrypted_base64)
  decrypted_string = pkey.decrypt(encrypted_blob)
  return decrypted_string

Ruby Code fails "padding check failed"

def decrypt_secret(encrypted_base64, private_key)
  key = File.read(private_key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted_blob = Base64.urlsafe_decode64(encrypted_base64)
  decrypted_string = pkey.private_decrypt(encrypted_blob, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
  return decrypted_string
end

Body:
I found the needed functions contained in the JOSE gem to support SHA256 OAEP.  The following code does the job:

require 'jose'
def decrypt_secret(encrypted_base64, private_key)
  key = File.read(private_key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted_blob = Base64.urlsafe_decode64(encrypted_base64)
  decrypted_string = JOSE::JWA::PKCS1::rsaes_oaep_decrypt(OpenSSL::Digest::SHA256, encrypted_blob, pkey)
  return decrypted_string
end