问:
Python: 'module' object has no attribute 'logout_view'
I'm currently trying to implement the ability to log out into my django site and I'm getting the following error when attempting to use the command python manage.py runserver while in the virtual environment:

```<code>(ll_env) C:\Users\me\Desktop\learning_log>python manage.py runserver
Performing system checks...

Unhandled exception in thread started by <function wrapper at 0x0000000006693BA8>
Traceback (most recent call last):
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
    return check_method()
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "c:\users\me\python27\Lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "C:\Users\me\Desktop\learning_log\learning_log\urls.py", line 22, in <module>
    url(r'^users/', include('users.urls', namespace='users')),
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\conf\urls\__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "c:\users\me\python27\Lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "C:\Users\me\Desktop\learning_log\users\urls.py", line 13, in <module>
    url(r'^logout/$', views.logout_view, name='logout'),
AttributeError: 'module' object has no attribute 'logout_view'
</code>```

This is my urls.py file in the learning_log\users directory:

```<code>from django.conf.urls import url
from django.contrib.auth.views import login

from . import views

urlpatterns = [
    # Login page
    url(r'^login/$', login, {'template_name': 'users/login.html'},
        name='login'),
    # Logout page
    url(r'^logout/$', views.logout_view, name='logout'),
    # Registration page
    url(r'^register/$', views.register, name='register'),
]
</code>```

The most recent addition to the above file was:

```<code>    # Logout page
    url(r'^logout/$', views.logout_view, name='logout'),
</code>```

The following code was added onto the end of my views.py file as the most recent addition:

```<code>from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import logout

def logout_view(request):
    """Log the user out."""
    logout(request)
    return HttpResponseRedirect(reverse('learning_logs:index'))
</code>```

This is my base.html file:

```<code><p>
  <a href="{% url 'learning_logs:index' %}">Learning Log</a> -
  <a href="{% url 'learning_logs:topics' %}">Topics</a> -
  {% if user.is_authenticated %}
    Hello, {{ user.username }}.
    <a href="{% url 'users:logout' %}">log out</a>
  {% else %}
    <a href="{% url 'users:login' %}">log in</a>
  {% endif %}
</p>

{% block content %}{% endblock content %}
</code>```

This was the most recent addition to my base.html file:

```<code>    <a href="{% url 'users:logout' %}">log out</a>
</code>```

The code worked fine before the additions mentioned above. Knowing me it's probably an easy fix, but does anybody have a solution for this issue? I'm currently using Django 1.11.7 and Python 2.7.14.

答:
When you use a relative import in users\urls.py

```<code>from . import views
</code>```

This is equivalent to

```<code>from users import views
</code>```

However, it sounds like your logout_view is in learning_logs\views.py. If that is the case, then you should change the import to

```<code>from learning_logs import views
</code>```

Note that Django has a logout view, so you don't have to write your own. Change your import and URL pattern to:

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

url(r'^logout/$', logout, name='logout'),
</code>```

Then set LOGOUT_REDIRECT_URL in your settings so that Django redirects to the index after logging out the user:

```<code>LOGOUT_REDIRECT_URL = 'learning_logs:index'
</code>```

Body:
I'm currently trying to implement the ability to log out into my django site and I'm getting the following error when attempting to use the command python manage.py runserver while in the virtual environment:

(ll_env) C:\Users\me\Desktop\learning_log>python manage.py runserver
Performing system checks...

Unhandled exception in thread started by <function wrapper at 0x0000000006693BA8>
Traceback (most recent call last):
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
    return check_method()
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "c:\users\me\python27\Lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "C:\Users\me\Desktop\learning_log\learning_log\urls.py", line 22, in <module>
    url(r'^users/', include('users.urls', namespace='users')),
  File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\conf\urls\__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "c:\users\me\python27\Lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "C:\Users\me\Desktop\learning_log\users\urls.py", line 13, in <module>
    url(r'^logout/$', views.logout_view, name='logout'),
AttributeError: 'module' object has no attribute 'logout_view'

This is my urls.py file in the learning_log\users directory:

from django.conf.urls import url
from django.contrib.auth.views import login

from . import views

urlpatterns = [
    # Login page
    url(r'^login/$', login, {'template_name': 'users/login.html'},
        name='login'),
    # Logout page
    url(r'^logout/$', views.logout_view, name='logout'),
    # Registration page
    url(r'^register/$', views.register, name='register'),
]

The most recent addition to the above file was:

    # Logout page
    url(r'^logout/$', views.logout_view, name='logout'),

The following code was added onto the end of my views.py file as the most recent addition:

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import logout

def logout_view(request):
    """Log the user out."""
    logout(request)
    return HttpResponseRedirect(reverse('learning_logs:index'))

This is my base.html file:

  Learning Log -
  Topics -
  {% if user.is_authenticated %}
    Hello, {{ user.username }}.
    log out
  {% else %}
    log in
  {% endif %}

{% block content %}{% endblock content %}

This was the most recent addition to my base.html file:

    log out

The code worked fine before the additions mentioned above. Knowing me it's probably an easy fix, but does anybody have a solution for this issue? I'm currently using Django 1.11.7 and Python 2.7.14.

Body:
When you use a relative import in users\urls.py

from . import views

This is equivalent to

from users import views

However, it sounds like your logout_view is in learning_logs\views.py. If that is the case, then you should change the import to

from learning_logs import views

Note that Django has a logout view, so you don't have to write your own. Change your import and URL pattern to:

from django.contrib.auth.views import logout

url(r'^logout/$', logout, name='logout'),

Then set LOGOUT_REDIRECT_URL in your settings so that Django redirects to the index after logging out the user:

LOGOUT_REDIRECT_URL = 'learning_logs:index'


来源: stackexchange

问:
How to create a ColorSlider by picking start and end color in hexdec in android
I want to create a seekbar in Android which the startcolor is going to be for example "00AA10" and endcolor "0FFF99" and then I can change the color by incrementing this hex decimal value and get the new color by calculating the distance of the 2 given colors.</p>

答:
```<code> String hexString= "00AA10";
 int a=Integer.parseInt(hexString, 16);
 //if you want increment by 5 means i++ replace i=i+5
 for(int i=0;i<100;i++)
 {
 i= a+i;
 String incHex = Integer.toHexString(i);
 seekBar.setBackgroundColor(Color.parseColor("#"+incHex));
 }
</code>```

ContentLicense: CC BY-SA 3.0


问:
Enter triggers button click
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

```<code>$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})
</code>```

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

答:
It is important to read the HTML specifications to truly understand what behavior is to be expected:

The HTML5 spec explicitly states what happens in implicit submissions:

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).

Edit to add:

The simplest answer I can think of is to put your submit button as the first [type="submit"] item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.

ContentLicense: CC BY-SA 4.0

Title: Enter triggers button click

Body:
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.


问:
Migrate from plain kubernetes to helm without downtime
I have several apps deployed into a kubernetes cluster. I have the receipts and etc as yaml files and I deploy and apply everything with kubectl.

I decided to migrate to helm because of its features and to avoid replicating code between dev and prod (I could use variables and etc).

The problem is: my services are AWS ELBs, and, as far as I found out, to migrate something already deployed with kubectl to helm, I need to delete it and install it again with helm - which will destroy and re-create my ELBs, so I'll need to change DNS records, etc. On top of all that, I'll have downtime - which is not really desired.

I thought about renaming the old-things and create the new things with the right name, keeping a common label to use in the service - so I could create the new one, change the DNS records, and then delete the old stuff - but apparently renames are not allowed by kubernetes.

Another strategy would be to launch a new cluster - which I don't really want to do.

Are there any other alternatives?

答: A properly designed chart should namespace deployed resources by .Release.Name. That way you can deploy chart side by side with existing software you have. It's likely that you will be able create large part of your stack in parallel and then update your off-chart services to point to on-chart pods, that way you can have both on-chart and off-chart services defined and working with two distinct ELBs and if you want to get rid of off-charts, just edit DNS and let it propagate, then, after a day, week or month you can scrap it and be left with chart only.


问:
Not able to create/import Gradle (4.3) project in Eclipse Oxygen and Java 9
I am trying to develop project in Gradle and Spring Boot using Eclipse Oxygen. I have latest Gradle version. My system in MAC 10.10.2 (14C109) OS X Yosemite.

Following are details over the issue. While creating project, Gradle user home directory is coming 'unknown' at the last page I have attached image of it:

```<code>$gradle -version
------------------------------------------------------------
Gradle 4.3.1
------------------------------------------------------------

Build time:   2017-11-08 08:59:45 UTC
Revision:     e4f4804807ef7c2829da51877861ff06e07e006d

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          9.0.1 (Oracle Corporation 9.0.1+11)
OS:           Mac OS X 10.10.2 x86_64
</code>```

The erro coming in eclipse
The following will be send to: Eclipse

REPORT

```<code>anonymousId         a9e8db44-ee8e-4012-9e8e-302774ee01b3
name                Taushif
email
comment
eclipseBuildId      4.7.1.M20171009-0410
eclipseProduct      org.eclipse.epp.package.jee.product
javaRuntimeVersion  9.0.1+11
osgiWs              cocoa
osgiOs              MacOSX
osgiOsVersion       10.10.2
osgiArch            x86_64
severity            UNKNOWN

STATUS

pluginId            org.eclipse.ui
pluginVersion       3.109.0.v20170411-1742
code                0
severity            4
message             Unhandled event loop exception
fingerprint         2d8cf2c7a5898a92b35629394884ede6

Exception:java.lang.IllegalArgumentException: Could not determine java version from '9.0.1'.
     at org.gradle.api.JavaVersion.toVersion(JavaVersion.java:70)
     at org.gradle.api.JavaVersion.current(JavaVersion.java:80)
     at org.gradle.internal.jvm.UnsupportedJavaRuntimeException.assertUsingVersion(UnsupportedJavaRuntimeException.java:29)
     at org.gradle.tooling.internal.consumer.ConnectorServices.checkJavaVersion(ConnectorServices.java:57)
     at org.gradle.tooling.internal.consumer.ConnectorServices.createCancellationTokenSource(ConnectorServices.java:39)
     at org.gradle.tooling.GradleConnector.newCancellationTokenSource(GradleConnector.java:95)
     at org.eclipse.buildship.core.util.progress.ToolingApiJob.<init>(ToolingApiJob.java:57)
     at org.eclipse.buildship.core.workspace.internal.SynchronizeGradleBuildsJob.<init>(SynchronizeGradleBuildsJob.java:46)
     at org.eclipse.buildship.core.workspace.internal.SynchronizeGradleBuildsJob.forSingleGradleBuild(SynchronizeGradleBuildsJob.java:122)
     at org.eclipse.buildship.core.workspace.internal.DefaultGradleBuild.synchronize(DefaultGradleBuild.java:58)
     at org.eclipse.buildship.ui.wizard.project.ProjectImportWizardController.performImportProject(ProjectImportWizardController.java:167)
     at org.eclipse.buildship.ui.wizard.project.ProjectCreationWizard.performFinish(ProjectCreationWizard.java:180)
     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:4257)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1502)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1525)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1510)
     at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1314)
     at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4081)
     at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3698)
     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 HIDDEN.HIDDEN(HIDDEN:-1)
     at HIDDEN.HIDDEN(HIDDEN:-1)
     at HIDDEN.HIDDEN(HIDDEN:-1)
     at java.lang.reflect.Method.invoke(Method.java:564)
     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.ui.internal.actions.CommandAction.run(CommandAction.java:161)
     at org.eclipse.ui.actions.NewWizardDropDownAction.run(NewWizardDropDownAction.java:175)
     at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
     at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
     at org.eclipse.jface.action.ActionContributionItem.lambda$5(ActionContributionItem.java:436)
     at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
     at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4257)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1502)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1525)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1510)
     at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1314)
     at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4081)
     at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3698)
     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 HIDDEN.HIDDEN(HIDDEN:-1)
     at HIDDEN.HIDDEN(HIDDEN:-1)
     at HIDDEN.HIDDEN(HIDDEN:-1)
     at java.lang.reflect.Method.invoke(Method.java:564)
     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)

BUNDLES

name                org.eclipse.buildship.core
version             2.1.2.v20170807-1324

name                org.eclipse.buildship.ui
version             2.1.2.v20170807-1324

name                org.eclipse.core.commands
version             3.9.0.v20170530-1048

name                org.eclipse.core.databinding.observable
version             1.6.100.v20170515-1119

name                org.eclipse.core.databinding
version             1.6.100.v20170515-1119

name                org.eclipse.core.runtime
version             3.13.0.v20170207-1030

name                org.eclipse.e4.core.commands
version             0.12.100.v20170513-0428

name                org.eclipse.e4.core.contexts
version             1.6.0.v20170322-1144

name                org.eclipse.e4.core.di
version             1.6.100.v20170421-1418

name                org.eclipse.e4.ui.workbench
version             1.5.1.v20170815-1446

name                org.eclipse.e4.ui.workbench.swt
version             0.14.101.v20170710-1119

name                org.eclipse.equinox.app
version             1.3.400.v20150715-1528

name                org.eclipse.equinox.launcher
version             1.4.0.v20161219-1356

name                org.eclipse.jface
version             3.13.1.v20170810-0135

name                org.eclipse.swt
version             3.106.1.v20170926-0519

name                org.eclipse.ui
version             3.109.0.v20170411-1742

name                org.eclipse.ui.ide.application
version             1.2.0.v20170512-1452

name                org.eclipse.ui.ide
version             3.13.1.v20170822-1526
</code>```

NOTE
Not sure what helped, but this get resolved. I did 2 things:-
1.I ran gradle command from terminal in workspace of eclipse.
2.Updated Buildship gradle integration from eclipse ide.

答:
The Buildship team has released a milestone 2.2 build that fixes this issue.

You can either install the milestone 2.2 in eclipse. Help > Install New Software... > Work with: http://download.eclipse.org/buildship/updates/e47/milestones/2.x > Select most recent version > Finish

Or you can wait until the official 2.2 release of Buildship and update the Buildship plugin.

Milestone Announcement: https://discuss.gradle.org/t/buildship-2-2-milestone-is-now-available/24551

Body:
I am trying to develop project in Gradle and Spring Boot using Eclipse Oxygen. I have latest Gradle version. My system in MAC 10.10.2 (14C109) OS X Yosemite.

Following are details over the issue. While creating project, Gradle user home directory is coming 'unknown' at the last page I have attached image of it:

$gradle -version
------------------------------------------------------------
Gradle 4.3.1
------------------------------------------------------------

Build time:   2017-11-08 08:59:45 UTC
Revision:     e4f4804807ef7c2829da51877861ff06e07e006d

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          9.0.1 (Oracle Corporation 9.0.1+11)
OS:           Mac OS X 10.10.2 x86_64

The erro coming in eclipse
The following will be send to: Eclipse

REPORT

anonymousId         a9e8db44-ee8e-4012-9e8e-302774ee01b3
name                Taushif
email
comment
eclipseBuildId      4.7.1.M20171009-0410
eclipseProduct      org.eclipse.epp.package.jee.product
javaRuntimeVersion  9.0.1+11
osgiWs              cocoa
osgiOs              MacOSX
osgiOsVersion       10.10.2
osgiArch            x86_64
severity            UNKNOWN

STATUS

pluginId            org.eclipse.ui
pluginVersion       3.109.0.v20170411-1742
code                0
severity            4
message             Unhandled event loop exception
fingerprint         2d8cf2c7a5898a92b35629394884ede6

Exception:java.lang.IllegalArgumentException: Could not determine java version from '9.0.1'.
     at org.gradle.api.JavaVersion.toVersion(JavaVersion.java:70)
     at org.gradle.api.JavaVersion.current(JavaVersion.java:80)
     at org.gradle.internal.jvm.UnsupportedJavaRuntimeException.assertUsingVersion(UnsupportedJavaRuntimeException.java:29)
     at org.gradle.tooling.internal.consumer.ConnectorServices.checkJavaVersion(ConnectorServices.java:57)
     at org.gradle.tooling.internal.consumer.ConnectorServices.createCancellationTokenSource(ConnectorServices.java:39)
     at org.gradle.tooling.GradleConnector.newCancellationTokenSource(GradleConnector.java:95)
     at org.eclipse.buildship.core.util.progress.ToolingApiJob.<init>(ToolingApiJob.java:57)
     at org.eclipse.buildship.core.workspace.internal.SynchronizeGradleBuildsJob.<init>(SynchronizeGradleBuildsJob.java:46)
     at org.eclipse.buildship.core.workspace.internal.SynchronizeGradleBuildsJob.forSingleGradleBuild(SynchronizeGradleBuildsJob.java:122)
     at org.eclipse.buildship.core.workspace.internal.DefaultGradleBuild.synchronize(DefaultGradleBuild.java:58)
     at org.eclipse.buildship.ui.wizard.project.ProjectImportWizardController.performImportProject(ProjectImportWizardController.java:167)
     at org.eclipse.buildship.ui.wizard.project.ProjectCreationWizard.performFinish(ProjectCreationWizard.java:180)
     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:4257)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1502)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1525)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1510)
     at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1314)
     at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4081)
     at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3698)
     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 HIDDEN.HIDDEN(HIDDEN:-1)
     at HIDDEN.HIDDEN(HIDDEN:-1)
     at HIDDEN.HIDDEN(HIDDEN:-1)
     at java.lang.reflect.Method.invoke(Method.java:564)
     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.ui.internal.actions.CommandAction.run(CommandAction.java:161)
     at org.eclipse.ui.actions.NewWizardDropDownAction.run(NewWizardDropDownAction.java:175)
     at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
     at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
     at org.eclipse.jface.action.ActionContributionItem.lambda$5(ActionContributionItem.java:436)
     at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
     at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4257)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1502)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1525)
     at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1510)
     at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1314)
     at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4081)
     at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3698)
     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 HIDDEN.HIDDEN(HIDDEN:-1)
     at HIDDEN.HIDDEN(HIDDEN:-1)
     at HIDDEN.HIDDEN(HIDDEN:-1)
     at java.lang.reflect.Method.invoke(Method.java:564)
     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)

BUNDLES

name                org.eclipse.buildship.core
version             2.1.2.v20170807-1324

name                org.eclipse.buildship.ui
version             2.1.2.v20170807-1324

name                org.eclipse.core.commands
version             3.9.0.v20170530-1048

name                org.eclipse.core.databinding.observable
version             1.6.100.v20170515-1119

name                org.eclipse.core.databinding
version             1.6.100.v20170515-1119

name                org.eclipse.core.runtime
version             3.13.0.v20170207-1030

name                org.eclipse.e4.core.commands
version             0.12.100.v20170513-0428

name                org.eclipse.e4.core.contexts
version             1.6.0.v20170322-1144

name                org.eclipse.e4.core.di
version             1.6.100.v20170421-1418

name                org.eclipse.e4.ui.workbench
version             1.5.1.v20170815-1446

name                org.eclipse.e4.ui.workbench.swt
version             0.14.101.v20170710-1119

name                org.eclipse.equinox.app
version             1.3.400.v20150715-1528

name                org.eclipse.equinox.launcher
version             1.4.0.v20161219-1356

name                org.eclipse.jface
version             3.13.1.v20170810-0135

name                org.eclipse.swt
version             3.106.1.v20170926-0519

name                org.eclipse.ui
version             3.109.0.v20170411-1742

name                org.eclipse.ui.ide.application
version             1.2.0.v20170512-1452

name                org.eclipse.ui.ide
version             3.13.1.v20170822-1526

NOTE
Not sure what helped, but this get resolved. I did 2 things:-
1.I ran gradle command from terminal in workspace of eclipse.
2.Updated Buildship gradle integration from eclipse ide.


问:
Error: Source path does not exist: resources\android\icon\drawable-hdpi-icon.png
I'm trying to get an APK file from a Ionic project with the "cordova build --release android" command on a Mac and it doesn't work as I get this error

"Error: Source path does not exist:
  resources\android\icon\drawable-hdpi-icon.png"

.
Anyone knows where it might come from?

Here is the copy of the config.xml file :

```<code><?xml version='1.0' encoding='utf-8'?>
<widget id="com.ionicframework.rise268787" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>RISE</name>
<description>
    Discover music as you go
</description>
<author email="infos@olivierlam.fr" href="http://olivierlam.fr/">
  Olivier Lam
</author>
<content src="index.html" />
<access origin="*" />
<preference name="webviewbounce" value="false" />
<preference name="UIWebViewBounce" value="false" />
<preference name="DisallowOverscroll" value="true" />
<preference name="SplashScreen" value="screen" />
<preference name="orientation" value="portrait" />
<preference name="SplashScreenDelay" value="1000" />
<preference name="android-minSdkVersion" value="16" />
<preference name="BackupWebStorage" value="none" />
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="1000" />
<feature name="StatusBar">
    <param name="ios-package" onload="true" value="CDVStatusBar" />
</feature>
<platform name="android">
    <preference name="android-minSdkVersion" value="23" />
    <preference name="android-targetSdkVersion" value="23" />
    <icon density="ldpi" src="resources\android\icon\drawable-ldpi-icon.png" />
    <icon density="mdpi" src="resources\android\icon\drawable-mdpi-icon.png" />
    <icon density="hdpi" src="resources\android\icon\drawable-hdpi-icon.png" />
    <icon density="xhdpi" src="resources\android\icon\drawable-xhdpi-icon.png" />
    <icon density="xxhdpi" src="resources\android\icon\drawable-xxhdpi-icon.png" />
    <icon density="xxxhdpi" src="resources\android\icon\drawable-xxxhdpi-icon.png" />
    <splash density="port-ldpi" src="resources\android\splash\drawable-port-ldpi-screen.png" />
    <splash density="port-mdpi" src="resources\android\splash\drawable-port-mdpi-screen.png" />
    <splash density="port-hdpi" src="resources\android\splash\drawable-port-hdpi-screen.png" />
    <splash density="port-xhdpi" src="resources\android\splash\drawable-port-xhdpi-screen.png" />
    <splash density="port-xxhdpi" src="resources\android\splash\drawable-port-xxhdpi-screen.png" />
    <splash density="port-xxxhdpi" src="resources\android\splash\drawable-port-xxxhdpi-screen.png" />
</platform>
<platform name="ios">
    <icon height="57" src="resources/ios/icon/icon.png" width="57" />
    <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
    <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
    <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
    <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
    <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
    <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
    <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
    <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
    <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
    <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
    <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
    <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
    <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
    <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
    <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
    <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
    <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
    <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
    <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
    <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
    <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
    <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
    <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
    <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
</platform>
<icon src="resources/ios/icon/icon-small@3x.png" />
<plugin name="cordova-plugin-facebook4" spec="~1.7.1">
    <variable name="APP_ID" value="XXXXXXX" />
    <variable name="APP_NAME" value="Rise" />
</plugin>
<allow-intent href="mailto:*" />
<allow-navigation href="*.youtube.com" />
<plugin name="cordova-plugin-whitelist" spec="~1.2.2" />
</code>```

Thanks for your help.

答:
Just try to find the path of this resource inside the Ionic structure.
Sometimes, or in some versions, this path may be like this:

Your resource:

```<code>resources/android/icon/drawable-hdpi.png
</code>```

Try this:

```<code>res/android/icon/drawable-hdpi.png
</code>```

Body:
I'm trying to get an APK file from a Ionic project with the "cordova build --release android" command on a Mac and it doesn't work as I get this error

"Error: Source path does not exist:
  resources\android\icon\drawable-hdpi-icon.png"

.
Anyone knows where it might come from?

Here is the copy of the config.xml file :

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.ionicframework.rise268787" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>RISE</name>
<description>
    Discover music as you go
</description>
<author email="infos@olivierlam.fr" href="http://olivierlam.fr/">
  Olivier Lam
</author>
<content src="index.html" />
<access origin="*" />
<preference name="webviewbounce" value="false" />
<preference name="UIWebViewBounce" value="false" />
<preference name="DisallowOverscroll" value="true" />
<preference name="SplashScreen" value="screen" />
<preference name="orientation" value="portrait" />
<preference name="SplashScreenDelay" value="1000" />
<preference name="android-minSdkVersion" value="16" />
<preference name="BackupWebStorage" value="none" />
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="1000" />
<feature name="StatusBar">
    <param name="ios-package" onload="true" value="CDVStatusBar" />
</feature>
<platform name="android">
    <preference name="android-minSdkVersion" value="23" />
    <preference name="android-targetSdkVersion" value="23" />
    <icon density="ldpi" src="resources\android\icon\drawable-ldpi-icon.png" />
    <icon density="mdpi" src="resources\android\icon\drawable-mdpi-icon.png" />
    <icon density="hdpi" src="resources\android\icon\drawable-hdpi-icon.png" />
    <icon density="xhdpi" src="resources\android\icon\drawable-xhdpi-icon.png" />
    <icon density="xxhdpi" src="resources\android\icon\drawable-xxhdpi-icon.png" />
    <icon density="xxxhdpi" src="resources\android\icon\drawable-xxxhdpi-icon.png" />
    <splash density="port-ldpi" src="resources\android\splash\drawable-port-ldpi-screen.png" />
    <splash density="port-mdpi" src="resources\android\splash\drawable-port-mdpi-screen.png" />
    <splash density="port-hdpi" src="resources\android\splash\drawable-port-hdpi-screen.png" />
    <splash density="port-xhdpi" src="resources\android\splash\drawable-port-xhdpi-screen.png" />
    <splash density="port-xxhdpi" src="resources\android\splash\drawable-port-xxhdpi-screen.png" />
    <splash density="port-xxxhdpi" src="resources\android\splash\drawable-port-xxxhdpi-screen.png" />
</platform>
<platform name="ios">
    <icon height="57" src="resources/ios/icon/icon.png" width="57" />
    <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
    <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
    <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
    <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
    <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
    <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
    <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
    <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
    <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
    <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
    <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
    <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
    <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
    <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
    <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
    <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
    <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
    <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
    <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
    <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
    <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
    <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
    <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
    <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
</platform>
<icon src="resources/ios/icon/icon-small@3x.png" />
<plugin name="cordova-plugin-facebook4" spec="~1.7.1">
    <variable name="APP_ID" value="XXXXXXX" />
    <variable name="APP_NAME" value="Rise" />
</plugin>
<allow-intent href="mailto:*" />
<allow-navigation href="*.youtube.com" />
<plugin name="cordova-plugin-whitelist" spec="~1.2.2" />

Thanks for your help.

Body:
Just try to find the path of this resource inside the Ionic structure.
Sometimes, or in some versions, this path may be like this:

Your resource:

resources/android/icon/drawable-hdpi.png

Try this:

res/android/icon/drawable-hdpi.png


问:
Unable to resovle macro in call symput
I am calling a user defined macro within a data step. The macro contains a do loop and I would like to assign the value of i counter of the do loop to a macro variable for which I am using a call symput. please find my code below. Can you tell me where I am going wrong.</p>

```<code>%let RedressStartYear=2007;
%let RedressEndDate= '31OCT2017'D;

*Yearly Interest Rate;
%let int_rt_2007= '0.0421';
%let int_rt_2008= '0.0421';
%let int_rt_2009= '0.0421';
%let int_rt_2010= '0.0421';
%let int_rt_2011= '0.0421';
%let int_rt_2012= '0.0419';
%let int_rt_2013= '0.0429';
%let int_rt_2014= '0.0430';
%let int_rt_2015= '0.0401';
%let int_rt_2016= '0.0378';
%let int_rt_2017= '0.0358';

Data Redress_Data;
format BilledMonth date9.;
BilledMonth='01MAR2013'D;
BilledYear=Year(BilledMonth);
Customer='ABC Ltd.';
OverChargeAmt=34.6656;
run;

%macro Calculate_CI(billmon, Amt,Payday);

CI_AMT=0;

do i=&RedressStartYear. to year(&payday.) by 1;

*The value of i not getting resolved and getting assigned to the macro variable yr;
Call symput ('yr',i);

    if i<year(&billmon.) then CI_AMT= CI_AMT+0;

    if i=Year(&billmon.) then do;

        No_days_Int_&yr.=intck('day',&billmon.,MDY(12,31,i))+1;
        Days_in_Year_&yr.=intck('day',MDY(01,01,i),MDY(12,31,i))+1;
        CI_AMT= CI_AMT+ (&&int_rt_&yr.* No_days_Int_&yr. * &Amt.)/Days_in_Year_&yr.; end;

    if i>Year(&billmon.) and Year(&billmon.)< Year(&Payday.) then CI_AMT=CI_AMT + (&&int_rt_&yr. * &Amt.);

    if i=Year(&Payday.) then do;
        No_days_Int_&yr.=intck('day',MDY(01,01,i),&Payday.)+1;
        Days_in_Year_&yr.=intck('day',MDY(01,01,i),MDY(12,31,i))+1;
        CI_AMT=CI_AMT+ (&&int_rt_&yr. * No_days_Int_&yr. * &Amt.)/Days_in_Year_&yr. ; end;

end;

%mend Calculate_CI;

Data Redress_Data_CI;
set Redress_Data;
    %Calculate_CI(BilledMonth, OverChargeAmt,&RedressEndDate.);
run;
</code>```

答:
You are mixing macro code and data step code. The value of the macro variable references (like &yr. and &&int_rt_&yr.) are evaluated before the data step is compiled and long before the DO loop runs.

If you want to create a bunch of variables in a data step then use an ARRAY.  You can then use I to index into the array.

To create a macro you need to start with working SAS code. Then you can try to make a macro that will generate different versions of that code for you.

Title: Unable to resovle macro in call symput

Body:
I am calling a user defined macro within a data step. The macro contains a do loop and I would like to assign the value of i counter of the do loop to a macro variable for which I am using a call symput. please find my code below. Can you tell me where I am going wrong.

%let RedressStartYear=2007;
%let RedressEndDate= '31OCT2017'D;

*Yearly Interest Rate;
%let int_rt_2007= '0.0421';
%let int_rt_2008= '0.0421';
%let int_rt_2009= '0.0421';
%let int_rt_2010= '0.0421';
%let int_rt_2011= '0.0421';
%let int_rt_2012= '0.0419';
%let int_rt_2013= '0.0429';
%let int_rt_2014= '0.0430';
%let int_rt_2015= '0.0401';
%let int_rt_2016= '0.0378';
%let int_rt_2017= '0.0358';

Data Redress_Data;
format BilledMonth date9.;
BilledMonth='01MAR2013'D;
BilledYear=Year(BilledMonth);
Customer='ABC Ltd.';
OverChargeAmt=34.6656;
run;

%macro Calculate_CI(billmon, Amt,Payday);

CI_AMT=0;

do i=&RedressStartYear. to year(&payday.) by 1;

*The value of i not getting resolved and getting assigned to the macro variable yr;
Call symput ('yr',i);

    if i<year(&billmon.) then CI_AMT= CI_AMT+0;

    if i=Year(&billmon.) then do;

        No_days_Int_&yr.=intck('day',&billmon.,MDY(12,31,i))+1;
        Days_in_Year_&yr.=intck('day',MDY(01,01,i),MDY(12,31,i))+1;
        CI_AMT= CI_AMT+ (&&int_rt_&yr.* No_days_Int_&yr. * &Amt.)/Days_in_Year_&yr.; end;

    if i>Year(&billmon.) and Year(&billmon.)< Year(&Payday.) then CI_AMT=CI_AMT + (&&int_rt_&yr. * &Amt.);

    if i=Year(&Payday.) then do;
        No_days_Int_&yr.=intck('day',MDY(01,01,i),&Payday.)+1;
        Days_in_Year_&yr.=intck('day',MDY(01,01,i),MDY(12,31,i))+1;
        CI_AMT=CI_AMT+ (&&int_rt_&yr. * No_days_Int_&yr. * &Amt.)/Days_in_Year_&yr. ; end;

end;

%mend Calculate_CI;

Data Redress_Data_CI;
set Redress_Data;
    %Calculate_CI(BilledMonth, OverChargeAmt,&RedressEndDate.);
run;


问:
Calculate the estimated page load time
Is it possible using jQuery/Javascript to calculate the estimated load time of a page?

I've tried the following which I found somewhere online but the time increments on each reload by 200 and when it gets to 6000 it resets back to 0

```<code>var perfData = window.performance.timing,
    EstimatedTime = -(perfData.loadEventEnd - perfData.navigationStart),
    time = parseInt((EstimatedTime/1000)%60)*100;

if (time >= 700) {
    $(window).load(function() {
        // Do something
    });
} else {
    // Do something else
}
</code>```

I wanted it to use a preloader if the estimated page load time was 700ms or more.

答:
What is the end of page load? window.onload?

```<code>var first= new Date();

$(window).load(function() {
   $('body').html(new Date() - first);
});
</code>```

Title: Calculate the estimated page load time

Body:
Is it possible using jQuery/Javascript to calculate the estimated load time of a page?

I've tried the following which I found somewhere online but the time increments on each reload by 200 and when it gets to 6000 it resets back to 0

var perfData = window.performance.timing,
    EstimatedTime = -(perfData.loadEventEnd - perfData.navigationStart),
    time = parseInt((EstimatedTime/1000)%60)*100;

if (time >= 700) {
    $(window).load(function() {
        // Do something
    });
} else {
    // Do something else
}

I wanted it to use a preloader if the estimated page load time was 700ms or more.

Body:
What is the end of page load? window.onload?

var first= new Date();

$(window).load(function() {
   $('body').html(new Date() - first);
});


问:
I want to have data from 2 tables in MySQL ordered by date
I would like to get data from two tables in MySQL, ordered by date.</p>

```<code>$sql = "
SELECT
    items.*, invoice.*
FROM
    items
JOIN
    invoice
ON
    items.user_id = invoice.buyer_id
WHERE
    items.user_id = '$user_id'"
LIMIT
    10
ORDER BY
    date;
";
</code>```

答:
Try with:

```<code>$sql = "SELECT *";
$sql .= " FROM items, invoice";
$sql .= " WHERE items.user_id = invoice.buyer_id";
$sql .= " AND items.user_id = '$user_id'";
$sql .= " ORDER BY date DESC";
$sql .= " LIMIT 10";
</code>```

Also it is better if you use it as a prepared statement instead of having the variable inside the SQL query to avoid SQL injection.

Body:
I would like to get data from two tables in MySQL, ordered by date.

$sql = "
SELECT
    items.*, invoice.*
FROM
    items
JOIN
    invoice
ON
    items.user_id = invoice.buyer_id
WHERE
    items.user_id = '$user_id'"
LIMIT
    10
ORDER BY
    date;
";

Body:
Try with:

$sql = "SELECT *";
$sql .= " FROM items, invoice";
$sql .= " WHERE items.user_id = invoice.buyer_id";
$sql .= " AND items.user_id = '$user_id'";
$sql .= " ORDER BY date DESC";
$sql .= " LIMIT 10";

Also it is better if you use it as a prepared statement instead of having the variable inside the SQL query to avoid SQL injection.


问:
Perl function: findOddCount

Hello,

I am trying to write a Perl findOddCount function which finds a value in the given list that occurs an odd number of times.

```<code>#!/usr/bin/perl

sub findOddCount{
    @array1 = $_[0];
    $res=0;
    for( $i=0; $i < $#array1; $i++) {
            $res=($res ^ $array1[i])
            }
    return $res
}

@a1 = (1,1,2,2,3,3,4,4,5,5,6,7,7,7,7);
@a2 = (10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
@a3 = (6,6,10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
@a4 = (10,10,7,7, 2,2,3,3,4,4,5,5,7,7,7,7,10,10,6);
@a5 = (6,6);
@a6 = (1);

print "odd value in a1 is "; print findOddCount(@a1); print "\n";
print "odd value in a2 is "; print findOddCount(@a2); print "\n";
print "odd value in a3 is "; print findOddCount(@a3); print "\n";
print "odd value in a4 is "; print findOddCount(@a4); print "\n";
print "odd value in a5 is "; print findOddCount(@a5); print "\n";
print "odd value in a6 is "; print findOddCount(@a6); print "\n";
</code>```

Expected Output:

```<code>odd value in a1 is 6
odd value in a2 is 6
odd value in a3 is 6
odd value in a4 is 6
odd value in a5 is 0
odd value in a6 is 1
</code>```

However, my actual output showed all 0:

```<code>odd value in a1 is 0
odd value in a2 is 0
odd value in a3 is 0
odd value in a4 is 0
odd value in a5 is 0
odd value in a6 is 0
</code>```

Any help would be appreciated. Thanks.

答:
Try inserting some debugging statements into your code to see if the code is doing what you think it should be doing. Also put use strict and use warnings at the top of your script (and the top of every script). Those pragmas help both beginning and experienced Perl programmers catch typos and many other not-what-I-really-wanted-to-do kind of constructions.

```<code>use strict;
use warnings;

sub findOddCount {
    my @array1 = $_[0];
    print STDERR "Length of \@array1 is ",0+@array1,", expected ",0+@_,"\n";
    my $res=0;
    print STDERR "\$#array1 is $#array1, expected $#_\n";
    for (my $i=0; $i < $#array1; $i++) {
        $res=($res ^ $array1[$i]);
        print STDERR "\$array1[$i] is $array1[$i], value for \$res is $res\n";
    }
    return $res
}
</code>```

Title: Perl function: findOddCount

Body:
Hello,

I am trying to write a Perl findOddCount function which finds a value in the given list that occurs an odd number of times.

#!/usr/bin/perl

sub findOddCount{
    @array1 = $_[0];
    $res=0;
    for( $i=0; $i < $#array1; $i++) {
            $res=($res ^ $array1[i])
            }
    return $res
}

@a1 = (1,1,2,2,3,3,4,4,5,5,6,7,7,7,7);
@a2 = (10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
@a3 = (6,6,10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
@a4 = (10,10,7,7, 2,2,3,3,4,4,5,5,7,7,7,7,10,10,6);
@a5 = (6,6);
@a6 = (1);

print "odd value in a1 is "; print findOddCount(@a1); print "\n";
print "odd value in a2 is "; print findOddCount(@a2); print "\n";
print "odd value in a3 is "; print findOddCount(@a3); print "\n";
print "odd value in a4 is "; print findOddCount(@a4); print "\n";
print "odd value in a5 is "; print findOddCount(@a5); print "\n";
print "odd value in a6 is "; print findOddCount(@a6); print "\n";

Expected Output:

odd value in a1 is 6
odd value in a2 is 6
odd value in a3 is 6
odd value in a4 is 6
odd value in a5 is 0
odd value in a6 is 1

However, my actual output showed all 0:

odd value in a1 is 0
odd value in a2 is 0
odd value in a3 is 0
odd value in a4 is 0
odd value in a5 is 0
odd value in a6 is 0

Any help would be appreciated. Thanks.

Body:
Try inserting some debugging statements into your code to see if the code is doing what you think it should be doing. Also put use strict and use warnings at the top of your script (and the top of every script). Those pragmas help both beginning and experienced Perl programmers catch typos and many other not-what-I-really-wanted-to-do kind of constructions.

use strict;
use warnings;

sub findOddCount {
    my @array1 = $_[0];
    print STDERR "Length of \@array1 is ",0+@array1,", expected ",0+@_,"\n";
    my $res=0;
    print STDERR "\$#array1 is $#array1, expected $#_\n";
    for (my $i=0; $i < $#array1; $i++) {
        $res=($res ^ $array1[$i]);
        print STDERR "\$array1[$i] is $array1[$i], value for \$res is $res\n";
    }
    return $res
}


问:
TensorFlow Lite: Is tensor string buffer format ASCII or UTF-8?
Are the strings stored in a .tflite tensor buffer in ASCII or UTF-8 format?</p>

答:
The few TensorFlow Lite ops that deal with string can handle UTF-8 and adhere to the format described in https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lite/string_util.h#L17

That is:

4 bytes specifying the number of strings in the tensor

a section describing the length and location (offset) of each string inside the buffer, and the length of the buffer itself.

a section containing the actual strings.


问:
Storing a list of functions
The code

```<code>for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, function( e:Event ):void
    {
        markers[i].openInfoWindow( infoWindows[i] );
    });
    map.addOverlay( markers[i] );
}
</code>```

I have a list of markers in markers array, and a list of associated InfoWindowOptions in the infoWindow array.

The Issue

By the time the marker is clicked and the anonymous function called, the for loop has already finished and i is now equal to markers.length. So I get an out of bounds error on markers[i] and infoWindows[i].

I would like to create a list of associated functions as well and store it in an array. So I can do something like this instead:

```<code>for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, markerListeners[i] );
}
</code>```

So what I need to know is either,

How can I can store a list of function references in an array?

Is there a better way of doing this?

答:
Is there a better way of doing this?

Good question. Marker should be the target of MapMouseEvent, so you can use regular function and distinguish markers by target.

ContentLicense: CC BY-SA 2.5

Title: Storing a list of functions

Body:
The code

for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, function( e:Event ):void
    {
        markers[i].openInfoWindow( infoWindows[i] );
    });
    map.addOverlay( markers[i] );
}

I have a list of markers in markers array, and a list of associated InfoWindowOptions in the infoWindow array.

The Issue

By the time the marker is clicked and the anonymous function called, the for loop has already finished and i is now equal to markers.length. So I get an out of bounds error on markers[i] and infoWindows[i].

I would like to create a list of associated functions as well and store it in an array. So I can do something like this instead:

for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, markerListeners[i] );
}

So what I need to know is either,

How can I can store a list of function references in an array?

Is there a better way of doing this?


问:
Hosting several websites on wamp with laravel breaks the routes
I'm currently hosting several applications on a quite out-dated wamp version but that's not really the case. Everything is working fine on that part, besides my laravel application.

My .htaccess in the www folder looks like this;

```<code>RewriteCond %{HTTP_HOST} ^sapdfr.org$ [NC]
RewriteRule ^((?!sapdfr/websitev3).*)$ /sapdfr/websitev3/public/$1 [NC,L]
</code>```

The thing that's strange, is that the first page is working but when I'm going deeper into the website, it just totally breaks. I've been trying to rewrite these rules but I'm seriously mindblown about all the possibilities. Any help will be greatly appreciated since I'm entirely lost here.

答:
Maybe a silly question but have you try that ? :)

Laravel includes a public/.htaccess file that is used to provide URLs without the index.php front controller in the path. Before serving Laravel with Apache, be sure to enable the mod_rewrite module so the .htaccess file will be honored by the server.

If the .htaccess file that ships with Laravel does not work with your Apache installation, try this alternative:

```<code>Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</code>```

and then just redirect your domain to the laravel public folder

Body:
I'm currently hosting several applications on a quite out-dated wamp version but that's not really the case. Everything is working fine on that part, besides my laravel application.

My .htaccess in the www folder looks like this;

RewriteCond %{HTTP_HOST} ^sapdfr.org$ [NC]
RewriteRule ^((?!sapdfr/websitev3).*)$ /sapdfr/websitev3/public/$1 [NC,L]

The thing that's strange, is that the first page is working but when I'm going deeper into the website, it just totally breaks. I've been trying to rewrite these rules but I'm seriously mindblown about all the possibilities. Any help will be greatly appreciated since I'm entirely lost here.

Body:
Maybe a silly question but have you try that ? :)

Laravel includes a public/.htaccess file that is used to provide URLs without the index.php front controller in the path. Before serving Laravel with Apache, be sure to enable the mod_rewrite module so the .htaccess file will be honored by the server.

If the .htaccess file that ships with Laravel does not work with your Apache installation, try this alternative:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

and then just redirect your domain to the laravel public folder


问:
Filter on generic types

I'm trying to write a function using TypeScript that will allow me to filter a list of objects depending on their type. The result should be a function that will allow me to do either:

```<code>filter<Foo>(items);
</code>```

or

```<code>filter(items, Foo);
</code>```

I've been trying to do it in the following way:

```<code>class Foo {
    public constructor(public name: string, public type: string) {

    }
}

class Bar extends Foo { }

const items: Foo[] = [
    new Foo('Foo', 'A'),
    new Bar('bar', 'A'),
    new Foo('baz', 'B'),
];

const filter = <T extends Foo>(items: any[], typeT: T): T[] => {
    return items.filter(item => item instanceof typeT)
};

console.log(filter(items, Foo));
</code>```

But this doesn't work.

How can I make this work?

TypeScript example

答:
You can simplify things by using the name property of the class:

```<code>class Foo {
    public constructor(public name: string, public type: string) {

    }
}

class Bar extends Foo { }

const items: Foo[] = [
    new Foo('Foo', 'A'),
    new Bar('bar', 'A'),
    new Foo('baz', 'B'),
];

const filter = (items: Foo[], typeT: Function): Foo[] => {
    return items.filter(item => item.constructor.name === typeT.name)
};

console.log(filter(items, Foo)); // Array [ {…}, {…} ]
</code>```

Title: Filter on generic types

Body:
I'm trying to write a function using TypeScript that will allow me to filter a list of objects depending on their type. The result should be a function that will allow me to do either:

filter<Foo>(items);

or

filter(items, Foo);

I've been trying to do it in the following way:

class Foo {
    public constructor(public name: string, public type: string) {

    }
}

class Bar extends Foo { }

const items: Foo[] = [
    new Foo('Foo', 'A'),
    new Bar('bar', 'A'),
    new Foo('baz', 'B'),
];

const filter = <T extends Foo>(items: any[], typeT: T): T[] => {
    return items.filter(item => item instanceof typeT)
};

console.log(filter(items, Foo));

But this doesn't work.

How can I make this work?

<a href="https://www.typescriptlang.org/play/#src=class%20Foo%20%7B%0D%0A%20%20%20%20public%20constructor(public%20name%3A%20string%2C%20public%20type%3A%20string)%20%7B%0D%0A%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20Bar%20extends%20Foo%20%7B%20%7D%0D%0A%0D%0Aconst%20items%3A%20Foo%5B%5D%20%3D%20%5B%0D%0A%20%20%20%20new%20Foo('Foo'%2C%20'A')%2C%0D%0A%20%20%20%20new%20Bar('bar'%2C%20'A')%2C%0D%0A%20%20%20%20new%20Foo('baz'%2C%20'B')%2C%0D%0A%5D%3B%0D%0A%0D%0Aconst%20filter%20%3D%20%3CT%20extends%20Foo%3E(items%3A%20any%5B%5D%2C%20typeT%3A%20T)%3A%20T%5B%5D%20%3D%3E%20%7B%0D%0A%20%20%20%20return%20items.filter(item%20%3D%3E%20item%20instanceof%20typeT)%0D%0A%7D%3B%0D%0A%0D%0Aconsole.log(filter(items%2C%20Foo))%3B" rel="noreferrer">TypeScript example

Body:
You can simplify things by using the name property of the class:

class Foo {
    public constructor(public name: string, public type: string) {

    }
}

class Bar extends Foo { }

const items: Foo[] = [
    new Foo('Foo', 'A'),
    new Bar('bar', 'A'),
    new Foo('baz', 'B'),
];

const filter = (items: Foo[], typeT: Function): Foo[] => {
    return items.filter(item => item.constructor.name === typeT.name)
};

console.log(filter(items, Foo)); // Array [ {…}, {…} ]


问:
Callback/webhook when shopify charge my clients
I'm working on a Shopify app, so my business plan is to charge user monthly for using the app, i have three plans each plan has a limit of actions, so we can say I'm using a combination of a monthly limited plan for example :

```<code>plan 1 => 50$/month for 5000/month actions (actions = click on a button)
plan 2 => 99$/month for 15000/month actions (actions = click on a button)
plan 3 => 119$/month for 20000/month actions (actions = click on a button)
</code>```

so the problem is how I can get a callback or webhook from Shopify when the user has paid the monthly fee so i can update his actions count at the end of each month.

thanks

答:
I don't think you can get a webhook or callback for this. You have to query the api on some periodic basis.

When a customer installs your app you should use the RecurringApplicationCharge api call so the customer can set up your terms and Shopify will charge them.

You can either record the charge id or just query for it as part of your app's process.

Once you have the recurring charge and have activated it you can query it for the "billing_on" date. Your app can record that and check only on that date for that app which saves some API governance. If the RecurringApplicationCharge status is active and the billing_on date advances then the customer has been successfully charged. As long as you have a standard process for running your checks (e.g. use the shop's midnight which you can determine from their iana_timezone then it's an easy thing to explain to customers when their limits will reset.

If they update their plan mid-month due to running out of actions then your app will be part of that update (e.g. you'll send them a notice with a link to your app) so you'll be able to track the application charge status and reset their limits as soon as you successfully activate the new charge.

Body:
I'm working on a Shopify app, so my business plan is to charge user monthly for using the app, i have three plans each plan has a limit of actions, so we can say I'm using a combination of a monthly limited plan for example :

plan 1 => 50$/month for 5000/month actions (actions = click on a button)
plan 2 => 99$/month for 15000/month actions (actions = click on a button)
plan 3 => 119$/month for 20000/month actions (actions = click on a button)

so the problem is how I can get a callback or webhook from Shopify when the user has paid the monthly fee so i can update his actions count at the end of each month.

thanks


问:
Scipy.minimize not correctly minimizing
I am currently doing a project that maps the velocity of stars as you move out from the center of the galaxy(the distance to the center is denoted by r).

Essentially, I am aiming to minimize the distance between my model function and my observed function. To do this, I have to minimize the function: np.sum(((v_model-v_obs)/errors)**2) where errors is an array of the error at each different r value. v_obs is the observed velocity at each r value  (r is just an array of numbers). To minimize the function, I have to manipulate v_model which can be done via manipulating two "fixing parameters" p0 and r0 in the equation (integrand is shown below):

```<code>np.sqrt(4.302*10**(-6)*quad(integrand,0,r.all(),args=(p0,r0))[0]/r.all())
</code>```

Before I get into the problem, I want to know if r.all() is appropriate since it wouldn't allow me to put r due to it being an array. An alternative I had was to make an array of v_model via:

```<code>#am is the amount of elements in the array r
#r, v_model,v_obs, and errors all have the same size
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2
integrals = []
for i in r:
     integrals.append(quad(integrand, 0 ,i,args=(p0,r0)))

v_model = []

for x in range (0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10**(-6)*k)/i))
</code>```

Regardless, to minimize the function np.sum(((v_model-v_obs)/errors)**2)
I tried to do something like this:

```<code>def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = []
    for x in range(0,am):
        v_model.append(np.sqrt(4.302*10.0**(-6)*quad(integrand, 0, r[x], args=(p0,r0))[0]/r[x]))
    chisq = np.sum(((v_model-v_obs)/errors)**2)
    return chisq
x0 = np.array([10**6,24])
resolution = minimize(chisqfunc,x0)
</code>```

However, the values I get back aren't good fits at all (which is evident when I graph the observed data and my model)

In conclusion, I have two main question:

1.) Is my function taking the model minus the observed at each different r value, and if not, how do I fix this? (I think I messed up my v_model equation)

2.) Why is it returning wrong numbers for r0 and p0?

Here is my full code (By the way, to know if the minimization is working properly: r0 should be around 1.5 and p0 should be around: 3.5*10**8)

```<code>from scipy.optimize import*
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad

#number of measurements
am = 18

r0 = 1.8
p0 = 3.5*10**8.62

#Observed Data
v_obs = np.array([
234.00,
192.00,
212.00,
223.00,
222.00,
224.00,
224.00,
226.00,
226.00,
227.00,
227.00,
224.00,
220.00,
218.00,
217.00,
216.00,
210.00,
208.00

]
)

r = np.array([0.92,
2.32,
3.24,
4.17,
5.10,
6.03,
6.96,
7.89,
8.80,
9.73,
10.64,
11.58,
12.52,
13.46,
14.40,
15.33,
16.27,
17.11

]
)

errors = np.array([
3.62,
4.31,
3.11,
5.5,
3.9,
3.5,
2.7,
2.5,
2.3,
2.1,
2.3,
2.6,
3.1,
3.2,
3.2,
3.1,
2.9,
2.8
    ])

#integral
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2
integrals = []
for i in r:
     integrals.append(quad(integrand, 0 ,i,args=(p0,r0)))

v_model = []

for x in range (0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10**(-6)*k)/i))

def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = np.sqrt(4.302*10**(-6)*quad(integrand,0,r.all(),args=(p0,r0))[0]/r.all())
    chisq = np.sum(((v_model-v_obs)/errors)**2)
    print(v_model)
    return chisq
x0 = np.array([10**6,24])
resolution = minimize(chisqfunc,x0)
print("This is the function",resolution)
</code>```

Let me know if I left out any data and thank you in advance!

Title: Scipy.minimize not correctly minimizing

Body:
I am currently doing a project that maps the velocity of stars as you move out from the center of the galaxy(the distance to the center is denoted by r).

Essentially, I am aiming to minimize the distance between my model function and my observed function. To do this, I have to minimize the function: np.sum(((v_model-v_obs)/errors)**2) where errors is an array of the error at each different r value. v_obs is the observed velocity at each r value  (r is just an array of numbers). To minimize the function, I have to manipulate v_model which can be done via manipulating two "fixing parameters" p0 and r0 in the equation (integrand is shown below):

np.sqrt(4.302*10**(-6)*quad(integrand,0,r.all(),args=(p0,r0))[0]/r.all())

Before I get into the problem, I want to know if r.all() is appropriate since it wouldn't allow me to put r due to it being an array. An alternative I had was to make an array of v_model via:

#am is the amount of elements in the array r
#r, v_model,v_obs, and errors all have the same size
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2
integrals = []
for i in r:
     integrals.append(quad(integrand, 0 ,i,args=(p0,r0)))

v_model = []

for x in range (0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10**(-6)*k)/i))

Regardless, to minimize the function np.sum(((v_model-v_obs)/errors)**2)
I tried to do something like this:

def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = []
    for x in range(0,am):
        v_model.append(np.sqrt(4.302*10.0**(-6)*quad(integrand, 0, r[x], args=(p0,r0))[0]/r[x]))
    chisq = np.sum(((v_model-v_obs)/errors)**2)
    return chisq
x0 = np.array([10**6,24])
resolution = minimize(chisqfunc,x0)

However, the values I get back aren't good fits at all (which is evident when I graph the observed data and my model)

In conclusion, I have two main question:

1.) Is my function taking the model minus the observed at each different r value, and if not, how do I fix this? (I think I messed up my v_model equation)

2.) Why is it returning wrong numbers for r0 and p0?

Here is my full code (By the way, to know if the minimization is working properly: r0 should be around 1.5 and p0 should be around: 3.5*10**8)

from scipy.optimize import*
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad

#number of measurements
am = 18

r0 = 1.8
p0 = 3.5*10**8.62

#Observed Data
v_obs = np.array([
234.00,
192.00,
212.00,
223.00,
222.00,
224.00,
224.00,
226.00,
226.00,
227.00,
227.00,
224.00,
220.00,
218.00,
217.00,
216.00,
210.00,
208.00

]
)

r = np.array([0.92,
2.32,
3.24,
4.17,
5.10,
6.03,
6.96,
7.89,
8.80,
9.73,
10.64,
11.58,
12.52,
13.46,
14.40,
15.33,
16.27,
17.11

]
)

errors = np.array([
3.62,
4.31,
3.11,
5.5,
3.9,
3.5,
2.7,
2.5,
2.3,
2.1,
2.3,
2.6,
3.1,
3.2,
3.2,
3.1,
2.9,
2.8
    ])

#integral
def integrand(r,p0,r0):
    return (p0 * r0**3)/((r+r0)*((r**2)+(r0**2)))*4*3.1415926535*r**2
integrals = []
for i in r:
     integrals.append(quad(integrand, 0 ,i,args=(p0,r0)))

v_model = []

for x in range (0,am):
    k = integrals[x][0]
    i = r[x]
    v_model.append(np.sqrt((4.302*10**(-6)*k)/i))

def chisqfunc(parameters):
    p0 = parameters[0]
    r0 = parameters[1]
    v_model = np.sqrt(4.302*10**(-6)*quad(integrand,0,r.all(),args=(p0,r0))[0]/r.all())
    chisq = np.sum(((v_model-v_obs)/errors)**2)
    print(v_model)
    return chisq
x0 = np.array([10**6,24])
resolution = minimize(chisqfunc,x0)
print("This is the function",resolution)

Let me know if I left out any data and thank you in advance!

Body:
If you change p0 in the function it brings the number down in the optimizer routine.  That seems to work well, I guess the numbers are so large it causes some numerical errors in the solver. Just remember to multiply the p0 answer by 3.85e+09, just like is done in the chisqfunc routine.

from scipy.optimize import*
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad
#-----------------------------------------------------------------------------
am = 18 # number of measurements
#Observed Data
v_obs = np.array([
234.00, 192.00, 212.00, 223.00, 222.00, 224.00, 224.00, 226.00, 226.00, 227.00,
227.00, 224.00, 220.00, 218.00, 217.00, 216.00, 210.00, 208.00,
])
r = np.array([
 0.92,  2.32,  3.24,  4.17,  5.10,  6.03,  6.96,  7.89, 8.80, 9.73,
10.64, 11.58, 12.52, 13.46, 14.40, 15.33, 16.27, 17.11
])
errors = np.array([
3.62, 4.31, 3.11, 5.5, 3.9, 3.5, 2.7, 2.5, 2.3, 2.1,
2.3, 2.6, 3.1, 3.2, 3.2, 3.1, 2.9, 2.8
])
grav_const = 4.302e-06
#print "np.pi, grav_const = " + str(np.pi) + ", " + str(grav_const)
#-----------------------------------------------------------------------------
def func_to_integrate(rx, p0, r0):
    rho = (p0 * r0**3) / ( (rx + r0) * (rx**2 + r0**2) )
    function_result = rho * 4.0 * np.pi * rx**2
    #print "rx, p0, r0 = " + str(rx) + ", " + str(p0) + ", " + str(r0)
    return function_result
#-----------------------------------------------------------------------------
def simpsonsRule(func, a, b, n, p0, r0):
    if n%2 == 1:
        return "Not applicable"
    else:
        h = (b - a) / float(n)
        s = func(a, p0, r0) + sum((4 if i%2 == 1 else 2) * func(a+i*h, p0, r0) for i in range(1,n)) + func(b, p0, r0)
        return s*h/3.0
#-----------------------------------------------------------------------------
def chisqfunc(iter_vars):
    global v_model
    p0 = iter_vars[0] * 3.85e+09
    r0 = iter_vars[1]
    v_model = []
    for index in range(0, am):
        integral_result = simpsonsRule(func_to_integrate, 0.0, r[index], 200, p0, r0)
        v_mod_result = np.sqrt(grav_const * integral_result / r[index])
        v_model.append(v_mod_result)
    chisq = 0.0
    for index in range(0, am):
        chisq += ((v_model[index] - v_obs[index])/errors[index])**2
        #chisq += ((v_model[index] - v_obs[index]))**2
    chisq = np.sqrt(chisq)
    #chisq = np.sum(((v_model - v_obs)/errors)**2)
    print "chisq = " + str(chisq)
    #print "iterated p0, r0 = " + str(p0) + ", " + str(r0)
    return chisq
#-----------------------------------------------------------------------------
initial_guess = np.array([1.0, 2.0])
#initial_guess = np.array([3.5*10**8.62, 1.5])
#resolution = minimize(chisqfunc, initial_guess, method='TNC') # , tol=1e-12, options={'accuracy':0})
#resolution = minimize(chisqfunc, initial_guess, method='TNC', options={'rescale':-1})
#resolution = minimize(chisqfunc, initial_guess, method='CG')
resolution = minimize(chisqfunc, initial_guess, method='Nelder-Mead')
# # options tried
# 'gtol':1e-6, 'xtol':-1, 'rescale':0, 'ftol':0, 'accuracy':0, 'offset':None, 'scale':None
print("This is the function",resolution)
#print "resolution.x"
#print resolution.x
print "iterated p0 = " + str(resolution.x[0])
print "iterated p0 * 3.85e+09 = " + str(resolution.x[0] * 3.85e+09)
print "iterated r0 = " + str(resolution.x[1])
print "p0 should be about = " + str(3.5e+08)
print "r0 should be about = " + str(1.5)
print "-----------------------------------------------"
print "iterated model errors"
for index in range(0,am):
    print "v_obs, v_model, error = " + str(v_obs[index]) + ", " + str(v_model[index]) + ", " + str(v_obs[index] - v_model[index])
chisq = 0.0
for index in range(0, am):
    chisq += ((v_model[index] - v_obs[index])/errors[index])**2
    #chisq += ((v_model[index] - v_obs[index]))**2
chisq = np.sqrt(chisq)
print "iterated chisq = " + str(chisq)
print ""
#-----------------------------------------------------------------------------
print "model errors using p0 = 3.5*10**8.62, r0 = 1.8"
p0 = 3.5*10**8.62
r0 = 1.8
# chisq = 118 for p0 = 3.5*10**8.62, r0 = 1.8
# chisq = 564 for p0 = 3.5*10**8   , r0 = 1.5
chisq = 0.0
for index in range(0, am):
    integral_result = simpsonsRule(func_to_integrate, 0.0, r[index], 200, p0, r0)
    v_mod = np.sqrt(grav_const * integral_result / r[index])
    print "v_obs, v_mod, error = " + str(v_obs[index]) + ", " + str(v_mod) + ", " + str(v_obs[index] - v_mod)
    #chisq += ((v_mod - v_obs[index]))**2
    chisq += ((v_mod - v_obs[index])/errors[index])**2
chisq = np.sqrt(chisq)
print "using p0 = 3.5*10**8.62, r0 = 1.8, the chisq = " + str(chisq)
#-----------------------------------------------------------------------------


问:
Emmet expression expanded to single line
I'm learning to use Emmet with Visual Studio Code in TypeScript React files *.tsx.

When I type div.buttons>button.something+button.something-else and hit TAB, it is expanded to the following:

```<code><div className="buttons"><button className="something"></button><button className="something-else"></button></div>
</code>```

However, if I type .outer>.inner>h1+p and hit TAB, it is expanded like this:

```<code><div className="outer">
  <div className="inner">
    <h1></h1>
    <p></p>
  </div>
</div>
</code>```

So I have two questions:

What determines if some expression will be expanded to a single line or to one line per tag?

Can I force the first expression to expand to one line per tag?

Like this:

```<code><div className="buttons">
  <button className="something"></button>
  <button className="something-else"></button>
</div>
</code>```

EDIT:

I found this related question, and I added the following setting to the Visual Studio Code user settings file, but nothing changed:

```<code>"emmet.syntaxProfiles": {
    "html": {
        "tag_nl": true
    }
}
</code>```

答:
After playing with the documentation I have found a solution to make it work as I want. You have to include this in the Visual Studio Code's user settings file:

```<code>"emmet.syntaxProfiles": {
    "jsx": {
        "inline_break": 1
    }
</code>```

It forces a new line for each tag.

Bizarrely, setting tag_nl to true didn't produce any effect.

Body:
I'm learning to use Emmet with Visual Studio Code in TypeScript React files *.tsx.

When I type div.buttons>button.something+button.something-else and hit TAB, it is expanded to the following:

<button className="something"></button><button className="something-else"></button>

However, if I type .outer>.inner>h1+p and hit TAB, it is expanded like this:

So I have two questions:

What determines if some expression will be expanded to a single line or to one line per tag?

Can I force the first expression to expand to one line per tag?

Like this:

  <button className="something"></button>
  <button className="something-else"></button>

EDIT:

I found this related question, and I added the following setting to the Visual Studio Code user settings file, but nothing changed:

"emmet.syntaxProfiles": {
    "html": {
        "tag_nl": true
    }
}

Body:
After playing with the documentation I have found a solution to make it work as I want. You have to include this in the Visual Studio Code's user settings file:

"emmet.syntaxProfiles": {
    "jsx": {
        "inline_break": 1
    }

It forces a new line for each tag.

Bizarrely, setting tag_nl to true didn't produce any effect.


问:
How to split a string of characters/alphabets without space/separator into dictionary words?
I have a string that consists of two or more dictionary English words, but the spaces between the words is missing. How can I separate the words in R or Python?

Example:

```<code>Input_string = "thequickbrownfox"

Desired_output_string = "the quick brown fox"
</code>```

Is there an algorithm to do such text processing?

答:
This is not a linear problem.  Among other difficulties, some character sequences can be separated into more than one reasonable string of words.

However, the approach is straightforward with a recursive routine.  Go through your lexicon (dictionary of legal words) and find each word you can form from the start of the given sentence.  Iterate through those words; for each, parse the rest of the sentence.  If successful, return the properly separated input (current word + parsing of the remainder).

```<code>// Parse a character sequence
//   return a list of legal word separations
// Assume a word list, lexicon, as a global
sep_string(str sentence)
    result = <empty list>
    sent_size = length of sentence

    for word_size in 1:sent_size
        word = sentence[0:word_size-1]  // next potential word

        if word in lexicon
            // Found a legal word; remove it and parse
            //   the rest of the sequence
            sep_rest = sep_string(sentence[word_size:sent_size])
            // sep_rest is a list of parsings for
            //   the rest of the sequence

            for each solution in sep_rest
                append (word + " " + solution) to result

    return result
</code>```

Body:
I have a string that consists of two or more dictionary English words, but the spaces between the words is missing. How can I separate the words in R or Python?

Example:

Input_string = "thequickbrownfox"

Desired_output_string = "the quick brown fox"

Is there an algorithm to do such text processing?

Body:
This is not a linear problem.  Among other difficulties, some character sequences can be separated into more than one reasonable string of words.

However, the approach is straightforward with a recursive routine.  Go through your lexicon (dictionary of legal words) and find each word you can form from the start of the given sentence.  Iterate through those words; for each, parse the rest of the sentence.  If successful, return the properly separated input (current word + parsing of the remainder).

// Parse a character sequence
//   return a list of legal word separations
// Assume a word list, lexicon, as a global
sep_string(str sentence)
    result = <empty list>
    sent_size = length of sentence

    for word_size in 1:sent_size
        word = sentence[0:word_size-1]  // next potential word

        if word in lexicon
            // Found a legal word; remove it and parse
            //   the rest of the sequence
            sep_rest = sep_string(sentence[word_size:sent_size])
            // sep_rest is a list of parsings for
            //   the rest of the sequence

            for each solution in sep_rest
                append (word + " " + solution) to result

    return result


问:
Flask redirect after login with token in header
I'm new to web development and I'm trying to do a web server using flask for a school project. The problem is that, after login, I want to redirect to another page, which requires authentication, and pass the authorization token via the header. However, the page freezes, showing Redirecting... and says that I should be automatically redirected (which does not happen).

This is the code for the login POST and the redirected page.

```<code>@app.route('/login', methods=['POST'])
def login_verify():
    username = models.User.query.get(request.form['username'])
    if username == None or username.verify_password(request.form['password']) == False:
        abort(401)
    redir = redirect(url_for('map'))
    redir.headers = {'headers':username.encode_auth_token()}
    return redir

@app.route('/map')
def map():
    token = request.headers.get('headers')
    if token == None or models.User.decode_auth_token(token) == None:
        abort(403)
    deviceList = list(db.session.query(models.Location.terminalId.distinct()).all())
    return render_template('seeLocations.html',token = str(token),deviceList =  deviceList)
</code>```

I have also tried this (and worked), but the token should not appear as an URL parameter.

```<code>return redirect(url_for('map',headers=username.encode_auth_token()))
</code>```

答:
You could use the session to accomplish what you're looking for

In your login you could save a token into session which can later be used in your route to map as needed.

```<code>session['token] = token
</code>```

And to access it's value you could use

You can access it anywhere in the program just by

```<code>variable = session['token']
</code>```

to unset the value and key from session you can use

```<code>session.pop('token' none)
</code>```

more about flask sessions here

Body:
I'm new to web development and I'm trying to do a web server using flask for a school project. The problem is that, after login, I want to redirect to another page, which requires authentication, and pass the authorization token via the header. However, the page freezes, showing Redirecting... and says that I should be automatically redirected (which does not happen).

This is the code for the login POST and the redirected page.

@app.route('/login', methods=['POST'])
def login_verify():
    username = models.User.query.get(request.form['username'])
    if username == None or username.verify_password(request.form['password']) == False:
        abort(401)
    redir = redirect(url_for('map'))
    redir.headers = {'headers':username.encode_auth_token()}
    return redir

@app.route('/map')
def map():
    token = request.headers.get('headers')
    if token == None or models.User.decode_auth_token(token) == None:
        abort(403)
    deviceList = list(db.session.query(models.Location.terminalId.distinct()).all())
    return render_template('seeLocations.html',token = str(token),deviceList =  deviceList)

I have also tried this (and worked), but the token should not appear as an URL parameter.

return redirect(url_for('map',headers=username.encode_auth_token()))

Body:
You could use the session to accomplish what you're looking for

In your login you could save a token into session which can later be used in your route to map as needed.

session['token] = token

And to access it's value you could use

You can access it anywhere in the program just by

variable = session['token']

to unset the value and key from session you can use

session.pop('token' none)

more about flask sessions here


问:
arrange items by two values in Python dictionary
I practice python recently. for a few days my script has stopped, because I'm struggling on a problem.
I want to sort the items by both values which has in common. like an chain. as you can see lower.

what I have:

```<code>dic= {'A': [62, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 58], 'E': [61, 62], 'F': [58, 59]}
</code>```

what I want:

```<code>dic={'A': [62, 17], 'E': [31, 62],'C': [60, 31],'B': [3, 60],'F': [58, 3],'D': [57, 58]}
</code>```

to see clearly:

```<code>'A': [62, 17]

'E': [*31*, 62]

'C': [60, *31*]

'B': [3, 60]

'F': [58, 3]

'D': [57, 58]
</code>```

there is a simple method to sort them ? if the topic already exists,
can you send me the link. i haven't found it.
thank you in advance.
nb. in all case, I know the first and the last value of the chain (17 and 57)

答:
Given what others have said about the order of a dictionary and violating the posters desire to have a dictionary, I return a sorted list.
I used the accepted answer at In Python, how do I index a list with another list?</p>

```<code>d= {'A': [62, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 58], 'E': [61, 62], 'F': [58, 59]}
myList = [max(value) for key,value in d.items()]
print(myList)
myIndex = sorted(range(len(myList)),key=lambda x:myList[x],reverse=True)
L = [(key,value) for key,value in d.items()]
[L[i] for i in myIndex]
</code>```

Body:
I practice python recently. for a few days my script has stopped, because I'm struggling on a problem.
I want to sort the items by both values which has in common. like an chain. as you can see lower.

what I have:

dic= {'A': [62, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 58], 'E': [61, 62], 'F': [58, 59]}

what I want:

dic={'A': [62, 17], 'E': [31, 62],'C': [60, 31],'B': [3, 60],'F': [58, 3],'D': [57, 58]}

to see clearly:

'A': [62, 17]

'E': [*31*, 62]

'C': [60, *31*]

'B': [3, 60]

'F': [58, 3]

'D': [57, 58]

there is a simple method to sort them ? if the topic already exists,
can you send me the link. i haven't found it.
thank you in advance.
nb. in all case, I know the first and the last value of the chain (17 and 57)

Body:
Given what others have said about the order of a dictionary and violating the posters desire to have a dictionary, I return a sorted list.
I used the accepted answer at In Python, how do I index a list with another list?

d= {'A': [62, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 58], 'E': [61, 62], 'F': [58, 59]}
myList = [max(value) for key,value in d.items()]
print(myList)
myIndex = sorted(range(len(myList)),key=lambda x:myList[x],reverse=True)
L = [(key,value) for key,value in d.items()]
[L[i] for i in myIndex]