问:
Resolving relative paths when using ph-schematron
I'm using ph-schematron, a Java library that validates XML documents via ISO Schematron:

This library provides 2 ways of XML document validation:

Validation via XSLT

Validation via Pure Schematron

I would love to use the second type, but my Schematron files contain XSLT functions so we MUST use the validation using XSLT and not the pure one.

I have a validation method that has two input paramters:

The XSLT representation of the schematron file

The XML document to validate

Now my XSLT file contains lines like this:

```<code><xsl:when test="count(hl7:confidentialityCode[concat(@code,@codeSystem)=doc('include/voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml')//valueSet[1]/conceptList/concept/concat(@code,@codeSystem) or @nullFlavor])>=1" />
</code>```

And the doc function looks for a folder called 'include' in the home directory of my project instead of the folder relative to the XSLT document (which would be more logic).

Now I got exceptions like:

```<code>java.io.FileNotFoundException: C:\LocalData\Development\projectname\include\voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at net.sf.saxon.event.Sender.sendSAXSource(Sender.java:451)
at net.sf.saxon.event.Sender.send(Sender.java:153)
at net.sf.saxon.functions.DocumentFn.makeDoc(DocumentFn.java:330)
at net.sf.saxon.functions.Doc.call(Doc.java:138)
at net.sf.saxon.functions.Doc.call(Doc.java:24)
at net.sf.saxon.expr.FunctionCall.iterate(FunctionCall.java:546)
at net.sf.saxon.expr.Expression.evaluateItem(Expression.java:773)
at net.sf.saxon.expr.SimpleStepExpression.iterate(SimpleStepExpression.java:108)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.value.MemoClosure.iterate(MemoClosure.java:109)
at net.sf.saxon.expr.VariableReference.iterate(VariableReference.java:482)
at net.sf.saxon.expr.GeneralComparison.effectiveBooleanValue(GeneralComparison.java:621)
at net.sf.saxon.expr.OrExpression.effectiveBooleanValue(OrExpression.java:131)
at net.sf.saxon.expr.FilterIterator$NonNumeric.matches(FilterIterator.java:198)
at net.sf.saxon.expr.FilterIterator.getNextMatchingItem(FilterIterator.java:81)
at net.sf.saxon.expr.FilterIterator.next(FilterIterator.java:64)
at net.sf.saxon.functions.Exists$1.effectiveBooleanValue(Exists.java:67)
at net.sf.saxon.expr.instruct.Choose.choose(Choose.java:865)
at net.sf.saxon.expr.instruct.Choose.processLeavingTail(Choose.java:840)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:653)
at net.sf.saxon.expr.instruct.TemplateRule.applyLeavingTail(TemplateRule.java:353)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:456)
at net.sf.saxon.trans.TextOnlyCopyRuleSet.process(TextOnlyCopyRuleSet.java:65)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:433)
at net.sf.saxon.expr.instruct.ApplyTemplates.apply(ApplyTemplates.java:298)
at net.sf.saxon.expr.instruct.ApplyTemplates.processLeavingTail(ApplyTemplates.java:255)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:653)
at net.sf.saxon.expr.instruct.Instruction.process(Instruction.java:149)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:364)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:311)
at net.sf.saxon.expr.instruct.TemplateRule.applyLeavingTail(TemplateRule.java:353)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:456)
at net.sf.saxon.Controller.transformDocument(Controller.java:2321)
at net.sf.saxon.Controller.transform(Controller.java:1892)
at net.sf.saxon.s9api.XsltTransformer.transform(XsltTransformer.java:579)
at net.sf.saxon.jaxp.TransformerImpl.transform(TransformerImpl.java:185)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.applySchematronValidation(AbstractSchematronXSLTBasedResource.java:273)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.applySchematronValidationToSVRL(AbstractSchematronXSLTBasedResource.java:288)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.getSchematronValidity(AbstractSchematronXSLTBasedResource.java:197)
at com.helger.schematron.AbstractSchematronResource.getSchematronValidity(AbstractSchematronResource.java:210)
at epsos.ccd.posam.tm.util.NewSchematronValidator.doValidate(NewSchematronValidator.java:47)
at epsos.ccd.posam.tm.util.NewSchematronValidator.validate(NewSchematronValidator.java:39)
at epsos.ccd.posam.tm.util.SchematronValidatorTest.testValidationNew(SchematronValidatorTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

How can I force the doc function to look at the include folder in the same directory as the XSLT file and not in the root of my Java Project?

答:
It seems this is an open issue for ph-schematron library when an xslt funcion is used, so no solution for now I think =(

https://github.com/phax/ph-schematron/issues/60

Body:
I'm using ph-schematron, a Java library that validates XML documents via ISO Schematron:

This library provides 2 ways of XML document validation:

Validation via XSLT

Validation via Pure Schematron

I would love to use the second type, but my Schematron files contain XSLT functions so we MUST use the validation using XSLT and not the pure one.

I have a validation method that has two input paramters:

The XSLT representation of the schematron file

The XML document to validate

Now my XSLT file contains lines like this:

<xsl:when test="count(hl7:confidentialityCode[concat(@code,@codeSystem)=doc('include/voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml')//valueSet[1]/conceptList/concept/concat(@code,@codeSystem) or @nullFlavor])>=1" />

And the doc function looks for a folder called 'include' in the home directory of my project instead of the folder relative to the XSLT document (which would be more logic).

Now I got exceptions like:

java.io.FileNotFoundException: C:\LocalData\Development\projectname\include\voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at net.sf.saxon.event.Sender.sendSAXSource(Sender.java:451)
at net.sf.saxon.event.Sender.send(Sender.java:153)
at net.sf.saxon.functions.DocumentFn.makeDoc(DocumentFn.java:330)
at net.sf.saxon.functions.Doc.call(Doc.java:138)
at net.sf.saxon.functions.Doc.call(Doc.java:24)
at net.sf.saxon.expr.FunctionCall.iterate(FunctionCall.java:546)
at net.sf.saxon.expr.Expression.evaluateItem(Expression.java:773)
at net.sf.saxon.expr.SimpleStepExpression.iterate(SimpleStepExpression.java:108)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.value.MemoClosure.iterate(MemoClosure.java:109)
at net.sf.saxon.expr.VariableReference.iterate(VariableReference.java:482)
at net.sf.saxon.expr.GeneralComparison.effectiveBooleanValue(GeneralComparison.java:621)
at net.sf.saxon.expr.OrExpression.effectiveBooleanValue(OrExpression.java:131)
at net.sf.saxon.expr.FilterIterator$NonNumeric.matches(FilterIterator.java:198)
at net.sf.saxon.expr.FilterIterator.getNextMatchingItem(FilterIterator.java:81)
at net.sf.saxon.expr.FilterIterator.next(FilterIterator.java:64)
at net.sf.saxon.functions.Exists$1.effectiveBooleanValue(Exists.java:67)
at net.sf.saxon.expr.instruct.Choose.choose(Choose.java:865)
at net.sf.saxon.expr.instruct.Choose.processLeavingTail(Choose.java:840)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:653)
at net.sf.saxon.expr.instruct.TemplateRule.applyLeavingTail(TemplateRule.java:353)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:456)
at net.sf.saxon.trans.TextOnlyCopyRuleSet.process(TextOnlyCopyRuleSet.java:65)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:433)
at net.sf.saxon.expr.instruct.ApplyTemplates.apply(ApplyTemplates.java:298)
at net.sf.saxon.expr.instruct.ApplyTemplates.processLeavingTail(ApplyTemplates.java:255)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:653)
at net.sf.saxon.expr.instruct.Instruction.process(Instruction.java:149)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:364)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:311)
at net.sf.saxon.expr.instruct.TemplateRule.applyLeavingTail(TemplateRule.java:353)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:456)
at net.sf.saxon.Controller.transformDocument(Controller.java:2321)
at net.sf.saxon.Controller.transform(Controller.java:1892)
at net.sf.saxon.s9api.XsltTransformer.transform(XsltTransformer.java:579)
at net.sf.saxon.jaxp.TransformerImpl.transform(TransformerImpl.java:185)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.applySchematronValidation(AbstractSchematronXSLTBasedResource.java:273)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.applySchematronValidationToSVRL(AbstractSchematronXSLTBasedResource.java:288)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.getSchematronValidity(AbstractSchematronXSLTBasedResource.java:197)
at com.helger.schematron.AbstractSchematronResource.getSchematronValidity(AbstractSchematronResource.java:210)
at epsos.ccd.posam.tm.util.NewSchematronValidator.doValidate(NewSchematronValidator.java:47)
at epsos.ccd.posam.tm.util.NewSchematronValidator.validate(NewSchematronValidator.java:39)
at epsos.ccd.posam.tm.util.SchematronValidatorTest.testValidationNew(SchematronValidatorTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

How can I force the doc function to look at the include folder in the same directory as the XSLT file and not in the root of my Java Project?


来源: stackexchange

问:
SQL: Comparing two tables for missing records and then on the date fields
I have two tables as below

work_assignments

```<code>emp_id   | start_date  |   End Date
------------------------------------------
  1      | May-10-2017 | May-30-2017
  1      | Jun-05-2017 | null
  2      | May-08-2017 | null
</code>```

hourly_pay

```<code>emp_id   | start_date  |   End Date    |  Rate
-----------------------------------------------
  1      | May-20-2017 | Jun-30-2017   |  75
  1      | Jul-01-2017 | null          |  80
</code>```

These 2 tables share the emp_id (employee id) foreign key and joining these two I should be able to:

find employee records missing in the hourly_pay table.
Given the data here, the query should return emp_id 2 from work_assignments table

find the records where the hourly_pay start_date that are later than the work assignments start_date. Again, given the data here, the query should return emp_id 1 (because work_assignments.start_date has May-10-2017, while the earliest hourly_pay.start_date is on May-20-2017)

I am able to achieve the first part of result using the join query below

```<code>select distinct emp_id from work_contracts
left join hourly_pay hr USING(emp_id)
where hr.emp_id is null
</code>```

I am stuck on the second part where probably  I need a correlated subquery to tell the hourly pay table records that did not start before the work_assignments start_date? or is there any other way?

答:
This hints at a between condition, with some twists, but I've had extremely bad luck using betweens in joins.  They appear to perform some form of cross-join on the back and end then filter out the actual join where-clause style.  I know that's not very technical, but I've never done a non-equality condition in a join that's turned out well.

So, this may seem counter-intuitive, but I think exploding all date possibilities might actually be your best bet.  Without knowing how big your date ranges actually are it's hard to say.

Also, I think this will actually satisfy both conditions in your question at once -- by telling you all work assignments that do not have corresponding pay rates.

Try this against your actual data and see how it works (and how long it takes).

```<code>with pay_dates as (
  select
    emp_id, rate,
    generate_series (start_date, coalesce (end_date, current_date), interval '1 day') as pd
  from hourly_pay
),
assignment_dates as (
  select
    emp_id, start_date,
    generate_series (start_date, coalesce (end_date, current_date), interval '1 day') as wd
  from work_assignments
)
select
  emp_id, min (wd)::date as from_date,
  max (wd)::date as thru_date
from
  assignment_dates a
where
  not exists (
    select null
    from pay_dates p
    where p.emp_id = a.emp_id
    and a.wd = p.pd
  )
group by
  emp_id, start_date
</code>```

The results should be all work assignment ranges with no rates:

```<code>emp     from             thru
1    '2017-05-10'    '2017-05-19'
2    '2017-05-08'    '2017-11-14'
</code>```

The cool thing is it would also remove any overlaps, where a work assignment was partially covered.

-- Edit 3/20/2018 --

Per your request, here is a break-down of what the logic does.

```<code>with pay_dates as(
  select
    emp_id, rate,
    generate_series (start_date, coalesce (end_date, current_date), interval '1 day') as pd
  from hourly_pay
)
</code>```

This takes the hourly_pay data and breaks it into a record for each employee, for each day:

```<code>emp_id    rate    pay date
1         75      5/20/17
1         75      5/21/17
1         75      5/22/17
...
1         75      6/30/17
1         80      6/01/17
1         80      6/02/17
...
1         80      today
</code>```

Next,

```<code>[implied "with"]
assignment_dates as (
  select
    emp_id, start_date,
    generate_series (start_date, coalesce (end_date, current_date), interval '1 day') as wd
  from work_assignments
)
</code>```

Effectively does the same thing for the work assignments table, only preserving the "start date column" in each row.

Then the main query is this:

```<code>select
  emp_id, min (wd)::date as from_date,
  max (wd)::date as thru_date
from
  assignment_dates a
where
  not exists (
    select null
    from pay_dates p
    where p.emp_id = a.emp_id
    and a.wd = p.pd
  )
group by
  emp_id, start_date
</code>```

Which draws from the two queries above.  The important part is the anti-join:

```<code>not exists (
  select null
  from pay_dates p
  where p.emp_id = a.emp_id
  and a.wd = p.pd
)
</code>```

That identifies every work assignment where there is no corresponding record for that employee, for that day.

So in essence, the query takes the data ranges from both tables, comes up with every possible date combination and then does an anti-join to see where they don't match.

While it seems counterintuitive, to take a single record and blow it up into multiple records, two things to consider:

Dates are very bounded creatures -- even in 10 years worth of data that only constitutes 4,000 or so records, which isn't much to a database, even when multiplied by an employee database.  Your time frame looks much less than that.

I've had very, VERY bad luck using joins other than =, for example between or >.  It seems in the background it does cartesians and then filters the results.  By comparison, exploding the ranges at least gives you some control over how much data explosion occurs.

For grins, I did it with your sample data above and came up with this, which actually looks accurate:

```<code>1   '2017-05-10'    '2017-05-19'
2   '2017-05-08'    '2018-03-20'
</code>```

Let me know if any of that is unclear.

ContentLicense: CC BY-SA 3.0

Body:
I have two tables as below

work_assignments

emp_id   | start_date  |   End Date
------------------------------------------
  1      | May-10-2017 | May-30-2017
  1      | Jun-05-2017 | null
  2      | May-08-2017 | null

hourly_pay

emp_id   | start_date  |   End Date    |  Rate
-----------------------------------------------
  1      | May-20-2017 | Jun-30-2017   |  75
  1      | Jul-01-2017 | null          |  80

These 2 tables share the emp_id (employee id) foreign key and joining these two I should be able to:

find employee records missing in the hourly_pay table.
Given the data here, the query should return emp_id 2 from work_assignments table

find the records where the hourly_pay start_date that are later than the work assignments start_date. Again, given the data here, the query should return emp_id 1 (because work_assignments.start_date has May-10-2017, while the earliest hourly_pay.start_date is on May-20-2017)

I am able to achieve the first part of result using the join query below

select distinct emp_id from work_contracts
left join hourly_pay hr USING(emp_id)
where hr.emp_id is null

I am stuck on the second part where probably  I need a correlated subquery to tell the hourly pay table records that did not start before the work_assignments start_date? or is there any other way?

Body:
This hints at a between condition, with some twists, but I've had extremely bad luck using betweens in joins.  They appear to perform some form of cross-join on the back and end then filter out the actual join where-clause style.  I know that's not very technical, but I've never done a non-equality condition in a join that's turned out well.

So, this may seem counter-intuitive, but I think exploding all date possibilities might actually be your best bet.  Without knowing how big your date ranges actually are it's hard to say.

Also, I think this will actually satisfy both conditions in your question at once -- by telling you all work assignments that do not have corresponding pay rates.

Try this against your actual data and see how it works (and how long it takes).

with pay_dates as (
  select
    emp_id, rate,
    generate_series (start_date, coalesce (end_date, current_date), interval '1 day') as pd
  from hourly_pay
),
assignment_dates as (
  select
    emp_id, start_date,
    generate_series (start_date, coalesce (end_date, current_date), interval '1 day') as wd
  from work_assignments
)
select
  emp_id, min (wd)::date as from_date,
  max (wd)::date as thru_date
from
  assignment_dates a
where
  not exists (
    select null
    from pay_dates p
    where p.emp_id = a.emp_id
    and a.wd = p.pd
  )
group by
  emp_id, start_date

The results should be all work assignment ranges with no rates:

emp     from             thru
1    '2017-05-10'    '2017-05-19'
2    '2017-05-08'    '2017-11-14'

The cool thing is it would also remove any overlaps, where a work assignment was partially covered.

-- Edit 3/20/2018 --

Per your request, here is a break-down of what the logic does.

with pay_dates as(
  select
    emp_id, rate,
    generate_series (start_date, coalesce (end_date, current_date), interval '1 day') as pd
  from hourly_pay
)

This takes the hourly_pay data and breaks it into a record for each employee, for each day:

emp_id    rate    pay date
1         75      5/20/17
1         75      5/21/17
1         75      5/22/17
...
1         75      6/30/17
1         80      6/01/17
1         80      6/02/17
...
1         80      today

Next,

[implied "with"]
assignment_dates as (
  select
    emp_id, start_date,
    generate_series (start_date, coalesce (end_date, current_date), interval '1 day') as wd
  from work_assignments
)

Effectively does the same thing for the work assignments table, only preserving the "start date column" in each row.

Then the main query is this:

select
  emp_id, min (wd)::date as from_date,
  max (wd)::date as thru_date
from
  assignment_dates a
where
  not exists (
    select null
    from pay_dates p
    where p.emp_id = a.emp_id
    and a.wd = p.pd
  )
group by
  emp_id, start_date

Which draws from the two queries above.  The important part is the anti-join:

not exists (
  select null
  from pay_dates p
  where p.emp_id = a.emp_id
  and a.wd = p.pd
)

That identifies every work assignment where there is no corresponding record for that employee, for that day.

So in essence, the query takes the data ranges from both tables, comes up with every possible date combination and then does an anti-join to see where they don't match.

While it seems counterintuitive, to take a single record and blow it up into multiple records, two things to consider:

Dates are very bounded creatures -- even in 10 years worth of data that only constitutes 4,000 or so records, which isn't much to a database, even when multiplied by an employee database.  Your time frame looks much less than that.

I've had very, VERY bad luck using joins other than =, for example between or >.  It seems in the background it does cartesians and then filters the results.  By comparison, exploding the ranges at least gives you some control over how much data explosion occurs.

For grins, I did it with your sample data above and came up with this, which actually looks accurate:

1   '2017-05-10'    '2017-05-19'
2   '2017-05-08'    '2018-03-20'

Let me know if any of that is unclear.


问:
How do I merge elements in my array of strings in which there are leading and trailing parens?
In Ruby, let's say I have an array of strings

```<code>["a", "(b", "c)", "d", "e"]
</code>```

How do I merge (with a space in between) strings in my array where the first character of one is a "(" and the last character of another one is ")"?  In the above example, I would want the resulting array to be

```<code>["a", "(b c)", "d", "e"]
</code>```

Similarly, if my array were

```<code>["a", "(b", "e", "c)", "d"]
</code>```

I would want the result to be

```<code>["a", "(b e c)", "d"]
</code>```

However if the array were

```<code>["(a", "c"]
</code>```

or

```<code>["c)", "e", "(b"]
</code>```

I would want the arrays to be unchanged b/c in the first instance, there is no element with a ")" and in the second instance the element with the ")" is before the element beginning with the "(".  I hope this makes sense.

答:
My first question would be, how did you get such a weird array? It looks like the result of splitting something that maybe shouldn't have been split that way.

I'm sure there are cleverer ways to do it, but a simple approach would be to iterate through the array and maintain a buffer of items to concatenate (or append to the end of the output if no closing item is found):

```<code>def regroup(arr)
  out, buf = [], []

  arr.each do |elem|
    if buf.empty? && !elem.start_with?('(')
      out << elem
    else
      buf << elem

      if elem.end_with?(')')
        out << buf.join(' ')

        buf.clear
      end
    end
  end

  out.concat(buf)
end
</code>```

The main issue with this approach is that it doesn't handle nested groups. To support that, you need some way to ensure an equal number of opening and closing items before flushing the buffer:

```<code>def regroup(arr)
  out, buf, count = [], [], 0

  arr.each do |elem|
    if buf.empty? && !elem.start_with?('(')
      out << elem
    else
      buf << elem

      if elem.start_with?('(')
        count += 1
      elsif elem.end_with?(')')
        count -= 1
      end

      if count.zero?
        out << buf.join(' ')

        buf.clear
      end
    end
  end

  out.concat(buf)
end
</code>```

This should be pretty efficient, since it's one iteration through the array with a minimal amount of objects created. Unfortunately, it still doesn't handle some cases, e.g. if ["(a", "(b", "c)"] should return ["(a", "(b c)"]. For that, you'll likely need a recursive function. Let me know if you'd like to see that solution.

UPDATE: It was much more difficult to implement a recursive solution than I thought it would be. I have a working version, but it's so ugly that I'm reluctant to share it! If I needed backtracking, I would probably use Amadan's regex solution or something similar. I also wrote a version of my solution with primitive backtracking:

```<code>def regroup(arr)
  out, pos = [], 0

  loop do
    should_retry = regroup_worker(arr.drop(pos)) do |elem, size=1|
      out << elem

      pos += size
    end

    break out unless should_retry
  end
end

def regroup_worker(arr)
  buf, count = [], 0

  arr.each do |elem|
    if buf.empty? && !elem.start_with?('(')
      yield elem
    else
      buf << elem

      if elem.start_with?('(')
        count += 1
      elsif elem.end_with?(')')
        count -= 1
      end

      if count.zero?
        yield buf.join(' '), buf.size

        buf.clear
      end
    end
  end

  # we have unbalanced parens, so let the caller consume the "bad" opening
  # paren and try again (returns false if nothing left to do)
  yield buf.first unless buf.empty?
end

regroup(["(a", "(b", "c)"]) # => ["(a", "(b c)"]
</code>```

I hope this has been helpful! It was certainly an interesting problem to think about and try to solve.

Body:
In Ruby, let's say I have an array of strings

["a", "(b", "c)", "d", "e"]

How do I merge (with a space in between) strings in my array where the first character of one is a "(" and the last character of another one is ")"?  In the above example, I would want the resulting array to be

["a", "(b c)", "d", "e"]

Similarly, if my array were

["a", "(b", "e", "c)", "d"]

I would want the result to be

["a", "(b e c)", "d"]

However if the array were

["(a", "c"]

or

["c)", "e", "(b"]

I would want the arrays to be unchanged b/c in the first instance, there is no element with a ")" and in the second instance the element with the ")" is before the element beginning with the "(".  I hope this makes sense.

Body:
My first question would be, how did you get such a weird array? It looks like the result of splitting something that maybe shouldn't have been split that way.

I'm sure there are cleverer ways to do it, but a simple approach would be to iterate through the array and maintain a buffer of items to concatenate (or append to the end of the output if no closing item is found):

def regroup(arr)
  out, buf = [], []

  arr.each do |elem|
    if buf.empty? && !elem.start_with?('(')
      out << elem
    else
      buf << elem

      if elem.end_with?(')')
        out << buf.join(' ')

        buf.clear
      end
    end
  end

  out.concat(buf)
end

The main issue with this approach is that it doesn't handle nested groups. To support that, you need some way to ensure an equal number of opening and closing items before flushing the buffer:

def regroup(arr)
  out, buf, count = [], [], 0

  arr.each do |elem|
    if buf.empty? && !elem.start_with?('(')
      out << elem
    else
      buf << elem

      if elem.start_with?('(')
        count += 1
      elsif elem.end_with?(')')
        count -= 1
      end

      if count.zero?
        out << buf.join(' ')

        buf.clear
      end
    end
  end

  out.concat(buf)
end

This should be pretty efficient, since it's one iteration through the array with a minimal amount of objects created. Unfortunately, it still doesn't handle some cases, e.g. if ["(a", "(b", "c)"] should return ["(a", "(b c)"]. For that, you'll likely need a recursive function. Let me know if you'd like to see that solution.

UPDATE: It was much more difficult to implement a recursive solution than I thought it would be. I have a working version, but it's so ugly that I'm reluctant to share it! If I needed backtracking, I would probably use Amadan's regex solution or something similar. I also wrote a version of my solution with primitive backtracking:

def regroup(arr)
  out, pos = [], 0

  loop do
    should_retry = regroup_worker(arr.drop(pos)) do |elem, size=1|
      out << elem

      pos += size
    end

    break out unless should_retry
  end
end

def regroup_worker(arr)
  buf, count = [], 0

  arr.each do |elem|
    if buf.empty? && !elem.start_with?('(')
      yield elem
    else
      buf << elem

      if elem.start_with?('(')
        count += 1
      elsif elem.end_with?(')')
        count -= 1
      end

      if count.zero?
        yield buf.join(' '), buf.size

        buf.clear
      end
    end
  end

  # we have unbalanced parens, so let the caller consume the "bad" opening
  # paren and try again (returns false if nothing left to do)
  yield buf.first unless buf.empty?
end

regroup(["(a", "(b", "c)"]) # => ["(a", "(b c)"]

I hope this has been helpful! It was certainly an interesting problem to think about and try to solve.


问:
How to get the cache misses in rails
I am using Rails.cache for caching

```<code>config.action_controller.perform_caching = true
config.cache_store = :file_store, "location"
</code>```

How can I check if there was a cache miss?

Also, I am not able to see the cache miss information in my logs.

Thanks

答: To get pragmatic notifications about cache events, look to ActiveSupport::Notifications to subscribe to cache events.

Title: How to get the cache misses in rails

Body:
I am using Rails.cache for caching

config.action_controller.perform_caching = true
config.cache_store = :file_store, "location"

How can I check if there was a cache miss?

Also, I am not able to see the cache miss information in my logs.

Thanks


问:
Math needed for Sql Server
I've been working in Sql server jobs since 2 years now. Although I like it, sometimes I get the feeling that at certain times, I stall too much on some tasks, and I seem to be discouraged easily from things that involve relatively simple logic. It's like, at some point I must repeat a logical condition inside my head more than 2 or 3 times in order to understand it completely.

I have the feeling that this might be of my lack of math knowledge. Can anyone please let me know what area of mathematics I can study, that would improve my Sql server coding skills?

Thank you.

答: Get a copy of this book. It should prove to be most useful: The Art of SQL, by Stephane Faroult.

OwnerDisplayName: anon

LastEditorDisplayName: anon

Title: Math needed for Sql Server

ContentLicense: CC BY-SA 2.5


问:
How to set custom Firebase Security?
I haven't used Firebase Authentication. All my data is used from the database. The storage and database rules are set to public. Finally, How do i set it so that only admins can write/delete data?

Here are 2 pictures of the database :

1.Tree View With User Details

2.Tree View With Admin Details

答:
Use Firebase Auth. Sign up an account for the Admin users, then add the admin users user ID as the only one that can read/write.

```<code> "rules": {
    "users": {
      "$uid": {
        ".read": auth.uid == 'ansiodfnio3n20nas0dnf0asn',
        ".write": auth.uid == 'ansiodfnio3n20nas0dnf0asn'",
      },
</code>```

Without setting up firebase admin, there isn't much you can do except totally lock it down and using a backend server to access the DB.

Title: How to set custom Firebase Security?

Body:
Use Firebase Auth. Sign up an account for the Admin users, then add the admin users user ID as the only one that can read/write.

 "rules": {
    "users": {
      "$uid": {
        ".read": auth.uid == 'ansiodfnio3n20nas0dnf0asn',
        ".write": auth.uid == 'ansiodfnio3n20nas0dnf0asn'",
      },

Without setting up firebase admin, there isn't much you can do except totally lock it down and using a backend server to access the DB.


问:
How Can I Browse/View The Values Stored in Redis
Are there any good browsers/explorer for viewing Redis out there ?
Am new to Redis so my expectation is if there is something similar to MongoVUE,Toad or SQLExplorer.

I tried Redis Admin UI from service stack but ran into 500 error when trying on IIS

答: I really like qredis, it is a Python + Qt graphical interface to explore redis databases that should deserve more popularity IMO.</p>

ContentLicense: CC BY-SA 4.0


问:
Add a pop up modal to WooCommerce product "view more" button
I'm developing a wordpress website which has a product page, listing products in a grid. All products are as in the picture below.
products grid

I want to know: when click on the view more button, a pop up shows, which has 2 columns, in the left, product full description and images, at the right a form, with placeholders and options and a submit order button. the goal is when click sumbit after client entered all data, the product, with all data that has been entered send as an email to the admin.

I naturally dont want all the code needed, just the workflow. like first do this, then do that and etc...

Appreciate all helps

答:
Here, this should be more than enough to get you started.

First you need to add the css, js elements to your page, you can add them separately into CSS, and JS files using WordPress enqueue hook, this is just basic example:

I copied the Modal sample on: https://www.w3schools.com/howto/howto_css_modals.asp to use in this example.

```<code>function pop_up() {
?>
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <div class="content-left">
         <!-- Leave empty to be able to populate later with ajax -->
    </div>

    <div class="content-right">
         <!-- Put your form here -->
    </div>
  </div>

</div>
<style>
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
</style>

<script>
jQuery(document).ready(function($) {
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
    modal.style.display = "none";
}
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
// Let's do the magic
    // make sure to change #myBtn to read more button selector
    $(document).on("click","#myBtn",function(e) {
    e.stopImmediatePropagation();
    e.preventDefault();
    // get url
        var url = $(this).attr('href');
        var container = $('#myModal').find('.content-left');
        var data = {
            action: 'show_product',
            url: url,

        };
        $.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
           // display the response
           console.log(response);
           $(container).empty();
           $(container).html(response);
            modal.style.display = "block";
        });
    });
});
</script>
<?php
}
add_action( 'wp_footer', 'pop_up' );
</code>```

Now we will create a response with php based on the url send by the post request, you can use this to get product image, content, description, price or anything, and put it together to return it in HTML form inside ajax response to display it inside the modal

```<code>add_action('wp_ajax_show_product', 'show_product_callback_wp');
add_action( 'wp_ajax_nopriv_show_product', 'show_product_callback_wp' );
function show_product_callback_wp() {
     $url = $_POST['url'];
     $product_id = url_to_postid( $url );

    // product content
    $content_post = get_post($product_id);
    $content = $content_post->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]>', $content);

     $output = "";
     $output .= get_the_post_thumbnail( $product_id, 'medium');;
     $output .= $content;

     echo $output;
     exit();
}
</code>```

This is tested and working.

Body:
Here, this should be more than enough to get you started.

First you need to add the css, js elements to your page, you can add them separately into CSS, and JS files using WordPress enqueue hook, this is just basic example:

I copied the Modal sample on: https://www.w3schools.com/howto/howto_css_modals.asp to use in this example.

function pop_up() {
?>
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <div class="content-left">
         <!-- Leave empty to be able to populate later with ajax -->
    </div>

    <div class="content-right">
         <!-- Put your form here -->
    </div>
  </div>

</div>
<style>
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
</style>

<script>
jQuery(document).ready(function($) {
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
    modal.style.display = "none";
}
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
// Let's do the magic
    // make sure to change #myBtn to read more button selector
    $(document).on("click","#myBtn",function(e) {
    e.stopImmediatePropagation();
    e.preventDefault();
    // get url
        var url = $(this).attr('href');
        var container = $('#myModal').find('.content-left');
        var data = {
            action: 'show_product',
            url: url,

        };
        $.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
           // display the response
           console.log(response);
           $(container).empty();
           $(container).html(response);
            modal.style.display = "block";
        });
    });
});
</script>
<?php
}
add_action( 'wp_footer', 'pop_up' );

Now we will create a response with php based on the url send by the post request, you can use this to get product image, content, description, price or anything, and put it together to return it in HTML form inside ajax response to display it inside the modal

add_action('wp_ajax_show_product', 'show_product_callback_wp');
add_action( 'wp_ajax_nopriv_show_product', 'show_product_callback_wp' );
function show_product_callback_wp() {
     $url = $_POST['url'];
     $product_id = url_to_postid( $url );

    // product content
    $content_post = get_post($product_id);
    $content = $content_post->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]&gt;', $content);

     $output = "";
     $output .= get_the_post_thumbnail( $product_id, 'medium');;
     $output .= $content;

     echo $output;
     exit();
}

This is tested and working.


问:
digit_sum error, iterating through a string and then changing to an integer, python
On Codecademy.com I am on section 8, "Practice Makes Perfect", exercise 4 they ask you to:

Write a function called digit_sum that takes a positive integer n
  as input and returns the sum of all that number's digits. For example:
  digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that
  the number you are given will always be positive.)

```<code>def digit_sum(n):
    total = 0
    n = str(n)
    for i in n:
        total += int(n[i])
    return total
</code>```

Since you have to only add one of the digits, I wrote a program that changed the number into a string and then iterate over each digit. When I iterate, I add each number to a local varible, total, by accessing the digit and then changing the number back into an integer. After writing my program, I was thrown the error "string indices must be integers, not str". This is the error you get when you try to add a number to a string. I was confused by this so I researched if other people were having the same problem. I also asked my programming teacher and we still could not figure it out. Can someone explain what I am doing wrong?

It does not tell me what line is throwing the error either. I forgot to mention but on the website they give a solution, but it is not at all in the terms of what I am doing, I am just severely confused of why this error is occurring.

答:
Just change it to:

```<code>   def digit_sum(n):
    total = 0
    n = str(n)
    for i in n:
        total += int(i)
    return total
</code>```

In python, unike c++ and other languages:

 the for loop iterates the element   itself and not its index.

Body:
On Codecademy.com I am on section 8, "Practice Makes Perfect", exercise 4 they ask you to:

Write a function called digit_sum that takes a positive integer n
  as input and returns the sum of all that number's digits. For example:
  digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that
  the number you are given will always be positive.)

def digit_sum(n):
    total = 0
    n = str(n)
    for i in n:
        total += int(n[i])
    return total

Since you have to only add one of the digits, I wrote a program that changed the number into a string and then iterate over each digit. When I iterate, I add each number to a local varible, total, by accessing the digit and then changing the number back into an integer. After writing my program, I was thrown the error "string indices must be integers, not str". This is the error you get when you try to add a number to a string. I was confused by this so I researched if other people were having the same problem. I also asked my programming teacher and we still could not figure it out. Can someone explain what I am doing wrong?

It does not tell me what line is throwing the error either. I forgot to mention but on the website they give a solution, but it is not at all in the terms of what I am doing, I am just severely confused of why this error is occurring.

Body:
Just change it to:

   def digit_sum(n):
    total = 0
    n = str(n)
    for i in n:
        total += int(i)
    return total

In python, unike c++ and other languages:

 the for loop iterates the element   itself and not its index.


问:
MyFirebaseMessagingService is not working but notification is shown
I receive notifications from Firebase but my classes I've created not working (not involved in the actions). Seems like they are shown by default. </p>

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String title = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();
        String click_action = remoteMessage.getNotification().getClickAction();
        Intent intent = new Intent(click_action);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this)

                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notifiBuilder.build());

    }
}
</code>```

答:
There are two types of FCM messages: notification and data.  They are handled differently in the receiving device.  If you are sending a notification message with no data fields, the notification is generated by the client SDK and onMessageReceived() is not invoked.  This is explained in more detail in the documentation:

Notification Message: FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages
  have a predefined set of user-visible keys and an optional data
  payload of custom key-value pairs.

Data Message: Client app is responsible for processing data messages. Data messages have only custom key-value pairs.

Body:
I receive notifications from Firebase but my classes I've created not working (not involved in the actions). Seems like they are shown by default.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String title = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();
        String click_action = remoteMessage.getNotification().getClickAction();
        Intent intent = new Intent(click_action);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this)

                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notifiBuilder.build());

    }
}


问:
How to change button text in Swift Xcode 6?
Here's what I'm trying to do. If you've ever played Halo or CoD, you'd know that you could change the name of a weapon load-out.

What I'm doing is making it so you can change your load-out name using a text field. Here's the problem, the load-out name in the load-out menu is a button (to select and view info about that load-out) and I could just write this:

```<code>@IBAction func renameClassButton(sender: AnyObject) {
    classTopButton.text = "\(classTopTextField)"
}
</code>```

Except it [classTopButton] is a button which doesn't allow the '.text' suffix

答:
swift 4 work as well as 3

```<code>libero.setTitle("---", for: .normal)
</code>```

where libero is a uibutton

Body:
Here's what I'm trying to do. If you've ever played Halo or CoD, you'd know that you could change the name of a weapon load-out.

What I'm doing is making it so you can change your load-out name using a text field. Here's the problem, the load-out name in the load-out menu is a button (to select and view info about that load-out) and I could just write this:

@IBAction func renameClassButton(sender: AnyObject) {
    classTopButton.text = "\(classTopTextField)"
}

Except it [classTopButton] is a button which doesn't allow the '.text' suffix

Body:
swift 4 work as well as 3

libero.setTitle("---", for: .normal)

where libero is a uibutton


问:
How To Connect To Remote Server IP Using MSSQL2005?
I have a following details provided by our mssql2005 database provider

```<code>Server IP : 100.20.255.34
Databaase name : insss
User: nas0
password : ymkv45SEv
</code>```

i have the following connectionstring in my web.config file in my offline site as :

```<code><add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</code>```

I want

how to edit my web.config connection string mentioned above using the details provided above so that it connect to my MSSQl2005 hosting provider .... ?

I don't know how to edit connection string to do that !!

When i run my site www.vbi.volvobusesindia.com then the following error occurs in top of the page ...

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

答:
This should work just fine:</p>

```<code><add name="ConnectionString" connectionString="Data Source=100.20.255.34;Initial Catalog=insss;User ID=nas0;Password=ymkv45SEv;Integrated Security=False" providerName="System.Data.SqlClient"/>
</code>```

Body:
I have a following details provided by our mssql2005 database provider

Server IP : 100.20.255.34
Databaase name : insss
User: nas0
password : ymkv45SEv

i have the following connectionstring in my web.config file in my offline site as :

<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

I want

how to edit my web.config connection string mentioned above using the details provided above so that it connect to my MSSQl2005 hosting provider .... ?

I don't know how to edit connection string to do that !!

When i run my site www.vbi.volvobusesindia.com then the following error occurs in top of the page ...

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Body:
This should work just fine:

<add name="ConnectionString" connectionString="Data Source=100.20.255.34;Initial Catalog=insss;User ID=nas0;Password=ymkv45SEv;Integrated Security=False" providerName="System.Data.SqlClient"/>


问:
Django 1.10 seed database without using fixtures
So I've looked at the documentation, as well as this SO question, and the django-seed package, but none of these seem to fit what I'm trying to do.

Basically, I want to programmatically seed my Games model from an external API, but all the information I can find seems to be reliant on generating a fixture first, which seems like an unnecessary step.

For example, in Ruby/Rails you can write directly to seed.rb and seed the database in anyway that's desired.

If a similar functionality available in Django, or do I need to generate the fixture first from the API, and then import it?

答:
You can use a data migration for this. First create an empty migration for your app:

```<code>$ python manage.py makemigrations yourappname --empty
</code>```

In your empty migration, create a function to load your data and add a migrations.RunPython operation. Here's a modified version of the one from the Django documentation on migrations:

```<code>from __future__ import unicode_literals
from django.db import migrations

def stream_from_api():
    ...

def load_data(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model('yourappname', 'Person')

    for item in stream_from_api():
        person = Person(first=item['first'], last=item['last'], age=item['age'])
        person.save()

class Migration(migrations.Migration):
    dependencies = [('yourappname', '0009_something')]
    operations = [migrations.RunPython(load_data)]
</code>```

If you have a lot of simple data, you might benefit from the bulk-creation methods:

```<code>from __future__ import unicode_literals
from django.db import migrations

def stream_from_api():
    ...

def load_data(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model('yourappname', 'Person')

    def stream_people():
        for item in stream_from_api():
            yield Person(first=item['first'], last=item['last'], age=item['age'])

    # Adjust (or remove) the batch size depending on your needs.
    # You won't be able to use this method if your objects depend on one-another
    Person.objects.bulk_create(stream_people(), batch_size=10000)

class Migration(migrations.Migration):
    dependencies = [('yourappname', '0009_something')]
    operations = [migrations.RunPython(load_data)]
</code>```

Migrations have the added benefit of being automatically enclosed in a transaction, so you can stop the migration at any time and it won't leave your database in an inconsistent state.

Body:
You can use a data migration for this. First create an empty migration for your app:

$ python manage.py makemigrations yourappname --empty

In your empty migration, create a function to load your data and add a migrations.RunPython operation. Here's a modified version of the one from the Django documentation on migrations:

from __future__ import unicode_literals
from django.db import migrations

def stream_from_api():
    ...

def load_data(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model('yourappname', 'Person')

    for item in stream_from_api():
        person = Person(first=item['first'], last=item['last'], age=item['age'])
        person.save()

class Migration(migrations.Migration):
    dependencies = [('yourappname', '0009_something')]
    operations = [migrations.RunPython(load_data)]

If you have a lot of simple data, you might benefit from the bulk-creation methods:

from __future__ import unicode_literals
from django.db import migrations

def stream_from_api():
    ...

def load_data(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model('yourappname', 'Person')

    def stream_people():
        for item in stream_from_api():
            yield Person(first=item['first'], last=item['last'], age=item['age'])

    # Adjust (or remove) the batch size depending on your needs.
    # You won't be able to use this method if your objects depend on one-another
    Person.objects.bulk_create(stream_people(), batch_size=10000)

class Migration(migrations.Migration):
    dependencies = [('yourappname', '0009_something')]
    operations = [migrations.RunPython(load_data)]

Migrations have the added benefit of being automatically enclosed in a transaction, so you can stop the migration at any time and it won't leave your database in an inconsistent state.


问:
Project nested array field values by their indexes in aggregation
I'm doing an aggregation in MongoDB which should have an array fields projection in its $project stage . But I can't access array fields by their indexes :

```<code>{//projection stage
  $project: {
    'foo' : { '$ifNull' : ['$bar.0.baz.0.qux', '*'] }
  }
}
</code>```

This sets foo to an empty array . bar is a multidimensional array field. my MongoDB version is 3.2 . What can I do for this without the hassle of $unwind/$group old heavy solution ?

Thanks for your help .

答:
Use multiple $project stage with $arrayElemAt operator with temporary fields.

{$project:{"tmp": {$arrayElemAt:["$bar",0]}}},
{$project:{"tmp2": {$arrayElemAt:["$tmp.baz",0]}}}

than your value is at $tmp2.qux.

Body:
I'm doing an aggregation in MongoDB which should have an array fields projection in its $project stage . But I can't access array fields by their indexes :

{//projection stage
  $project: {
    'foo' : { '$ifNull' : ['$bar.0.baz.0.qux', '*'] }
  }
}

This sets foo to an empty array . bar is a multidimensional array field. my MongoDB version is 3.2 . What can I do for this without the hassle of $unwind/$group old heavy solution ?

Thanks for your help .


问:
Whats the best way to write nested sums in haskell
So if the limits of the nested sums don't depend on each other I can write this:

```<code>sumgrand k q l r = k*q*l*r
kspace = [1..10]
qspace = [1..10]
lspace = [1..10]
rspace = [1..10]
result = sum $ map sumgrand kSpace <*> qSpace <*> lSpace <*> rSpace
</code>```

This seems to be efficient and clean,  but suppose the limits of the inner sums depend at where I'm at in the outer sum (the limits of the q sum depend on the k sum or the limits of the r sum depend on the q sum).  What's the best (efficient and clean) way to do this?  What I came up with is the following:

```<code>applyNsaveIdx y f x = (f x, (y, x))

sumInAtIdx limitsFunction (outerGrand, oindex) =
    map ( applyNsaveIdx oindex outerGrand) innerSpace where
      innerSpace = limitsFunction oindex

sumInner partiallyAppliedOuter limitF = foldl (++) [] $
    map (sumInAtIdx limitF) partiallyAppliedOuter

kspace = [0..10]
qspace (0,k)         = [0..k]
lspace ((0,k),q)     = [0..q]
rspace (((0,k),q),l) = [0..l]

kSum     = map (applyNsaveIdx 0 sumgrand) kspace
qkSum    = sumInner kSum   qspace
lqkSum   = sumInner qkSum  lspace
rlqkSum  = sumInner lqkSum rspace
result = sum $ map fst rlqkSum
</code>```

This ends up being much slower.  I imagine I can do it faster if I use recursion, but I can't think of a clean way to do recursion. It seems like monads (controlling a sequence of computations) would be helpful here, but I don't understand them well enough.  My applyNsaveIdx reminds me of what I vaguely know of the writer monad, but I'm not sure how to use it here or if it's all that usefull.

Thanks for any help or suggestions.

答:
What about a list comprehension?</p>

```<code>sum [f x y z | x <- [1..10], y <- [x..2*x], z <- [x+y..x+y+4]]
</code>```

Body:
So if the limits of the nested sums don't depend on each other I can write this:

sumgrand k q l r = k*q*l*r
kspace = [1..10]
qspace = [1..10]
lspace = [1..10]
rspace = [1..10]
result = sum $ map sumgrand kSpace <*> qSpace <*> lSpace <*> rSpace

This seems to be efficient and clean,  but suppose the limits of the inner sums depend at where I'm at in the outer sum (the limits of the q sum depend on the k sum or the limits of the r sum depend on the q sum).  What's the best (efficient and clean) way to do this?  What I came up with is the following:

applyNsaveIdx y f x = (f x, (y, x))

sumInAtIdx limitsFunction (outerGrand, oindex) =
    map ( applyNsaveIdx oindex outerGrand) innerSpace where
      innerSpace = limitsFunction oindex

sumInner partiallyAppliedOuter limitF = foldl (++) [] $
    map (sumInAtIdx limitF) partiallyAppliedOuter

kspace = [0..10]
qspace (0,k)         = [0..k]
lspace ((0,k),q)     = [0..q]
rspace (((0,k),q),l) = [0..l]

kSum     = map (applyNsaveIdx 0 sumgrand) kspace
qkSum    = sumInner kSum   qspace
lqkSum   = sumInner qkSum  lspace
rlqkSum  = sumInner lqkSum rspace
result = sum $ map fst rlqkSum

This ends up being much slower.  I imagine I can do it faster if I use recursion, but I can't think of a clean way to do recursion. It seems like monads (controlling a sequence of computations) would be helpful here, but I don't understand them well enough.  My applyNsaveIdx reminds me of what I vaguely know of the writer monad, but I'm not sure how to use it here or if it's all that usefull.

Thanks for any help or suggestions.

Body:
What about a list comprehension?

sum [f x y z | x <- [1..10], y <- [x..2*x], z <- [x+y..x+y+4]]


问:
How to maintain the Try/Catch stack in an async operation
I have a windows service which runs a number of async tasks, however I'm having a problem with catching exceptions and returning them back to the calling method. In the following psuedo-code example, the try/catch is simply stopping the entire service rather than running up the stack. What's the best way to implement a Try/Catch in an async task?

```<code>foreach (var t in tables)
{
    try
    {
        new Task(async () =>
            {
                try
                {
                    //Do stuff
                }
                catch (DataError e)
                {
                    throw e;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        };
    }
    catch (Exception e)
    {
        return new DatabaseActionResult();
    }
}
</code>```

Ultimately, I want to catch and return a DatabaseActionResult object no matter what happens in any task. Again though, once the throw e happens, it totally shuts down the service and none of the other Try/Catch blocks catch anything.

How can I get this working without "awaiting" the task?

答:
It seems to me that async is intended to be used with await for error catching by design. I don't see a good way to do what you're trying to do.

If you want more control over the way the errors are handled without having to await the task, you could maybe run the task in a separate thread explicitly, rather than letting async handle it.

Body:
I have a windows service which runs a number of async tasks, however I'm having a problem with catching exceptions and returning them back to the calling method. In the following psuedo-code example, the try/catch is simply stopping the entire service rather than running up the stack. What's the best way to implement a Try/Catch in an async task?

foreach (var t in tables)
{
    try
    {
        new Task(async () =>
            {
                try
                {
                    //Do stuff
                }
                catch (DataError e)
                {
                    throw e;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        };
    }
    catch (Exception e)
    {
        return new DatabaseActionResult();
    }
}

Ultimately, I want to catch and return a DatabaseActionResult object no matter what happens in any task. Again though, once the throw e happens, it totally shuts down the service and none of the other Try/Catch blocks catch anything.

How can I get this working without "awaiting" the task?


问:
Error in embeding icons in PopUpMenuButton node
I am trying to create a popupmenubutton, with images and label as its nodes. But I am unable to embed the icons. It gives me and error(given below). Thou the label alone are working fine.

```<code><mx:PopUpMenuButton id="menu_file" labelField="@label" itemClick="{menuClickHandler(event);}" visible="false"
        height="20" left="0" top="0" width="15" alpha="0.5" cornerRadius="5" useHandCursor="true"
        toolTip="Delete, Move, Rename or Modify other properties">
        <mx:dataProvider>
            <mx:XMLList>
                <node label="{LABEL_DELETE}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
                <node label="{LABEL_DOWNLOAD}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
                <node label="{LABEL_MOVE}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
                <node label="{LABEL_RENAME}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
                <node label="{LABEL_SET_PRIVACY}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
            </mx:XMLList>
        </mx:dataProvider>
</code>```

This gives me an error: Initializer for 'Embed': unrecognized compile-time directive.

Plz can someone tell me what I am doing wrong here.

Thanks
Zeeshan

答:
I think the problem is that the code as written is attempting to embed an image as the value of the icon attribute in your node - the value of an attribute can only be a String.

Without knowing anything else about your application, I'd say you'd have to re-write your dataProvider like this:

```<code><mx:dataProvider>
        <mx:XMLList>
            <node label="{LABEL_DELETE}" icon="assets/FileManager/images/cancel2.png"/>
            <node label="{LABEL_DOWNLOAD}" icon="assets/FileManager/images/cancel2.png"/>
            <node label="{LABEL_MOVE}" icon="assets/FileManager/images/cancel2.png"/>
            <node label="{LABEL_RENAME}" icon="assets/FileManager/images/cancel2.png"/>
            <node label="{LABEL_SET_PRIVACY}" icon="assets/FileManager/images/cancel2.png"/>
        </mx:XMLList>
    </mx:dataProvider>
</code>```

Obviously, you wouldn't have the ability to embed the icon images this way, but maybe you don't need to?  I'm not 100% sure, but I think the dataProvider is applied at runtime, which would mean that there is no way to embed icon images with this approach.

If I'm wrong about that, you could write an item renderer that would look at the value of the icon attribute and embed the image found at that path.

If I'm right, you could write a custom item renderer that embeds all of the icon images and then displays the correct icon based on the value of label, or some other identifying attribute.

Body:
I am trying to create a popupmenubutton, with images and label as its nodes. But I am unable to embed the icons. It gives me and error(given below). Thou the label alone are working fine.

<mx:PopUpMenuButton id="menu_file" labelField="@label" itemClick="{menuClickHandler(event);}" visible="false"
        height="20" left="0" top="0" width="15" alpha="0.5" cornerRadius="5" useHandCursor="true"
        toolTip="Delete, Move, Rename or Modify other properties">
        <mx:dataProvider>
            <mx:XMLList>
                <node label="{LABEL_DELETE}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
                <node label="{LABEL_DOWNLOAD}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
                <node label="{LABEL_MOVE}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
                <node label="{LABEL_RENAME}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
                <node label="{LABEL_SET_PRIVACY}" icon="@Embed(source='assets/FileManager/images/cancel2.png')"/>
            </mx:XMLList>
        </mx:dataProvider>

This gives me an error: Initializer for 'Embed': unrecognized compile-time directive.

Plz can someone tell me what I am doing wrong here.

Thanks
Zeeshan

Body:
I think the problem is that the code as written is attempting to embed an image as the value of the icon attribute in your node - the value of an attribute can only be a String.

Without knowing anything else about your application, I'd say you'd have to re-write your dataProvider like this:

<mx:dataProvider>
        <mx:XMLList>
            <node label="{LABEL_DELETE}" icon="assets/FileManager/images/cancel2.png"/>
            <node label="{LABEL_DOWNLOAD}" icon="assets/FileManager/images/cancel2.png"/>
            <node label="{LABEL_MOVE}" icon="assets/FileManager/images/cancel2.png"/>
            <node label="{LABEL_RENAME}" icon="assets/FileManager/images/cancel2.png"/>
            <node label="{LABEL_SET_PRIVACY}" icon="assets/FileManager/images/cancel2.png"/>
        </mx:XMLList>
    </mx:dataProvider>

Obviously, you wouldn't have the ability to embed the icon images this way, but maybe you don't need to?  I'm not 100% sure, but I think the dataProvider is applied at runtime, which would mean that there is no way to embed icon images with this approach.

If I'm wrong about that, you could write an item renderer that would look at the value of the icon attribute and embed the image found at that path.

If I'm right, you could write a custom item renderer that embeds all of the icon images and then displays the correct icon based on the value of label, or some other identifying attribute.


问:
Laravel 5.4 Eloquent SUM and ORDER BY pivot table column
I need an Eloquent query that retrieves the most purchased products in my database. The tables are products, products_purchases, purchases. Products and purchases both have a many-to-many relationship.

The pivot table products_purchases has a pivot field called quantity, which has the total quantity of a product bought on a purchase.

I tried to get the records like this:

```<code>$data['most_purchased'] = Products::whereHas('purchases', function($query){
        $query->selectRaw('SUM(products_purchases.quantity) AS qty')->orderBy('qty', 'desc')->groupBy('product_id');
})->get();
</code>```

But it doesn't give accurate values, what is the right way to do this?

答:
This code works:

```<code>Products::join('products_purchases', 'product.id','=','products_purchases.product_id')
           ->selectRaw('product.*, SUM(products_purchases.quantity) AS qty')
           ->groupBy('product.id')
           ->orderBy('qty', 'desc')
           ->get();
</code>```

But, is there another "cleaner" way to do this without using join?

Body:
I need an Eloquent query that retrieves the most purchased products in my database. The tables are products, products_purchases, purchases. Products and purchases both have a many-to-many relationship.

The pivot table products_purchases has a pivot field called quantity, which has the total quantity of a product bought on a purchase.

I tried to get the records like this:

$data['most_purchased'] = Products::whereHas('purchases', function($query){
        $query->selectRaw('SUM(products_purchases.quantity) AS qty')->orderBy('qty', 'desc')->groupBy('product_id');
})->get();

But it doesn't give accurate values, what is the right way to do this?

Body:
This code works:

Products::join('products_purchases', 'product.id','=','products_purchases.product_id')
           ->selectRaw('product.*, SUM(products_purchases.quantity) AS qty')
           ->groupBy('product.id')
           ->orderBy('qty', 'desc')
           ->get();

But, is there another "cleaner" way to do this without using join?


问:
C++-CLI Button Arrays to C# Button Arrays in Winforms
I am designing an application in C# Winforms (for the first time). I've designed several applications in C++ in the past, and am having difficulty converting some of my C++-CLI functions to C#.

I have 5 buttons along a side bar that toggles the visibility of the button's corresponding panel per button click. In order to do this, I set the visibility of all other panels to false. In order to achieve this in C++-CLI, I've done the following:

```<code>private: System::Void panels_Click(System::Object^  sender, System::EventArgs^  e) {
    System::Windows::Forms::Button ^ currentbutton = (System::Windows::Forms::Button ^) sender;
    array < Panel ^ > ^ objects = { panel1, panel2, panel3, panel4, panel5, panel6};
    array < Button ^ > ^ buttons = { button1, button2, button3, button4, button5, button6 };

    for (int i = 0; i < 6; i++) {
        if (buttons[i]->Equals(currentbutton)) {
            objects[i]->Visible = true;
        }
        else objects[i]->Visible = false;
    }
}
</code>```

The issue I am having is with the " array Panel ^" portion, as I can not find an equivalent in C#. Any help is appreciated.

答:
You can cast the Controls collection to a List<Control>, and then access the control name for comparison. The Cast<T>() method is a linq extension method, so you'll have to add using System.Linq; to your namespace:

```<code>private void panels_Click(object sender, EventArgs e)
{
    List<string> panelNames = new List<string>
    {"panel1", "panel2", "panel3", "panel4", "panel5", "panel6"};

    List<string> buttonNames = new List<string>
    {"button1", "button2", "button3", "button4", "button5", "button6"};

    List<Control> panels = this.Controls.Cast<Control>()
        .Where(ctrl => panelNames.Contains(ctrl.Name)).ToList();

    List<Control> buttons = this.Controls.Cast<Control>()
        .Where(ctrl => buttonNames.Contains(ctrl.Name)).ToList();

    Button thisButton = sender as Button;

    for (int i = 0; i < buttons.Count; i++)
    {
        if (i < panels.Count) panels[i].Visible = buttons[i] == thisButton;
    }
}
</code>```

Body:
I am designing an application in C# Winforms (for the first time). I've designed several applications in C++ in the past, and am having difficulty converting some of my C++-CLI functions to C#.

I have 5 buttons along a side bar that toggles the visibility of the button's corresponding panel per button click. In order to do this, I set the visibility of all other panels to false. In order to achieve this in C++-CLI, I've done the following:

private: System::Void panels_Click(System::Object^  sender, System::EventArgs^  e) {
    System::Windows::Forms::Button ^ currentbutton = (System::Windows::Forms::Button ^) sender;
    array < Panel ^ > ^ objects = { panel1, panel2, panel3, panel4, panel5, panel6};
    array < Button ^ > ^ buttons = { button1, button2, button3, button4, button5, button6 };

    for (int i = 0; i < 6; i++) {
        if (buttons[i]->Equals(currentbutton)) {
            objects[i]->Visible = true;
        }
        else objects[i]->Visible = false;
    }
}

The issue I am having is with the " array Panel ^" portion, as I can not find an equivalent in C#. Any help is appreciated.

Body:
You can cast the Controls collection to a List<Control>, and then access the control name for comparison. The Cast<T>() method is a linq extension method, so you'll have to add using System.Linq; to your namespace:

private void panels_Click(object sender, EventArgs e)
{
    List<string> panelNames = new List<string>
    {"panel1", "panel2", "panel3", "panel4", "panel5", "panel6"};

    List<string> buttonNames = new List<string>
    {"button1", "button2", "button3", "button4", "button5", "button6"};

    List<Control> panels = this.Controls.Cast<Control>()
        .Where(ctrl => panelNames.Contains(ctrl.Name)).ToList();

    List<Control> buttons = this.Controls.Cast<Control>()
        .Where(ctrl => buttonNames.Contains(ctrl.Name)).ToList();

    Button thisButton = sender as Button;

    for (int i = 0; i < buttons.Count; i++)
    {
        if (i < panels.Count) panels[i].Visible = buttons[i] == thisButton;
    }
}


问:
Add file to desktop when users login on a machine
I have setup a test lab for some pieces of software that is slowly expanding and having new machines decommissioned and added to the environment. I am trying to write a GPO in the test domain to place a file on the desktop with some information and stuff to help them get started.

This is what the configuration looks like, but it doesn't appear to be working after forcing a GP update.  I was using this as a reference: https://social.technet.microsoft.com/Forums/windowsserver/en-US/02dc525d-fe7a-497a-b6ec-a2bff4df98ac/how-to-place-files-on-users-desktop-with-gpp?forum=winserverGP

What am I missing here?  All servers are on Server 2012 R2 I've tried various paths, such as c:\user\%userprofile%\Desktop, %Desktop%, I just can't seem to get it to propagate to the desktop. I added an environmental variable named DesktopDir that should point to %USERPROFILE%\Desktop but when I look on the machine it is labeled was c:\user\machinename$\desktop.

答: I figured this out - the file path it didn't like because I was using a c$ share.  I created a fully qualified share path and it worked. </p>


问:
Index datatime in a dateframe from a list of datetimes
First of all, I did this function that returns one date frame but I wanna use in a list of dates and then concatenate them in one data frame with the index being the date time stamp that is in the list

```<code>lista = [datetime.datetime(2017, 11, 11, 0, 0), datetime.datetime(2017, 11, 12, 0, 0), datetime.datetime(2017, 11, 13, 0, 0)]
</code>```

This is my function:

```<code>def min_f(yyear,mmonth,dday):

    a_00_04 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,4)+timedelta(hours=2))) ].min() ) #.tolist()[0]#
    a_04_08 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,4,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,8,00)+timedelta(hours=2))) ].min() )
    a_08_12 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,8,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,12,00)+timedelta(hours=2))) ].min() )
    a_12_16 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,12,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,16,00)+timedelta(hours=2))) ].min() )
    a_16_20 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,16,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,20,00)+timedelta(hours=2))) ].min() )
    a_20_24 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,20,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday+1,00,00)+timedelta(hours=2))) ].min() )

    d = {'00_04': [a_04_08], '04_08': [a_04_08], '08_12': [a_08_12], '12_16': [a_12_16],'20_24': [a_20_24]}
    df = pd.DataFrame(data=d)

    return df
</code>```

Right now from one looks like this:

```<code>   00_04  04_08  08_12  12_16  20_24
0  21359  21359  10486   6747  14335
</code>```

And I wanna to set it like this:

```<code>           00_04  04_08  08_12  12_16  20_24
2017-11-10  21359  21359  10486   6747  14335
</code>```

But adding also the results from my list

答:
Not positive what you're going for, but maybe something like this:

```<code>def create_df(dl):
    idx = []
    cols = {
        '00_04': [],
        '04_08': [],
        '08_12': [],
        '12_16': [],
        '20_24': [],
    }

    for date in dl:
        col['00_04'].append(int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,4)+timedelta(hours=2))) ].min() ))
        ...

        index.append(date)

    return pd.DataFrame(cols, index=idx)
</code>```

It's hard to tell what you're going for here, but it seems you may be missing a 16-24 field as well?

Hope this helps.

Body:
First of all, I did this function that returns one date frame but I wanna use in a list of dates and then concatenate them in one data frame with the index being the date time stamp that is in the list

lista = [datetime.datetime(2017, 11, 11, 0, 0), datetime.datetime(2017, 11, 12, 0, 0), datetime.datetime(2017, 11, 13, 0, 0)]

This is my function:

def min_f(yyear,mmonth,dday):

    a_00_04 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,4)+timedelta(hours=2))) ].min() ) #.tolist()[0]#
    a_04_08 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,4,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,8,00)+timedelta(hours=2))) ].min() )
    a_08_12 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,8,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,12,00)+timedelta(hours=2))) ].min() )
    a_12_16 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,12,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,16,00)+timedelta(hours=2))) ].min() )
    a_16_20 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,16,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,20,00)+timedelta(hours=2))) ].min() )
    a_20_24 = int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,20,00)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday+1,00,00)+timedelta(hours=2))) ].min() )

    d = {'00_04': [a_04_08], '04_08': [a_04_08], '08_12': [a_08_12], '12_16': [a_12_16],'20_24': [a_20_24]}
    df = pd.DataFrame(data=d)

    return df

Right now from one looks like this:

   00_04  04_08  08_12  12_16  20_24
0  21359  21359  10486   6747  14335

And I wanna to set it like this:

           00_04  04_08  08_12  12_16  20_24
2017-11-10  21359  21359  10486   6747  14335

But adding also the results from my list

Body:
Not positive what you're going for, but maybe something like this:

def create_df(dl):
    idx = []
    cols = {
        '00_04': [],
        '04_08': [],
        '08_12': [],
        '12_16': [],
        '20_24': [],
    }

    for date in dl:
        col['00_04'].append(int( df_output.loc[ (df_output.index > timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday)-timedelta(hours=1)))  &  (df_output.index <= timezone('Europe/Berlin').localize(datetime(yyear,mmonth,dday,4)+timedelta(hours=2))) ].min() ))
        ...

        index.append(date)

    return pd.DataFrame(cols, index=idx)

It's hard to tell what you're going for here, but it seems you may be missing a 16-24 field as well?

Hope this helps.


问:
graph similarity having multiple edges between two nodes
There are many theories about calculating of graph similarity such as vertex edge overlap, jacard, co-sine, edit distance, signature similarity, lambda distance, deltacon so on. These things are based on single edge of the graph. But there are many graphs having multiple edges in real world.

Given similar two graphs like above, how could we calculate graph similarity?
Using previous graph similarity, there are only 2-dimension vector and the entry is just scalar that is number, but in multiple edge's graph, the entry should be tuple. Because there are one more actions between nodes. For the previous method, it could be called who-knows-whom schem, but latter graph, it could be said who-knows-whom*-how*. I think the previous mothods could be used for the multiple edge's graph easily, so there aren't logic or methods about it.
Thanks in advance!

答:
There is not "the" way yo compute graph similarity.

Depending on your data and problem, very different approaches may be good. In many cases, simply merging the two edges into one makes perfect sense. For example, if I have two roads of capacity x and y to go from A to B - for many analyses this is comparable to having just one rode, with the combined capacity.


问:
What Firestore Security Rule matches an empty map? [Bug?]
Here are some Firestore security rules that I've tried to use to match an empty map in a "create" rule:

```<code>request.resource.data.myMap == {}

(request.resource.data.myMap is map &&
 request.resource.data.myMap.size() == 0)

(request.resource.data.myMap is map &&
 request.resource.data.myMap.keys().size() == 0)
</code>```

I've double-checked that the thing I'm putting is indeed an empty map by changing the security rule to:

```<code>request.resource.data.myMap is map
</code>```

...and examining the database from the Firebase Console. It contains an "object" with no fields -- which is, as I understand it, an empty map.

I'm guessing this is a bug. If not, how can I match an empty map?

答: This no longer seems to be an issue. request.resource.data.myMap == {} now seems to work.</p>

Body:
Here are some Firestore security rules that I've tried to use to match an empty map in a "create" rule:

request.resource.data.myMap == {}

(request.resource.data.myMap is map &&
 request.resource.data.myMap.size() == 0)

(request.resource.data.myMap is map &&
 request.resource.data.myMap.keys().size() == 0)

I've double-checked that the thing I'm putting is indeed an empty map by changing the security rule to:

request.resource.data.myMap is map

...and examining the database from the Firebase Console. It contains an "object" with no fields -- which is, as I understand it, an empty map.

I'm guessing this is a bug. If not, how can I match an empty map?


问:
Get class DisplayName attribute value
Iv'e spent the last hour trying to get the value of a DisplayName attribute that's applied to a Class.

I find it simple enough to get the attribute values from methods and properties but I'm struggling with the class.

Could anyone help me out with this relatively small issue?

Sample below:

The Class

```<code> [DisplayName("Opportunity")]
 public class Opportunity
 {
  // Code Omitted
 }
</code>```

The Variable

```<code>var classDisplayName = typeof(T).GetCustomAttributes(typeof(DisplayNameAttribute),true).FirstOrDefault().ToString();
</code>```

I have spent much time on MSDN and SO but I guess I'm missing something stupidly simple.

Either way great question for future readers too

Any help greatly appreciated!

答:
Some valid solutions already exist but you could also create an extension method like this:

```<code>using System.ComponentModel.DataAnnotations;
using System.Reflection;

public static class PropertyExtension
{
    public static string GetDisplayName<T>(this string property)
    {
        MemberInfo propertyInfo = typeof(T).GetProperty(property);
        var displayAttribute = propertyInfo?.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;

        return displayAttribute != null ? displayAttribute.Name : "";
    }
}
</code>```

The way you use this is by providing the name of the property as a string and then the type of the class.

```<code>var propertyNameInClass = "DateCreated"; // Could be any property
// You could probably do something like nameof(myOpportunity.DateCreated)
// to keep it strongly-typed
var displayName = propertyNameInClass.GetDisplayName<Opportunity>();
if(!string.IsNullOrEmpty(displayName))
{
    // Do something
}
</code>```

I think this is more dynamic and cleaner than some other solutions around. It might be a good idea to wrap it all with a try/catch statement because of it's dynamic nature.

Title: Get class DisplayName attribute value

Body:
Iv'e spent the last hour trying to get the value of a DisplayName attribute that's applied to a Class.

I find it simple enough to get the attribute values from methods and properties but I'm struggling with the class.

Could anyone help me out with this relatively small issue?

Sample below:

The Class

 [DisplayName("Opportunity")]
 public class Opportunity
 {
  // Code Omitted
 }

The Variable

var classDisplayName = typeof(T).GetCustomAttributes(typeof(DisplayNameAttribute),true).FirstOrDefault().ToString();

I have spent much time on MSDN and SO but I guess I'm missing something stupidly simple.

Either way great question for future readers too

Any help greatly appreciated!

Body:
Some valid solutions already exist but you could also create an extension method like this:

using System.ComponentModel.DataAnnotations;
using System.Reflection;

public static class PropertyExtension
{
    public static string GetDisplayName<T>(this string property)
    {
        MemberInfo propertyInfo = typeof(T).GetProperty(property);
        var displayAttribute = propertyInfo?.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;

        return displayAttribute != null ? displayAttribute.Name : "";
    }
}

The way you use this is by providing the name of the property as a string and then the type of the class.

var propertyNameInClass = "DateCreated"; // Could be any property
// You could probably do something like nameof(myOpportunity.DateCreated)
// to keep it strongly-typed
var displayName = propertyNameInClass.GetDisplayName<Opportunity>();
if(!string.IsNullOrEmpty(displayName))
{
    // Do something
}

I think this is more dynamic and cleaner than some other solutions around. It might be a good idea to wrap it all with a try/catch statement because of it's dynamic nature.


问:
Vagrant & Symfony 3.3: Failed to remove directory
Trying to set up a Symfony 3.3 environment with Flex. Currently, when trying to require some packages like the following:

```<code>composer req annotations security orm template asset validator
</code>```

Everything goes well, except on cache:clear I'm getting the following errors:

```<code>!!    [Symfony\Component\Filesystem\Exception\IOException]
!!    Failed to remove directory "/home/vagrant/Code/multi-user-gallery-blog/var/
!!    cache/loca~/pools": rmdir(/home/vagrant/Code/multi-user-gallery-blog/var/ca
!!    che/loca~/pools): Directory not empty.
</code>```

I already tried to remove the folders manually, but those are generated automatically in the installation process, and then Symfony cannot remove them.

I'm running this on Vagrant Homestead.

Any idea on how can I solve this problem?

答:
This is an issue with the way Vagrant/VirtualBox maps shared folders between the host and guest machines. In Symfony projects, the cache directory is typically placed within the project directory that gets synced from the host machine.

We can change the cache directory to use a location within the guest machine's filesystem to avoid these problems by adding an override method to the app/AppKernel.php class:

```<code>class AppKernel extends Kernel
{
    ...
    public function getCacheDir()
    {
        if ($this->environment === 'local') {
            return '/tmp/symfony/cache';
        }

        return parent::getCacheDir();
    }
}
</code>```

The example above demonstrates how we can set a custom cache directory for local development environments while retaining the default behavior for production. /tmp/symfony/cache is just an example. We can choose a location anywhere on the guest machine's filesystem that the application has permission to write to. Replace 'local' with the name of the environment the project uses for development.

Body:
Trying to set up a Symfony 3.3 environment with Flex. Currently, when trying to require some packages like the following:

composer req annotations security orm template asset validator

Everything goes well, except on cache:clear I'm getting the following errors:

!!    [Symfony\Component\Filesystem\Exception\IOException]
!!    Failed to remove directory "/home/vagrant/Code/multi-user-gallery-blog/var/
!!    cache/loca~/pools": rmdir(/home/vagrant/Code/multi-user-gallery-blog/var/ca
!!    che/loca~/pools): Directory not empty.

I already tried to remove the folders manually, but those are generated automatically in the installation process, and then Symfony cannot remove them.

I'm running this on Vagrant Homestead.

Any idea on how can I solve this problem?

Body:
This is an issue with the way Vagrant/VirtualBox maps shared folders between the host and guest machines. In Symfony projects, the cache directory is typically placed within the project directory that gets synced from the host machine.

We can change the cache directory to use a location within the guest machine's filesystem to avoid these problems by adding an override method to the app/AppKernel.php class:

class AppKernel extends Kernel
{
    ...
    public function getCacheDir()
    {
        if ($this->environment === 'local') {
            return '/tmp/symfony/cache';
        }

        return parent::getCacheDir();
    }
}

The example above demonstrates how we can set a custom cache directory for local development environments while retaining the default behavior for production. /tmp/symfony/cache is just an example. We can choose a location anywhere on the guest machine's filesystem that the application has permission to write to. Replace 'local' with the name of the environment the project uses for development.