问:
I recently updated my Android Studio and now, I am unable to create a new activity/fragment in Android Studio
for some reasons, I am unable to create a new Activity/Fragment.

I have checked similar questions here but none of them helped.  I have also followed the workaround here https://github.com/udacity/ud851-Exercises/issues/67

Things that I've tried:
- deleted .gradle and .idea
- https://github.com/udacity/ud851-Exercises/issues/67
- changing the minSDK to 9 or 15
- rebuild project
- clean project
- restart project

Everytime I attempt to create an Empty Activity, there is an IDE Error

```<code>java.lang.RuntimeException: Could not find a JavaToKotlinConversionProvider, even though one should be bundled with Studio
    at com.android.tools.idea.npw.model.JavaToKotlinHandler.getJavaToKotlinConversionProvider(JavaToKotlinHandler.java:50)
    at com.android.tools.idea.npw.template.TemplateValueInjector.addKotlinVersion(TemplateValueInjector.java:392)
    at com.android.tools.idea.npw.template.TemplateValueInjector.setFacet(TemplateValueInjector.java:133)
    at com.android.tools.idea.npw.model.RenderTemplateModel$FreeMarkerTemplateRenderer.init(RenderTemplateModel.java:250)
    at com.android.tools.idea.npw.model.MultiTemplateRenderer.countDown(MultiTemplateRenderer.java:152)
    at com.android.tools.idea.npw.model.MultiTemplateRenderer.requestRender(MultiTemplateRenderer.java:120)
    at com.android.tools.idea.npw.model.RenderTemplateModel.handleFinished(RenderTemplateModel.java:218)
    at com.android.tools.idea.wizard.model.ModelWizard.handleFinished(ModelWizard.java:403)
    at com.android.tools.idea.wizard.model.ModelWizard.goForward(ModelWizard.java:331)
    at com.android.tools.idea.wizard.model.ModelWizardDialog$FinishAction.doAction(ModelWizardDialog.java:311)
    at com.intellij.openapi.ui.DialogWrapper$DialogWrapperAction.actionPerformed(DialogWrapper.java:1831)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6548)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3325)
    at java.awt.Component.processEvent(Component.java:6313)
    at java.awt.Container.processEvent(Container.java:2237)
    at java.awt.Component.dispatchEventImpl(Component.java:4903)
    at java.awt.Container.dispatchEventImpl(Container.java:2295)
    at java.awt.Component.dispatchEvent(Component.java:4725)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4526)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    at java.awt.Container.dispatchEventImpl(Container.java:2281)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4725)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:737)
    at java.awt.EventQueue$4.run(EventQueue.java:735)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:755)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:700)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:391)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:109)
    at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:190)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:235)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:233)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:233)
    at java.awt.Dialog.show(Dialog.java:1077)
    at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl$MyDialog.show(DialogWrapperPeerImpl.java:698)
    at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.show(DialogWrapperPeerImpl.java:430)
    at com.intellij.openapi.ui.DialogWrapper.invokeShow(DialogWrapper.java:1681)
    at com.intellij.openapi.ui.DialogWrapper.show(DialogWrapper.java:1630)
    at com.android.tools.idea.actions.NewAndroidComponentAction.actionPerformed(NewAndroidComponentAction.java:171)
    at com.intellij.openapi.actionSystem.ex.ActionUtil$1.run(ActionUtil.java:258)
    at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAware(ActionUtil.java:275)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem$ActionTransmitter.lambda$actionPerformed$0(ActionMenuItem.java:287)
    at com.intellij.openapi.wm.impl.FocusManagerImpl.runOnOwnContext(FocusManagerImpl.java:283)
    at com.intellij.openapi.wm.impl.IdeFocusManagerImpl.runOnOwnContext(IdeFocusManagerImpl.java:106)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem$ActionTransmitter.actionPerformed(ActionMenuItem.java:277)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem.lambda$fireActionPerformed$0(ActionMenuItem.java:111)
    at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88)
    at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransaction$1(TransactionGuardImpl.java:111)
    at com.intellij.openapi.application.TransactionGuardImpl.submitTransaction(TransactionGuardImpl.java:120)
    at com.intellij.openapi.application.TransactionGuard.submitTransaction(TransactionGuard.java:122)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem.fireActionPerformed(ActionMenuItem.java:111)
    at com.intellij.ui.plaf.beg.BegMenuItemUI.doClick(BegMenuItemUI.java:524)
    at com.intellij.ui.plaf.beg.BegMenuItemUI.access$300(BegMenuItemUI.java:35)
    at com.intellij.ui.plaf.beg.BegMenuItemUI$MyMouseInputHandler.mouseReleased(BegMenuItemUI.java:546)
    at java.awt.Component.processMouseEvent(Component.java:6548)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3325)
    at java.awt.Component.processEvent(Component.java:6313)
    at java.awt.Container.processEvent(Container.java:2237)
    at java.awt.Component.dispatchEventImpl(Component.java:4903)
    at java.awt.Container.dispatchEventImpl(Container.java:2295)
    at java.awt.Component.dispatchEvent(Component.java:4725)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4526)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    at java.awt.Container.dispatchEventImpl(Container.java:2281)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4725)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:737)
    at java.awt.EventQueue$4.run(EventQueue.java:735)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:755)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:700)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:391)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

答: just Update Android studio 3.4 then problem will be solved</p>

Body:
for some reasons, I am unable to create a new Activity/Fragment.

I have checked similar questions here but none of them helped.  I have also followed the workaround here https://github.com/udacity/ud851-Exercises/issues/67

Things that I've tried:
- deleted .gradle and .idea
- https://github.com/udacity/ud851-Exercises/issues/67
- changing the minSDK to 9 or 15
- rebuild project
- clean project
- restart project

Everytime I attempt to create an Empty Activity, there is an IDE Error

java.lang.RuntimeException: Could not find a JavaToKotlinConversionProvider, even though one should be bundled with Studio
    at com.android.tools.idea.npw.model.JavaToKotlinHandler.getJavaToKotlinConversionProvider(JavaToKotlinHandler.java:50)
    at com.android.tools.idea.npw.template.TemplateValueInjector.addKotlinVersion(TemplateValueInjector.java:392)
    at com.android.tools.idea.npw.template.TemplateValueInjector.setFacet(TemplateValueInjector.java:133)
    at com.android.tools.idea.npw.model.RenderTemplateModel$FreeMarkerTemplateRenderer.init(RenderTemplateModel.java:250)
    at com.android.tools.idea.npw.model.MultiTemplateRenderer.countDown(MultiTemplateRenderer.java:152)
    at com.android.tools.idea.npw.model.MultiTemplateRenderer.requestRender(MultiTemplateRenderer.java:120)
    at com.android.tools.idea.npw.model.RenderTemplateModel.handleFinished(RenderTemplateModel.java:218)
    at com.android.tools.idea.wizard.model.ModelWizard.handleFinished(ModelWizard.java:403)
    at com.android.tools.idea.wizard.model.ModelWizard.goForward(ModelWizard.java:331)
    at com.android.tools.idea.wizard.model.ModelWizardDialog$FinishAction.doAction(ModelWizardDialog.java:311)
    at com.intellij.openapi.ui.DialogWrapper$DialogWrapperAction.actionPerformed(DialogWrapper.java:1831)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6548)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3325)
    at java.awt.Component.processEvent(Component.java:6313)
    at java.awt.Container.processEvent(Container.java:2237)
    at java.awt.Component.dispatchEventImpl(Component.java:4903)
    at java.awt.Container.dispatchEventImpl(Container.java:2295)
    at java.awt.Component.dispatchEvent(Component.java:4725)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4526)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    at java.awt.Container.dispatchEventImpl(Container.java:2281)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4725)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:737)
    at java.awt.EventQueue$4.run(EventQueue.java:735)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:755)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:700)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:391)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:109)
    at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:190)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:235)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:233)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:233)
    at java.awt.Dialog.show(Dialog.java:1077)
    at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl$MyDialog.show(DialogWrapperPeerImpl.java:698)
    at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.show(DialogWrapperPeerImpl.java:430)
    at com.intellij.openapi.ui.DialogWrapper.invokeShow(DialogWrapper.java:1681)
    at com.intellij.openapi.ui.DialogWrapper.show(DialogWrapper.java:1630)
    at com.android.tools.idea.actions.NewAndroidComponentAction.actionPerformed(NewAndroidComponentAction.java:171)
    at com.intellij.openapi.actionSystem.ex.ActionUtil$1.run(ActionUtil.java:258)
    at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAware(ActionUtil.java:275)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem$ActionTransmitter.lambda$actionPerformed$0(ActionMenuItem.java:287)
    at com.intellij.openapi.wm.impl.FocusManagerImpl.runOnOwnContext(FocusManagerImpl.java:283)
    at com.intellij.openapi.wm.impl.IdeFocusManagerImpl.runOnOwnContext(IdeFocusManagerImpl.java:106)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem$ActionTransmitter.actionPerformed(ActionMenuItem.java:277)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem.lambda$fireActionPerformed$0(ActionMenuItem.java:111)
    at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88)
    at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransaction$1(TransactionGuardImpl.java:111)
    at com.intellij.openapi.application.TransactionGuardImpl.submitTransaction(TransactionGuardImpl.java:120)
    at com.intellij.openapi.application.TransactionGuard.submitTransaction(TransactionGuard.java:122)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem.fireActionPerformed(ActionMenuItem.java:111)
    at com.intellij.ui.plaf.beg.BegMenuItemUI.doClick(BegMenuItemUI.java:524)
    at com.intellij.ui.plaf.beg.BegMenuItemUI.access$300(BegMenuItemUI.java:35)
    at com.intellij.ui.plaf.beg.BegMenuItemUI$MyMouseInputHandler.mouseReleased(BegMenuItemUI.java:546)
    at java.awt.Component.processMouseEvent(Component.java:6548)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3325)
    at java.awt.Component.processEvent(Component.java:6313)
    at java.awt.Container.processEvent(Container.java:2237)
    at java.awt.Component.dispatchEventImpl(Component.java:4903)
    at java.awt.Container.dispatchEventImpl(Container.java:2295)
    at java.awt.Component.dispatchEvent(Component.java:4725)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4526)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    at java.awt.Container.dispatchEventImpl(Container.java:2281)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4725)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:737)
    at java.awt.EventQueue$4.run(EventQueue.java:735)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:755)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:700)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:391)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)


来源: stackexchange

问:
jQuery iterate integer as orderly
What I have done, iterate integer orderly on elements based on own attribute. but it is not in order, already it set css order to elements like: 2,3,5, but I want to ignore those elements that not have attribute on iterating.

var i = 0;
jQuery('.each-order').each(function() {
  i++;

  if (jQuery(this).attr('data-payment') === '1') {
    console.log(i);
    jQuery(this).css('order', i);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#orders {
  display: flex
}

.each-order {
  border: 1px solid red;
  padding: 10px;
  margin: 10px;
}</code>```

Test 1

Test 2

Test 3

Test 4

Test 5

```
</div>
</div>
</p>

<p>Already output:</p>

```

Test 1

Test 2

Test 3

Test 4

Test 5

```

<p>Desire output:</p>

```

Test 1

Test 2

Test 3

Test 4

Test 5

```

答:
Just don't increment i if you don't use it:

```<code>var i = 0;
jQuery('.each-order').each(function() {
  if (jQuery(this).attr('data-payment') === '1') {
    jQuery(this).css('order', ++i); // Prefix increment, only if you use it
  }
});
</code>```

Updated snippet:

var i = 0;
jQuery('.each-order').each(function() {
  if (jQuery(this).attr('data-payment') === '1') {
    jQuery(this).css('order', ++i); // Prefix increment, only if you use it
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#orders {
  display: flex
}

.each-order {
  border: 1px solid red;
  padding: 10px;
  margin: 10px;
}</code>```

Test 1

Test 2

Test 3

Test 4

Test 5

```

ContentLicense: CC BY-SA 4.0

Title: jQuery iterate integer as orderly

Body:
What I have done, iterate integer orderly on elements based on own attribute. but it is not in order, already it set css order to elements like: 2,3,5, but I want to ignore those elements that not have attribute on iterating.

var i = 0;
jQuery('.each-order').each(function() {
  i++;

  if (jQuery(this).attr('data-payment') === '1') {
    console.log(i);
    jQuery(this).css('order', i);
  }
});

#orders {
  display: flex
}

.each-order {
  border: 1px solid red;
  padding: 10px;
  margin: 10px;
}

Test 1

Test 2

Test 3

Test 4

Test 5

Already output:

Test 1

Test 2

Test 3

Test 4

Test 5

Desire output:

Test 1

Test 2

Test 3

Test 4

Test 5

Body:
Just don't increment i if you don't use it:

var i = 0;
jQuery('.each-order').each(function() {
  if (jQuery(this).attr('data-payment') === '1') {
    jQuery(this).css('order', ++i); // Prefix increment, only if you use it
  }
});

Updated snippet:

var i = 0;
jQuery('.each-order').each(function() {
  if (jQuery(this).attr('data-payment') === '1') {
    jQuery(this).css('order', ++i); // Prefix increment, only if you use it
  }
});

#orders {
  display: flex
}

.each-order {
  border: 1px solid red;
  padding: 10px;
  margin: 10px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="orders">
  <div class=each-order data-payment="0">Test 1</div>
  <div class=each-order data-payment="1">Test 2</div>
  <div class=each-order data-payment="1">Test 3</div>
  <div class=each-order data-payment="0">Test 4</div>
  <div class=each-order data-payment="1">Test 5</div>
</div>


问:
RegEx for passing punctuation
I am using:

```<code>(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)
</code>```

to represent

```<code>3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY).
</code>```

However, the first Single quotation mark cannot be covered by the regex code. Could you please tell me why?

```<code>s/(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)/$1 CO $2
</code>```

I expect to get:

```<code>3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)
</code>```

but I get

```<code>3M CO A'(MINNESOTA MINING AND MANUFACTURING COMPANY)
</code>```

答:
The ' does not match because in the second capturing group because you use a character class which can be written as CO\s?[(.*)|[\]{}'"] and then it will match CO '

So your pattern actually looks like:

```<code>(.*) CO\s?[.*()|[\]{}'"](.*)
^         ^             ^
group 1   Char class    group 2
</code>```

What you might do to get those matching in 2 groups is to use:

```<code>(.*?)CO\s?((?:(['"]).*?\3|\(.*?\)|\[.*?\]|\{.*?\}).*)
</code>```

Explanation

(.*?) Capturing group 1, match any char except newline non greedy

CO\s? Match CO and optional whitespace char

( Capturing group 2

(?: Non capturing group, match any of the options

(['"]).*?\3 Match ' or " and use a backreference to what is captured

| Or

\(.*?\) Match (....)

| Or

\[.*?\] Match [....]

| Or

\{.*?\} Match {....}

) Close non capturing group

.* Match any char until the end of the string

) Close group 2

Regex demo

Note that the .*? is non greedy to prevent unnecessary backtracking and over matching.

Title: RegEx for passing punctuation

Body:
I am using:

(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)

to represent

3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY).

However, the first Single quotation mark cannot be covered by the regex code. Could you please tell me why?

s/(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)/$1 CO $2

I expect to get:

3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)

but I get

3M CO A'(MINNESOTA MINING AND MANUFACTURING COMPANY)

Body:
The ' does not match because in the second capturing group because you use a character class which can be written as CO\s?[(.*)|[\]{}'"] and then it will match CO '

So your pattern actually looks like:

(.*) CO\s?[.*()|[\]{}'"](.*)
^         ^             ^
group 1   Char class    group 2

What you might do to get those matching in 2 groups is to use:

(.*?)CO\s?((?:(['"]).*?\3|\(.*?\)|\[.*?\]|\{.*?\}).*)

Explanation

(.*?) Capturing group 1, match any char except newline non greedy

CO\s? Match CO and optional whitespace char

( Capturing group 2

(?: Non capturing group, match any of the options

(['"]).*?\3 Match ' or " and use a backreference to what is captured

| Or

\(.*?\) Match (....)

| Or

\[.*?\] Match [....]

| Or

\{.*?\} Match {....}

) Close non capturing group

.* Match any char until the end of the string

) Close group 2

Regex demo

Note that the .*? is non greedy to prevent unnecessary backtracking and over matching.


问:
How to trigger a function when the iPhone is rotated 90 degrees?
How do I detect the rotation of the iPhone for approximately 90 degrees?  Additionally, I don't need/want the screen itself to rotate.  I just want to call a function when the phone has been rotated.  Thanks!</p>

答:
you should first implement the instance method "shouldAutorotateToInterfaceOrientation" and return YES.
and then the two method will be called.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


Title: Replace NumPy array elements with other element

Body:
Suppose I have a randomly generated 3d array srouceArray:

ex: np.random.rand(3, 3, 3)

array([[[0.61961383, 0.26927599, 0.03847151],
        [0.03497162, 0.77748313, 0.15807293],
        [0.15108821, 0.36729448, 0.19007034]],

      [[0.67734758, 0.88312758, 0.97610746],
       [0.5643174 , 0.20660141, 0.58836553],
       [0.59084109, 0.77019768, 0.35961768]],

      [[0.19352397, 0.47284641, 0.97912889],
       [0.48519117, 0.37189048, 0.37113941],
       [0.94934848, 0.92755083, 0.52662299]]])

I would like to randomly replace all 3rd dimennsion elements to zeroes.

Expected array:

array([[[0, 0, 0],
        [0.03497162, 0.77748313, 0.15807293],
        [0.15108821, 0.36729448, 0.19007034]],

      [[0.67734758, 0.88312758, 0.97610746],
       [0 , 0, 0],
       [0.59084109, 0.77019768, 0.35961768]],

      [[0, 0, 0],
       [0, 0, 0],
       [0.94934848, 0.92755083, 0.52662299]]])

I was thinking about generating "mask"? using random

np.random.choice([True, False], sourceArray.shape, p=[...])

and somehow transforming it to 3d array where False=[0, 0, 0] and True=[1, 1, 1] and multiplying with source...

But I do not know how to achieve that transformation. And I bet there is a simpler way I do not know about.

Body:
If I correctly understood data structure, can use this (this will change original array):

import numpy as np

l = np.random.rand(5, 4, 3)
m = np.random.choice([True, False], size=(l.shape[0], l.shape[1]))
l[m] = [0, 0, 0]
l
array([[[0.62551611, 0.26268253, 0.51863006],
        [0.        , 0.        , 0.        ],
        [0.45038189, 0.97229114, 0.63736078],
        [0.        , 0.        , 0.        ]],

       [[0.54282399, 0.14585025, 0.80753245],
        [0.        , 0.        , 0.        ],
        [0.        , 0.        , 0.        ],
        [0.18190234, 0.19806439, 0.3052623 ]],

       [[0.        , 0.        , 0.        ],
        [0.46409806, 0.39734112, 0.21864433],
        [0.        , 0.        , 0.        ],
        [0.65046231, 0.78573179, 0.76362864]],

       [[0.05296007, 0.50762852, 0.18839052],
        [0.52568072, 0.8271628 , 0.24588153],
        [0.92039708, 0.8653368 , 0.96737845],
        [0.        , 0.        , 0.        ]],

       [[0.        , 0.        , 0.        ],
        [0.37039626, 0.64673356, 0.01186108],
        [0.        , 0.        , 0.        ],
        [0.        , 0.        , 0.        ]]])


问:
makedirs() in loop creates invisible directory/folder?
I am trying to mass produce folders that would be numbered 0,1,2...

I use os.makedirs() in Python to do so.  It works if I am just creating a single folder, but when I use a for loop for mass production something weird happens.

When I open Finder (file browser in Mac), I don't see the folder there. Yet when I type in the folder's path in Mac's Go box (cmd-shift-G), then it magically appears, which means that the folder actually exists but was invisible for some reason.

Does anyone know why the folders are invisible?

```<code>import os
for i in range(3):
    os.makedirs('/Users/Olivia/code/'+str(i))
</code>```

答:
I apologise if I'm interpreting the question wrong, but if you are saying that the folders cannot be seen on the desktop, I found that the folders are saved in your home ('/Users/Olivia' in your case) folder, so if you want to save the folders in your desktop, then you can do:

import os
for i in range(3):
    os.makedirs("/Users/Olivia/Desktop/code/"+str(i))
```

Body:
I am trying to mass produce folders that would be numbered 0,1,2...

I use os.makedirs() in Python to do so.  It works if I am just creating a single folder, but when I use a for loop for mass production something weird happens.

When I open Finder (file browser in Mac), I don't see the folder there. Yet when I type in the folder's path in Mac's Go box (cmd-shift-G), then it magically appears, which means that the folder actually exists but was invisible for some reason.

Does anyone know why the folders are invisible?

import os
for i in range(3):
    os.makedirs('/Users/Olivia/code/'+str(i))


问:
Is the https://www.googleapis.com/auth/drive.file enough to create and update files or is the scope /drive needed?
Currently we only have the scope https://www.googleapis.com/auth/drive.readonly but we want to be able to write and update files to google drive as well. Reading the documentation they state that https://www.googleapis.com/auth/drive.file is enough to create and update files. But before we apply to this I want to make sure this scope is enough.</p>

答:
As written in the Documentation  https://www.googleapis.com/auth/drive.file will only allow you access to files created or opened by the app(you).

https://www.googleapis.com/auth/drive allows you to access all of a user's files, excluding the Application Data folder.

So if you want to access all the user files https://www.googleapis.com/auth/drive else https://www.googleapis.com/auth/drive.file is enough to create and update the files.


问:
What is the best way to limit concurrency when using ES6's Promise.all()?
I have some code that is iterating over a list that was queried out of a database and making an HTTP request for each element in that list.  That list can sometimes be a reasonably large number (in the thousands), and I would like to make sure I am not hitting a web server with thousands of concurrent HTTP requests.

An abbreviated version of this code currently looks something like this...

```<code>function getCounts() {
  return users.map(user => {
    return new Promise(resolve => {
      remoteServer.getCount(user) // makes an HTTP request
      .then(() => {
        /* snip */
        resolve();
      });
    });
  });
}

Promise.all(getCounts()).then(() => { /* snip */});
</code>```

This code is running on Node 4.3.2.  To reiterate, can Promise.all be managed so that only a certain number of Promises are in progress at any given time?

答:
No external libraries. Just plain JS.

It can be resolved using recursion.

The idea is that initially we immediately execute the maximum allowed number of queries and each of these queries should recursively initiate a new query on its completion.

In this example I populate successful responses together with errors and I execute all queries but it's possible to slightly modify algorithm if you want to terminate batch execution on the first failure.

async function batchQuery(queries, limit) {
  limit = Math.min(queries.length, limit);

  return new Promise((resolve, reject) => {
    const responsesOrErrors = new Array(queries.length);
    let startedCount = 0;
    let finishedCount = 0;
    let hasErrors = false;

    function recursiveQuery() {
      let index = startedCount++;

      doQuery(queries[index])
        .then(res => {
          responsesOrErrors[index] = res;
        })
        .catch(error => {
          responsesOrErrors[index] = error;
          hasErrors = true;
        })
        .finally(() => {
          finishedCount++;
          if (finishedCount === queries.length) {
            hasErrors ? reject(responsesOrErrors) : resolve(responsesOrErrors);
          } else if (startedCount < queries.length) {
            recursiveQuery();
          }
        });
    }

    for (let i = 0; i < limit; i++) {
      recursiveQuery();
    }
  });
}

async function doQuery(query) {
  console.log(`${query} started`);
  const delay = Math.floor(Math.random() * 1500);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (delay <= 1000) {
        console.log(`${query} finished successfully`);
        resolve(`${query} success`);
      } else {
        console.log(`${query} finished with error`);
        reject(`${query} error`);
      }
    }, delay);
  });
}

const queries = new Array(10).fill('query').map((query, index) => `${query}_${index + 1}`);

batchQuery(queries, 3)
  .then(responses => console.log('All successfull', responses))
  .catch(responsesWithErrors => console.log('All with several failed', responsesWithErrors));```

Body:
I have some code that is iterating over a list that was queried out of a database and making an HTTP request for each element in that list.  That list can sometimes be a reasonably large number (in the thousands), and I would like to make sure I am not hitting a web server with thousands of concurrent HTTP requests.

An abbreviated version of this code currently looks something like this...

function getCounts() {
  return users.map(user => {
    return new Promise(resolve => {
      remoteServer.getCount(user) // makes an HTTP request
      .then(() => {
        /* snip */
        resolve();
      });
    });
  });
}

Promise.all(getCounts()).then(() => { /* snip */});

This code is running on Node 4.3.2.  To reiterate, can Promise.all be managed so that only a certain number of Promises are in progress at any given time?


问:
max thread per process in linux
I wrote a simple program to calculate the maximum number of threads that a process can have in linux (Centos 5). here is the code:

```<code>int main()
{
    pthread_t thrd[400];
    for(int i=0;i<400;i++)
    {
        int err=pthread_create(&thrd[i],NULL,thread,(void*)i);
        if(err!=0)
            cout << "thread creation failed: " << i <<" error code: " << err << endl;
    }
    return 0;
}

void * thread(void* i)
{
    sleep(100);//make the thread still alive
    return 0;
}
</code>```

I figured out that max number for threads is only 300!? What if i need more than that?
I have to mention that pthread_create returns 12 as error code.

Thanks before

答: Your system limits may not be allowing you to map the stacks of all the threads you require. Look at /proc/sys/vm/max_map_count, and see this answer. I'm not 100% sure this is your problem, because most people run into problems at much larger thread counts.

Title: max thread per process in linux

Body:
I wrote a simple program to calculate the maximum number of threads that a process can have in linux (Centos 5). here is the code:

int main()
{
    pthread_t thrd[400];
    for(int i=0;i<400;i++)
    {
        int err=pthread_create(&thrd[i],NULL,thread,(void*)i);
        if(err!=0)
            cout << "thread creation failed: " << i <<" error code: " << err << endl;
    }
    return 0;
}

void * thread(void* i)
{
    sleep(100);//make the thread still alive
    return 0;
}

I figured out that max number for threads is only 300!? What if i need more than that?
I have to mention that pthread_create returns 12 as error code.

Thanks before


问:
How to obtain affine transform with some points fixed?
For example I have 4 points in one coordinate system and 4 points in another coordinate system, if I estimate affine transform in naive way corner points [points 1,4] will not precisely warp to corresponding corner points in another coordinate system.

How to obtain affine transform with limitation that some points should warp on corresponding points in another coordinate system?

答:
As far as I understand, you need to recover affine transform, when images of 4 certain points are known.
I think, the following code may help you (sorry for bad codestyle -- I'm mathematician, not programmer)

import numpy as np
# input data
ins = np.array([[1, 1, 2], [2, 3, 0], [3, 2, -2], [-2, 2, 3]]) # <- primary system
out = np.array([[0, 2, 1], [1, 2, 2], [-2, -1, 6], [4, 1, -3]]) # <- secondary system
p = np.array([1, 2, 3]) #<- transform this point
# finding transformation
l = len(ins)
e = lambda r,d: np.linalg.det(np.delete(np.vstack([r, ins.T, np.ones(l)]), d, axis=0))
M = np.array([[(-1)**i * e(R, i) for R in out.T] for i in range(l+1)])
A, t = np.hsplit(M[1:].T/(-M[0])[:,None], [l-1])
t = np.transpose(t)[0]
# output transformation
print("Affine transformation matrix:\n", A)
print("Affine transformation translation vector:\n", t)
# unittests
print("TESTING:")
for p, P in zip(np.array(ins), np.array(out)):
  image_p = np.dot(A, p) + t
  result = "[OK]" if np.allclose(image_p, P) else "[ERROR]"
  print(p, " mapped to: ", image_p, " ; expected: ", P, result)
# calculate points
print("CALCULATION:")
P = np.dot(A, p) + t
print(p, " mapped to: ", P)
```

This code demonstrates how to recover affine transformation as matrix + vector and tests that initial points are mapped to where they should. You can test this code with Google colab, so you don't have to install anything.

Regarding theory behind this code: it is based on equation presented in "Beginner's guide to mapping simplexes affinely", matrix recovery is described in section "Recovery of canonical notation" and number of points needed to pinpoint the exact affine transformation is discussed in "How many points do we need?" section. The same authors published "Workbook on mapping simplexes affinely" that contains many practical examples of this kind.

Body:
As far as I understand, you need to recover affine transform, when images of 4 certain points are known.
I think, the following code may help you (sorry for bad codestyle -- I'm mathematician, not programmer)

import numpy as np
# input data
ins = np.array([[1, 1, 2], [2, 3, 0], [3, 2, -2], [-2, 2, 3]]) # <- primary system
out = np.array([[0, 2, 1], [1, 2, 2], [-2, -1, 6], [4, 1, -3]]) # <- secondary system
p = np.array([1, 2, 3]) #<- transform this point
# finding transformation
l = len(ins)
e = lambda r,d: np.linalg.det(np.delete(np.vstack([r, ins.T, np.ones(l)]), d, axis=0))
M = np.array([[(-1)**i * e(R, i) for R in out.T] for i in range(l+1)])
A, t = np.hsplit(M[1:].T/(-M[0])[:,None], [l-1])
t = np.transpose(t)[0]
# output transformation
print("Affine transformation matrix:\n", A)
print("Affine transformation translation vector:\n", t)
# unittests
print("TESTING:")
for p, P in zip(np.array(ins), np.array(out)):
  image_p = np.dot(A, p) + t
  result = "[OK]" if np.allclose(image_p, P) else "[ERROR]"
  print(p, " mapped to: ", image_p, " ; expected: ", P, result)
# calculate points
print("CALCULATION:")
P = np.dot(A, p) + t
print(p, " mapped to: ", P)

This code demonstrates how to recover affine transformation as matrix + vector and tests that initial points are mapped to where they should. You can test this code with Google colab, so you don't have to install anything.

Regarding theory behind this code: it is based on equation presented in "Beginner's guide to mapping simplexes affinely", matrix recovery is described in section "Recovery of canonical notation" and number of points needed to pinpoint the exact affine transformation is discussed in "How many points do we need?" section. The same authors published "Workbook on mapping simplexes affinely" that contains many practical examples of this kind.


问:
Linq retrive the parent object
Im using entityframework and the parent object MyObject already exist in my context (and childs loaded).

    public class MyObject
    {
        public int id { get; set; }
        public string name { get; set; }
        public IEnumerable<Child> child { get; set; }
    }

    public class Child
    {
        public int id { get; set; }
        public string name { get; set; }
        public IEnumerable<Child2> child2 { get; set; }
    }

    public class Child2
    {
        public int id { get; set; }
        public string name { get; set; }
    }
```

I want to make a condition on a Child2 property with keeping an instance of the Parent object.

var myFiletredMyObject = myObject.child.Where(c => c.child2.Any(c2 => c2.id == 1));
This gives me back a collection of Child object, how can I do to get the parent : MyObject ?

答:
If you've followed the entity framework code first conventions, then you should have written the relations between your tables as virtual properties.

In entity framework, the columns of your tables are represented by non-virtual properties; the virtual properties represent the relations between your tables (one-to-many, many-to-many).

Furthermore: it is better to describe the one-to-many as an ICollection<...> instead of an IEnumerable<...>. This enables you to ask for the number of children, and to Add a Child, something that entity framework can translate into SQL easily.

So with a little change in your code, changes that will give you the same database (well, I've renamed the properties a little, to make it easier in my example)

```<code>public class Parent
{
    public int id { get; set; }
    public string name { get; set; }

    // every Parent has zero or more Children (one-to-many)
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public int id { get; set; }
    public string name { get; set; }

    // every Child is the child of exactly one Parent, using a foreign key
    public int ParentId {get; set;}
    public virtual Parent Parent {get; set;}

    // every Child has zero or more Child2 (one-to-many)
    public virtual ICollection<Child2> Children2 { get; set; }
}

public class Child2
{
    public int id { get; set; }
    public string name { get; set; }

    // every Child2 belongs to exactly one Child, using foreign key
    public int ChildId {get; set;}
    public virtual Child Child {get; set;}
}
</code>```

And the DbContext:

```<code>public class FamilyDbContext
{
    public DbSet<Parent> Parents {get; set;}
    public DbSet<Child> Children {get; set;}
    public DbSet<Child2> Children2 {get; set;}
}
</code>```

This is enough for entity framework to detect your tables, the columns in the tables and the relations between the tables (in this case: one-to-many).

Because of the odd plural of Child you might get an odd table name: Childs. To prevent this, you might want to use fluent API. Add to your DbContext:

```<code>public override void OnModelCreating(DbModelBuilder modelBuilder);
{
    // configure the one-to-many between Parent and Child using the foreign key:
    modelBuilder.Entity<Parent>()
        .HasMany(parent => parent.Children)
        .HasRequired(child => child.Parent)
        .HasForeignKey(child => child.ParentId);

    // configure the one-to-many between Child and Child2 using foreign key
    // make sure that the table gets a proper name
    modelBuilder.Entity<Child>().ToTable("Children")
         .HasMany(child => child.Children2)
         .HasRequired(child2 => child2.Child)
         .HasForeignKey(child2 => child2.ChildId);

    // the one-to-many relations are configured. Set the last table name
    modelBuilder.Entity<Child2>().ToTable("Children2");
}
</code>```

Back to your question

If you've configured your classes the way that entity framework was meant, your query will be easy:

```<code>var myFilteredChildrenWithTheirParents = dbContext.Children
    .Where(child => ...)
    .Select(child => new
    {
        // select only the Child properties you really plan to use:
        Id = child.Id,
        Name = child.Name,

        Parent = new
        {   // again: select only the Parent properties you plan to use:
            Id = parent.Id,
            Name = parent.Name,
        },

        // no need for the foreign key, you already selected the value in Parent
        // ParentId = child.ParentId,
});
</code>```

Title: Linq retrive the parent object

Body:
Im using entityframework and the parent object MyObject already exist in my context (and childs loaded).

    public class MyObject
    {
        public int id { get; set; }
        public string name { get; set; }
        public IEnumerable<Child> child { get; set; }
    }

    public class Child
    {
        public int id { get; set; }
        public string name { get; set; }
        public IEnumerable<Child2> child2 { get; set; }
    }

    public class Child2
    {
        public int id { get; set; }
        public string name { get; set; }
    }

I want to make a condition on a Child2 property with keeping an instance of the Parent object.

var myFiletredMyObject = myObject.child.Where(c => c.child2.Any(c2 => c2.id == 1));
This gives me back a collection of Child object, how can I do to get the parent : MyObject ?

Body:
If you've followed the entity framework code first conventions, then you should have written the relations between your tables as virtual properties.

In entity framework, the columns of your tables are represented by non-virtual properties; the virtual properties represent the relations between your tables (one-to-many, many-to-many).

Furthermore: it is better to describe the one-to-many as an ICollection<...> instead of an IEnumerable<...>. This enables you to ask for the number of children, and to Add a Child, something that entity framework can translate into SQL easily.

So with a little change in your code, changes that will give you the same database (well, I've renamed the properties a little, to make it easier in my example)

public class Parent
{
    public int id { get; set; }
    public string name { get; set; }

    // every Parent has zero or more Children (one-to-many)
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public int id { get; set; }
    public string name { get; set; }

    // every Child is the child of exactly one Parent, using a foreign key
    public int ParentId {get; set;}
    public virtual Parent Parent {get; set;}

    // every Child has zero or more Child2 (one-to-many)
    public virtual ICollection<Child2> Children2 { get; set; }
}

public class Child2
{
    public int id { get; set; }
    public string name { get; set; }

    // every Child2 belongs to exactly one Child, using foreign key
    public int ChildId {get; set;}
    public virtual Child Child {get; set;}
}

And the DbContext:

public class FamilyDbContext
{
    public DbSet<Parent> Parents {get; set;}
    public DbSet<Child> Children {get; set;}
    public DbSet<Child2> Children2 {get; set;}
}

This is enough for entity framework to detect your tables, the columns in the tables and the relations between the tables (in this case: one-to-many).

Because of the odd plural of Child you might get an odd table name: Childs. To prevent this, you might want to use fluent API. Add to your DbContext:

public override void OnModelCreating(DbModelBuilder modelBuilder);
{
    // configure the one-to-many between Parent and Child using the foreign key:
    modelBuilder.Entity<Parent>()
        .HasMany(parent => parent.Children)
        .HasRequired(child => child.Parent)
        .HasForeignKey(child => child.ParentId);

    // configure the one-to-many between Child and Child2 using foreign key
    // make sure that the table gets a proper name
    modelBuilder.Entity<Child>().ToTable("Children")
         .HasMany(child => child.Children2)
         .HasRequired(child2 => child2.Child)
         .HasForeignKey(child2 => child2.ChildId);

    // the one-to-many relations are configured. Set the last table name
    modelBuilder.Entity<Child2>().ToTable("Children2");
}

Back to your question

If you've configured your classes the way that entity framework was meant, your query will be easy:

var myFilteredChildrenWithTheirParents = dbContext.Children
    .Where(child => ...)
    .Select(child => new
    {
        // select only the Child properties you really plan to use:
        Id = child.Id,
        Name = child.Name,

        Parent = new
        {   // again: select only the Parent properties you plan to use:
            Id = parent.Id,
            Name = parent.Name,
        },

        // no need for the foreign key, you already selected the value in Parent
        // ParentId = child.ParentId,
});


问:
How to set click listener on a whole ListView (not on the individual items of ListView)?
I want to set onClickListener() on the whole layout space of ListView i.e. if I click anywhere on layout area of a ListView, a specific task should be performed. How can I accomplish that in Android using java?

Notice that I do not want onItemClickListener(), tapping anywhere on the screen should perform the task.

ChatActivity.java

```<code>chatList = (ListView) findViewById(R.id.chat_list);

        adapter = new ChatMessageAdapter(ChatActivity.this, tempList);

        chatList.setAdapter(adapter);

        chatList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // code here
                return false;
            }
        });
</code>```

activity_chat.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/parent_layout"
    tools:context=".MainActivity"
    android:layout_marginRight="18dp"
    android:layout_marginLeft="18dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="18dp"
        android:backgroundTint="@color/colorAccent">

        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Person 1"
            android:textStyle="bold"
            android:gravity="left"/>
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Person 2"
            android:textStyle="bold"
            android:gravity="right"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ListView
        android:id="@+id/chat_list"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@null"/>

    </LinearLayout>

</LinearLayout>
</code>```

答:
Try this sample:

MainActivity.java

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

final private static float TOUCH_TOLERANCE = 10;
float fingerDownX, fingerDownY;

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

    ArrayList<String> datalist = new ArrayList<>();
    for(int i=0; i<30; i++){
        datalist.add("Item " + i);
    }
    ListView listView = findViewById(R.id.listView);
    ArrayAdapter adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, datalist);
    listView.setAdapter(adapter);

    listView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            float fingerX = motionEvent.getX();
            float fingerY = motionEvent.getY();
            if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                fingerDownX = fingerX;
                fingerDownY = fingerY;
            }
            if((motionEvent.getAction() == MotionEvent.ACTION_UP)&&
                    (Math.abs(fingerDownX - fingerX) < TOUCH_TOLERANCE)&&
                    (Math.abs(fingerDownY - fingerY) < TOUCH_TOLERANCE)){
                Toast.makeText(getApplicationContext(), "List Clicked!", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });
}
}
</code>```

activity_main.xml

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

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></ListView>

</LinearLayout>
</code>```

Hope that helps!

Body:
I want to set onClickListener() on the whole layout space of ListView i.e. if I click anywhere on layout area of a ListView, a specific task should be performed. How can I accomplish that in Android using java?

Notice that I do not want onItemClickListener(), tapping anywhere on the screen should perform the task.

ChatActivity.java

chatList = (ListView) findViewById(R.id.chat_list);

        adapter = new ChatMessageAdapter(ChatActivity.this, tempList);

        chatList.setAdapter(adapter);

        chatList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // code here
                return false;
            }
        });

activity_chat.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/parent_layout"
    tools:context=".MainActivity"
    android:layout_marginRight="18dp"
    android:layout_marginLeft="18dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="18dp"
        android:backgroundTint="@color/colorAccent">

        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Person 1"
            android:textStyle="bold"
            android:gravity="left"/>
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Person 2"
            android:textStyle="bold"
            android:gravity="right"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ListView
        android:id="@+id/chat_list"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@null"/>

    </LinearLayout>

</LinearLayout>

Body:
Try this sample:

MainActivity.java

public class MainActivity extends AppCompatActivity {

final private static float TOUCH_TOLERANCE = 10;
float fingerDownX, fingerDownY;

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

    ArrayList<String> datalist = new ArrayList<>();
    for(int i=0; i<30; i++){
        datalist.add("Item " + i);
    }
    ListView listView = findViewById(R.id.listView);
    ArrayAdapter adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, datalist);
    listView.setAdapter(adapter);

    listView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            float fingerX = motionEvent.getX();
            float fingerY = motionEvent.getY();
            if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                fingerDownX = fingerX;
                fingerDownY = fingerY;
            }
            if((motionEvent.getAction() == MotionEvent.ACTION_UP)&&
                    (Math.abs(fingerDownX - fingerX) < TOUCH_TOLERANCE)&&
                    (Math.abs(fingerDownY - fingerY) < TOUCH_TOLERANCE)){
                Toast.makeText(getApplicationContext(), "List Clicked!", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });
}
}

activity_main.xml

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

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></ListView>

</LinearLayout>

Hope that helps!


问:
Scala list with same adjacent values
I have this list:

```<code>List("Black","Black","Green","White")
</code>```

How can I check if a list has two adjacent values which are the same? Like so:

```<code>List("Black","Black","Green","White") true

List("Black","Yellow","Green","White") false

List("Black","Yellow","Black","Yellow") false
</code>```

答:
You can try:

def check[A](l: List[A]): Boolean =
 l.zip(l.tail).exists{ case (x,y) => x == y }

check(List("Black","Black","Green","White"))
//res5: Boolean = true

check(List("Black","Yellow","Green","White"))
//res6: Boolean = false

check(List("Black","Yellow","Black","Yellow"))
//res7: Boolean = false
```

Title: Scala list with same adjacent values

Body:
I have this list:

List("Black","Black","Green","White")

How can I check if a list has two adjacent values which are the same? Like so:

List("Black","Black","Green","White") true

List("Black","Yellow","Green","White") false

List("Black","Yellow","Black","Yellow") false


问:
Resource blocked due to MIME type?
For many years I have successfully included javscript files which are dynamically created.

Here is an example:
https://granadainfo.com/sups.php?locs=95

As you can see it loads OK.

I usually put them into the head of my html document like this.

script type="text/javascript" src="https://granadainfo.com/sups.php?locs=95"

/script

In the last few days they have stopped working.

The error message from firefox debugger console is the following.

The resource from “https://granadainfo.com/sups.php?locs=95” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

I use a2 web hosting. They must have made some change in configuration to make it stop working.

It may be that I can get over this problem with a line in the .htaccess file.

A2 hosting suggested this line but it does not work.
Header always unset X-Frame-Options

The problem only happen when there is a get request.
ie ?locs=95

There is no problem with static files.

I tried changing the file name to .js and changed the .htaccess file to parse .js as php but it makes no difference.

答:
PHP defaults to Content-Type: text/html. If you aren't serving HTML, then you need to use the header() function to state what you are serving.

```<code><?php
    header("Content-Type: application/javascript");
</code>```

Title: Resource blocked due to MIME type?

Body:
PHP defaults to Content-Type: text/html. If you aren't serving HTML, then you need to use the header() function to state what you are serving.

<?php
    header("Content-Type: application/javascript");


问:
How to validate input fields before the submit and if the validation is ok, show message block
enter link description here/*I try to make validation form and after submit

    message show success block
    How can i validate at first and then if validation
    is ok show success message.
    But now i can only see success block after submit
    validation

```<code>$(document).ready(function() {
  ('#submit').on('click', function() {
    var first_name = $('#first-name').val();
    var last_name = $('#last-name').val();
    var textarea = $('#textarea').val();
    var email = $('#email').val();
    var company = $('#company').val();
    var submit_button = $('#submit').val();
    $(".error").remove();
    /*check first-name length*/
    if (first_name.length < 3) {
      $('#first-
        name ').addClass('
        invalid ').after(' < span class = "error" >
  Must be at least 3 characters < /span>');
      }
      else {
        $('#first-name').removeClass('invalid');
      }
      /*check last-name length*/
      if (last_name.length < 3) {
        $('#last-
          name ').addClass('
          invalid ').after(' < span class = "error"
 > Must be at least 3 characters < /span>');
        }
        else {
          $('#last-name').removeClass('invalid');
        }
        if (textarea.length < 3) {

 $('#textarea').addClass('invalid').after('<span
            class = "error" > Must be at least 3
 characters < /span>');
          }
          else {
            $('#textarea').removeClass('invalid');
          }
          if (email.length < 3) {
            /*check email length and check with
  regexp*/

 $('#email').addClass('invalid').after('<span
              class = "error" > Must be at least 3
characters < /span>');
            }
            else {
              /*reg exp*/
              var regEx = /^(([^<>()\[\]\\.,;:\s@"]+
</code>```

(.[^<>()\  []\.,;: \s @ "]+)*)|(". + "))@(([[0-9]
    {1,3}.[0-9]  {
                  1,
                  3
                }.[0 - 9] {
                  1,
                  3
                }.[0 - 9] {
                  1,
                  3
                }]) | (([a - zA - Z\ - 0 - 9] + .) +
     [a - zA - Z] {
              2,
            })) $ / ;
          var validEmail = regEx.test(email);
          if (!validEmail) {

```<code>        $('#email').addClass('invalid').after('<span
          class = "error" > Enter a valid email <
/span>');
        }
      }
      if (company.length < 3) {
        /*check company fieled length*/

 $('#company').addClass('invalid').after('<span
          class = "error" > Must be at least 3
 characters < /span>');
        }
        else {
          $('#company').removeClass('invalid');
        }
        /*call submit*/
        $('#first_form').submit(function(e) {
          $('.success-message').fadeIn();
          $('.contact-form').fadeOut();
        })
        $('#first_form').submit()
      })
    `I want to submit form and show success message, if the dorm is valid
  });
</code>```

I cant finish the last block how to chech validation before submit

I expect that, before submitting, the form check all field according to  my valid params and if all field are valid show the message

答:
I have modified the js to fix the issue, let me know if it works.</p>

```<code>
$(document).ready(function() {
  $('#submit').on('click', function(e) {
    var first_name = $('#first-name').val();
    var last_name = $('#last-name').val();
    var textarea = $('#textarea').val();
    var email = $('#email').val();
    var company = $('#company').val();
    var submit_button = $('#submit').val();
    $(".error").remove();
    var invalid= false;

    if (first_name.length < 3) {
    invalid=true;
      $('#first-name').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      $('#first-name').removeClass('invalid');
    }

    if (last_name.length < 3) {
    invalid=true;
      $('#last-name').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      $('#last-name').removeClass('invalid');
    }

    if (textarea.length < 3) {
    invalid=true;
      $('#textarea').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      $('#textarea').removeClass('invalid');
    }

    if (email.length < 3) {
    invalid=true;
      $('#email').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      var regEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      var validEmail = regEx.test(email);

      if (!validEmail) {
    invalid=true;
        $('#email').addClass('invalid').after('<span class="error">Enter a valid email</span>');
      }
    }

    if (company.length < 3) {
    invalid=true;
      $('#company').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      $('#company').removeClass('invalid');
    }

  /*  var isFormValid = true; */

if(!invalid){
$('#first_form').submit(function() {
     /* var isFormValid = true; */

   })
$('.success-message').fadeIn();
      $('.contact-form').fadeOut();
   $('#first_form').submit()
}

e.preventDefault();

 })
});

</code>```

Body:
enter link description here/*I try to make validation form and after submit

    message show success block
    How can i validate at first and then if validation
    is ok show success message.
    But now i can only see success block after submit
    validation

$(document).ready(function() {
  ('#submit').on('click', function() {
    var first_name = $('#first-name').val();
    var last_name = $('#last-name').val();
    var textarea = $('#textarea').val();
    var email = $('#email').val();
    var company = $('#company').val();
    var submit_button = $('#submit').val();
    $(".error").remove();
    /*check first-name length*/
    if (first_name.length < 3) {
      $('#first-
        name ').addClass('
        invalid ').after('
  Must be at least 3 characters ');
      }
      else {
        $('#first-name').removeClass('invalid');
      }
      /*check last-name length*/
      if (last_name.length < 3) {
        $('#last-
          name ').addClass('
          invalid ').after('  Must be at least 3 characters ');
        }
        else {
          $('#last-name').removeClass('invalid');
        }
        if (textarea.length < 3) {

 $('#textarea').addClass('invalid').after(' Must be at least 3
 characters ');
          }
          else {
            $('#textarea').removeClass('invalid');
          }
          if (email.length < 3) {
            /*check email length and check with
  regexp*/

 $('#email').addClass('invalid').after(' Must be at least 3
characters ');
            }
            else {
              /*reg exp*/
              var regEx = /^(([^<>()\[\]\\.,;:\s@"]+

(.[^<>()\  []\.,;: \s @ "]+)*)|(". + "))@(([[0-9]
    {1,3}.[0-9]  {
                  1,
                  3
                }.[0 - 9] {
                  1,
                  3
                }.[0 - 9] {
                  1,
                  3
                }]) | (([a - zA - Z\ - 0 - 9] + .) +
     [a - zA - Z] {
              2,
            })) $ / ;
          var validEmail = regEx.test(email);
          if (!validEmail) {

        $('#email').addClass('invalid').after(' Enter a valid email ');
        }
      }
      if (company.length < 3) {
        /*check company fieled length*/

 $('#company').addClass('invalid').after(' Must be at least 3
 characters ');
        }
        else {
          $('#company').removeClass('invalid');
        }
        /*call submit*/
        $('#first_form').submit(function(e) {
          $('.success-message').fadeIn();
          $('.contact-form').fadeOut();
        })
        $('#first_form').submit()
      })
    `I want to submit form and show success message, if the dorm is valid
  });

I cant finish the last block how to chech validation before submit

I expect that, before submitting, the form check all field according to  my valid params and if all field are valid show the message

Body:
I have modified the js to fix the issue, let me know if it works.

$(document).ready(function() {
  $('#submit').on('click', function(e) {
    var first_name = $('#first-name').val();
    var last_name = $('#last-name').val();
    var textarea = $('#textarea').val();
    var email = $('#email').val();
    var company = $('#company').val();
    var submit_button = $('#submit').val();
    $(".error").remove();
    var invalid= false;

    if (first_name.length < 3) {
    invalid=true;
      $('#first-name').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      $('#first-name').removeClass('invalid');
    }

    if (last_name.length < 3) {
    invalid=true;
      $('#last-name').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      $('#last-name').removeClass('invalid');
    }

    if (textarea.length < 3) {
    invalid=true;
      $('#textarea').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      $('#textarea').removeClass('invalid');
    }

    if (email.length < 3) {
    invalid=true;
      $('#email').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      var regEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      var validEmail = regEx.test(email);

      if (!validEmail) {
    invalid=true;
        $('#email').addClass('invalid').after('<span class="error">Enter a valid email</span>');
      }
    }

    if (company.length < 3) {
    invalid=true;
      $('#company').addClass('invalid').after('<span class="error">Must be at least 3 characters</span>');
    } else {
      $('#company').removeClass('invalid');
    }

  /*  var isFormValid = true; */

if(!invalid){
$('#first_form').submit(function() {
     /* var isFormValid = true; */

   })
$('.success-message').fadeIn();
      $('.contact-form').fadeOut();
   $('#first_form').submit()
}

e.preventDefault();

 })
});


问:
How to set up Kotlin's byte code version in Gradle project to Java 8?
In Kotlin project, what is a proper Gradle script to make sure my classes will be compiled to byte code ver 52 (Java 8)?

For some reason my classes are compiled as ver 50 (Java 6) even though I set up source and target compatibility. At least this is what Idea shows me when I open file from directory build/classes/... after building the project.

My current set up looks like this.

```<code>buildscript {
    ext {
        kotlinVersion = '1.0.5-2'
        springBootVersion = '1.4.2.RELEASE'
    }
    repositories { mavenCentral() }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
    }
}

apply plugin: 'kotlin'
apply plugin: 'org.springframework.boot'

tasks.withType(JavaCompile) {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

// I also tried this and it hasn't helped
//sourceCompatibility = 1.8
//targetCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile("org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}")
    compile('org.springframework.cloud:spring-cloud-starter-stream-rabbit')
}

dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:Camden.SR2" } }
</code>```

答:
```<code>import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

// JVM target applied to all Kotlin tasks across all subprojects

// Kotlin DSL
tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8.toString()
}

//Groovy
tasks.withType(KotlinCompile) {
    kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8
}
</code>```

Body:
In Kotlin project, what is a proper Gradle script to make sure my classes will be compiled to byte code ver 52 (Java 8)?

For some reason my classes are compiled as ver 50 (Java 6) even though I set up source and target compatibility. At least this is what Idea shows me when I open file from directory build/classes/... after building the project.

My current set up looks like this.

buildscript {
    ext {
        kotlinVersion = '1.0.5-2'
        springBootVersion = '1.4.2.RELEASE'
    }
    repositories { mavenCentral() }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
    }
}

apply plugin: 'kotlin'
apply plugin: 'org.springframework.boot'

tasks.withType(JavaCompile) {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

// I also tried this and it hasn't helped
//sourceCompatibility = 1.8
//targetCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile("org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}")
    compile('org.springframework.cloud:spring-cloud-starter-stream-rabbit')
}

dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:Camden.SR2" } }


问:
Compare the columns of a dataframe in reverse order and create a new column with the index of the column which has value 0
I have imported data from a csv file into my program and then used set_index to set 'rule_id' as index. I used this code:

```<code>df = pd.read_excel('stack.xlsx')
df.set_index(['rule_id'])
</code>```

and the data looks like this:

Now I want to compare one column with another but in reverse order , for eg; I want to compare 'c' data with 'b' , then compare 'b' with 'a' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.
The result should look like this:

I am not able to write the code of how should I approach this problem, if you guys could help me , that would be great.

Edit: A minor edit. I have imported the data from an excel which looks like this , this is just a part of data , there are multiple columns:

Then I used pivot_table to manipulate the data as per my requirement using this code:

```<code>df = df.pivot_table(index = 'rule_id' , columns = ['date'], values = 'rid_fc', fill_value = 0)
</code>```

and my data looks like this now:

Now I want to compare one column with another but in reverse order , for eg; I want to compare '2019-04-25 16:36:32' data with '2019-04-25 16:29:05' , then compare '2019-04-25 16:29:05' with '2019-04-25 16:14:14' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.

答:
IIUC you can try with:

```<code>d={i:e for e,i in enumerate(df.columns)}
m1=df[['c','b']]
m2=df[['b','a']]
</code>```

```<code>df['comp1']=m1.eq(0).dot(m1.columns).map(d)
m3=m2.eq(0).dot(m2.columns)
m3.loc[m3.str.len()!=1]=np.nan
df['comp2']=m3.map(d)
print(df)
</code>```

```<code>         a  b  c  comp1  comp2
rule_id
51234    0  7  6    NaN    0.0
53219    0  0  1    1.0    NaN
56195    0  2  2    NaN    0.0
</code>```

Body:
I have imported data from a csv file into my program and then used set_index to set 'rule_id' as index. I used this code:

df = pd.read_excel('stack.xlsx')
df.set_index(['rule_id'])

and the data looks like this:

Now I want to compare one column with another but in reverse order , for eg; I want to compare 'c' data with 'b' , then compare 'b' with 'a' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.
The result should look like this:

I am not able to write the code of how should I approach this problem, if you guys could help me , that would be great.

Edit: A minor edit. I have imported the data from an excel which looks like this , this is just a part of data , there are multiple columns:

Then I used pivot_table to manipulate the data as per my requirement using this code:

df = df.pivot_table(index = 'rule_id' , columns = ['date'], values = 'rid_fc', fill_value = 0)

and my data looks like this now:

Now I want to compare one column with another but in reverse order , for eg; I want to compare '2019-04-25 16:36:32' data with '2019-04-25 16:29:05' , then compare '2019-04-25 16:29:05' with '2019-04-25 16:14:14' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.

Body:
IIUC you can try with:

d={i:e for e,i in enumerate(df.columns)}
m1=df[['c','b']]
m2=df[['b','a']]

df['comp1']=m1.eq(0).dot(m1.columns).map(d)
m3=m2.eq(0).dot(m2.columns)
m3.loc[m3.str.len()!=1]=np.nan
df['comp2']=m3.map(d)
print(df)

         a  b  c  comp1  comp2
rule_id
51234    0  7  6    NaN    0.0
53219    0  0  1    1.0    NaN
56195    0  2  2    NaN    0.0


问:
Java Spark application logs through logger is not showing in EMR log
I have a Spark java application running on an EMR. When I am trying to run the spark job locally logging into the EMR EC2 instance i am getting my Logger info from the java application on the console.

/usr/lib/spark/bin/spark-submit --class com.myproject.MyMainSparkClass --conf 'spark.driver.extraJavaOptions=-Dcong.parameters=somepropertiesparameter' --conf 'spark.executor.extraJavaOptions=-Dcong.parameters=somepropertiesparameter' --master local s3://myJarS3Location/myjar.jar

on console my logger info: 19/05/29 01:50:11 INFO DataTransforFileProcessUtility: ############ Job started at :2019-05-29 01:50:11.391 ############

Where as when i use the cluster mode :

/usr/lib/spark/bin/spark-submit --deploy-mode cluster --master yarn --class com.myproject.MyMainSparkClass --conf 'spark.driver.extraJavaOptions=-Dcong.parameters=somepropertiesparameter' --conf 'spark.executor.extraJavaOptions=-Dcong.parameters=somepropertiesparameter' s3://myJarS3Location/myjar.jar

I am not able to get the logger info from my application on my console. If i execute the cluster mode command as a step on EMR still i m not finding the application logger info in any of the log files. Does the application logger info gets logged anywhere if we run on cluster mode with Yarn?

答:
When running in Yarn cluster mode, the driver code runs in the same process as that of Application master(AM).

The logs will be logged in AM logs.

You could find the AM from the resource manager, from where you could find the link to logs as well.


问:
Select all checkbox not triggering their individual .change functions
I have a table with a checkbox on each row, plus a header checkbox that lets you select them all, that works fine with this code :

var idArray = [];

$(function(event, request, settings){

    //This method is explained later in the post
    //It takes care of storing checked rows into an array
    setupStoreSelected();

    $(function(){
        //Get every checkbox in table body
        var $checkboxes = $("tbody").find(":checkbox");

        //When checkAll is clicked, check/uncheck every enabled checkbox
        $("#checkAll").on("click", function(){
            $($checkboxes).not(":disabled").prop('checked', $(this).prop('checked'));
        });

        //Uncheck global if any individual checkbox is unchecked
        $("tbody").on("change", function () {
            if (!$(this).prop("checked")) {
                $("#checkAll").prop("checked", false);
            }
        });
    });
});

function setupStoreSelected(){

    //This selector listens to every checkbox except for the CheckAll
    $("input:checkbox:not('#checkAll')").change(function(){
        //Get that row's ID value from its column
        var id = $(this).closest("tr").find("td.idColumn").text();

        //If it is checked now, push that ID into a global array
        if($(this).prop("checked")){
            idArray.push(id);
            console.log("Added ID : " + id);
        }

        //Search and delete it from array if it gets unchecked
        else{
            var index = idArray.indexOf(id);
            if(index > -1){
                idArray.splice(index,1);
                console.log("Deleted ID : " + id);
            }
        }
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table{
  border : 1px solid grey;
}

thead{
  background-color : silver;
}

td{
  text-align : center;
}</code>```

    ID
    <input type="checkbox" id="checkAll" value="false">

      001
      <input type="checkbox"/>

      002
      <input type="checkbox"/>

      003
      <input type="checkbox"/>

      004
      <input type="checkbox"/>

```

The problem is that the checkAll checkbox does not trigger the .change(...) function of the individual checkboxes, so it doesnt work at all.

How can i modify my code so both individual and checkAll checkboxes store the ID's??

答:
You could trigger a change event for all individual check boxes using trigger('change') as:

```<code>//When checkAll is clicked, check/uncheck every enabled checkbox
 $("#checkAll").on("click", function(){
      $($checkboxes).not(":disabled").prop('checked', $(this).prop('checked')).trigger('change');
 });
</code>```

Body:
I have a table with a checkbox on each row, plus a header checkbox that lets you select them all, that works fine with this code :

var idArray = [];

$(function(event, request, settings){

    //This method is explained later in the post
    //It takes care of storing checked rows into an array
    setupStoreSelected();

    $(function(){
        //Get every checkbox in table body
        var $checkboxes = $("tbody").find(":checkbox");

        //When checkAll is clicked, check/uncheck every enabled checkbox
        $("#checkAll").on("click", function(){
            $($checkboxes).not(":disabled").prop('checked', $(this).prop('checked'));
        });

        //Uncheck global if any individual checkbox is unchecked
        $("tbody").on("change", function () {
            if (!$(this).prop("checked")) {
                $("#checkAll").prop("checked", false);
            }
        });
    });
});

function setupStoreSelected(){

    //This selector listens to every checkbox except for the CheckAll
    $("input:checkbox:not('#checkAll')").change(function(){
        //Get that row's ID value from its column
        var id = $(this).closest("tr").find("td.idColumn").text();

        //If it is checked now, push that ID into a global array
        if($(this).prop("checked")){
            idArray.push(id);
            console.log("Added ID : " + id);
        }

        //Search and delete it from array if it gets unchecked
        else{
            var index = idArray.indexOf(id);
            if(index > -1){
                idArray.splice(index,1);
                console.log("Deleted ID : " + id);
            }
        }
    });
}

table{
  border : 1px solid grey;
}

thead{
  background-color : silver;
}

td{
  text-align : center;
}

    ID
    <input type="checkbox" id="checkAll" value="false">

      001
      <input type="checkbox"/>

      002
      <input type="checkbox"/>

      003
      <input type="checkbox"/>

      004
      <input type="checkbox"/>

The problem is that the checkAll checkbox does not trigger the .change(...) function of the individual checkboxes, so it doesnt work at all.

How can i modify my code so both individual and checkAll checkboxes store the ID's??

Body:
You could trigger a change event for all individual check boxes using trigger('change') as:

//When checkAll is clicked, check/uncheck every enabled checkbox
 $("#checkAll").on("click", function(){
      $($checkboxes).not(":disabled").prop('checked', $(this).prop('checked')).trigger('change');
 });


问:
Define a class is not working globally but locally it is
When I define a code for a class within the custom CSS of a post this is working however if I define the same code globally under my theme options-> Custom CSS this is not working.

```<code>.learndash-wrapper .ld-table-list a.ld-table-list-item-preview {
    color: #13fff8;
}.
</code>```

Therefore I have to go post by post adding this code to get the proper font color... and I would like to have it globally working.

Any idea why this happened?

答: Check with the order of the css files loaded. If you have declared multiple css for same element latest class css will be applied. Along with that check the specificity of the css selectors. The selector with higher specificity will be affect the style.</p>

Body:
When I define a code for a class within the custom CSS of a post this is working however if I define the same code globally under my theme options-> Custom CSS this is not working.

.learndash-wrapper .ld-table-list a.ld-table-list-item-preview {
    color: #13fff8;
}.

Therefore I have to go post by post adding this code to get the proper font color... and I would like to have it globally working.

Any idea why this happened?


问:
Drawing Rectangles on an image from a different class
I am attempting to generate a set of rectangles on an image. To achieve this, I call a method that is present in a seperate class (Because multiple forms need to call this function.) Let's say I have Form A and Form B that both need to draw said set of rectangles:

From Form A it works just fine, from Form B it doesn't draw anything, but it doesn't return an exception either.

To make sure I haven't missed anything, I went as far as to copy and paste the function calls from both forms so the two of them are identical. I have also triple checked any semantic errors but have been unable to find any.

The function call from Form A is as follows:

```<code> private void PbPreview_Click(object sender, EventArgs e)
 {
     if (NewPage) //This bool is true when the user is displaying a new page(Image)
     {
         StartingY = MousePosition.Y - 76; //Save the Y position of the click in a float variable
         Form1.MainController.DrawRect(StartingY, PbPreview.Image); //Function call
         NewPage = false; //Set the new Page bool to false to prevent overdrawing
     }
 }
</code>```

The function call from Form B is as follows:

```<code> private void PbFactuur_Click(object sender, EventArgs e)
 {
     if (NewPage) //Same use as the NewPage bool from above
     {
         MouseY = MousePosition.Y - 76; //Saving mouse position
         Form1.MainController.DrawRect(MouseY, PbFactuur.Image); //Function call
         NewPage = false; //Set new page to false to prevent overdrawing
         MessageBox.Show("I have executed the function"); //Debug info
     }
 }
</code>```

And here is the code that is present within the function:

```<code> public void DrawRect(float Ypos, Image DrawSubject)
 {
     try
     {
         foreach (Rectangle R in Form1.nieuwBedrijf.Rects)
         {
             Rectangle TempRect = R;
             TempRect.Y = Convert.ToInt32(Ypos);
             Graphics G = Graphics.FromImage(DrawSubject);
             G.DrawRectangle(Pens.Black, TempRect.X * Form1.nieuwBedrijf.ScaleX, TempRect.Y * Form1.nieuwBedrijf.ScaleY, TempRect.Width * Form1.nieuwBedrijf.ScaleX, 1920);
         }
     }
     catch
     {
          MessageBox.Show("No rectangles have been defined yet.");
     }
 }
</code>```

Sidenote: Rects is a list of user defined rectangles.

The expected result would be that at the location where the user clicks, the set of rectangles will appear. But in reality, nothing appears at all.

The application doesn't return any sort of error message, and with the use of breakpoints and messageboxes I have been able to verify that the function does execute.

I hope anyone is able to point me to a potential solution to this problem.

Many thanks in advance
~Melvin

答:
After some tinkering around I have found the following solution:

The rectangles were actually being drawn, but it was not being shown on screen. To have the rectangles show up on screen, I had to add the following line of code:

```<code>private void PbFactuur_Click(object sender, EventArgs e)
 {
     if (NewPage) //Same use as the NewPage bool from above
     {
         MouseY = MousePosition.Y - 76; //Saving mouse position
         Form1.MainController.DrawRect(MouseY, PbFactuur.Image); //Function call
         NewPage = false; //Set new page to false to prevent overdrawing
         MessageBox.Show("I have executed the function"); //Debug info
         Refresh();//<----- This line fixed the problem
     }
 }
</code>```

Body:
I am attempting to generate a set of rectangles on an image. To achieve this, I call a method that is present in a seperate class (Because multiple forms need to call this function.) Let's say I have Form A and Form B that both need to draw said set of rectangles:

From Form A it works just fine, from Form B it doesn't draw anything, but it doesn't return an exception either.

To make sure I haven't missed anything, I went as far as to copy and paste the function calls from both forms so the two of them are identical. I have also triple checked any semantic errors but have been unable to find any.

The function call from Form A is as follows:

 private void PbPreview_Click(object sender, EventArgs e)
 {
     if (NewPage) //This bool is true when the user is displaying a new page(Image)
     {
         StartingY = MousePosition.Y - 76; //Save the Y position of the click in a float variable
         Form1.MainController.DrawRect(StartingY, PbPreview.Image); //Function call
         NewPage = false; //Set the new Page bool to false to prevent overdrawing
     }
 }

The function call from Form B is as follows:

 private void PbFactuur_Click(object sender, EventArgs e)
 {
     if (NewPage) //Same use as the NewPage bool from above
     {
         MouseY = MousePosition.Y - 76; //Saving mouse position
         Form1.MainController.DrawRect(MouseY, PbFactuur.Image); //Function call
         NewPage = false; //Set new page to false to prevent overdrawing
         MessageBox.Show("I have executed the function"); //Debug info
     }
 }

And here is the code that is present within the function:

 public void DrawRect(float Ypos, Image DrawSubject)
 {
     try
     {
         foreach (Rectangle R in Form1.nieuwBedrijf.Rects)
         {
             Rectangle TempRect = R;
             TempRect.Y = Convert.ToInt32(Ypos);
             Graphics G = Graphics.FromImage(DrawSubject);
             G.DrawRectangle(Pens.Black, TempRect.X * Form1.nieuwBedrijf.ScaleX, TempRect.Y * Form1.nieuwBedrijf.ScaleY, TempRect.Width * Form1.nieuwBedrijf.ScaleX, 1920);
         }
     }
     catch
     {
          MessageBox.Show("No rectangles have been defined yet.");
     }
 }

Sidenote: Rects is a list of user defined rectangles.

The expected result would be that at the location where the user clicks, the set of rectangles will appear. But in reality, nothing appears at all.

The application doesn't return any sort of error message, and with the use of breakpoints and messageboxes I have been able to verify that the function does execute.

I hope anyone is able to point me to a potential solution to this problem.

Many thanks in advance
~Melvin

Body:
After some tinkering around I have found the following solution:

The rectangles were actually being drawn, but it was not being shown on screen. To have the rectangles show up on screen, I had to add the following line of code:

private void PbFactuur_Click(object sender, EventArgs e)
 {
     if (NewPage) //Same use as the NewPage bool from above
     {
         MouseY = MousePosition.Y - 76; //Saving mouse position
         Form1.MainController.DrawRect(MouseY, PbFactuur.Image); //Function call
         NewPage = false; //Set new page to false to prevent overdrawing
         MessageBox.Show("I have executed the function"); //Debug info
         Refresh();//<----- This line fixed the problem
     }
 }


问:
TypeScript: How to return conditional types in function with rest parameter?
I want to make a function with rest parameter which will return conditional types like this:

null when provided undefined value

string when provided one number

array of strings when provided multiple numbers

I was trying to write this function in multiple forms using TypeScript extends syntax but unfortunately none of these was working.

I was also trying to write function where first parameter was a number and the second one was rest parameter but it also didn't work.

This is how working code looks right now except of proper conditional return of types:

import { rem } from "polished";

type UnitValue = number | undefined;

const unit = (...values: UnitValue[]): string | string[] | null => {
  const result: string[] = [];

  values.forEach(value => {
    if (value) {
      result.push(rem(value));
    }
  });

  if (result.length === 1) {
    return result[0];
  }

  if (result.length > 1) {
    return result;
  }

  return null;
};
```

Recreated case in codesansbox.io -> link

I need this function to return exactly and only these types in those three cases:

unit(undefined) -> null

unit(16) -> string

unit(16, 32) -> string[]

答:
You can achieve this behavior by using function overloads.
Your code will look like this:

```<code>import { rem } from "polished";

function unit(...values: undefined[]): null;
function unit(...values: [number]): string;
function unit(...values: number[]): string[];
function unit(...values): null | string | string[] {
  const result: string[] = [];

  values.forEach(value => {
    if (value) {
      result.push(rem(value));
    }
  });

  if (result.length === 1) {
    return result[0];
  }

  if (result.length > 1) {
    return result;
  }

  return null;
}
</code>```

You can check out in this playground.

Body:
I want to make a function with rest parameter which will return conditional types like this:

null when provided undefined value

string when provided one number

array of strings when provided multiple numbers

I was trying to write this function in multiple forms using TypeScript extends syntax but unfortunately none of these was working.

I was also trying to write function where first parameter was a number and the second one was rest parameter but it also didn't work.

This is how working code looks right now except of proper conditional return of types:

import { rem } from "polished";

type UnitValue = number | undefined;

const unit = (...values: UnitValue[]): string | string[] | null => {
  const result: string[] = [];

  values.forEach(value => {
    if (value) {
      result.push(rem(value));
    }
  });

  if (result.length === 1) {
    return result[0];
  }

  if (result.length > 1) {
    return result;
  }

  return null;
};

Recreated case in codesansbox.io -> link

I need this function to return exactly and only these types in those three cases:

unit(undefined) -> null

unit(16) -> string

unit(16, 32) -> string[]

Body:
You can achieve this behavior by using function overloads.
Your code will look like this:

import { rem } from "polished";

function unit(...values: undefined[]): null;
function unit(...values: [number]): string;
function unit(...values: number[]): string[];
function unit(...values): null | string | string[] {
  const result: string[] = [];

  values.forEach(value => {
    if (value) {
      result.push(rem(value));
    }
  });

  if (result.length === 1) {
    return result[0];
  }

  if (result.length > 1) {
    return result;
  }

  return null;
}

You can check out in <a href="https://www.typescriptlang.org/play/#src=%0D%0Afunction%20unit(...values%3A%20undefined[])%3A%20null%3B%0D%0Afunction%20unit(...values%3A%20[number])%3A%20string%3B%0D%0Afunction%20unit(...values%3A%20number[])%3A%20string[]%3B%0D%0Afunction%20unit(...values)%3A%20null%20%7C%20string%20%7C%20string[]%20%7B%0D%0A%20%20%20%20const%20result%3A%20string[]%20%3D%20[]%3B%0D%0A%0D%0A%20%20%20%20values.forEach(value%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20if%20(value)%20%7B%0D%0A%20%20%20%20%20%20%20%20result.push(rem(value))%3B%0D%0A%20%20%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%7D)%3B%0D%0A%0D%0A%20%20%20%20if%20(result.length%20%3D%3D%3D%201)%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20result[0]%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20if%20(result.length%20%3E%201)%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20result%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20return%20null%3B%0D%0A%7D%0D%0A%0D%0Aconst%20test1%20%3D%20unit()%20%2F%2F%20Hover%20%22test1%22%20%3D%20null%0D%0Aconst%20test2%20%3D%20unit(10)%20%2F%2F%20Hover%20%22test2%22%20%3D%20string%0D%0Aconst%20test3%20%3D%20unit(10%2C%2020)%20%2F%2F%20Hover%20%22test3%22%20%3D%20string[]" rel="nofollow noreferrer">this playground.


问:
How to logout using Expo.Facebook
I am using Expo.Facebook.logInWithReadPermissionsAsync.

I have read all the documentation and there is no document on how to logout from Facebook.

答:
If somebody wants to remove his profile in the modal window that pops up after You start the Expo.Facebook's login, here is how to do it:

On iOS (simulator or real device):
Go to Settings > Safari > Clear History and Website data

On android (tested on real device only):
Go to Settings > Storage > Other Apps > Chrome > CLEAR STORAGE > CLEAR ALL DATA (you may tap on "CLEAR CACHE" as well, but the CLEAR STORAGE option did the trick for me).

Title: How to logout using Expo.Facebook