问:
Error on Gluon Mobile
My eclipse has the following error when trying to create a GLUON project:

java.lang.NoSuchMethodError: org.eclipse.buildship.core.projectimport.ProjectImportConfiguration.toFixedAttributes()Lcom/gradleware/tooling/toolingmodel/repository/FixedRequestAttributes;
    at com.gluonhq.plugin.eclipse.wizard.GluonProjectWizard.performFinish(GluonProjectWizard.java:58)
    at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:778)
    at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:417)
    at org.eclipse.jface.dialogs.Dialog.lambda$0(Dialog.java:619)
    at org.eclipse.swt.events.SelectionListener$1.widgetSelected(SelectionListener.java:81)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:249)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:5268)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1348)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4522)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4107)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:818)
    at org.eclipse.jface.window.Window.open(Window.java:794)
    at org.eclipse.ui.internal.handlers.WizardHandler$New.executeHandler(WizardHandler.java:269)
    at org.eclipse.ui.internal.handlers.WizardHandler.execute(WizardHandler.java:290)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:291)
    at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:92)
    at sun.reflect.GeneratedMethodAccessor115.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55)
    at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:305)
    at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:239)
    at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
    at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:487)
    at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210)
    at org.eclipse.ui.internal.handlers.LegacyHandlerService.executeCommand(LegacyHandlerService.java:390)
    at org.eclipse.ui.internal.actions.CommandAction.runWithEvent(CommandAction.java:151)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
    at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:397)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:5268)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1348)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4522)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4107)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1150)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1039)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:153)
    at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:680)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:594)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:151)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1472)
```

Has anyone had this and solved it?

答:
Ok, the error was being generated, due to the gradle plugin being 2.0, gluon released a document stating this. I uninstalled Plugin 2.x and installed 1.x, solved the problem. Soon after, I did an update of it, and it kept working. Thank you very much to everyone. This error occurs in Oxygem 1.A

Eclipse gluon new project does not finish

Title: Error on Gluon Mobile

Body:
My eclipse has the following error when trying to create a GLUON project:

java.lang.NoSuchMethodError: org.eclipse.buildship.core.projectimport.ProjectImportConfiguration.toFixedAttributes()Lcom/gradleware/tooling/toolingmodel/repository/FixedRequestAttributes;
    at com.gluonhq.plugin.eclipse.wizard.GluonProjectWizard.performFinish(GluonProjectWizard.java:58)
    at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:778)
    at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:417)
    at org.eclipse.jface.dialogs.Dialog.lambda$0(Dialog.java:619)
    at org.eclipse.swt.events.SelectionListener$1.widgetSelected(SelectionListener.java:81)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:249)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:5268)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1348)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4522)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4107)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:818)
    at org.eclipse.jface.window.Window.open(Window.java:794)
    at org.eclipse.ui.internal.handlers.WizardHandler$New.executeHandler(WizardHandler.java:269)
    at org.eclipse.ui.internal.handlers.WizardHandler.execute(WizardHandler.java:290)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:291)
    at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:92)
    at sun.reflect.GeneratedMethodAccessor115.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55)
    at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:305)
    at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:239)
    at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
    at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:152)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:494)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:487)
    at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210)
    at org.eclipse.ui.internal.handlers.LegacyHandlerService.executeCommand(LegacyHandlerService.java:390)
    at org.eclipse.ui.internal.actions.CommandAction.runWithEvent(CommandAction.java:151)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
    at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:397)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:5268)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1348)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4522)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4107)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1150)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1039)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:153)
    at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:680)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:594)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:151)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1472)

Has anyone had this and solved it?


来源: stackexchange

问:
Select2 search options
I downloaded Select2 jquery plug in and have it all set up - I have a basic dropdown here.

```<code><SELECT NAME="GENDER">
 <OPTION VALUE="1">MALE
 <OPTION VALUE="2">FEMALE
 <OPTION VALUE="3">UNDEFINED
</SELECT>
</code>```

I applied the plug in and it works - not a problem.

I've been reviewing  the select2 documentation and what I'm trying to do is instead of searching by gender such as typing Female and Male, etc - I want the user to simply press 1 thus it brings up Male, 2 for Female.

Has anyone attempted this in select2?

答:
The parameters for the "matcher" option has changed since this has been answered. I came across this same issue when implementing a US State dropdown and each option was like <option value="PA">Pennsylvania</option> and I wanted users to be able to either spell the state or simply type their code and it'd work. Based on the updated documentation, I modified it like this:

```<code>$('select').select2({
    matcher: function(params, data) {
        // If there are no search terms, return all of the data
        if ($.trim(params.term) === '') { return data; }

        // Do not display the item if there is no 'text' property
        if (typeof data.text === 'undefined') { return null; }

        // `params.term` is the user's search term
        // `data.id` should be checked against
        // `data.text` should be checked against
        var q = params.term.toLowerCase();
        if (data.text.toLowerCase().indexOf(q) > -1 || data.id.toLowerCase().indexOf(q) > -1) {
            return $.extend({}, data, true);
        }

        // Return `null` if the term should not be displayed
        return null;
    }
});
</code>```

Here is a working CodePen demo I whipped up that demonstrates this using both the OP's select field and a select field of the U.S. states.

ContentLicense: CC BY-SA 3.0

Title: Select2 search options

Body:
I downloaded Select2 jquery plug in and have it all set up - I have a basic dropdown here.

<SELECT NAME="GENDER">
 <OPTION VALUE="1">MALE
 <OPTION VALUE="2">FEMALE
 <OPTION VALUE="3">UNDEFINED
</SELECT>

I applied the plug in and it works - not a problem.

I've been reviewing  the select2 documentation and what I'm trying to do is instead of searching by gender such as typing Female and Male, etc - I want the user to simply press 1 thus it brings up Male, 2 for Female.

Has anyone attempted this in select2?

Body:
The parameters for the "matcher" option has changed since this has been answered. I came across this same issue when implementing a US State dropdown and each option was like <option value="PA">Pennsylvania</option> and I wanted users to be able to either spell the state or simply type their code and it'd work. Based on the updated documentation, I modified it like this:

$('select').select2({
    matcher: function(params, data) {
        // If there are no search terms, return all of the data
        if ($.trim(params.term) === '') { return data; }

        // Do not display the item if there is no 'text' property
        if (typeof data.text === 'undefined') { return null; }

        // `params.term` is the user's search term
        // `data.id` should be checked against
        // `data.text` should be checked against
        var q = params.term.toLowerCase();
        if (data.text.toLowerCase().indexOf(q) > -1 || data.id.toLowerCase().indexOf(q) > -1) {
            return $.extend({}, data, true);
        }

        // Return `null` if the term should not be displayed
        return null;
    }
});

Here is a working CodePen demo I whipped up that demonstrates this using both the OP's select field and a select field of the U.S. states.


问:
How to Subscribe with async method in Rx?
I have following code:

```<code>IObservable<Data> _source;

...

_source.Subscribe(StoreToDatabase);

private async Task StoreToDatabase(Data data) {
    await dbstuff(data);
}
</code>```

However, this does not compile. Is there any way how to observe data asynchronously? I tried async void, it works, but I feel that given solution is not feasible.

I also checked Reactive Extensions Subscribe calling await, but it does not answer my question (I do not care about the SelectMany result.)

答:
I've been using TPL DataFlow to control back pressure and have used it to solve this problem.

The key part is ITargetBlock<TInput>.AsObserver() - source.

```<code>// Set a block to handle each element
ITargetBlock<long> targetBlock = new ActionBlock<long>(async p =>
{
    Console.WriteLine($"Received {p}");
    await Task.Delay(1000);
    Console.WriteLine($"Finished handling {p}");
},
new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });

// Generate an item each second for 10 seconds
var sequence = Observable.Interval(TimeSpan.FromSeconds(1)).Take(10);

// Subscribe with an observer created from the target block.
sequence.Subscribe(targetBlock.AsObserver());

// Await completion of the block
await targetBlock.Completion;
</code>```

The important part here is that the ActionBlock's bounded capacity is set to 1. This prevents the block from receiving more than one item at a time and will block OnNext if an item is already being processed!

My big surprise here was that it can be safe to call Task.Wait and Task.Result inside your subscription. Obviously, if you have called ObserverOnDispatcher() or similar you will probably hit deadlocks. Be careful!

Body:
I have following code:

IObservable<Data> _source;

...

_source.Subscribe(StoreToDatabase);

private async Task StoreToDatabase(Data data) {
    await dbstuff(data);
}

However, this does not compile. Is there any way how to observe data asynchronously? I tried async void, it works, but I feel that given solution is not feasible.

I also checked Reactive Extensions Subscribe calling await, but it does not answer my question (I do not care about the SelectMany result.)

Body:
I've been using TPL DataFlow to control back pressure and have used it to solve this problem.

The key part is ITargetBlock<TInput>.AsObserver() - source.

// Set a block to handle each element
ITargetBlock<long> targetBlock = new ActionBlock<long>(async p =>
{
    Console.WriteLine($"Received {p}");
    await Task.Delay(1000);
    Console.WriteLine($"Finished handling {p}");
},
new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });

// Generate an item each second for 10 seconds
var sequence = Observable.Interval(TimeSpan.FromSeconds(1)).Take(10);

// Subscribe with an observer created from the target block.
sequence.Subscribe(targetBlock.AsObserver());

// Await completion of the block
await targetBlock.Completion;

The important part here is that the ActionBlock's bounded capacity is set to 1. This prevents the block from receiving more than one item at a time and will block OnNext if an item is already being processed!

My big surprise here was that it can be safe to call Task.Wait and Task.Result inside your subscription. Obviously, if you have called ObserverOnDispatcher() or similar you will probably hit deadlocks. Be careful!


问:
Check if exist and create
I try generate and save uncial slug for title in DB.

```<code>                $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);
</code>```

How check if such field in url exist? And if exist save:

```<code>'url' => str_slug($feed->name,"-1"),
</code>```

I think:

```<code>  if (FriendlyUrl::whereUrl(str_slug($feed->name))){
            $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);} else {
                $feed->friendlyUrl()->make([
                    'url' => str_slug($feed->name),
                    'action' => "feeds/{$feed->id}-1",
                    'complicated' => false,
                    'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            };
            break;
</code>```

But it not clean and what if such url - str_slug($feed->name,"-1") already exists?

答:
You can use this : </p>

```<code>$friendlyUrl = friendlyUrl::firstOrNew(
    ['url' => str_slug($feed->name,"-1")], [
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,]
);

$friendlyUrl->save();
</code>```

Title: Check if exist and create

Body:
I try generate and save uncial slug for title in DB.

                $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);

How check if such field in url exist? And if exist save:

'url' => str_slug($feed->name,"-1"),

I think:

  if (FriendlyUrl::whereUrl(str_slug($feed->name))){
            $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);} else {
                $feed->friendlyUrl()->make([
                    'url' => str_slug($feed->name),
                    'action' => "feeds/{$feed->id}-1",
                    'complicated' => false,
                    'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            };
            break;

But it not clean and what if such url - str_slug($feed->name,"-1") already exists?

Body:
You can use this :

$friendlyUrl = friendlyUrl::firstOrNew(
    ['url' => str_slug($feed->name,"-1")], [
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,]
);

$friendlyUrl->save();


问:
What is the VBA formula to copy and paste the Output from a User Form into multiple rows
I have created a User Form in Excel that follows the following VBA code:

```<code>Private Sub CommandButton1_Click()

If TextBox1.Value = "" Then
    If MsgBox("Form is not complete. Continue?", vbQuestion + vbYesNo) <> vbYes Then
    Exit Sub
    End If
End If

ActiveCell = TextBox1.Value

ActiveCell.Offset(20, 0).Select

Call resetForm

End Sub

Sub resetForm()

TextBox1.Value = ""
UserForm1.TextBox1.SetFocus

End Sub
</code>```

This VBA code provides me the result generated in the User Form in the active cell of the WorkSheet.

I want to copy and paste this result into 18 rows below and then the active cell should be offset to the row below this cell.

The idea being if a User generates another result through the User Form (command button) will copy and paste this result 18 rows below and then the active cell should be offset to the row below this cell.

答:
After ActiveCell = TextBox1.Value write:

```<code>ActiveCell.Offset(18, 0) = ActiveCell
ActiveCell.Offset(1, 0).Activate
</code>```

The first line generates value 18 rows below the active cell and the second line moves the activecell with one row, thus exactly I want to copy and paste this result into 18 rows below and then the active cell should be offset to the row below this cell.

Body:
I have created a User Form in Excel that follows the following VBA code:

Private Sub CommandButton1_Click()

If TextBox1.Value = "" Then
    If MsgBox("Form is not complete. Continue?", vbQuestion + vbYesNo) <> vbYes Then
    Exit Sub
    End If
End If

ActiveCell = TextBox1.Value

ActiveCell.Offset(20, 0).Select

Call resetForm

End Sub

Sub resetForm()

TextBox1.Value = ""
UserForm1.TextBox1.SetFocus

End Sub

This VBA code provides me the result generated in the User Form in the active cell of the WorkSheet.

I want to copy and paste this result into 18 rows below and then the active cell should be offset to the row below this cell.

The idea being if a User generates another result through the User Form (command button) will copy and paste this result 18 rows below and then the active cell should be offset to the row below this cell.

Body:
After ActiveCell = TextBox1.Value write:

ActiveCell.Offset(18, 0) = ActiveCell
ActiveCell.Offset(1, 0).Activate

The first line generates value 18 rows below the active cell and the second line moves the activecell with one row, thus exactly I want to copy and paste this result into 18 rows below and then the active cell should be offset to the row below this cell.


问:
Immutable.js updateIn does not work with plain objects?
Docs state that it should work:

Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and updateIn() can update those values as well, treating them immutably by creating new copies of those values with the changes applied.

However, the following code does not work:

```<code>import { Map } from 'immutable';
let m = new Map({a: {b: 5}})
m = m.updateIn(["a", "b"], x => x + 1);
console.log(m);
</code>```

With exception Error: invalid keyPath. Same code with fromJS instead of new Map works.

Am I misunderstanding the docs or why is my code not working?

Edit: seems that this feature is new to 4.0.0, which is not installed by default.

答:
I am using Immutable 4.0.0-rc.9

Well, it works here in the console. You might want to consider trying to import like this import Immutable from 'immutable'; May be the ES6 Map and the import { Map } are clashing. I am not sure, please correct me if that is not the case.

let m = Immutable.Map({a: {b: 5}})
m = m.updateIn(["a", "b"], x => x + 1);
console.log(m);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script></code>```

Body:
Docs state that it should work:

Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and updateIn() can update those values as well, treating them immutably by creating new copies of those values with the changes applied.

However, the following code does not work:

import { Map } from 'immutable';
let m = new Map({a: {b: 5}})
m = m.updateIn(["a", "b"], x => x + 1);
console.log(m);

With exception Error: invalid keyPath. Same code with fromJS instead of new Map works.

Am I misunderstanding the docs or why is my code not working?

Edit: seems that this feature is new to 4.0.0, which is not installed by default.

Body:
I am using Immutable 4.0.0-rc.9

Well, it works here in the console. You might want to consider trying to import like this import Immutable from 'immutable'; May be the ES6 Map and the import { Map } are clashing. I am not sure, please correct me if that is not the case.

let m = Immutable.Map({a: {b: 5}})
m = m.updateIn(["a", "b"], x => x + 1);
console.log(m);

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>


问:
Find out who logged in as me, using su
On linux one can (if he has sudo rights) log in, and take control of another users account/username, doing sudo su - username

But is there a way to find out who logged in like this, and used my account?

答:
You can use last command .

man last :

last, lastb - show a listing of last logged in users

```<code>DESCRIPTION

       last  searches  back through the /var/log/wtmp file (or the file desig‐
       nated by the -f option) and displays a list of all users logged in (and
       out)  since  that  file was created.  One or more usernames and/or ttys
       can be given, in which case last will show only  the  entries  matching
       those  arguments.  Names of ttys can be abbreviated, thus last 0 is the
       same as last tty0.
</code>```

Title: Find out who logged in as me, using su

Body:
You can use last command .

man last :

last, lastb - show a listing of last logged in users

DESCRIPTION

       last  searches  back through the /var/log/wtmp file (or the file desig‐
       nated by the -f option) and displays a list of all users logged in (and
       out)  since  that  file was created.  One or more usernames and/or ttys
       can be given, in which case last will show only  the  entries  matching
       those  arguments.  Names of ttys can be abbreviated, thus last 0 is the
       same as last tty0.


问:
Loss of precision when casting Math.pow()
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

```<code>2_147_483_647
</code>```

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

```<code>System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);
</code>```

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

答:
Typecast the whole Math.pow(2, 31) - 1). Like this

```<code>System.out.println((int) (Math.pow(2, 31) - 1));
</code>```

Body:
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

2_147_483_647

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

Body:
Typecast the whole Math.pow(2, 31) - 1). Like this

System.out.println((int) (Math.pow(2, 31) - 1));


问:
QTablewidget : How to get inserted Picture from certain (Row,Col)
I've inserted a picture to a table.

```<code>    QTableWidgetItem *template_to_insert = new QTableWidgetItem();
    template_to_insert->setData(Qt::DecorationRole, QPixmap::fromImage(templ_));
    ui->tableWidget_2->insertRow(ui->tableWidget_2->rowCount());
    ui->tableWidget_2->setItem(0, 0, template_to_insert);
</code>```

Now I want to select the inserted picture and move it to another table.

My try:

```<code>    QTableWidgetItem * item = ui->tableWidget->item(0, 0);
    ui->tableWidget_3->insertRow(ui->tableWidget_2->rowCount());
    ui->tableWidget_3->setItem(ui->tableWidget_2->rowCount()-1, 0, item);
</code>```

But I insert an empty row to the target.
Can you maybe explain me my mistake ? Or can you maybe show me an example how to do it ?

Thank you.

答:
Ok, I've found my mistake.
Instead of item() I have to use takeitem().

Solution:

```<code>    QTableWidgetItem * item = ui->tableWidget->takeitem(0, 0);
    ui->tableWidget_3->insertRow(ui->tableWidget_2->rowCount());
    ui->tableWidget_3->setItem(ui->tableWidget_2->rowCount()-1, 0, item);
</code>```

Body:
I've inserted a picture to a table.

    QTableWidgetItem *template_to_insert = new QTableWidgetItem();
    template_to_insert->setData(Qt::DecorationRole, QPixmap::fromImage(templ_));
    ui->tableWidget_2->insertRow(ui->tableWidget_2->rowCount());
    ui->tableWidget_2->setItem(0, 0, template_to_insert);

Now I want to select the inserted picture and move it to another table.

My try:

    QTableWidgetItem * item = ui->tableWidget->item(0, 0);
    ui->tableWidget_3->insertRow(ui->tableWidget_2->rowCount());
    ui->tableWidget_3->setItem(ui->tableWidget_2->rowCount()-1, 0, item);

But I insert an empty row to the target.
Can you maybe explain me my mistake ? Or can you maybe show me an example how to do it ?

Thank you.

Body:
Ok, I've found my mistake.
Instead of item() I have to use takeitem().

Solution:

    QTableWidgetItem * item = ui->tableWidget->takeitem(0, 0);
    ui->tableWidget_3->insertRow(ui->tableWidget_2->rowCount());
    ui->tableWidget_3->setItem(ui->tableWidget_2->rowCount()-1, 0, item);


问:
captureOutput not being called
I have been looking into this for way too long now.

I am trying to get MacOS webcam data and run CIDetect on the frames that the webcam outputs.

I know I need to:

connect AVCaptureDevice (as in input to) into AVCaptureSession

connect AVCaptureVideoDataOutput (as an output to) into AVCaptureSession

call .setSampleBufferDelegate(AVCaptureVideoDataOutputSampleBufferDelegate, DelegateQueue)

For some reason, after calling .setSampleBufferDelegate(...) (and of course after calling .startRunning() on the AVCaptureSession instance), my AVCaptureVideoDataOutputSampleBufferDelegate's captureOutput is not being called.

I found so many people having trouble with this online, but I was not able to find any solution.

It seems to me like it has to do with the DispatchQueue.

MyDelegate.swift:

```<code>class MyDelegate : NSObject {

    var context: CIContext?;
    var detector : CIDetector?;

    override init() {
        context = CIContext();
        detector = CIDetector(ofType: CIDetectorTypeFace, context: context);
        print("set up!");

    }

}
extension MyDelegate : AVCaptureVideoDataOutputSampleBufferDelegate {
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection) {
        print("success?");
        var pixelBuffer : CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!;
        var image : CIImage = CIImage(cvPixelBuffer: pixelBuffer);
        var features : [CIFeature] = detector!.features(in: image);
        for feature in features {
            print(feature.type);
            print(feature.bounds);
        }
    }

    func captureOutput(_ : AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection) {
        print("fail?");
    }
}
</code>```

ViewController.swift:

```<code>var captureSession : AVCaptureSession;
var captureDevice : AVCaptureDevice?
var previewLayer : AVCaptureVideoPreviewLayer?

var vdo : AVCaptureVideoDataOutput;

var videoDataOutputQueue : DispatchQueue;

override func viewDidLoad() {
    super.viewDidLoad()

    camera.layer = CALayer()

    // Do any additional setup after loading the view, typically from a nib.
    captureSession.sessionPreset = AVCaptureSessionPresetLow

    // Get all audio and video devices on this machine
    let devices = AVCaptureDevice.devices()

    // Find the FaceTime HD camera object
    for device in devices! {
        print(device)

        // Camera object found and assign it to captureDevice
        if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)) {
            print(device)
            captureDevice = device as? AVCaptureDevice
        }
    }

    if captureDevice != nil {
        do {
            try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            // vdo : AVCaptureVideoDataOutput;
            vdo.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable: NSNumber(value: kCVPixelFormatType_32BGRA)]

            try captureDevice!.lockForConfiguration()
            captureDevice!.activeVideoMinFrameDuration = CMTimeMake(1, 30)
            captureDevice!.unlockForConfiguration()

            videoDataOutputQueue.sync{
                vdo.setSampleBufferDelegate(
                    MyDelegate,
                    queue: videoDataOutputQueue
                );
                vdo.alwaysDiscardsLateVideoFrames = true
                captureSession.addOutput(vdo)
                captureSession.startRunning();
            }
        } catch {
            print(AVCaptureSessionErrorKey.description)
        }
    }
</code>```

All of the necessary variables inside viewDidLoad relating to AVFoundation have been instantiated inside the Viewcontroller's init(). I've omitted that for clarity.

Any ideas?

Thanks, SO!

Kovek

EDIT:
  - Fixed setting delegate from self to MyDelegate.

And this is how I initialize videoDataOutputQueue:

```<code>    videoDataOutputQueue = DispatchQueue(
        label: "VideoDataOutputQueue"
    );
</code>```

答:
I had a similar problem: in my case the problem was that writing in Swift 4 you have to implement the following method:

```<code>func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection)
</code>```

instead of:

```<code>func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!)
</code>```

Hope it helps.

EDIT

This method has to be implemented by the AVCaptureMetadataOutputObjectsDelegate (e.g., your viewcontroller). In order to start QRCode capture session you can try something like this:

```<code>    captureSession = AVCaptureSession()

    let videoCaptureDevice = AVCaptureDevice.default(for: AVMediaType.video);
    var videoInput:AVCaptureDeviceInput? =  nil;

    do {
        if let v = videoCaptureDevice{
            videoInput = try AVCaptureDeviceInput(device: v)
        }
        else{
            print("Error: can't find videoCaptureDevice");
        }

    } catch {
        let ac = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "Ok", style: .default))
        present(ac, animated: true)
        return
    }

    if let videoInput = videoInput{
        if (captureSession.canAddInput(videoInput)) {
            captureSession.addInput(videoInput)
        } else {
            //Show error
            return;
        }
    }
    else{
        //Show error
        return;
    }

    let metadataOutput = AVCaptureMetadataOutput()

    if (captureSession.canAddOutput(metadataOutput)) {
        captureSession.addOutput(metadataOutput);

        metadataOutput.setMetadataObjectsDelegate(/*YOUR DELEGATE*/, queue: DispatchQueue.main);
        metadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr, AVMetadataObject.ObjectType.code128];
    } else {
        //Show error
        return;
    }

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
    previewLayer.frame = view.layer.bounds;

    previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill;
    view.layer.addSublayer(previewLayer);

    captureSession.startRunning();
</code>```

Title: captureOutput not being called

Body:
I have been looking into this for way too long now.

I am trying to get MacOS webcam data and run CIDetect on the frames that the webcam outputs.

I know I need to:

connect AVCaptureDevice (as in input to) into AVCaptureSession

connect AVCaptureVideoDataOutput (as an output to) into AVCaptureSession

call .setSampleBufferDelegate(AVCaptureVideoDataOutputSampleBufferDelegate, DelegateQueue)

For some reason, after calling .setSampleBufferDelegate(...) (and of course after calling .startRunning() on the AVCaptureSession instance), my AVCaptureVideoDataOutputSampleBufferDelegate's captureOutput is not being called.

I found so many people having trouble with this online, but I was not able to find any solution.

It seems to me like it has to do with the DispatchQueue.

MyDelegate.swift:

class MyDelegate : NSObject {

    var context: CIContext?;
    var detector : CIDetector?;

    override init() {
        context = CIContext();
        detector = CIDetector(ofType: CIDetectorTypeFace, context: context);
        print("set up!");

    }

}
extension MyDelegate : AVCaptureVideoDataOutputSampleBufferDelegate {
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection) {
        print("success?");
        var pixelBuffer : CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!;
        var image : CIImage = CIImage(cvPixelBuffer: pixelBuffer);
        var features : [CIFeature] = detector!.features(in: image);
        for feature in features {
            print(feature.type);
            print(feature.bounds);
        }
    }

    func captureOutput(_ : AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection) {
        print("fail?");
    }
}

ViewController.swift:

var captureSession : AVCaptureSession;
var captureDevice : AVCaptureDevice?
var previewLayer : AVCaptureVideoPreviewLayer?

var vdo : AVCaptureVideoDataOutput;

var videoDataOutputQueue : DispatchQueue;

override func viewDidLoad() {
    super.viewDidLoad()

    camera.layer = CALayer()

    // Do any additional setup after loading the view, typically from a nib.
    captureSession.sessionPreset = AVCaptureSessionPresetLow

    // Get all audio and video devices on this machine
    let devices = AVCaptureDevice.devices()

    // Find the FaceTime HD camera object
    for device in devices! {
        print(device)

        // Camera object found and assign it to captureDevice
        if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)) {
            print(device)
            captureDevice = device as? AVCaptureDevice
        }
    }

    if captureDevice != nil {
        do {
            try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            // vdo : AVCaptureVideoDataOutput;
            vdo.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable: NSNumber(value: kCVPixelFormatType_32BGRA)]

            try captureDevice!.lockForConfiguration()
            captureDevice!.activeVideoMinFrameDuration = CMTimeMake(1, 30)
            captureDevice!.unlockForConfiguration()

            videoDataOutputQueue.sync{
                vdo.setSampleBufferDelegate(
                    MyDelegate,
                    queue: videoDataOutputQueue
                );
                vdo.alwaysDiscardsLateVideoFrames = true
                captureSession.addOutput(vdo)
                captureSession.startRunning();
            }
        } catch {
            print(AVCaptureSessionErrorKey.description)
        }
    }

All of the necessary variables inside viewDidLoad relating to AVFoundation have been instantiated inside the Viewcontroller's init(). I've omitted that for clarity.

Any ideas?

Thanks, SO!

Kovek

EDIT:
  - Fixed setting delegate from self to MyDelegate.

And this is how I initialize videoDataOutputQueue:

    videoDataOutputQueue = DispatchQueue(
        label: "VideoDataOutputQueue"
    );

Body:
I had a similar problem: in my case the problem was that writing in Swift 4 you have to implement the following method:

func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection)

instead of:

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!)

Hope it helps.

EDIT

This method has to be implemented by the AVCaptureMetadataOutputObjectsDelegate (e.g., your viewcontroller). In order to start QRCode capture session you can try something like this:

    captureSession = AVCaptureSession()

    let videoCaptureDevice = AVCaptureDevice.default(for: AVMediaType.video);
    var videoInput:AVCaptureDeviceInput? =  nil;

    do {
        if let v = videoCaptureDevice{
            videoInput = try AVCaptureDeviceInput(device: v)
        }
        else{
            print("Error: can't find videoCaptureDevice");
        }

    } catch {
        let ac = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "Ok", style: .default))
        present(ac, animated: true)
        return
    }

    if let videoInput = videoInput{
        if (captureSession.canAddInput(videoInput)) {
            captureSession.addInput(videoInput)
        } else {
            //Show error
            return;
        }
    }
    else{
        //Show error
        return;
    }

    let metadataOutput = AVCaptureMetadataOutput()

    if (captureSession.canAddOutput(metadataOutput)) {
        captureSession.addOutput(metadataOutput);

        metadataOutput.setMetadataObjectsDelegate(/*YOUR DELEGATE*/, queue: DispatchQueue.main);
        metadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr, AVMetadataObject.ObjectType.code128];
    } else {
        //Show error
        return;
    }

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
    previewLayer.frame = view.layer.bounds;

    previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill;
    view.layer.addSublayer(previewLayer);

    captureSession.startRunning();


问:
Universal Image Loader Set unrelated images
I am Using Universal Image Loader library in order to set images from the server in my recycler view.
In my recycler View when I start to scroll on it, It will setup unrelated images for a few seconds and after that, it will set true image.
I don't know where is the problem.

This is my Adapter That I'm using:

```<code>public class HistoryDetailAdapter extends RecyclerView.Adapter<HistoryDetailAdapter.ViewHolder> {
  private List<PList> menuItems;
  private Context mContext;
  private ActivityHistoryDetails activityHistoryDetails;
  private DisplayImageOptions defaultOptions;
  private ImageLoaderConfiguration config;

  public HistoryDetailAdapter(List<PList> menuItems, Context mContext) {
    this.menuItems = menuItems;
    this.mContext = mContext;
    this.activityHistoryDetails = (ActivityHistoryDetails) mContext;

    byte[] toEncrypt = (G.getPremiumState()[0] + ":" + G.getPremiumState()[1]).getBytes();
    String encryptedCredentials = Base64.encodeToString(toEncrypt, Base64.DEFAULT);
    Map<String, String> headers = new HashMap();
    headers.put("Authorization", "Basic " + encryptedCredentials);

    defaultOptions = new DisplayImageOptions.Builder()
      .cacheInMemory(false)
      .cacheOnDisk(false)
      .resetViewBeforeLoading(true)
      .delayBeforeLoading(5000)
      .showImageOnLoading(R.drawable.loading_02)
      .showImageOnFail(R.drawable.ic_empty_white_box)
      .extraForDownloader(headers)
      .build();

    config = new ImageLoaderConfiguration.Builder(activityHistoryDetails)
      .defaultDisplayImageOptions(defaultOptions)
      .imageDownloader(new AuthDownloader(activityHistoryDetails))
      .build();

  }

  public static class ViewHolder extends RecyclerView.ViewHolder {

    ImageView imgDefault;
    LinearLayout parentLayout;
    CoordinatorLayout coordinatorLayout;

    public ViewHolder(View v) {
      super(v);

      imgDefault = (ImageView) v.findViewById(R.id.img_defaultImage);
      parentLayout = (LinearLayout) v.findViewById(R.id.parentLayout);
      coordinatorLayout = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout);

    }
  }

  @Override
  public HistoryDetailAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    // Create a new View
    final View v = LayoutInflater.from(activityHistoryDetails).inflate(R.layout.activity_history_detail_recycler, parent, false);
    ViewHolder vh = new ViewHolder(v);
    return vh;
  }

  @Override
  public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Download and Load Default Image from server into imgDefault ImageView
    String url = "http://192.168.14.77:8080/api/images/download/";

    if (menuItems.get(position).getPDefaultImage().getIId() != null) {

      url += menuItems.get(position).getPDefaultImage().getIId();

      ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
      imageLoader.init(config);
      imageLoader.handleSlowNetwork(true);

      // Load image, decode it to Bitmap and return Bitmap to callback
      ImageSize targetSize = new ImageSize(120, 120); // result Bitmap will be fit to this size
      imageLoader.loadImage(url, targetSize, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
          // Do whatever you want with Bitmap
          holder.imgDefault.setImageBitmap(loadedImage);
        }
      });

    } else {
       holder.imgDefault.setImageResource(R.drawable.loading_01);
    }

  }

  @Override
  public int getItemCount() {
    if (menuItems.size() > 0) {

      return menuItems.size();

    } else {
      return 0;
    }

  }

  public List<PList> getList() {
    return menuItems;
  }
}
</code>```

Thank you for your answers.

答: You can use Glide or Fresco image library for it. They are working stable.</p>

Body:
I am Using Universal Image Loader library in order to set images from the server in my recycler view.
In my recycler View when I start to scroll on it, It will setup unrelated images for a few seconds and after that, it will set true image.
I don't know where is the problem.

This is my Adapter That I'm using:

public class HistoryDetailAdapter extends RecyclerView.Adapter<HistoryDetailAdapter.ViewHolder> {
  private List<PList> menuItems;
  private Context mContext;
  private ActivityHistoryDetails activityHistoryDetails;
  private DisplayImageOptions defaultOptions;
  private ImageLoaderConfiguration config;

  public HistoryDetailAdapter(List<PList> menuItems, Context mContext) {
    this.menuItems = menuItems;
    this.mContext = mContext;
    this.activityHistoryDetails = (ActivityHistoryDetails) mContext;

    byte[] toEncrypt = (G.getPremiumState()[0] + ":" + G.getPremiumState()[1]).getBytes();
    String encryptedCredentials = Base64.encodeToString(toEncrypt, Base64.DEFAULT);
    Map<String, String> headers = new HashMap();
    headers.put("Authorization", "Basic " + encryptedCredentials);

    defaultOptions = new DisplayImageOptions.Builder()
      .cacheInMemory(false)
      .cacheOnDisk(false)
      .resetViewBeforeLoading(true)
      .delayBeforeLoading(5000)
      .showImageOnLoading(R.drawable.loading_02)
      .showImageOnFail(R.drawable.ic_empty_white_box)
      .extraForDownloader(headers)
      .build();

    config = new ImageLoaderConfiguration.Builder(activityHistoryDetails)
      .defaultDisplayImageOptions(defaultOptions)
      .imageDownloader(new AuthDownloader(activityHistoryDetails))
      .build();

  }

  public static class ViewHolder extends RecyclerView.ViewHolder {

    ImageView imgDefault;
    LinearLayout parentLayout;
    CoordinatorLayout coordinatorLayout;

    public ViewHolder(View v) {
      super(v);

      imgDefault = (ImageView) v.findViewById(R.id.img_defaultImage);
      parentLayout = (LinearLayout) v.findViewById(R.id.parentLayout);
      coordinatorLayout = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout);

    }
  }

  @Override
  public HistoryDetailAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    // Create a new View
    final View v = LayoutInflater.from(activityHistoryDetails).inflate(R.layout.activity_history_detail_recycler, parent, false);
    ViewHolder vh = new ViewHolder(v);
    return vh;
  }

  @Override
  public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Download and Load Default Image from server into imgDefault ImageView
    String url = "http://192.168.14.77:8080/api/images/download/";

    if (menuItems.get(position).getPDefaultImage().getIId() != null) {

      url += menuItems.get(position).getPDefaultImage().getIId();

      ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
      imageLoader.init(config);
      imageLoader.handleSlowNetwork(true);

      // Load image, decode it to Bitmap and return Bitmap to callback
      ImageSize targetSize = new ImageSize(120, 120); // result Bitmap will be fit to this size
      imageLoader.loadImage(url, targetSize, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
          // Do whatever you want with Bitmap
          holder.imgDefault.setImageBitmap(loadedImage);
        }
      });

    } else {
       holder.imgDefault.setImageResource(R.drawable.loading_01);
    }

  }

  @Override
  public int getItemCount() {
    if (menuItems.size() > 0) {

      return menuItems.size();

    } else {
      return 0;
    }

  }

  public List<PList> getList() {
    return menuItems;
  }
}

Thank you for your answers.


问:
Force browser to disable horizontal bar even when you ZOOMING in at 150%
How do i force the browser to disable horizontal bar even when you are viewing your web content at 125% - 150%?</p>

答:
CSS:

```<code>html,body {
    overflow-x:hidden;
}
</code>```

HTML:

For mobile devices, you probably need this meta tag in your

```<code><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
</code>```

Body:
CSS:

html,body {
    overflow-x:hidden;
}

HTML:

For mobile devices, you probably need this meta tag in your <head>

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">


问:
Disable mouse middle click event with help of jQuery
I am trying to disable mouse middle click event in anchor tag. It works perfectly in Chrome. Here is my code for Chrome implementation:

```<code>//prevent mouse wheel middle click for chrome
$(document).on('auxclick', 'a', function (e) {
  if (e.which === 2) { //middle Click
          return false;
  }
return true;
});
</code>```

Note: above the implementation work only for Chrome 55 and their latest version

Reference auxclick documentation for Chrome: https://developers.google.com/web/updates/2016/10/auxclick

auxclick browser compatibility:

Reference Link: https://developer.mozilla.org/en-US/docs/Web/Events/auxclick

Unfortunately i am unable to disable mouse middle click event in rest of browser like Firefox, IE11 & Safari

I am trying to find possibility in rest of browser. Trying mousedown & mouseup event to disable mouse middle click event in rest of browser but those events don't help to achieve my expectation.

答:
The auxclick event is an experimental technology and therefor it has limited browser support.

You could use the mousedown event:

$('button').on('mousedown', function(e) {
    if (e.which === 2) {
      console.log('Disabled');
      return false;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button></code>```

This should work in all major browsers, though I don't like the idea of changing native behavior.

Body:
I am trying to disable mouse middle click event in anchor tag. It works perfectly in Chrome. Here is my code for Chrome implementation:

//prevent mouse wheel middle click for chrome
$(document).on('auxclick', 'a', function (e) {
  if (e.which === 2) { //middle Click
          return false;
  }
return true;
});

Note: above the implementation work only for Chrome 55 and their latest version

Reference auxclick documentation for Chrome: https://developers.google.com/web/updates/2016/10/auxclick

auxclick browser compatibility:

Reference Link: https://developer.mozilla.org/en-US/docs/Web/Events/auxclick

Unfortunately i am unable to disable mouse middle click event in rest of browser like Firefox, IE11 & Safari

I am trying to find possibility in rest of browser. Trying mousedown & mouseup event to disable mouse middle click event in rest of browser but those events don't help to achieve my expectation.

Body:
The auxclick event is an experimental technology and therefor it has limited browser support.

You could use the mousedown event:

$('button').on('mousedown', function(e) {
    if (e.which === 2) {
      console.log('Disabled');
      return false;
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>

This should work in all major browsers, though I don't like the idea of changing native behavior.


问:
Fortran 77 Do Loop block clarification
Both NUM and ARRAY double precision variables, not sure how the if block will execute. When will it stop? What is it actually doing?, If we go to 8, then are we exiting the do loop? </p>

<p>Thanks </p>

```<code>DO 7 I = 1,28
IF (NUM - ARRAY(I)) 8,7,7
7 CONTINUE
I=29
8 NUM = ARRAY(I)
....
....
....
....
</code>```

答:
As previously stated the conditional in the loop is an arithmetic if statement.

We know (and that's explicitly stated in the previous answer here) that if num is less than array(i) the label 8 is chosen, otherwise label 7 is chosen.  It's also stated in that other answer that these have the effect of exiting the loop or cycling it.  To be precise, I'll continue.

A DO construct has a range.  A nonblock DO construct like the one in the question has range consisting of the statements between and including the do statement and the DO termination statement (in this case 7 continue).  The DO termination statement is a valid target for a jump from within the range of the construct.

When the DO termination statement is jumped to, execution remains within the scope of the construct.  That termination statement is executed (in this case, continue, doing nothing) and the loop iteration condition is again tested.  That is, the loop cycles.

From within a DO construct, a jump to a statement outside the range of the construct terminates execution of the construct: like an exit.

This example, then, has the equivalent form using an IF construct (with go tos - bear with me)

```<code>DO 7 I = 1,28
IF (NUM < ARRAY(I)) THEN
  GO TO 8
ELSE
  GO TO 7
END IF
7 CONTINUE
I=29
8 NUM = ARRAY(I)
</code>```

Now, because the statement labelled 7 is a continue statement, we can write this as

```<code>DO 7 I = 1,28
IF (NUM < ARRAY(I)) THEN
  GO TO 8
ELSE
  CYCLE
END IF
7 CONTINUE
I=29
8 NUM = ARRAY(I)
</code>```

That's still pretty ugly (and not just because of all the upper case).  Fortunately, we can make this prettier.  The i=29 statement will be executed only when the loop terminates without the statement labelled 8 being jumped to.  Now, the loop index i has control I = 1,28 so when the loop terminates naturally the index already has the value 29.  That assignment does nothing (in modern Fortran) so we can remove it.  Which leaves us with

```<code>DO 7 I = 1,28
IF (NUM < ARRAY(I)) THEN
  GO TO 8
ELSE
  CYCLE
END IF
7 CONTINUE
8 NUM = ARRAY(I)
</code>```

When we also note that the IF construct is immediately followed by the end of the loop (and so we don't need to explicitly cycle) we have

```<code>DO 7 I = 1,28
IF (NUM < ARRAY(I)) EXIT
7 CONTINUE
NUM = ARRAY(I)
</code>```

or (more nicely)

```<code>DO I = 1,28
  IF (NUM < ARRAY(I)) EXIT
END DO
NUM = ARRAY(I)
</code>```

All this example is doing is finding the value of the earliest element in array(1:28) which is larger than num, or array(29) if none is.

Title: Fortran 77 Do Loop block clarification

Body:
Both NUM and ARRAY double precision variables, not sure how the if block will execute. When will it stop? What is it actually doing?, If we go to 8, then are we exiting the do loop?

Thanks

DO 7 I = 1,28
IF (NUM - ARRAY(I)) 8,7,7
7 CONTINUE
I=29
8 NUM = ARRAY(I)
....
....
....
....

Body:
As previously stated the conditional in the loop is an arithmetic if statement.

We know (and that's explicitly stated in the previous answer here) that if num is less than array(i) the label 8 is chosen, otherwise label 7 is chosen.  It's also stated in that other answer that these have the effect of exiting the loop or cycling it.  To be precise, I'll continue.

A DO construct has a range.  A nonblock DO construct like the one in the question has range consisting of the statements between and including the do statement and the DO termination statement (in this case 7 continue).  The DO termination statement is a valid target for a jump from within the range of the construct.

When the DO termination statement is jumped to, execution remains within the scope of the construct.  That termination statement is executed (in this case, continue, doing nothing) and the loop iteration condition is again tested.  That is, the loop cycles.

From within a DO construct, a jump to a statement outside the range of the construct terminates execution of the construct: like an exit.

This example, then, has the equivalent form using an IF construct (with go tos - bear with me)

DO 7 I = 1,28
IF (NUM < ARRAY(I)) THEN
  GO TO 8
ELSE
  GO TO 7
END IF
7 CONTINUE
I=29
8 NUM = ARRAY(I)

Now, because the statement labelled 7 is a continue statement, we can write this as

DO 7 I = 1,28
IF (NUM < ARRAY(I)) THEN
  GO TO 8
ELSE
  CYCLE
END IF
7 CONTINUE
I=29
8 NUM = ARRAY(I)

That's still pretty ugly (and not just because of all the upper case).  Fortunately, we can make this prettier.  The i=29 statement will be executed only when the loop terminates without the statement labelled 8 being jumped to.  Now, the loop index i has control I = 1,28 so when the loop terminates naturally the index already has the value 29.  That assignment does nothing (in modern Fortran) so we can remove it.  Which leaves us with

DO 7 I = 1,28
IF (NUM < ARRAY(I)) THEN
  GO TO 8
ELSE
  CYCLE
END IF
7 CONTINUE
8 NUM = ARRAY(I)

When we also note that the IF construct is immediately followed by the end of the loop (and so we don't need to explicitly cycle) we have

DO 7 I = 1,28
IF (NUM < ARRAY(I)) EXIT
7 CONTINUE
NUM = ARRAY(I)

or (more nicely)

DO I = 1,28
  IF (NUM < ARRAY(I)) EXIT
END DO
NUM = ARRAY(I)

All this example is doing is finding the value of the earliest element in array(1:28) which is larger than num, or array(29) if none is.


问:
How to set required claims for IdentityServer4 API Resources?
I am using IdentityServer4 1.0.0 with the configuration information for the clients and API resources stored in SQL Server using the IdentityServer4.EntityFramework 1.0.0 package.

Is there a way to set a list of claims that must be present to access my API in the tables that are managed with the IdentityServer4.EntityFramework 1.0.0 package?

答:
I had the same problem,  the weird thing was the claims that I've added was present in access token, but the secured API was refusing it. What you need to do is to add the claims to your client, suppose we have this API:

```<code>[Produces("application/json")]
[Authorize("Founder")]
[Route("api/ApiResourceWithPolicy")]
public class ApiResourceWithPolicyController : Controller
{
    [HttpGet]
    public IActionResult Get()
    {
        return new JsonResult(new { ResourceType = "With Policy", ResourceName = "Api2" });
    }
}
</code>```

And this policy setup in your startup.cs:

```<code>ervices.AddAuthorization(options => options.AddPolicy("Founder", policy => policy.RequireClaim("Employee", "Mosalla")));
</code>```

Now add the necessary claims to your client, the important point here is to set the ClientClaimsPrefix to empty string:

```<code>public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "client1",

                // no interactive user, use the clientid/secret for authentication
                AllowedGrantTypes = GrantTypes.ClientCredentials,

                // secret for authentication
                ClientSecrets =
                {
                    new Secret("123654".Sha256())
                },

                // scopes that client has access to
                AllowedScopes = {"Api1"},
                Claims = new[]
                {
                    new Claim("Employee", "Mosalla"),
                    new Claim("website", "http://hamidmosalla.com")
                },
                ClientClaimsPrefix = ""
            }
   }
</code>```

That's because IdentityServer4 prefixes the claims and make them unrecognizable to the resource server:

If you need more explanation visit my post about policy-based authorization with IdentityServer4.

Body:
I had the same problem,  the weird thing was the claims that I've added was present in access token, but the secured API was refusing it. What you need to do is to add the claims to your client, suppose we have this API:

[Produces("application/json")]
[Authorize("Founder")]
[Route("api/ApiResourceWithPolicy")]
public class ApiResourceWithPolicyController : Controller
{
    [HttpGet]
    public IActionResult Get()
    {
        return new JsonResult(new { ResourceType = "With Policy", ResourceName = "Api2" });
    }
}

And this policy setup in your startup.cs:

ervices.AddAuthorization(options => options.AddPolicy("Founder", policy => policy.RequireClaim("Employee", "Mosalla")));

Now add the necessary claims to your client, the important point here is to set the ClientClaimsPrefix to empty string:

public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "client1",

                // no interactive user, use the clientid/secret for authentication
                AllowedGrantTypes = GrantTypes.ClientCredentials,

                // secret for authentication
                ClientSecrets =
                {
                    new Secret("123654".Sha256())
                },

                // scopes that client has access to
                AllowedScopes = {"Api1"},
                Claims = new[]
                {
                    new Claim("Employee", "Mosalla"),
                    new Claim("website", "http://hamidmosalla.com")
                },
                ClientClaimsPrefix = ""
            }
   }

That's because IdentityServer4 prefixes the claims and make them unrecognizable to the resource server:

If you need more explanation visit my post about policy-based authorization with IdentityServer4.


问:
Searching for an item within a ListBox using a TextBox and a Button
I am creating a system that includes a ListBox of integers inserted by the user. I have contained a search button and a search TextBox for the user to input the integer they want to search for within the ListBox. Once the user has inputted the integer, I want a message box to be displayed either informing the user that there is e.g. 1 integer of value '3' in the list box, or an error message box informing the user that the integer does not exist within the list box.

```<code>private void buttonSearch_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.SelectedItems.Clear();
    for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
    {
        if (listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())) ;
        {
            listBoxAddedIntegers.SetSelected(i, true);
        }
    }

    // ...
}
</code>```

I am not really sure on the code that I am meant to include here, and the code that I have already inserted suggests that 'i' does not exist in the current content.

Can anyone help please?

答:
the code that I have already inserted suggests that 'i' does not exist in the current content

As @FrankM already mentioned in the comments. You have a trailing ; after your for-loop.

```<code>for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
</code>```

This will prevent the for-loop to execute your code within the { ... }. This can be transcribed to

```<code>for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--)
{
    // Do nothing.
}
{
   // now your code
}
</code>```

This means also that your code within the last curly braces will be in its own scope and so that all your defined variables will be unavailable to the following code.

Answering your actual question:

As you already do for selecting the matching items. You can extent this looping by counting up a counter. And later on show the results with a MessageBox.

With the following snippet of your code

```<code>listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower()))
</code>```

you are currently checking if an item of your list contains the entered TextBox.Text.

So if the user has entered 3, 4, 5, ..., 13,  23 in the ListBox and searches for 3. He will get 3 matches. If you want only 1 match you should use String.Equals(). I used StringComparison.InvariantCultureIgnoreCase to avoid calling ToLower().

```<code>private void buttonSearch_Click(object sender, EventArgs e)
{
    var counter = 0;

    for (int i = 0; i < this.listBoxAddedIntegers.Items.Count; i++)
    {
        var item = this.listBoxAddedIntegers.Items[i];
        if (string.Equals(item.ToString(), this.textBoxSearch.Text, StringComparison.InvariantCultureIgnoreCase))
        {
            this.listBoxAddedIntegers.SelectedItems.Add(item);
            counter++;
        }
    }

    if (counter == 0)
    {
        MessageBox.Show($"No matches for \"{this.textBoxSearch.Text}\" found!", "Search Results",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    else
    {
        MessageBox.Show($"{counter} items found for \"{this.textBoxSearch.Text}\"!", "Search Results",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
</code>```

Hint:

Since C#6 you can use string interpolation instead of String.Format() or string concatenation (+).

Body:
I am creating a system that includes a ListBox of integers inserted by the user. I have contained a search button and a search TextBox for the user to input the integer they want to search for within the ListBox. Once the user has inputted the integer, I want a message box to be displayed either informing the user that there is e.g. 1 integer of value '3' in the list box, or an error message box informing the user that the integer does not exist within the list box.

private void buttonSearch_Click(object sender, EventArgs e)
{
    listBoxAddedIntegers.SelectedItems.Clear();
    for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;
    {
        if (listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower())) ;
        {
            listBoxAddedIntegers.SetSelected(i, true);
        }
    }

    // ...
}

I am not really sure on the code that I am meant to include here, and the code that I have already inserted suggests that 'i' does not exist in the current content.

Can anyone help please?

Body:
the code that I have already inserted suggests that 'i' does not exist in the current content

As @FrankM already mentioned in the comments. You have a trailing ; after your for-loop.

for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--) ;

This will prevent the for-loop to execute your code within the { ... }. This can be transcribed to

for (int i = listBoxAddedIntegers.Items.Count - 1;i>=0; i--)
{
    // Do nothing.
}
{
   // now your code
}

This means also that your code within the last curly braces will be in its own scope and so that all your defined variables will be unavailable to the following code.

Answering your actual question:

As you already do for selecting the matching items. You can extent this looping by counting up a counter. And later on show the results with a MessageBox.

With the following snippet of your code

listBoxAddedIntegers.Items[i].ToString().ToLower().Contains(textBoxSearch.Text.ToLower()))

you are currently checking if an item of your list contains the entered TextBox.Text.

So if the user has entered 3, 4, 5, ..., 13,  23 in the ListBox and searches for 3. He will get 3 matches. If you want only 1 match you should use String.Equals(). I used StringComparison.InvariantCultureIgnoreCase to avoid calling ToLower().

private void buttonSearch_Click(object sender, EventArgs e)
{
    var counter = 0;

    for (int i = 0; i < this.listBoxAddedIntegers.Items.Count; i++)
    {
        var item = this.listBoxAddedIntegers.Items[i];
        if (string.Equals(item.ToString(), this.textBoxSearch.Text, StringComparison.InvariantCultureIgnoreCase))
        {
            this.listBoxAddedIntegers.SelectedItems.Add(item);
            counter++;
        }
    }

    if (counter == 0)
    {
        MessageBox.Show($"No matches for \"{this.textBoxSearch.Text}\" found!", "Search Results",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    else
    {
        MessageBox.Show($"{counter} items found for \"{this.textBoxSearch.Text}\"!", "Search Results",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

Hint:

Since C#6 you can use string interpolation instead of String.Format() or string concatenation (+).


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答: Godel's Theorems notwithstanding...What would be the point?  What simplistic "truths" would you like to prove?  What would you want to derive from those truths?  While I may eat these words...where's the practicality?</p>

ContentLicense: CC BY-SA 2.5

Title: Why can't programs be proven?

OwnerDisplayName: JPunyon


问:
Puzzle on looping statement

Possible Duplicate:

  Not able to solve the puzzle regarding this code…

The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that,
it doesn't work.

```<code>#include <stdio.h>
  int main()
  {
      int i;
      int n = 20;
      for( i = 0; i < n; i-- )
          printf("-");
      return 0;
  }
</code>```

Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above
code, by changing exactly one character

Title: Puzzle on looping statement

Body:
Possible Duplicate:

  Not able to solve the puzzle regarding this code…

The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that,
it doesn't work.

#include <stdio.h>
  int main()
  {
      int i;
      int n = 20;
      for( i = 0; i < n; i-- )
          printf("-");
      return 0;
  }

Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above
code, by changing exactly one character

Body:
One:

  for( i = 0; i < n; n-- )
      printf("-");

Two:

  for( i = 0;-i < n; i-- )
      printf("-");

Three:

  for( i = 0; i + n; i-- )
      printf("-");


问:
Angular - Use a Barrel File for all Component Imports
I am currently on Angular 5.

I have created a barrel file for all the common imports I use in my component files.  The question that I have is - is this a good idea or bad idea in regards to lazy loading, tree shaking, or anything else I didn't think of such as AOT?  Or is this approach completely fine and won't affect load time or anything else negatively.  If you could shine some light on the reason too that would be appreciated.

Examples:

```<code>  common-component-imports.ts:
    export { AppState, Event, EventPriority, EventType, Page, Unit, User, WindowSettings } from '../models/index';
    export { Component, ElementRef, Input, ViewChild, ViewChildren } from '@angular/core';
    export { Config, IonicPage, Loading, LoadingController, Modal, ModalController, Nav, NavController, NavParams, Platform, Toast, ToastController, ViewController } from 'ionic-angular';
etc../
</code>```

and than in my components I am doing this:

```<code>event.ts
import {
  Component,
  ElectronService,
  Event,
  AppState,
  IonicPage,
  NavController,
  NavParams,
  Store,
 } from '../shared/common-component-imports';
</code>```

and I import like that on several more files besides just event.ts.

答:
Barrels are a good idea in general but have no impact on lazy loading.
https://angular.io/guide/glossary#barrel (barrel has been removed from the glossary 2018)

UPDATE:
"Consider creating a "barrel" file that gathers all the interceptor providers into an httpInterceptorProviders array, starting with this first one, the NoopInterceptor." https://angular.io/guide/http

Style Guide" with NgModules (2016-09-27)
"StyleGuide explains recommended conventions for NgModules. Barrels now are far less useful and have been removed from the style guide; they remain valuable but are not a matter of Angular style. Also relaxed the rule that discouraged use of the @Component.host property." https://angular.io/guide/change-log

Body:
I am currently on Angular 5.

I have created a barrel file for all the common imports I use in my component files.  The question that I have is - is this a good idea or bad idea in regards to lazy loading, tree shaking, or anything else I didn't think of such as AOT?  Or is this approach completely fine and won't affect load time or anything else negatively.  If you could shine some light on the reason too that would be appreciated.

Examples:

  common-component-imports.ts:
    export { AppState, Event, EventPriority, EventType, Page, Unit, User, WindowSettings } from '../models/index';
    export { Component, ElementRef, Input, ViewChild, ViewChildren } from '@angular/core';
    export { Config, IonicPage, Loading, LoadingController, Modal, ModalController, Nav, NavController, NavParams, Platform, Toast, ToastController, ViewController } from 'ionic-angular';
etc../

and than in my components I am doing this:

event.ts
import {
  Component,
  ElectronService,
  Event,
  AppState,
  IonicPage,
  NavController,
  NavParams,
  Store,
 } from '../shared/common-component-imports';

and I import like that on several more files besides just event.ts.

ContentLicense: CC BY-SA 4.0


问:
Alphabetical order
i'm reading a book and i got an exercise to do. It says something like :"write in alphabetical order from a to z"in a while loop. I know that i have to start from 97 (a=97) and b=char('a'+1) , c=char('a'+2). Here's the code:

```<code>int main(){
int a = 97;
while (a<=122)
{
    cout << char('a'+1) << "\t" << 'a' + 1 << "\n";
    ++a;
}
</code>```

Now the problem is that is shows only b and increments on numbers only .. I'm kinda new to this , any help ?

答:
The problem ist that you use quotation marks in :

cout << char('a'+1) << "\t" << 'a' + 1 << "\n";

If you change the line to :

cout << char(a+1) << "\t" << a + 1 << "\n";

it should work.

If you write 'a' you are taking the value of the letter a(which is 97) and not the value of your variable a.

Title: Alphabetical order

Body:
i'm reading a book and i got an exercise to do. It says something like :"write in alphabetical order from a to z"in a while loop. I know that i have to start from 97 (a=97) and b=char('a'+1) , c=char('a'+2). Here's the code:

int main(){
int a = 97;
while (a<=122)
{
    cout << char('a'+1) << "\t" << 'a' + 1 << "\n";
    ++a;
}

Now the problem is that is shows only b and increments on numbers only .. I'm kinda new to this , any help ?


问:
how get company wise highest salaried employee name from this schema
the database schema is like this:

employee(emp_id#,person_name,dob,street,city)

company(company_id#, company_name,city)

works(emp_id,company_id,salary)

manages(emp_id,manager_id)

```<code>insert into employee values('e-1','dipankar pal','15-jul-1997','h.m raod','kolkata');
insert into employee values('e-2','subhadip roy','15-jan-1997','garia','kolkata');
</code>```

the manages table may be little bit confusing, here are some data I've inserted to clear my point

```<code>insert into manages values('e-3','e-1');
insert into manages values('e-4','e-1');
insert into manages values('e-5','e-1');
insert into manages values('e-6','e-2');
insert into manages values('e-7','e-2');
</code>```

答:
```<code>select company.company_name,employee.person_name as employee_name,y.salary as salary from employee,company,
(select works.emp_id,works.company_id,works.salary from works,
(select company_id,max(salary) as high from works group by(company_id)
)x where high=works.salary) y
where employee.emp_id=y.emp_id and company.company_id=y.company_id order by company_name
;
</code>```

Body:
the database schema is like this:

employee(emp_id#,person_name,dob,street,city)

company(company_id#, company_name,city)

works(emp_id,company_id,salary)

manages(emp_id,manager_id)

insert into employee values('e-1','dipankar pal','15-jul-1997','h.m raod','kolkata');
insert into employee values('e-2','subhadip roy','15-jan-1997','garia','kolkata');

the manages table may be little bit confusing, here are some data I've inserted to clear my point

insert into manages values('e-3','e-1');
insert into manages values('e-4','e-1');
insert into manages values('e-5','e-1');
insert into manages values('e-6','e-2');
insert into manages values('e-7','e-2');


问:
Symfony3 - Delete Entity with OneToMany - relationship in Doctrine - cascade not working
I have two entities:

```<code>/**
 * Course
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\CourseRepository")
 */
class Course
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var \Doctrine\Common\Collections\ArrayCollection()
 *
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\TimeTableEntry", mappedBy="course", cascade={"remove"}, orphanRemoval=true)
 *
 */
private $timeTableEntries;

/**
 * @var boolean
 *
 * @ORM\Column(name="enabled", type="boolean", nullable=true)
 */
private $enabled;
</code>```

and

```<code>/**
 * TimeTableEntry
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\TimeTableEntryRepository")
 */
class TimeTableEntry
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
 * @var \Doctrine\Common\Collections\ArrayCollection()
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Course", inversedBy="timeTableEntries", cascade={"ALL"})
 * @ORM\JoinColumn(name="course_id", referencedColumnName="id", nullable=true, onDelete="CASCADE")
 */
private $course;
</code>```

As you can see I tried with cascade={"ALL"}, onDelete="CASCADE" and orphanRemoval=true.

When I want to delete the Course Entity I get the error message:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (edutalk.teaching_event, CONSTRAINT FK_F2B1088B57042871 FOREIGN
  KEY (time_table_entry_id) REFERENCES time_table_entry (id))

What can I try to resolve this?

答:
I cannot comment on your post, so I post it as an answer.

Your problem is that you have another entity TeachingEvent with a reference to TimeTableEntry. When you try to delete a TimeTableEntry, it is impossible because this time_table_entry_id is still referenced as a foreign key in the TeachingEvent table.

Before deleting the TimeTableEntry, first you should unlink it from the TeachingEvent. I don't have your code, but depending on how TimeTableEntry and TeachingEvent relate to each other, it's probably something like:

```<code>$teachingEvent->setTimeTableEntry(null);
</code>```

or

```<code>$timeTableEntry->setTeachingEvent(null);
</code>```

Body:
I have two entities:

/**
 * Course
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\CourseRepository")
 */
class Course
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var \Doctrine\Common\Collections\ArrayCollection()
 *
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\TimeTableEntry", mappedBy="course", cascade={"remove"}, orphanRemoval=true)
 *
 */
private $timeTableEntries;

/**
 * @var boolean
 *
 * @ORM\Column(name="enabled", type="boolean", nullable=true)
 */
private $enabled;

and

/**
 * TimeTableEntry
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\TimeTableEntryRepository")
 */
class TimeTableEntry
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
 * @var \Doctrine\Common\Collections\ArrayCollection()
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Course", inversedBy="timeTableEntries", cascade={"ALL"})
 * @ORM\JoinColumn(name="course_id", referencedColumnName="id", nullable=true, onDelete="CASCADE")
 */
private $course;

As you can see I tried with cascade={"ALL"}, onDelete="CASCADE" and orphanRemoval=true.

When I want to delete the Course Entity I get the error message:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (edutalk.teaching_event, CONSTRAINT FK_F2B1088B57042871 FOREIGN
  KEY (time_table_entry_id) REFERENCES time_table_entry (id))

What can I try to resolve this?

Body:
I cannot comment on your post, so I post it as an answer.

Your problem is that you have another entity TeachingEvent with a reference to TimeTableEntry. When you try to delete a TimeTableEntry, it is impossible because this time_table_entry_id is still referenced as a foreign key in the TeachingEvent table.

Before deleting the TimeTableEntry, first you should unlink it from the TeachingEvent. I don't have your code, but depending on how TimeTableEntry and TeachingEvent relate to each other, it's probably something like:

$teachingEvent->setTimeTableEntry(null);

or

$timeTableEntry->setTeachingEvent(null);


问:
Python download youtube with specific filename
I'm trying to download youtube videos with pytube this way:

```<code>from pytube import YouTube
YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download()
</code>```

but the file will have the same name as the original video name. How do I specify a custom filename?

答:
To add to klutt's answer, it doesn't look like there's been a new pypi release since this feature was added, so for now you can either download the code directly as klutt suggests, or, as a workaround, manually rename the file after the download() call, e.g.:

```<code>import os
from pytube import YouTube

yt = YouTube('http://youtube.com/watch?v=9bZkp7q19f0')
yt.streams.first().download()
os.rename(yt.streams.first().default_filename, 'new_filename.ext')`
</code>```

Body:
I'm trying to download youtube videos with pytube this way:

from pytube import YouTube
YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download()

but the file will have the same name as the original video name. How do I specify a custom filename?

Body:
To add to klutt's answer, it doesn't look like there's been a new pypi release since this feature was added, so for now you can either download the code directly as klutt suggests, or, as a workaround, manually rename the file after the download() call, e.g.:

import os
from pytube import YouTube

yt = YouTube('http://youtube.com/watch?v=9bZkp7q19f0')
yt.streams.first().download()
os.rename(yt.streams.first().default_filename, 'new_filename.ext')`


问:
Why does docker say that -d and --rm are conflicting options for running a container?
A minor issue but I want to run docker containers in dev with docker run --rm so that I don't have to remove them after I stop them, especially since I'm changing the command line parameters with virtually every run.

However my containers pump out lots of logging onto stdout if I don't use docker run -d.

Then I can't use --rm anymore, because docker complains:

```<code>[adam@gondor ~]$ docker run --rm -d -p 10040:443 --name rproxy adam-rproxy
Conflicting options: --rm and -d
</code>```

Admittedly I could just run stop and rm together on the command line:

docker stop rproxy; docker rm rproxy

but I know I'll forget, get annoyed and start worrying I'm moving out on the autistic spectrum!

docker run options

答:
Docker added the ability to have --rm and -d when they moved the --rm to a server side action in 1.13.0. This was covered in PR 20848. Before this release, the delete was handled on the docker client, and with detached mode, the client was not monitoring the container to detect the exit.

You'll need to upgrade to at least this version on both your client and server for this feature to work. I'd recommend upgrading to 17.09 since it's the current stable CE release.

Body:
A minor issue but I want to run docker containers in dev with docker run --rm so that I don't have to remove them after I stop them, especially since I'm changing the command line parameters with virtually every run.

However my containers pump out lots of logging onto stdout if I don't use docker run -d.

Then I can't use --rm anymore, because docker complains:

[adam@gondor ~]$ docker run --rm -d -p 10040:443 --name rproxy adam-rproxy
Conflicting options: --rm and -d

Admittedly I could just run stop and rm together on the command line:

docker stop rproxy; docker rm rproxy

but I know I'll forget, get annoyed and start worrying I'm moving out on the autistic spectrum!

docker run options


Title: Puzzle on looping statement

Body:
1)

for( i = 0; i + n; i-- )
    printf("-");

2)

for( i = 0; i < n; n-- )
    printf("-");

3)

for( i = 0; -i < n; i-- )
    printf("-");


问:
Loss of precision when casting Math.pow()
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

```<code>2_147_483_647
</code>```

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

```<code>System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);
</code>```

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

答:
You put the brackets in the wrong place. It should be:</p>

```<code>System.out.println((int) (Math.pow(2, 31) - 1));
</code>```

Body:
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

2_147_483_647

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

Body:
You put the brackets in the wrong place. It should be:

System.out.println((int) (Math.pow(2, 31) - 1));


问:
How can I detect changes in location hash?
I am using Ajax and hash for navigation.

Is there a way to check if the window.location.hash changed like this?

http://example.com/blah#123 to http://example.com/blah#456

It works if I check it when the document loads.

But if I have #hash based navigation it doesn't work when I press the back button on the browser (so I jump from blah#456 to blah#123).

It shows inside the address box, but I can't catch it with JavaScript.

答:
I was using this in a React application to make the URL display different parameters depending what view the user was on.

I watched the hash parameter using

```<code>window.addEventListener('hashchange', doSomethingWithChangeFunction);
</code>```

Then

```<code>function doSomethingWithChangeFunction () {
    let urlParam = window.location.hash; // Get new hash value

    // ... Do something with new hash value
};
</code>```

It works a treat. It works with forward and back browser buttons and also in the browser history.

Body:
I was using this in a React application to make the URL display different parameters depending what view the user was on.

I watched the hash parameter using

window.addEventListener('hashchange', doSomethingWithChangeFunction);

Then

function doSomethingWithChangeFunction () {
    let urlParam = window.location.hash; // Get new hash value

    // ... Do something with new hash value
};

It works a treat. It works with forward and back browser buttons and also in the browser history.