问:
PyTest : Allow Failure Rate
I am currently working on a project where we are running a large suite of parameterized tests (>1M). The tests are randomly generated use-cases and in this large test space, it is expected that in each run certain edge cases will fail, ~1-2%. Is there a implementation for Pytest where you can pass a failure-rate argument, or handle this behavior?</p>

答:
I guess what you want is modify exit status of pytest command, there is a nonpublic hook, named pytest_sessionfinish, could do this.

consider you have following tests:

```<code>def test_spam():
    assert 0

def test_ham():
    pass

def test_eggs():
    pass
</code>```

and a hook in conftest.py:

```<code>import pytest, _pytest

ACCEPTABLE_FAILURE_RATE = 50

@pytest.hookimpl()
def pytest_sessionfinish(session, exitstatus):
    if exitstatus != _pytest.main.EXIT_TESTSFAILED:
        return
    failure_rate = (100.0 * session.testsfailed) / session.testscollected
    if failure_rate <= ACCEPTABLE_FAILURE_RATE:
        session.exitstatus = 0
</code>```

then invoke pytest:

```<code>$ pytest --tb=no -q tests.py
F..                                                                                [100%]
1 failed, 2 passed in 0.06 seconds
</code>```

here the failure rate is 1 / 3 == 33.3%, below 50%:

```<code>$ echo $?
0
</code>```

you could see the exit status of pytest is 0.

Title: PyTest : Allow Failure Rate

Body:
I guess what you want is modify exit status of pytest command, there is a nonpublic hook, named pytest_sessionfinish, could do this.

consider you have following tests:

def test_spam():
    assert 0

def test_ham():
    pass

def test_eggs():
    pass

and a hook in conftest.py:

import pytest, _pytest

ACCEPTABLE_FAILURE_RATE = 50

@pytest.hookimpl()
def pytest_sessionfinish(session, exitstatus):
    if exitstatus != _pytest.main.EXIT_TESTSFAILED:
        return
    failure_rate = (100.0 * session.testsfailed) / session.testscollected
    if failure_rate <= ACCEPTABLE_FAILURE_RATE:
        session.exitstatus = 0

then invoke pytest:

$ pytest --tb=no -q tests.py
F..                                                                                [100%]
1 failed, 2 passed in 0.06 seconds

here the failure rate is 1 / 3 == 33.3%, below 50%:

$ echo $?
0

you could see the exit status of pytest is 0.


来源: stackexchange

问:
Issue with Django logout URL redirection
I have configured login and logout redirect setting in Django settings as below -

```<code>LOGOUT_REDIRECT_URL = '/login/'
LOGIN_REDIRECT_URL = '/locations/'
</code>```

However, after logging out the redirection is done on the next= parameter, ie., the url is redirected to the same page from where logout is clicked.

For the reference, here is login/logout URL from my urls.py -

```<code>url(r'^', include('rest_framework.urls', namespace='rest_framework')),
</code>```

PS: I am using Django 1.11 & DRF 3.7.3

答:
I ran into the same issue. The LOGOUT_REDIRECT_URL was not always working.

Solved it inside my myapp/urls.py:

```<code>from django.contrib.auth.views import logout

urlpatterns = [
  url(r'^logout/$', logout, {'next_page': '/login/'}, name='logout'),
]
</code>```

Then in my desired template I inserted a link to: /'myapp'/logout/

You could as well define it in your main urls.py

ContentLicense: CC BY-SA 3.0

Body:
I have configured login and logout redirect setting in Django settings as below -

LOGOUT_REDIRECT_URL = '/login/'
LOGIN_REDIRECT_URL = '/locations/'

However, after logging out the redirection is done on the next= parameter, ie., the url is redirected to the same page from where logout is clicked.

For the reference, here is login/logout URL from my urls.py -

url(r'^', include('rest_framework.urls', namespace='rest_framework')),

PS: I am using Django 1.11 & DRF 3.7.3

Body:
I ran into the same issue. The LOGOUT_REDIRECT_URL was not always working.

Solved it inside my myapp/urls.py:

from django.contrib.auth.views import logout

urlpatterns = [
  url(r'^logout/$', logout, {'next_page': '/login/'}, name='logout'),
]

Then in my desired template I inserted a link to: /'myapp'/logout/

You could as well define it in your main urls.py


问:
Add-in for Visual Studio for project file editing (csproj)
Do you know an add-in for visual studio which adds properties for C# projects?
csproj file format is very powerful but only small amount of options can be changed through the standard properties page. For instance, I want to have several configurations and each of them should include it's own references. Or I just want to change the type of project from winforms to wpf or other one. In order to do stuff like that developer has to edit csproj by hands in text editor instead of using properties.
If you know that such add-in doesn't exist, do you think that it could be popular on codeplex? or only small amount of developers realy need it? what is your opinion?</p>

答:
How is it going?

To edit project files inside of Visual Studio I use PowerCommands, but those things you can change "using properties" are those in Project Menu -> [Project Name] Properties. What PowerCommands does (among other things...) is allow you to easily edit the XML of a project opened inside Visual Studio so you get all the benefits of using Visual Studio to edit XML. Makes sense?

XML is hierarchical, so hardly you can fit it comfortably on a property list better than on a text editor.

About "I want to have several configurations and each of them should include it's own references", try creating templates for your projects, take a look there: Visual Studio Templates.

So... you are looking for addins at codeplex? why not take a look at http://visualstudiogallery.msdn.microsoft.com there are free and paid addins, an some form codeplex too. While you are on it, look for "Productivity Power Tools", "VSCommands 2010", "AllMargins" and "VS10x Code Map". I use them all, and they are certainly worth a look. [Hmmm... I also use CodeRush, you can get CodeRush Xpress for free from http://www.devexpress.com ;)]

Hope of being of help.

ContentLicense: CC BY-SA 2.5


问:
jQuery Validation Plugin - show error messages and error summary
I need your help to solve a problem. I am using jQuery Validation plugin to validate the forms and I want to display validation summary as well as validation messages with each invalid field.
I tried the following code but i ran into 2 problems;

PROBLEM 1:
Error messages from invalid fields are not showing.

PROBLEM 2:
The error summary is displaying the list of all errors but without the name of the fields. I think the plugin uses the 'errorList' array which holds both the name of the element as well as its error message, but i have no idea how to use this. Ref: https://jqueryvalidation.org/validate

HTML

```<code><form id="theForm" class="formContainer">
   <div id="errorSummary">
      <div class="summaryTitle">
         <!-- FOR ERROR TITLE -->
      </div>
      <ul>
         <!-- FOR ERROR LIST -->
      </ul>
   </div>
   <div class="formbox">
    <label>First Name:</label>
    <input type="text" name="FirstName" class="required">
   </div>
   <div class="formbox">
    <label>Last Name:</label>
    <input type="text" name="Last Name" class="required">
   </div>
   <button type="Submit" id="submitButton">Submit</button>
</form>
</code>```

SCRIPT

```<code><script>
$(document).ready(function(){
   $("#theForm").validate({
     debug:true,
        errorLabelContainer: "#errorSummary ul",
        wrapper: "li",
        invalidHandler: function(event, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                  var message = errors == 1
                    ? '<h4>Submission Failed</h4>You missed 1 field. It has been highlighted'
                    : '<h4>Submission Failed</h4>You missed ' + errors + ' fields. They have been highlighted';
                  $("#errorSummary div.summaryTitle").html(message);
                  $("#errorSummary").show();
                } else {
                  $("#errorSummary").hide();
                }
        },
   });
});
</script>
</code>```

PLEASE NOTE: I am already using errorPlacement property of the plugin for other use

答:
this is how i do it in angular.js. include angular-validator.js and just use the input field like this

```<code><input class="form-control" type="number" validate-on="blur" required required-message="'required'" readonly>
</code>```

where required-message is the message you want to display

Hope it works for you

Body:
I need your help to solve a problem. I am using jQuery Validation plugin to validate the forms and I want to display validation summary as well as validation messages with each invalid field.
I tried the following code but i ran into 2 problems;

PROBLEM 1:
Error messages from invalid fields are not showing.

PROBLEM 2:
The error summary is displaying the list of all errors but without the name of the fields. I think the plugin uses the 'errorList' array which holds both the name of the element as well as its error message, but i have no idea how to use this. Ref: https://jqueryvalidation.org/validate

HTML

<form id="theForm" class="formContainer">

    First Name:
    <input type="text" name="FirstName" class="required">

    Last Name:
    <input type="text" name="Last Name" class="required">

   <button type="Submit" id="submitButton">Submit</button>
</form>

SCRIPT

PLEASE NOTE: I am already using errorPlacement property of the plugin for other use

Body:
this is how i do it in angular.js. include angular-validator.js and just use the input field like this

<input class="form-control" type="number" validate-on="blur" required required-message="'required'" readonly>

where required-message is the message you want to display

Hope it works for you


问:
c#, Microsoft Interop Excel , change font style for s selected range
I need to change the font style (font type ) of some cells in Excel sheet.
Excel sheet is generated by Microsoft.Office.Interop.Excel

I want to change B3 to B100 range to be in Arial font type.
here is my code

```<code>Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
worksheet.get_Range("B3", "B100").Cells.Font.FontStyle = "Arial";

for (int i = 1; i < records_datagridview.Columns.Count + 1; i++)
{
   worksheet.Cells[1, i] = records_datagridview.Columns[i - 1].HeaderText;
}

for (int i = 0; i < records_datagridview.Rows.Count; i++)
{
   for (int j = 0; j < records_datagridview.Columns.Count; j++)
   {
      worksheet.Cells[i + 2, j + 1] = records_datagridview.Rows[i].Cells[j].Value.ToString();
   }
}

String file_path = fbd.SelectedPath + "/records_sheet_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_.xlsx";

workbook.SaveAs(file_path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

app.Quit();
</code>```

I used

```<code>worksheet.get_Range("B3", "B4").Cells.Font.FontStyle = "Arial";
</code>```

But it's not working
Can any one help me on this

答:
You need to define style first.

```<code>Excel.Style style = workbook.Styles.Add("NewStyle");
style.Font.Name = "Arial";
</code>```

Then you need to define cell range and apply new style.

```<code>Excel.Range rangeStyles = app.get_Range("B3", "B100");
rangeStyles.Style = "NewStyle";
</code>```

For more info, check out Microsoft documentatation page https://msdn.microsoft.com/en-us/library/f1hh9fza.aspx

Body:
I need to change the font style (font type ) of some cells in Excel sheet.
Excel sheet is generated by Microsoft.Office.Interop.Excel

I want to change B3 to B100 range to be in Arial font type.
here is my code

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
worksheet.get_Range("B3", "B100").Cells.Font.FontStyle = "Arial";

for (int i = 1; i < records_datagridview.Columns.Count + 1; i++)
{
   worksheet.Cells[1, i] = records_datagridview.Columns[i - 1].HeaderText;
}

for (int i = 0; i < records_datagridview.Rows.Count; i++)
{
   for (int j = 0; j < records_datagridview.Columns.Count; j++)
   {
      worksheet.Cells[i + 2, j + 1] = records_datagridview.Rows[i].Cells[j].Value.ToString();
   }
}

String file_path = fbd.SelectedPath + "/records_sheet_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_.xlsx";

workbook.SaveAs(file_path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

app.Quit();

I used

worksheet.get_Range("B3", "B4").Cells.Font.FontStyle = "Arial";

But it's not working
Can any one help me on this

Body:
You need to define style first.

Excel.Style style = workbook.Styles.Add("NewStyle");
style.Font.Name = "Arial";

Then you need to define cell range and apply new style.

Excel.Range rangeStyles = app.get_Range("B3", "B100");
rangeStyles.Style = "NewStyle";

For more info, check out Microsoft documentatation page https://msdn.microsoft.com/en-us/library/f1hh9fza.aspx


问:
Pandoc: Markdown to Tex -- with using filter show error "failed to parse field blocks"
I try adapt this pandoc filter but I need use Span instead Div.

input file (myfile.md):

```<code>### MY HEADER

[File > Open]{.menu}

[\ctrl + C]{.keys}

Simply line
</code>```

filter file (myfilter.py):

```<code>#!/usr/bin/env python

from pandocfilters import *

def latex(x):
    return RawBlock('latex', x)

def latex_menukeys(key, value, format, meta):
    if key == 'Span':
    [[ident, classes, kvs], contents] = value

    if classes[0] == "menu":
        return([latex('\\menu{')] + contents + [latex('}')])
    elif classes[0] == "keys":
        return([latex('\\keys{')] + contents + [latex('}')])

if __name__ == "__main__":
    toJSONFilter(latex_menukeys)
</code>```

run:

```<code>pandoc myfile.md -o myfile.tex -F myfilter.py

pandoc:Error in $.blocks[1].c[0]: failed to parse field blocks: failed to parse field c: mempty
CallStack <fromHasCallStack>:
error, called at pandoc.hs:144:42 in main:Main
</code>```

How I should use varyable "contents" correct?

答: Suppose Span is inside a paragraph. Then you would be trying to replace it with a RawBlock, which is not going to work. Maybe try using RawInline instead?

Body:
I try adapt this pandoc filter but I need use Span instead Div.

input file (myfile.md):

### MY HEADER

[File > Open]{.menu}

[\ctrl + C]{.keys}

Simply line

filter file (myfilter.py):

#!/usr/bin/env python

from pandocfilters import *

def latex(x):
    return RawBlock('latex', x)

def latex_menukeys(key, value, format, meta):
    if key == 'Span':
    [[ident, classes, kvs], contents] = value

    if classes[0] == "menu":
        return([latex('\\menu{')] + contents + [latex('}')])
    elif classes[0] == "keys":
        return([latex('\\keys{')] + contents + [latex('}')])

if __name__ == "__main__":
    toJSONFilter(latex_menukeys)

run:

pandoc myfile.md -o myfile.tex -F myfilter.py

pandoc:Error in $.blocks[1].c[0]: failed to parse field blocks: failed to parse field c: mempty
CallStack <fromHasCallStack>:
error, called at pandoc.hs:144:42 in main:Main

How I should use varyable "contents" correct?


问:
React weird Firefox error
I've a react app and I'm getting this TypeError in Firefox, latest version, on chrome and safari it works fine.

```<code>message: "t.linkNamed(...).fetch(...).then(...).finally is not a function"
stack: "[1017]/h</t.prototype._fetch....."
</code>```

I tried to debug it without much success. Any ideas?

答:
Notice that fetch is supported on Chrome before it has been supported in your firefox . So it seems you are not using the native fetch . Even though, the response streaming is only supported on Chrome  :

So you have two options:

Either add a polyfill for fetch.

Or migrate to another http client.

REFERENCE: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Title: React weird Firefox error

Body:
I've a react app and I'm getting this TypeError in Firefox, latest version, on chrome and safari it works fine.

message: "t.linkNamed(...).fetch(...).then(...).finally is not a function"
stack: "[1017]/h</t.prototype._fetch....."

I tried to debug it without much success. Any ideas?


问:
string: replace "(" with "\("
i have to send a string to the bash, which contains an escape sequence. For example, i have to replace special characters like "(" with "(", because the bash else throws errors. I trtied like

```<code>public class escape {
    public static void main(String args[]) {
        System.out.println("\\");
        String s = "(foo)";
        System.out.println(s);
        s = s.replaceAll("(", "\\(");
        System.out.println(s);
    }
}
</code>```

with no luck. Please help!!

thanks

答:
String.replaceAll uses a regular expression, which isn't what you want here. Just use String.replace:

```<code>s = s.replace("(", "\\(");
</code>```

Title: string: replace "(" with "\("

Body:
i have to send a string to the bash, which contains an escape sequence. For example, i have to replace special characters like "(" with "(", because the bash else throws errors. I trtied like

public class escape {
    public static void main(String args[]) {
        System.out.println("\\");
        String s = "(foo)";
        System.out.println(s);
        s = s.replaceAll("(", "\\(");
        System.out.println(s);
    }
}

with no luck. Please help!!

thanks

Body:
String.replaceAll uses a regular expression, which isn't what you want here. Just use String.replace:

s = s.replace("(", "\\(");


问:
Hibernate Spring MVC
I am trying to get Products by categoryId, categoryName and so I was writing in some custom queries but nothing seems to work. I am new to hibernate.

// this is my product class

```<code>    package springmvc.java.domain;
    @Entity
    @Table(name = "product")
    public class Product {

        @Id
        @Column(name = "productId" , nullable = false)
        private Long productId;

        @Column(name = "productName", nullable = false)
        private String productName;

        @Column(name = "productCost", nullable = false)
        private double productCost;

        @Column(name = "productDescription")
        private String productDescription;

        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "categoryId", nullable = false)
        private Category category;

        public Long getProductId() {
            return productId;
        }

        public void setProductId(Long productId) {
            this.productId = productId;
        }

        public String getProductName() {
            return productName;
        }

        public void setProductName(String productName) {
            this.productName = productName;
        }

        public double getProductCost() {
            return productCost;
        }

        public void setProductCost(double productCost) {
            this.productCost = productCost;
        }

        public String getProductDescription() {
            return productDescription;
        }

        public void setProductDescription(String productDescription) {
            this.productDescription = productDescription;
        }

    }
</code>```

// ********************************************************

//category class

```<code>    package springmvc.java.domain;
    @Entity
    @Table(name = "category")
    public class Category {

        @Id
        @Column(name = "categoryId", nullable = false)
        private Long categoryId;

        @Column(name = "categoryName", nullable = false)
        private String categoryName;

        @Column(name = "categoryDescription")
        private String categoryDescription;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "category", fetch = FetchType.EAGER)
        private List<Product> products;

        public Long getCategoryId() {
            return categoryId;
        }

        public void setCategoryId(Long categoryId) {
            this.categoryId = categoryId;
        }

        public String getCategoryName() {
            return categoryName;
        }

        public void setCategoryName(String categoryName) {
            this.categoryName = categoryName;
        }

        public String getCategoryDescription() {
            return categoryDescription;
        }

        public void setCategoryDescription(String categoryDescription) {
            this.categoryDescription = categoryDescription;
        }

        public List<Product> getProducts() {
            return products;
        }

        public void setProducts(List<Product> products) {
            this.products = products;
        }

    }
</code>```

// ********************************************************
//My product DAO

which extends JPA Repository
 I am trying to write custom methods with the help of @Query Annotation

```<code>    package springmvc.java.dao;
    import springmvc.java.domain.Product;
    public interface ProductDAO extends JpaRepository<Product,Long> {

        @Query("select p from Product p where p.categoryId = :categoryId")
        public List<Product> findProductsByCategoryId(@Param("categoryId") Long categoryId);`enter code here`
    }
</code>```

// ********************************************************

//Stack Trace

```<code>Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List springmvc.java.dao.ProductDAO.findProductsByCategoryId(java.lang.Long)!
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:92)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:62)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:72)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:53)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:136)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:204)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:73)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:416)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:206)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:251)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:237)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    ... 47 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: categoryId of: springmvc.java.domain.Product [select p from springmvc.java.domain.Product p where p.categoryId = :categoryId]
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1374)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
    at com.sun.proxy.$Proxy36.createQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
    ... 60 more
Caused by: org.hibernate.QueryException: could not resolve property: categoryId of: springmvc.java.domain.Product [select p from springmvc.java.domain.Product p where p.categoryId = :categoryId]
    at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
    at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1968)
    at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:313)
    at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:494)
    at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:598)
    at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:266)
    at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:213)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:118)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:114)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:881)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1264)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4426)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3898)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2076)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:794)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:595)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)
    ... 67 more
</code>```

答:
categoryId - it's actually another entity in your relationship and you do need to access its id field.

Query("select p from Product p where p.categoryId.id = :categoryId")
public List<Product> findProductsByCategoryId(@Param("categoryId") Long categoryId);

Title: Hibernate Spring MVC

Body:
I am trying to get Products by categoryId, categoryName and so I was writing in some custom queries but nothing seems to work. I am new to hibernate.

// this is my product class

    package springmvc.java.domain;
    @Entity
    @Table(name = "product")
    public class Product {

        @Id
        @Column(name = "productId" , nullable = false)
        private Long productId;

        @Column(name = "productName", nullable = false)
        private String productName;

        @Column(name = "productCost", nullable = false)
        private double productCost;

        @Column(name = "productDescription")
        private String productDescription;

        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "categoryId", nullable = false)
        private Category category;

        public Long getProductId() {
            return productId;
        }

        public void setProductId(Long productId) {
            this.productId = productId;
        }

        public String getProductName() {
            return productName;
        }

        public void setProductName(String productName) {
            this.productName = productName;
        }

        public double getProductCost() {
            return productCost;
        }

        public void setProductCost(double productCost) {
            this.productCost = productCost;
        }

        public String getProductDescription() {
            return productDescription;
        }

        public void setProductDescription(String productDescription) {
            this.productDescription = productDescription;
        }

    }

// ********************************************************

//category class

    package springmvc.java.domain;
    @Entity
    @Table(name = "category")
    public class Category {

        @Id
        @Column(name = "categoryId", nullable = false)
        private Long categoryId;

        @Column(name = "categoryName", nullable = false)
        private String categoryName;

        @Column(name = "categoryDescription")
        private String categoryDescription;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "category", fetch = FetchType.EAGER)
        private List<Product> products;

        public Long getCategoryId() {
            return categoryId;
        }

        public void setCategoryId(Long categoryId) {
            this.categoryId = categoryId;
        }

        public String getCategoryName() {
            return categoryName;
        }

        public void setCategoryName(String categoryName) {
            this.categoryName = categoryName;
        }

        public String getCategoryDescription() {
            return categoryDescription;
        }

        public void setCategoryDescription(String categoryDescription) {
            this.categoryDescription = categoryDescription;
        }

        public List<Product> getProducts() {
            return products;
        }

        public void setProducts(List<Product> products) {
            this.products = products;
        }

    }

// ********************************************************
//My product DAO

which extends JPA Repository
 I am trying to write custom methods with the help of @Query Annotation

    package springmvc.java.dao;
    import springmvc.java.domain.Product;
    public interface ProductDAO extends JpaRepository<Product,Long> {

        @Query("select p from Product p where p.categoryId = :categoryId")
        public List<Product> findProductsByCategoryId(@Param("categoryId") Long categoryId);`enter code here`
    }

// ********************************************************

//Stack Trace

Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List springmvc.java.dao.ProductDAO.findProductsByCategoryId(java.lang.Long)!
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:92)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:62)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:72)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:53)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:136)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:204)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:73)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:416)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:206)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:251)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:237)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    ... 47 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: categoryId of: springmvc.java.domain.Product [select p from springmvc.java.domain.Product p where p.categoryId = :categoryId]
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1374)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
    at com.sun.proxy.$Proxy36.createQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
    ... 60 more
Caused by: org.hibernate.QueryException: could not resolve property: categoryId of: springmvc.java.domain.Product [select p from springmvc.java.domain.Product p where p.categoryId = :categoryId]
    at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
    at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1968)
    at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:313)
    at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:494)
    at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:598)
    at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:266)
    at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:213)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:118)
    at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:114)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:881)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1264)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4426)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3898)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2076)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:794)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:595)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)
    ... 67 more


问:
UWP: How to pass parameter to the ViewModel of navigated page?
So I'm creating UWP app, and using method

```<code>Frame.Navigate(Type type)
</code>```

to navigate through my views. But one of my pages requires passing an object with navigation, so i use this method

```<code>Frame.Navigate(Type type, object param)
</code>```

and then I can get the parameter in the code-behind of page like this:

```<code>public object NavigationParameter { get; private set; }

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    NavigationParameter = e.Parameter;
}
</code>```

That's great, but I'm using MVVM pattern, so I want to get this parameter on the VM of my page. How can I do that?

P.S.: Solution with zero code behind would be spectacular.

答:
If you are using UWP with MVVM Light and want to either:

Access the parameter that is passed in the NavigationServicesEx.Navigate method

Call a method in your ViewModel when a page is navigated to.

This blog by Marco Minerva advises how to hook in to the Frame_Navigating event (that it missing from the vanilla NavigationServiceEx class) to access the argument when the destination page is navigated to.

tl;dr

Create the INavigable interface described in the blog:

```<code>public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}
</code>```

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

```<code>NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);
</code>```

In the OnNavigatedToAsync method that you implement in your ViewModel:

```<code>public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}
</code>```

Body:
So I'm creating UWP app, and using method

Frame.Navigate(Type type)

to navigate through my views. But one of my pages requires passing an object with navigation, so i use this method

Frame.Navigate(Type type, object param)

and then I can get the parameter in the code-behind of page like this:

public object NavigationParameter { get; private set; }

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    NavigationParameter = e.Parameter;
}

That's great, but I'm using MVVM pattern, so I want to get this parameter on the VM of my page. How can I do that?

P.S.: Solution with zero code behind would be spectacular.

Body:
If you are using UWP with MVVM Light and want to either:

Access the parameter that is passed in the NavigationServicesEx.Navigate method

Call a method in your ViewModel when a page is navigated to.

This blog by Marco Minerva advises how to hook in to the Frame_Navigating event (that it missing from the vanilla NavigationServiceEx class) to access the argument when the destination page is navigated to.

tl;dr

Create the INavigable interface described in the blog:

public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);

In the OnNavigatedToAsync method that you implement in your ViewModel:

public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}


答:
You can try this.

```<code>;WITH CTE AS
(
    SELECT *,
        GRP = ROW_NUMBER() OVER(PARTITION BY id, CAST( [time_stamp] AS date )  ORDER BY time_stamp)
              - ROW_NUMBER() OVER(PARTITION BY id,CAST( [time_stamp] AS date ) , [AccessType] ORDER BY time_stamp)
    FROM table1
)
, CTE2 AS (
    SELECT
        [id]
        , MIN(CAST( [time_stamp] AS time )) MinTime
        , CAST( [time_stamp] AS date ) [date]
        , CASE [AccessType] WHEN 'IN' THEN 'check_in_' ELSE 'check_out_' END
            + CAST(ROW_NUMBER() OVER(PARTITION  BY id, [AccessType] ORDER BY GRP) AS varchar) ColHeader
    FROM CTE
    GROUP BY
        id
        , [AccessType]
        , GRP
        , CAST( [time_stamp] AS date )
)
SELECT
    id
    , [check_in_1] check_in
    , [check_out_1] check_out
    , CAST( DATEADD(MINUTE, DATEDIFF(MINUTE, [check_in_1] , [check_out_1]), '00:00') AS time) totalhrs
    , [check_in_2] check_in
    , [check_out_2] check_out
    , CAST( DATEADD(MINUTE, DATEDIFF(MINUTE, [check_in_2] , [check_out_2]), '00:00') AS time) totalhrs
    , [date]  FROM CTE2
PIVOT (MIN(MinTime) FOR ColHeader IN ([check_in_1], [check_out_1], [check_in_2], [check_out_2])) PVT
</code>```

Result:

```<code>id          check_in         check_out        totalhrs         check_in         check_out        totalhrs         date
----------- ---------------- ---------------- ---------------- ---------------- ---------------- ---------------- ----------
1001        09:35:00         12:00:00         02:25:00         13:00:00         17:00:00         04:00:00         2017-09-05
1002        11:00:00         12:25:00         01:25:00         14:00:00         18:00:00         04:00:00         2017-09-05
</code>```

Title: date in time and out time not get proper in sql?

Body:
Sql Fiddle Demo

When I change table data like this means result will be changed.

INSERT INTO Table1
    ([id], [time_stamp], [AccessType])
VALUES
    (1001, '2017-09-05 09:35:00', 'IN'),
      (1001, '2017-09-05 09:37:00', 'IN'),
       (1001, '2017-09-05 09:38:00', 'IN'),
    (1002, '2017-09-05 11:00:00', 'IN'),
    (1001, '2017-09-05 12:00:00', 'OUT'),
     (1001, '2017-09-05 12:01:00', 'OUT'),
      (1001, '2017-09-05 12:02:00', 'OUT'),
    (1002, '2017-09-05 12:25:00', 'OUT'),
    (1001, '2017-09-05 13:00:00', 'IN'),
    (1002, '2017-09-05 14:00:00', 'IN'),
    (1001, '2017-09-05 17:00:00', 'OUT'),
    (1002, '2017-09-05 18:00:00', 'OUT');

I want an exact result like this only:

id      check_in    check_out  totalhrs  check_in check_out totalhrs  date
    1001     09:35       12:00      2:25       13:00    17:00     2:00    2013-09-05
    1002     11:00       12:25      1:25       14:00    18:00     4:00    2013-09-05

Body:
You can try this.

;WITH CTE AS
(
    SELECT *,
        GRP = ROW_NUMBER() OVER(PARTITION BY id, CAST( [time_stamp] AS date )  ORDER BY time_stamp)
              - ROW_NUMBER() OVER(PARTITION BY id,CAST( [time_stamp] AS date ) , [AccessType] ORDER BY time_stamp)
    FROM table1
)
, CTE2 AS (
    SELECT
        [id]
        , MIN(CAST( [time_stamp] AS time )) MinTime
        , CAST( [time_stamp] AS date ) [date]
        , CASE [AccessType] WHEN 'IN' THEN 'check_in_' ELSE 'check_out_' END
            + CAST(ROW_NUMBER() OVER(PARTITION  BY id, [AccessType] ORDER BY GRP) AS varchar) ColHeader
    FROM CTE
    GROUP BY
        id
        , [AccessType]
        , GRP
        , CAST( [time_stamp] AS date )
)
SELECT
    id
    , [check_in_1] check_in
    , [check_out_1] check_out
    , CAST( DATEADD(MINUTE, DATEDIFF(MINUTE, [check_in_1] , [check_out_1]), '00:00') AS time) totalhrs
    , [check_in_2] check_in
    , [check_out_2] check_out
    , CAST( DATEADD(MINUTE, DATEDIFF(MINUTE, [check_in_2] , [check_out_2]), '00:00') AS time) totalhrs
    , [date]  FROM CTE2
PIVOT (MIN(MinTime) FOR ColHeader IN ([check_in_1], [check_out_1], [check_in_2], [check_out_2])) PVT

Result:

id          check_in         check_out        totalhrs         check_in         check_out        totalhrs         date
----------- ---------------- ---------------- ---------------- ---------------- ---------------- ---------------- ----------
1001        09:35:00         12:00:00         02:25:00         13:00:00         17:00:00         04:00:00         2017-09-05
1002        11:00:00         12:25:00         01:25:00         14:00:00         18:00:00         04:00:00         2017-09-05


问:
VBA: Edit ColorIndex in a protected sheet without providing passwrod
Today I am here with a tricky question, not sure how or whether this is possible.

My code having a line to edit the color of a button.

```<code>Dim myshape As Shape: Set myshape = Thisworkbook.Worksheet("Mastersheet").Shapes("Button 4")
With myshape
        .TextFrame.Characters.Font.ColorIndex = 15
End With
</code>```

Now my issue is that the Sheet called 'Mastersheet' is a protected sheet which cant be left unprotected. And my macro should be able to change the color of that button without un protecting the sheet.

I tried to left the fields unprotected where this button is placed, using with "Allow user to edit this range" option available, but thats not working. Is there any solution to overcome this??

Please help, thanks in advance.

答:
Right click your Sheet > Select PROTECT SHEET > Provide your desired Password > Scroll down > Checkin EDIT OBJECTS

Which will help your macro to update the Objects... (But there is one risk the users who are using, also able to update the text fields of any objects you placed in that sheet)

Good luck and choose wisely which options suits your need.

Body:
Today I am here with a tricky question, not sure how or whether this is possible.

My code having a line to edit the color of a button.

Dim myshape As Shape: Set myshape = Thisworkbook.Worksheet("Mastersheet").Shapes("Button 4")
With myshape
        .TextFrame.Characters.Font.ColorIndex = 15
End With

Now my issue is that the Sheet called 'Mastersheet' is a protected sheet which cant be left unprotected. And my macro should be able to change the color of that button without un protecting the sheet.

I tried to left the fields unprotected where this button is placed, using with "Allow user to edit this range" option available, but thats not working. Is there any solution to overcome this??

Please help, thanks in advance.


问:
Comparing two array objects
I am attempting to have a function compare objects in an array and see if they are the same

```<code>function alexareturn(alexaword, wordlist) {
  var rhyme = false
  console.log(alexaword + wordlist);
  for (var i = 0; i <= alexaword.length; i++) {
    for (var j = 0; j <= wordlist.length; j++) {
      if (alexaword[i].indexOf(wordlist[j]) > -1) {
        rhyme = true;
        break;
      }
    }
  }
  if (rhyme) {
    return true;
  } else {
    return false;
  }
}
</code>```

My console is returning two proper arrays, however I am getting the error Cannot read indexOf (undefined). If i am getting console to return a proper array right before, how can one of them be undefined?

I would just like to call my function, and have it return true if there is a match of the two arrays, Thanks for your help!

答:
Your outer for loop runs from 0 - alexaword.length (inclusive). In the last iteration alexaword[i] would be undefined.

for (var i = 0; i < alexaword.length; i++) would fix it.

Title: Comparing two array objects

Body:
I am attempting to have a function compare objects in an array and see if they are the same

function alexareturn(alexaword, wordlist) {
  var rhyme = false
  console.log(alexaword + wordlist);
  for (var i = 0; i <= alexaword.length; i++) {
    for (var j = 0; j <= wordlist.length; j++) {
      if (alexaword[i].indexOf(wordlist[j]) > -1) {
        rhyme = true;
        break;
      }
    }
  }
  if (rhyme) {
    return true;
  } else {
    return false;
  }
}

My console is returning two proper arrays, however I am getting the error Cannot read indexOf (undefined). If i am getting console to return a proper array right before, how can one of them be undefined?

I would just like to call my function, and have it return true if there is a match of the two arrays, Thanks for your help!


问:
Which one to go first, Grails or Groovy?
I wanted to create a web application. I thought of selecting Groovy or Grails. But I don't know from where to start! To start with Groovy or Grails?</p>

答:
I've just been in the same situation.

With my last Java experiences dating back some 7 years, I tried to start with Grails directly using "The Definitive Guide to Grails".

I went about 1/3rd thru and thought I understood enough to start out. But as soon as I started to hack I noticed I simply ran into too many errors that would take me hours to resolve, simply because of missing Groovy knowledge.

So I went and got myself "Groovy in Action" (a.k.a GinA). I studied the whole book and programmed each and every listing myself. As I didn't focus on this task solely, it took me several weeks to complete the 600+ pages.

Then I went back to my Grails project and found that I had even forgotten the things I already had known from the first book.

In hindsight, I would go about the task like this:

Directly start your Grails project (I recommend you setup NetBeans SpringSource Tool Suite IntelliJ IDEA Ultimate as your IDE)

Work on it every day for about one
hour

Learn ~50 pages in your
preferred Groovy resource.

Learn ~20 pages in your preferred
Grails resource.

Apply what you
learned

Keep in mind that the current edition of Groovy in Action is dated 2007 and The Definitive Guide to Grails is dated 2009.

In both cases this is quite old, though almost all of the GinA examples still work.

The most important parts of the official Grails Framework Reference are written well structured in chapters, thus it will suite perfectly as your Grails resource.

The following combination would be my personal choice:

Groovy: Groovy in Action, Second Edition as MEAP (Manning Early
Access Program) ($34.99 or $49.99)

Grails: The Grails Framework - Reference Documentation (free)

I'd love to hear about your success & subscribed to your questions as I might be able to help with some of your simpler ones.

Enjoy!


问:
Grunt clean - use one sub-task under other sub-task
I have 4 sub-tasks under grunt-clean

clean: {
    options: {force: true},
    lib: ['demo/client/lib'],
    jsTeamplate: ['src/js/*.template.js'],
    scripts:['dist/js'],
    scss:['src/css/*','dist/css']
},
```

I want to use sub-task lib under other 2 sub-tasks - scss and scripts.

How it should work: Whenever clean:scss is called then firstly it should clean its files and then it should run clean:lib.

The same workflow goes with clean:scripts

答:
You can utilize grunt.registerTask() to achieve this.

An excerpt from the documentation reads:

If a task list is specified, the new task will be an alias for one or more other tasks. Whenever this "alias task" is run, every specified task in taskList will be run, in the order specified. The taskList argument must be an array of tasks.

Given your requirements, register a couple of additional Tasks in your Gruntfile.js as follows:

Gruntfile.js

// ...

grunt.registerTask('foo', [ 'clean:scss', 'clean:lib' ]);

grunt.registerTask('quux ', [ 'clean:scripts', 'clean:lib' ]);

// ...
```

Running the Tasks

Then run the following commands via your CLI instead of $ grunt clean:scss:

$ grunt foo

...The command above will run the clean:scss target, then the clean:lib target

$ grunt quux

...The command above will run the clean:scripts target, then the clean:lib target

Body:
I have 4 sub-tasks under grunt-clean

clean: {
    options: {force: true},
    lib: ['demo/client/lib'],
    jsTeamplate: ['src/js/*.template.js'],
    scripts:['dist/js'],
    scss:['src/css/*','dist/css']
},

I want to use sub-task lib under other 2 sub-tasks - scss and scripts.

How it should work: Whenever clean:scss is called then firstly it should clean its files and then it should run clean:lib.

The same workflow goes with clean:scripts

Body:
You can utilize grunt.registerTask() to achieve this.

An excerpt from the documentation reads:

If a task list is specified, the new task will be an alias for one or more other tasks. Whenever this "alias task" is run, every specified task in taskList will be run, in the order specified. The taskList argument must be an array of tasks.

Given your requirements, register a couple of additional Tasks in your Gruntfile.js as follows:

Gruntfile.js

// ...

grunt.registerTask('foo', [ 'clean:scss', 'clean:lib' ]);

grunt.registerTask('quux ', [ 'clean:scripts', 'clean:lib' ]);

// ...

Running the Tasks

Then run the following commands via your CLI instead of $ grunt clean:scss:

$ grunt foo

...The command above will run the clean:scss target, then the clean:lib target

$ grunt quux

...The command above will run the clean:scripts target, then the clean:lib target


问:
Small python program involving newton method
I'm trying to write a small program in python that involves(among other things) Newton method, but i'm encountering several problems, that are probably pretty basic, but since I'm new at programming, i cant overcome..

First i defined the function and it's derivative:

```<code>import math
def f(x,e,m):
        return x-e*math.sin(x)-m

def df(x,e):
        return 1-e*math.cos(x)

def newtons_method(E0,m,e,q):#q is the error
    while abs(f(E0,e,m))>q:
        E=E0-f(E0,e,m)/df(E0,e)
        E0=E
    return (E0)

def trueanomaly(e,E):
     ta=2*math.arctan(math.sqrt((1+e)/(1-e))*math.tan(E))
     return (ta)

def keplerianfunction(T,P,e,K,y,w):
    for t in frange (0,100,0.5):
        m=(2*math.pi*((t-T)/P))
        E0=m+e*math.sin(m)+((e**2)/2)*math.sin(2*m)
        newtons_method(E0,m,e,0.001)
        trueanomaly(e,E0)
        rv=y+K*(e*math.cos(w)+math.cos(w+ta))
                return (ta)","(rv)

def frange(start, stop, step):
        i = start
        while i < stop:
                yield i
                i += step
</code>```

The question is that this keeps giving me errors, indentation errors and stuff, especially in the keplerianfunction ... Can someone help me? what am I doing wrong here?

Thank you in advance!

答:
Many things are wrong with this code, and I don't know what the desired behaviour is so can't guarantee that this will help, but I'm going to try and help you debug (although it looks like you mostly need to re-read your Python coursebook...).

First, in most languages if not all, there is a thing called the scope: a variable, function, or any other object, exists only within a certain scope. In particular, variables exist only in the scope of the function that they are defined in. This means that, to use the result of a function, you first need to return that result (which you are doing), and when you call that function you need to store that result into a variable, for example ta = trueanomaly(e, E0).

Then, you don't really need to use brackets when returning values, even if you want to return multiple values. If you do want to return multiple values though, you just need to separate them with a comma, but not with a string character of a comma: write return ta, rv instead of return ta","rv.

Finally, you seem to be iterating over a range of values, yet you don't return the whole range of values but either the first value (if your return is in the for loop), or the last one (if your return is under the for loop). Instead, you may want to store all the ta and rv values into one/two lists, and return that/those lists in the end, for example:

```<code>def keplerianfunction(T,P,e,K,y,w):
    # Initialise two empty lists
    tas = []
    rvs = []
    for t in frange (0,100,0.5):
        m = 2*math.pi*((t-T)/P)
        E0 = m+e*math.sin(m)+((e**2)/2)*math.sin(2*m)
        E0 = newtons_method(E0,m,e,0.001)
        ta = trueanomaly(e,E0)
        rv = y+K*(e*math.cos(w)+math.cos(w+ta))
        # At each step save the value for ta and rv into the appropriate list
        tas.append(ta)
        rvs.append(rv)
    # And finally return the lists
    return (tas,rvs)
</code>```

Also, why using a new frange function when range has the exact same behaviour and is probably more efficient?

Body:
I'm trying to write a small program in python that involves(among other things) Newton method, but i'm encountering several problems, that are probably pretty basic, but since I'm new at programming, i cant overcome..

First i defined the function and it's derivative:

import math
def f(x,e,m):
        return x-e*math.sin(x)-m

def df(x,e):
        return 1-e*math.cos(x)

def newtons_method(E0,m,e,q):#q is the error
    while abs(f(E0,e,m))>q:
        E=E0-f(E0,e,m)/df(E0,e)
        E0=E
    return (E0)

def trueanomaly(e,E):
     ta=2*math.arctan(math.sqrt((1+e)/(1-e))*math.tan(E))
     return (ta)

def keplerianfunction(T,P,e,K,y,w):
    for t in frange (0,100,0.5):
        m=(2*math.pi*((t-T)/P))
        E0=m+e*math.sin(m)+((e**2)/2)*math.sin(2*m)
        newtons_method(E0,m,e,0.001)
        trueanomaly(e,E0)
        rv=y+K*(e*math.cos(w)+math.cos(w+ta))
                return (ta)","(rv)

def frange(start, stop, step):
        i = start
        while i < stop:
                yield i
                i += step

The question is that this keeps giving me errors, indentation errors and stuff, especially in the keplerianfunction ... Can someone help me? what am I doing wrong here?

Thank you in advance!

Body:
Many things are wrong with this code, and I don't know what the desired behaviour is so can't guarantee that this will help, but I'm going to try and help you debug (although it looks like you mostly need to re-read your Python coursebook...).

First, in most languages if not all, there is a thing called the scope: a variable, function, or any other object, exists only within a certain scope. In particular, variables exist only in the scope of the function that they are defined in. This means that, to use the result of a function, you first need to return that result (which you are doing), and when you call that function you need to store that result into a variable, for example ta = trueanomaly(e, E0).

Then, you don't really need to use brackets when returning values, even if you want to return multiple values. If you do want to return multiple values though, you just need to separate them with a comma, but not with a string character of a comma: write return ta, rv instead of return ta","rv.

Finally, you seem to be iterating over a range of values, yet you don't return the whole range of values but either the first value (if your return is in the for loop), or the last one (if your return is under the for loop). Instead, you may want to store all the ta and rv values into one/two lists, and return that/those lists in the end, for example:

def keplerianfunction(T,P,e,K,y,w):
    # Initialise two empty lists
    tas = []
    rvs = []
    for t in frange (0,100,0.5):
        m = 2*math.pi*((t-T)/P)
        E0 = m+e*math.sin(m)+((e**2)/2)*math.sin(2*m)
        E0 = newtons_method(E0,m,e,0.001)
        ta = trueanomaly(e,E0)
        rv = y+K*(e*math.cos(w)+math.cos(w+ta))
        # At each step save the value for ta and rv into the appropriate list
        tas.append(ta)
        rvs.append(rv)
    # And finally return the lists
    return (tas,rvs)

Also, why using a new frange function when range has the exact same behaviour and is probably more efficient?


问:
Can a local variable exist before a combined declaration/assignment?
I'm currently trying to debug a small C program whose general structure looks like this:

```<code>int some_function(...) {
    ...
    size_t buf_len = some_other_function(...)
    ...
}

main() {
    ...
    int foo = some_function(...)
    ...
}
</code>```

I've set a breakpoint at some_function() (using lldb). However, if I inspect the stack frame at this breakpoint it shows the variable buf_len already existing with the local scope and even having an arbitrary(?) value. How is this possible if the variable is not declared anywhere before this function?

答: A stack frame contains the args passed in along with the local variables and some other stuff. Look at this, especially the "Structure" section. A breakpoint can not make you stop just between two functions. At a function call, a stack frame is one of the first things created.</p>

Body:
I'm currently trying to debug a small C program whose general structure looks like this:

int some_function(...) {
    ...
    size_t buf_len = some_other_function(...)
    ...
}

main() {
    ...
    int foo = some_function(...)
    ...
}

I've set a breakpoint at some_function() (using lldb). However, if I inspect the stack frame at this breakpoint it shows the variable buf_len already existing with the local scope and even having an arbitrary(?) value. How is this possible if the variable is not declared anywhere before this function?


问:
K-means clustering doesn't find all clusters in data
The set of data I am using is shown below. As one can see you would think the k-means cluster analysis would find the centers of these clusters easily.

However, when I run K-means cluster analysis and plot the centers I get this.

I am using just the basic kmeans code:

```<code>cluster <- kmeans(mydata,90)
cluster$centers
</code>```

答:
This data set is likely to be much better to be clustered by DBSCAN.

Choose epsilon less than the distance of clusters (e.g., 10), and Minpts should not matter much then, e.g., minpts=4

Body:
The set of data I am using is shown below. As one can see you would think the k-means cluster analysis would find the centers of these clusters easily.

However, when I run K-means cluster analysis and plot the centers I get this.

I am using just the basic kmeans code:

cluster <- kmeans(mydata,90)
cluster$centers


问:
Firebase storage: files always accessible via URL?
I am building a small web app using Firebase.

There is the steps :

The User connect (Firebase authentication)

The user upload an image (Firebase storage)

The user can download or see his images

```<code><img [src]="imageFromFirebase">
</code>```

The url given by firebase looks like :

```<code>https://firebasestorage.googleapis.com/v0/b/<Your API>/o/userData_YOQioOsgzUP0B0fTAa6BVK5KOxo2%2Fimages%2F-L-w7THGfT6qmX9UhLsK3.png?alt=media&token=61f6edf9-188e-4177-9ee2-34635ebc5a4a
</code>```

With this URL, I can display the image on the browser only if the user is conneted.

The real problem is that I copied this URL and past it in another web browser (without being authenticated)

And SURPRISE !! this image is displayed !

I don't understand why the image is displayed ?

It is normal ?

Thank you !

答:
When you generate a download URL for a file in Cloud Storage for Firebase, anyone who has the URL will be able to download its contents.  This is by design.  The URL is "unguessable", so only people who actually have the URL will be able to see the content.

If you don't want people to see that file, then don't share the URL.  If the URL is accidentally shared to others who shouldn't have access, you can revoke the token that allows everyone to see the content.

Body:
I am building a small web app using Firebase.

There is the steps :

The User connect (Firebase authentication)

The user upload an image (Firebase storage)

The user can download or see his images

The url given by firebase looks like :

https://firebasestorage.googleapis.com/v0/b/<Your API>/o/userData_YOQioOsgzUP0B0fTAa6BVK5KOxo2%2Fimages%2F-L-w7THGfT6qmX9UhLsK3.png?alt=media&token=61f6edf9-188e-4177-9ee2-34635ebc5a4a

With this URL, I can display the image on the browser only if the user is conneted.

The real problem is that I copied this URL and past it in another web browser (without being authenticated)

And SURPRISE !! this image is displayed !

I don't understand why the image is displayed ?

It is normal ?

Thank you !


问:
sparse 3d matrix/array in Python?
In scipy, we can construct a sparse matrix using scipy.sparse.lil_matrix() etc. But the matrix is in 2d.

I am wondering if there is an existing data structure for sparse 3d matrix / array (tensor) in Python?

p.s. I have lots of sparse data in 3d and need a tensor to store / perform multiplication. Any suggestions to implement such a tensor if there's no existing data structure?

答:
An alternative answer as of 2017 is the sparse package. According to the package itself it implements sparse multidimensional arrays on top of NumPy and scipy.sparse by generalizing the scipy.sparse.coo_matrix layout.

Here's an example taken from the docs:

```<code>import numpy as np
n = 1000
ndims = 4
nnz = 1000000
coords = np.random.randint(0, n - 1, size=(ndims, nnz))
data = np.random.random(nnz)

import sparse
x = sparse.COO(coords, data, shape=((n,) * ndims))
x
# <COO: shape=(1000, 1000, 1000, 1000), dtype=float64, nnz=1000000>

x.nbytes
# 16000000

y = sparse.tensordot(x, x, axes=((3, 0), (1, 2)))

y
# <COO: shape=(1000, 1000, 1000, 1000), dtype=float64, nnz=1001588>
</code>```

Title: sparse 3d matrix/array in Python?

Body:
An alternative answer as of 2017 is the sparse package. According to the package itself it implements sparse multidimensional arrays on top of NumPy and scipy.sparse by generalizing the scipy.sparse.coo_matrix layout.

Here's an example taken from the docs:

import numpy as np
n = 1000
ndims = 4
nnz = 1000000
coords = np.random.randint(0, n - 1, size=(ndims, nnz))
data = np.random.random(nnz)

import sparse
x = sparse.COO(coords, data, shape=((n,) * ndims))
x
# <COO: shape=(1000, 1000, 1000, 1000), dtype=float64, nnz=1000000>

x.nbytes
# 16000000

y = sparse.tensordot(x, x, axes=((3, 0), (1, 2)))

y
# <COO: shape=(1000, 1000, 1000, 1000), dtype=float64, nnz=1001588>

ContentLicense: CC BY-SA 4.0


问:
Why does erlang shell receive exit message from spawned processes only once?
Here is code:

```<code>Erlang/OTP 20 [erts-9.1] [source] [64-bit] [smp:2:2] [ds:2:2:10] [async-threads:10] [kernel-poll:false]

Eshell V9.1  (abort with ^G)
1> process_flag(trap_exit, true).
false
2> spawn_link(fun() -> exit(reason) end).
<0.63.0>
3> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.63.0>,reason}
4> spawn_link(fun() -> exit(reason) end).
<0.66.0>
5> receive X -> X after 0 -> 'end' end.
'end'
</code>```

Why doesn't erlang shell receive exit message from second spawned process?

答:
After the first receive succeeds, X gets bound to its returned value, which is {'EXIT', <...>, reason}. Since you use the same variable X in the second receive, receive waits for a message that exactly matches the old value of X, which won't match the second message because its PID is different than the first one.

To fix this, you can either use a different variable name:

```<code>1> process_flag(trap_exit, true).
false
2> spawn_link(fun() -> exit(reason) end).
<0.67.0>
3> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.67.0>,reason}
4> X.
{'EXIT',<0.67.0>,reason}
5> spawn_link(fun() -> exit(reason) end).
<0.71.0>
6> receive X2 -> X2 after 0 -> 'end' end.
{'EXIT',<0.71.0>,reason}
</code>```

or you can "forget" the value of X using f/1 and then use X again (this will only work in the REPL):

```<code>7> spawn_link(fun() -> exit(reason) end).
<0.74.0>
8> f(X).
ok
9> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.74.0>,reason}
</code>```

Body:
Here is code:

Erlang/OTP 20 [erts-9.1] [source] [64-bit] [smp:2:2] [ds:2:2:10] [async-threads:10] [kernel-poll:false]

Eshell V9.1  (abort with ^G)
1> process_flag(trap_exit, true).
false
2> spawn_link(fun() -> exit(reason) end).
<0.63.0>
3> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.63.0>,reason}
4> spawn_link(fun() -> exit(reason) end).
<0.66.0>
5> receive X -> X after 0 -> 'end' end.
'end'

Why doesn't erlang shell receive exit message from second spawned process?

Body:
After the first receive succeeds, X gets bound to its returned value, which is {'EXIT', <...>, reason}. Since you use the same variable X in the second receive, receive waits for a message that exactly matches the old value of X, which won't match the second message because its PID is different than the first one.

To fix this, you can either use a different variable name:

1> process_flag(trap_exit, true).
false
2> spawn_link(fun() -> exit(reason) end).
<0.67.0>
3> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.67.0>,reason}
4> X.
{'EXIT',<0.67.0>,reason}
5> spawn_link(fun() -> exit(reason) end).
<0.71.0>
6> receive X2 -> X2 after 0 -> 'end' end.
{'EXIT',<0.71.0>,reason}

or you can "forget" the value of X using f/1 and then use X again (this will only work in the REPL):

7> spawn_link(fun() -> exit(reason) end).
<0.74.0>
8> f(X).
ok
9> receive X -> X after 0 -> 'end' end.
{'EXIT',<0.74.0>,reason}


问:
Accessing current item from ListView data source
I figured this wouldn't be too difficult to do, but I can't seem to figure out how to do it. Is there a way to easily access the current item from a ListView data source? For instance, you can easily evaluate the current item's properties using Eval("propertyName"), but is there a way to access the object itself?

And if this isn't possible, what I ultimately want to do is get the Type of the object.

答:
Use FindControl Method.

For example,

```<code>int index=0; // obtain the index of an item.
TextBox num = (TextBox)ListView1.Items[index].FindControl("numTextBox");
</code>```

Body:
Use FindControl Method.

For example,

int index=0; // obtain the index of an item.
TextBox num = (TextBox)ListView1.Items[index].FindControl("numTextBox");


问:
Convert tuple to list in a dictionary
I have a dictionary like this:

```<code>a= {1982: [(1,2,3,4)],
    1542: [(4,5,6,7),
           (4,6,5,7)]}
</code>```

and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7) to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7]

I have tried

```<code>for key, value in a.items():
    for i in value:
        i = tuple(i)
</code>```

but it does now work. How can I achieve it?

答:
As far as I understand you want to convert each tuple in a list. You can do this using a dictionary comprehension:

```<code>{k: [list(ti) for ti in v] for k, v in a.items()}
</code>```

will give

```<code>{1542: [[4, 5, 6, 7], [4, 6, 5, 7]], 1982: [[1, 2, 3, 4]]}
</code>```

Is that what you are after?

Title: Convert tuple to list in a dictionary

Body:
I have a dictionary like this:

a= {1982: [(1,2,3,4)],
    1542: [(4,5,6,7),
           (4,6,5,7)]}

and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7) to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7]

I have tried

for key, value in a.items():
    for i in value:
        i = tuple(i)

but it does now work. How can I achieve it?

Body:
As far as I understand you want to convert each tuple in a list. You can do this using a dictionary comprehension:

{k: [list(ti) for ti in v] for k, v in a.items()}

will give

{1542: [[4, 5, 6, 7], [4, 6, 5, 7]], 1982: [[1, 2, 3, 4]]}

Is that what you are after?


问:
using Microsoft.Office.Interop Conditional coloring of the rows and column range in a excel sheet in C#
I have a dataTable and want to insert the data into excel file using  Microsoft.Office.Interop. I'm iterating the dataTable and checking each row and particular column and based on the particular column value I want to colour the row. I'm facing issues with section where I have commented. Now below code if I use then it is taking the last colour and overriding the other colors. Could you please help me

Suppose I have condition as "Failed" and "Running" "Interrupted" and "Succeeded" which needs to be compared with the particular column in the dataTable and based on it I need to colour the background of the data.

Output should be

```<code>Sample code
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using log4net;
using System.Data;
namespace ReadAppendExcel
{
    public static class DataTable_Extensions
    {
        /// <summary>
        /// Export DataTable to Excel file
        /// </summary>
        /// <param name="DataTable">Source DataTable</param>
        /// <param name="ExcelFilePath">Path to result file name</param>
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static void ExportToExcel(this System.Data.DataTable DataTable, string ExcelFilePath = null)
        {
            log4net.Config.BasicConfigurator.Configure();
            ILog log = log4net.LogManager.GetLogger(typeof(Program));
            try
            {
                int ColumnsCount;
                log.Info("In the ExportToExcel function");
                if (DataTable == null || (ColumnsCount = DataTable.Columns.Count) == 0)
                    throw new Exception("ExportToExcel: Null or empty input table!\n");

                // load excel, and create a new workbook
                Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
                Excel.Workbooks.Add();

                // single worksheet
                Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet;
                int RowsCount = DataTable.Rows.Count;
                object[] Header = new object[ColumnsCount];
                object[] RowsCol = new object[RowsCount];
                // column headings
                for (int i = 0; i < ColumnsCount; i++)
                    Header[i] = DataTable.Columns[i].ColumnName;

                Microsoft.Office.Interop.Excel.Range HeaderRange = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, ColumnsCount]));
                HeaderRange.Value = Header;
                HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Orange);
                HeaderRange.Font.Bold = true;

                // DataCells

                object[,] Cells = new object[RowsCount, ColumnsCount];
                Excel.Range range = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount]));
                range.Value = RowsCol;
                for (int j = 0; j < RowsCount; j++)
                {
                    for (int i = 0; i < ColumnsCount; i++)
                        Cells[j, i] = DataTable.Rows[j][i];
                    if (DataTable.Rows[j][1].ToString() == "Failed")  // CHECKING CONDITION WITH THE DATATABLE
                    {
                        // USE TO COLOR THE ROW AND THE COLUMN RANGE
                        range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

                    }
                    else if (DataTable.Rows[j][1].ToString() == "Running")
                    {
                        // USE TO COLOR THE ROW AND THE COLUMN RANGE
                        range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                    }
                    else if (DataTable.Rows[j][1].ToString() == "Interrupted")
                    {
                        // USE TO COLOR THE ROW AND THE COLUMN RANGE
                        range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                    }
                    else if (DataTable.Rows[j][1].ToString() == "Succeeded")
                    {
                        range.EntireRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                    }
                }
                Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount])).Value = Cells;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Color = Color.Black.ToArgb();
                // check fielpath
                if (ExcelFilePath != null && ExcelFilePath != "")
                {
                    try
                    {
                        Worksheet.SaveAs(ExcelFilePath);
                        Excel.Quit();
                        log.Info("excel successfully created");
                    }
                    catch (Exception ex)
                    {
                        log.Info("ExportToExcel: Excel file could not be saved! Check filepath.\n" + ex.Message.ToString());
                        throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                            + ex.Message);
                    }
                }
                else    // no filepath is given
                {
                    Excel.Visible = true;
                }
            }
            catch (Exception ex)
            {
                log.Info("ExportToExcel: \n" + ex.Message.ToString());
                throw new Exception("ExportToExcel: \n" + ex.Message);
            }
        }
    }
}
</code>```

答:
```<code>    enter code here
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using log4net;
using System.Data;
using System.Diagnostics;

namespace ReadAppendExcel
{
    public static class DataTable_Extensions
    {
        /// <summary>
        /// Export DataTable to Excel file
        /// </summary>
        /// <param name="DataTable">Source DataTable</param>
        /// <param name="ExcelFilePath">Path to result file name</param>
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static void ExportToExcel(this System.Data.DataTable DataTable, string ExcelFilePath = null)
        {
            log4net.Config.BasicConfigurator.Configure();
            ILog log = log4net.LogManager.GetLogger(typeof(Program));
            try
            {
                int ColumnsCount;
                log.Info("In the ExportToExcel function");
                if (DataTable == null || (ColumnsCount = DataTable.Columns.Count) == 0)
                    throw new Exception("ExportToExcel: Null or empty input table!\n");

                // load excel, and create a new workbook
                Excel.Application Excel = new Excel.Application();
                Excel.Workbooks.Add();
                // single worksheet
                Excel._Worksheet Worksheet = Excel.ActiveSheet;
                int RowsCount = DataTable.Rows.Count;
                object[] Header = new object[ColumnsCount];
                object[] RowsCol = new object[RowsCount];
                // column headings
                for (int i = 0; i < ColumnsCount; i++)
                    Header[i] = DataTable.Columns[i].ColumnName;
                // DataCells
                Excel.Range range;
                object[,] Cells = new object[RowsCount, ColumnsCount];
                //Excel.Range range = Worksheet.get_Range((Excel.Range)(Worksheet.Cells[RowsCount, ColumnsCount]), (Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount]));
                //range.Value = RowsCol;
                for (int j = 0; j <= RowsCount-1; j++)
                {
                    for (int i = 0; i < ColumnsCount; i++)
                    {
                        Cells[j, i] = DataTable.Rows[j][i];
                        if (DataTable.Rows[j][1].ToString() == "Failed")  // CHECKING CONDITION WITH THE DATATABLE
                        {
                              range = Worksheet.get_Range((Excel.Range)(Worksheet.Cells[j+1, i + 1]), (Excel.Range)(Worksheet.Cells[j+1, i + 1]));
                              range.Interior.Color = ColorTranslator.ToOle(Color.Red);
                        }
                        else if (DataTable.Rows[j][1].ToString() == "Running")
                        {
                            range = Worksheet.get_Range((Excel.Range)(Worksheet.Cells[j + 1, i + 1]), (Excel.Range)(Worksheet.Cells[j + 1, i + 1]));
                            range.Interior.Color = ColorTranslator.ToOle(Color.Yellow);
                        }
                        else if (DataTable.Rows[j][1].ToString() == "Interrupted")
                        {
                            range = Worksheet.get_Range((Excel.Range)(Worksheet.Cells[j + 1, i + 1]), (Excel.Range)(Worksheet.Cells[j + 1, i + 1]));
                            range.Interior.Color = ColorTranslator.ToOle(Color.Yellow);
                        }
                        else if (DataTable.Rows[j][1].ToString() == "Succeeded")
                        {
                            range = Worksheet.get_Range((Excel.Range)(Worksheet.Cells[j + 1, i + 1]), (Excel.Range)(Worksheet.Cells[j + 1, i + 1]));
                            range.Interior.Color = ColorTranslator.ToOle(Color.White);
                        }
                    }
                }
                Excel.Range HeaderRange = Worksheet.get_Range((Excel.Range)(Worksheet.Cells[1, 1]), (Excel.Range)(Worksheet.Cells[1, ColumnsCount]));
                HeaderRange.Value = Header;
                HeaderRange.Interior.Color = ColorTranslator.ToOle(Color.Orange);
                HeaderRange.Font.Bold = true;
                range = Worksheet.get_Range((Excel.Range)(Worksheet.Cells[2, 1]), (Excel.Range)(Worksheet.Cells[RowsCount, ColumnsCount]));
                Worksheet.get_Range((Excel.Range)(Worksheet.Cells[2, 1]), (Excel.Range)(Worksheet.Cells[RowsCount, ColumnsCount])).Value = Cells;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Color = Color.Black.ToArgb();
                range.Columns.AutoFit();
                // check fielpath
                if (ExcelFilePath != null && ExcelFilePath != "")
                {
                    try
                    {
                        Worksheet.SaveAs(ExcelFilePath);
                        Excel.Quit();
                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Worksheet);
                        GC.Collect();
                        Process[] excelProcesses = Process.GetProcessesByName("excel");
                        foreach (Process p in excelProcesses)
                        {
                            if (string.IsNullOrEmpty(p.MainWindowTitle)) // use MainWindowTitle to distinguish this excel process with other excel processes
                            {
                                p.Kill();
                            }
                        }
                        DataTable.Dispose();
                        log.Info("excel successfully created");
                    }
                    catch (Exception ex)
                    {
                        log.Info("ExportToExcel: Excel file could not be saved! Check filepath.\n" + ex.Message.ToString());
                        throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                            + ex.Message);
                    }
                }
                else    // no filepath is given
                {
                    Excel.Visible = true;
                }
            }
            catch (Exception ex)
            {
                log.Info("ExportToExcel: \n" + ex.Message.ToString());
                throw new Exception("ExportToExcel: \n" + ex.Message);
            }
        }
    }
}
</code>```

Body:
I have a dataTable and want to insert the data into excel file using  Microsoft.Office.Interop. I'm iterating the dataTable and checking each row and particular column and based on the particular column value I want to colour the row. I'm facing issues with section where I have commented. Now below code if I use then it is taking the last colour and overriding the other colors. Could you please help me

Suppose I have condition as "Failed" and "Running" "Interrupted" and "Succeeded" which needs to be compared with the particular column in the dataTable and based on it I need to colour the background of the data.

Output should be

Sample code
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using log4net;
using System.Data;
namespace ReadAppendExcel
{
    public static class DataTable_Extensions
    {
        ///
        /// Export DataTable to Excel file
        ///
        /// <param name="DataTable">Source DataTable</param>
        /// <param name="ExcelFilePath">Path to result file name</param>
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static void ExportToExcel(this System.Data.DataTable DataTable, string ExcelFilePath = null)
        {
            log4net.Config.BasicConfigurator.Configure();
            ILog log = log4net.LogManager.GetLogger(typeof(Program));
            try
            {
                int ColumnsCount;
                log.Info("In the ExportToExcel function");
                if (DataTable == null || (ColumnsCount = DataTable.Columns.Count) == 0)
                    throw new Exception("ExportToExcel: Null or empty input table!\n");

                // load excel, and create a new workbook
                Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
                Excel.Workbooks.Add();

                // single worksheet
                Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet;
                int RowsCount = DataTable.Rows.Count;
                object[] Header = new object[ColumnsCount];
                object[] RowsCol = new object[RowsCount];
                // column headings
                for (int i = 0; i < ColumnsCount; i++)
                    Header[i] = DataTable.Columns[i].ColumnName;

                Microsoft.Office.Interop.Excel.Range HeaderRange = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, ColumnsCount]));
                HeaderRange.Value = Header;
                HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Orange);
                HeaderRange.Font.Bold = true;

                // DataCells

                object[,] Cells = new object[RowsCount, ColumnsCount];
                Excel.Range range = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount]));
                range.Value = RowsCol;
                for (int j = 0; j < RowsCount; j++)
                {
                    for (int i = 0; i < ColumnsCount; i++)
                        Cells[j, i] = DataTable.Rows[j][i];
                    if (DataTable.Rows[j][1].ToString() == "Failed")  // CHECKING CONDITION WITH THE DATATABLE
                    {
                        // USE TO COLOR THE ROW AND THE COLUMN RANGE
                        range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

                    }
                    else if (DataTable.Rows[j][1].ToString() == "Running")
                    {
                        // USE TO COLOR THE ROW AND THE COLUMN RANGE
                        range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                    }
                    else if (DataTable.Rows[j][1].ToString() == "Interrupted")
                    {
                        // USE TO COLOR THE ROW AND THE COLUMN RANGE
                        range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                    }
                    else if (DataTable.Rows[j][1].ToString() == "Succeeded")
                    {
                        range.EntireRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                    }
                }
                Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount])).Value = Cells;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Color = Color.Black.ToArgb();
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Color = Color.Black.ToArgb();
                // check fielpath
                if (ExcelFilePath != null && ExcelFilePath != "")
                {
                    try
                    {
                        Worksheet.SaveAs(ExcelFilePath);
                        Excel.Quit();
                        log.Info("excel successfully created");
                    }
                    catch (Exception ex)
                    {
                        log.Info("ExportToExcel: Excel file could not be saved! Check filepath.\n" + ex.Message.ToString());
                        throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                            + ex.Message);
                    }
                }
                else    // no filepath is given
                {
                    Excel.Visible = true;
                }
            }
            catch (Exception ex)
            {
                log.Info("ExportToExcel: \n" + ex.Message.ToString());
                throw new Exception("ExportToExcel: \n" + ex.Message);
            }
        }
    }
}


问:
Laravel Eloquent belongsto relationship returns null
I have two Eloquent models:

1) Post

```<code>class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = ['id', 'user_id', 'product_id', 'site_id', 'link_id', 'body', 'created_at', 'updated_at'];

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function product(){
        return $this->belongsTo(Product::class);
    }
</code>```

2) Product

```<code>protected $table = 'products';
protected $fillable = ['id', 'user_id', 'manufacturer_id', 'shift_product_id', 'name', 'english_name',
                        'slug', 'text', 'spec', 'live', 'created_at', 'updated_at'];

public function posts(){
    return $this->hasMany(Post::class);
}
</code>```

I need to get the product from a post
I do that:

```<code>$posts = Post::get();

foreach($posts as $key){
    dd($key->product);
}
</code>```

Like this it returns NULL
If I do like this:
 dd($key->product());
I get the product but I can't to use that

but I need to get something like that to use whant I need:

答:
The relationship probably doesn't exist in the database.

Based on your fillable array on Post, the way you have the relationships setup looks correct as you are following naming conventions for keys and your belongsTo relationship methods have the correct name for convention.

$post->product() is not returning your Product model. It is returning a Relation type object (BelongsTo). This is used for querying the relationship. $post->product would be the dynamic property for the relationship that would return the already loaded relationship or load the relationship and give you the result.

Laravel 5.5 Docs - Eloquent - Relationships - Relationship Methods Vs. Dynamic Properties

If the relationships are setup correctly $post->product being null would mean the relationship doesn't actually exist in the database, no matching id in products for product_id or product_id being null. (assuming no foreign key constraint)

Side note: eager loading the relationship would be a good idea:

```<code>$posts = Post::with('product')->get();
</code>```

Body:
I have two Eloquent models:

1) Post

class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = ['id', 'user_id', 'product_id', 'site_id', 'link_id', 'body', 'created_at', 'updated_at'];

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function product(){
        return $this->belongsTo(Product::class);
    }

2) Product

protected $table = 'products';
protected $fillable = ['id', 'user_id', 'manufacturer_id', 'shift_product_id', 'name', 'english_name',
                        'slug', 'text', 'spec', 'live', 'created_at', 'updated_at'];

public function posts(){
    return $this->hasMany(Post::class);
}

I need to get the product from a post
I do that:

$posts = Post::get();

foreach($posts as $key){
    dd($key->product);
}

Like this it returns NULL
If I do like this:
 dd($key->product());
I get the product but I can't to use that

but I need to get something like that to use whant I need:

Body:
The relationship probably doesn't exist in the database.

Based on your fillable array on Post, the way you have the relationships setup looks correct as you are following naming conventions for keys and your belongsTo relationship methods have the correct name for convention.

$post->product() is not returning your Product model. It is returning a Relation type object (BelongsTo). This is used for querying the relationship. $post->product would be the dynamic property for the relationship that would return the already loaded relationship or load the relationship and give you the result.

Laravel 5.5 Docs - Eloquent - Relationships - Relationship Methods Vs. Dynamic Properties

If the relationships are setup correctly $post->product being null would mean the relationship doesn't actually exist in the database, no matching id in products for product_id or product_id being null. (assuming no foreign key constraint)

Side note: eager loading the relationship would be a good idea:

$posts = Post::with('product')->get();


问:
How do I change the headers that PHP sends when using file_get_contents on an external URL?
I need to change the headers that PHP sends when it requests a file using file_get_contents(). Is that possible or would I have to use CURL?</p>

答:
You can use file_get_contents() in conjunction with stream_context_create()

Exemple :

```<code><?php
$context = stream_context_create(array(
    'http'=>array(
        'method'=>"GET",
        'header'=>"Accept-language: en\r\n" .
                  "Cookie: foo=bar\r\n"
  )
));
$out = file_get_contents($filename, false, $context);
</code>```

Body:
You can use file_get_contents() in conjunction with stream_context_create()

Exemple :

<?php
$context = stream_context_create(array(
    'http'=>array(
        'method'=>"GET",
        'header'=>"Accept-language: en\r\n" .
                  "Cookie: foo=bar\r\n"
  )
));
$out = file_get_contents($filename, false, $context);