问:
Spring Amqp internal NullPointerException on RabbitTemplate convertAndSend
I randomically experience a NullPointerException while trying to publish a message using RabbitTemplate.convertAndSend

I tried both spring-amqp:1.7.6 and spring-amqp:1.7.8 and this should be the relevant part of my dependency tree:

```<code>[INFO] | +- org.springframework.amqp:spring-rabbit:jar:1.7.4.RELEASE:compile
[INFO] | | +- com.rabbitmq:http-client:jar:1.1.1.RELEASE:compile
[INFO] | | \- com.rabbitmq:amqp-client:jar:4.0.3:compile
</code>```

this is the stacktrace of the exception

```<code>org.springframework.amqp.UncategorizedAmqpException: java.lang.NullPointerException
        at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:83)
        at org.springframework.amqp.rabbit.connection.RabbitAccessor.convertRabbitAccessException(RabbitAccessor.java:113)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1461)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1411)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:712)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:813)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:791)

        at io.reactivex.internal.operators.completable.CompletableFromAction.subscribeActual(CompletableFromAction.java:34)
        at io.reactivex.Completable.subscribe(Completable.java:1635)
        at io.reactivex.internal.operators.completable.CompletableCache.subscribeActual(CompletableCache.java:59)
        at io.reactivex.Completable.subscribe(Completable.java:1635)
        at io.reactivex.internal.operators.completable.CompletableSubscribeOn$SubscribeOnObserver.run(CompletableSubscribeOn.java:64)
        at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
        at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
        at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: null
        at sun.reflect.GeneratedMethodAccessor487.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.invoke(CachingConnectionFactory.java:980)
        at com.sun.proxy.$Proxy174.basicPublish(Unknown Source)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.doSend(RabbitTemplate.java:1532)
        at org.springframework.amqp.rabbit.core.RabbitTemplate$3.doInRabbit(RabbitTemplate.java:716)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1455)
        ... 19 common frames omitted
</code>```

Any clue on what might be causing this?

edit: additional infos

i didn't notice the difference between spring-rabbit and spring-amqp at first, but looking inside the jar i have these dependencies:

```<code>128356 Tue May 29 17:50:46 CEST 2018 lib/spring-amqp-1.7.8.RELEASE.jar
469867 Mon Sep 11 15:28:04 CEST 2017 lib/spring-rabbit-1.7.4.RELEASE.jar
481919 Wed Jun 07 15:25:06 CEST 2017 lib/amqp-client-4.0.3.jar
</code>```

答:
I got the same error while publishing randomly in live environment, this is due to creating the channels and not closing them. Rabbitmq has a limit of 5000 channels.
This could not be easily reproducible in test environment as it requires opening 5k channels.</p>

Body:
I randomically experience a NullPointerException while trying to publish a message using RabbitTemplate.convertAndSend

I tried both spring-amqp:1.7.6 and spring-amqp:1.7.8 and this should be the relevant part of my dependency tree:

[INFO] | +- org.springframework.amqp:spring-rabbit:jar:1.7.4.RELEASE:compile
[INFO] | | +- com.rabbitmq:http-client:jar:1.1.1.RELEASE:compile
[INFO] | | \- com.rabbitmq:amqp-client:jar:4.0.3:compile

this is the stacktrace of the exception

org.springframework.amqp.UncategorizedAmqpException: java.lang.NullPointerException
        at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:83)
        at org.springframework.amqp.rabbit.connection.RabbitAccessor.convertRabbitAccessException(RabbitAccessor.java:113)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1461)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1411)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:712)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:813)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:791)

        at io.reactivex.internal.operators.completable.CompletableFromAction.subscribeActual(CompletableFromAction.java:34)
        at io.reactivex.Completable.subscribe(Completable.java:1635)
        at io.reactivex.internal.operators.completable.CompletableCache.subscribeActual(CompletableCache.java:59)
        at io.reactivex.Completable.subscribe(Completable.java:1635)
        at io.reactivex.internal.operators.completable.CompletableSubscribeOn$SubscribeOnObserver.run(CompletableSubscribeOn.java:64)
        at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
        at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
        at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: null
        at sun.reflect.GeneratedMethodAccessor487.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.invoke(CachingConnectionFactory.java:980)
        at com.sun.proxy.$Proxy174.basicPublish(Unknown Source)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.doSend(RabbitTemplate.java:1532)
        at org.springframework.amqp.rabbit.core.RabbitTemplate$3.doInRabbit(RabbitTemplate.java:716)
        at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1455)
        ... 19 common frames omitted

Any clue on what might be causing this?

edit: additional infos

i didn't notice the difference between spring-rabbit and spring-amqp at first, but looking inside the jar i have these dependencies:

128356 Tue May 29 17:50:46 CEST 2018 lib/spring-amqp-1.7.8.RELEASE.jar
469867 Mon Sep 11 15:28:04 CEST 2017 lib/spring-rabbit-1.7.4.RELEASE.jar
481919 Wed Jun 07 15:25:06 CEST 2017 lib/amqp-client-4.0.3.jar


来源: stackexchange

问:
Match calendar days with corresponding overwork rates
I have certain conditions for work rates. For example standard day is 8 hours (MO, TU, WE, TH, FR), extra hours are cost*1,5. Lets say cost is 50. I would like to count them based on week days MO, TU, WE, TH, FR, SA, SU.

How formula should look like for this matter? In my example result should be:

```<code>MO -> (50*8)+(50*1,5)+(50*1,5)
TU -> (50*8)
WE -> (50*8)+(50*1,5)+(50*1,5)
TH -> (50*8)+(50*1,5)+(50*1,5)
FR -> (50*8)+(50*1,5)+(50*1,5)
SA -> SKIP
SU -> SKIP

After all these calculations, sum of all of these
</code>```

I would like to make it work for the whole range somehow so basically compare row 11 to row 9 and do certain calculations based on matches. My real range is =$O$11:$BQS$41

The other way is extract extra hours from the row. They are all over 8 a day. So here we have 2 hours each day except TU. So the calculation would be 8*5+8*50*1,5

答:
It is the easiest if you just add a few more rows.

You need to have for each day:

rate for regular hours (NR);

rate for extra hours (XR);

number of worked normal hours (WN);

number of worked extra hours (WX);

Once you have these, you calculate the payment easily:

```<code>TOTAL = NR * WN + XR * WX
</code>```

You can make it more complicated, to specify for each day the maximum number of normal hours (WNMax) - but the formula gets more complicated.

```<code>if WNMax < WN print error
else TOTAL = NR * WN + XR * WX
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have certain conditions for work rates. For example standard day is 8 hours (MO, TU, WE, TH, FR), extra hours are cost*1,5. Lets say cost is 50. I would like to count them based on week days MO, TU, WE, TH, FR, SA, SU.

How formula should look like for this matter? In my example result should be:

MO -> (50*8)+(50*1,5)+(50*1,5)
TU -> (50*8)
WE -> (50*8)+(50*1,5)+(50*1,5)
TH -> (50*8)+(50*1,5)+(50*1,5)
FR -> (50*8)+(50*1,5)+(50*1,5)
SA -> SKIP
SU -> SKIP

After all these calculations, sum of all of these

I would like to make it work for the whole range somehow so basically compare row 11 to row 9 and do certain calculations based on matches. My real range is =$O$11:$BQS$41

The other way is extract extra hours from the row. They are all over 8 a day. So here we have 2 hours each day except TU. So the calculation would be 8*5+8*50*1,5

Body:
It is the easiest if you just add a few more rows.

You need to have for each day:

rate for regular hours (NR);

rate for extra hours (XR);

number of worked normal hours (WN);

number of worked extra hours (WX);

Once you have these, you calculate the payment easily:

TOTAL = NR * WN + XR * WX

You can make it more complicated, to specify for each day the maximum number of normal hours (WNMax) - but the formula gets more complicated.

if WNMax < WN print error
else TOTAL = NR * WN + XR * WX


问:
[PHP][LARAVEL] "Class 'App\User' not found" but there is clearly 'use App\User;' in the code
I'm using some very simple code in "api.php" in Laravel and this error is driving me nuts.

Code:

```<code><?php

use Illuminate\Http\Request;
use App\User;

// list new user
Route::get('users', function() {
    // If the Content-Type and Accept headers are set to 'application/json',
    // this will return a JSON structure. This will be cleaned up later.
    return User::all();
});

// create new user
Route::post('users/add', function(Request $request) {
    return User::create($request->all);
});
</code>```

Error:

Class 'App\User' not found

How is this even possible?

答:
Hi can you please verify that the namespace on top of User.php model is namespace App;?

Something like:

```<code><?php
namespace App;

use Illuminate\Notifications\Notifiable;`
use Illuminate\Notifications\MustVerifyEmail;
</code>```

Body:
I'm using some very simple code in "api.php" in Laravel and this error is driving me nuts.

Code:

<?php

use Illuminate\Http\Request;
use App\User;

// list new user
Route::get('users', function() {
    // If the Content-Type and Accept headers are set to 'application/json',
    // this will return a JSON structure. This will be cleaned up later.
    return User::all();
});

// create new user
Route::post('users/add', function(Request $request) {
    return User::create($request->all);
});

Error:

Class 'App\User' not found

How is this even possible?

Body:
Hi can you please verify that the namespace on top of User.php model is namespace App;?

Something like:

<?php
namespace App;

use Illuminate\Notifications\Notifiable;`
use Illuminate\Notifications\MustVerifyEmail;


问:
Does shapely LineString intersection works wrong?
While working with shapely I faced a strange issue. There're 2 points p1 and p2, where the first one belongs to polygon and the second is not. When I tried to find intersection between the LineString containing these 2 points as endpoints with boundary lines of the Polygon, I received message that no intersection was found. I wonder, how is it possible?

```<code>from shapely.geometry import Polygon as SPolygon, Point, LineString

p1 = Point(5.414213562373095, 2.585786437626905)
p2 = Point(15.17279752753168, -7.172797527531679)

l = LineString([p1, p2])

l1 = LineString([(2, 2), (2, 6)])
l2 = LineString([(2, 6), (6, 6)])
l3 = LineString([(6, 6), (6, 2)])
l4 = LineString([(6, 2), (2, 2)])

sp = SPolygon([(2, 2), (2, 6), (6, 6), (6, 2)])

print "Polygon contains p1:", sp.contains(p1)
print "Polygon contains p2:", sp.contains(p2)

for i, line in enumerate((l1, l2, l3, l4)):
    res = l.intersects(line)
    print "Line {0} intersects l1: {1}".format(i, res)

</code>```

And here are output:

```<code>Polygon contains p1: True
Polygon contains p2: False
Line 0 intersects l1: False
Line 1 intersects l1: False
Line 2 intersects l1: False
Line 3 intersects l1: False
</code>```

答:
I changed l.intersects(line) to l.intersection(line) and I did get an intersection at

```<code>LINESTRING (6 6, 6 2) at Point (6, 2)
</code>```

Not sure why .instersects() is acting differently.

Then I rounded p1 and p2

```<code>p1 = Point(round(5.414213562373095, 2), round(2.585786437626905, 2))
p2 = Point(round(15.17279752753168, 2), round(-7.172797527531679, 2))
</code>```

And I got 2 intersections at

```<code>LINESTRING (6 6, 6 2) at POINT (6 2)
LINESTRING (6 2, 2 2) at POINT (6 2)
</code>```

This fix also worked with .intersects() (2 True's)

Shapely can be a bit touchy with floating point precision, and I usually can fix an issue by rounding. Though this may not be acceptable for you.

Body:
While working with shapely I faced a strange issue. There're 2 points p1 and p2, where the first one belongs to polygon and the second is not. When I tried to find intersection between the LineString containing these 2 points as endpoints with boundary lines of the Polygon, I received message that no intersection was found. I wonder, how is it possible?

from shapely.geometry import Polygon as SPolygon, Point, LineString

p1 = Point(5.414213562373095, 2.585786437626905)
p2 = Point(15.17279752753168, -7.172797527531679)

l = LineString([p1, p2])

l1 = LineString([(2, 2), (2, 6)])
l2 = LineString([(2, 6), (6, 6)])
l3 = LineString([(6, 6), (6, 2)])
l4 = LineString([(6, 2), (2, 2)])

sp = SPolygon([(2, 2), (2, 6), (6, 6), (6, 2)])

print "Polygon contains p1:", sp.contains(p1)
print "Polygon contains p2:", sp.contains(p2)

for i, line in enumerate((l1, l2, l3, l4)):
    res = l.intersects(line)
    print "Line {0} intersects l1: {1}".format(i, res)

And here are output:

Polygon contains p1: True
Polygon contains p2: False
Line 0 intersects l1: False
Line 1 intersects l1: False
Line 2 intersects l1: False
Line 3 intersects l1: False

Body:
I changed l.intersects(line) to l.intersection(line) and I did get an intersection at

LINESTRING (6 6, 6 2) at Point (6, 2)

Not sure why .instersects() is acting differently.

Then I rounded p1 and p2

p1 = Point(round(5.414213562373095, 2), round(2.585786437626905, 2))
p2 = Point(round(15.17279752753168, 2), round(-7.172797527531679, 2))

And I got 2 intersections at

LINESTRING (6 6, 6 2) at POINT (6 2)
LINESTRING (6 2, 2 2) at POINT (6 2)

This fix also worked with .intersects() (2 True's)

Shapely can be a bit touchy with floating point precision, and I usually can fix an issue by rounding. Though this may not be acceptable for you.


问:
Fixed point combinator for mutually recursive functions?
Is there a fixed point combinator for creating tuples of mutually recursive functions?  I.e. I'm looking for something like the Y-Combinator but which takes multiple "recursive"* functions, and will return a tuple of functions?

*: not really recursive of course, as they are written to take themselves (and siblings) as arguments, in the usual Y-Combinator way.

答:
I'm not entirely sure about this one.  I'm still trying to find a formal proof of it.  But it seems to me you don't need one.
In Haskell, if you have something like:

fix :: (a -> a) -> a

fix f = let x = f x in x

main = let { x = ... y ...; y = ... x ... } in x

you can rewrite main to

main = fst $ fix $ \(x, y) -> (... y ..., ... x ...)

But like I said, I'm not 100% sure about this one.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Does SonarCloud's "delete branch" remove the origin branch from your repo?
I'm using SonarCloud to quality control the code that I am writing on my open source project. I have a master (main branch) from which I have develop from which I make all of my feature branch.

SonarCloud is connected to my GitHub repo from which I can do all of my branch manipulation.

Develop is shown to be a short lived branch but I want to convert it to a long lived branch.

From the documentation that Sonar provides https://docs.sonarqube.org/latest/branches/overview/ it says:

Once a branch type has been set, it cannot be changed. Explicitly, you cannot transform a long-lived to short-lived branch, or vice-versa.

I therefore want to:

Delete all of the information that Sonar has about the branch.

Change my "long lived branch regular expression" to mark develop as long lived.

Get Sonar to re-analyse the code on my develop branch.

In order to do this I believe the only way is to delete the branch from Sonar BUT I don't want to delete my source code.

Can anyone confirm the functionality of this "Delete branch" feature?
i.e. Does it delete your origin repo branch?
thank you

答: No. SonarQube wont touch the actual repository. This just deletes the branch information from the SonarQube database.</p>


问:
How to fix: No samples will be generated with the provided ratio settings. (imblearn)
I have this code:

from imblearn.over_sampling import ADASYN

```<code>Y = df.target
X = df.drop('target', axis=1)

ad = ADASYN()
X_adasyn, y_adasyn = ad.fit_sample(X, Y)

getting this error:

ValueError: No samples will be generated with the provided ratio
settings.
</code>```

答:
Make it a two. There is github and it explicitly says:

```<code>if not np.sum(n_samples_generate):
                raise ValueError("No samples will be generated with the"
                                 " provided ratio settings.")
</code>```

but, yeah......#

Body:
I have this code:

from imblearn.over_sampling import ADASYN

Y = df.target
X = df.drop('target', axis=1)

ad = ADASYN()
X_adasyn, y_adasyn = ad.fit_sample(X, Y)

getting this error:

ValueError: No samples will be generated with the provided ratio
settings.

Body:
Make it a two. There is github and it explicitly says:

if not np.sum(n_samples_generate):
                raise ValueError("No samples will be generated with the"
                                 " provided ratio settings.")

but, yeah......#


问:
Why Datatable breaks the last bar using shiny?
We have an shiny app that encapsulate an DT that in turn contains a the green bar as shown at the picture bellow. Is there anyone that faced the same problem with the very last line? Other applications we have up and running works perfectly.

答:
You probably used styleColorBar. With this function, the bar for the cell containing the minimum value has length 0, so the output you get is the expected one. To have a bar with a length proportional to the value, you can use my function styleColorBar2 provided below. This function accepts two colors, one for the negative values and the other one for the positive values.

```<code>library(DT)

modelData <- data.frame(Channel = c("A", "B", "C"),
                        Current = c(2000, 3000, 4000),
                        Modified = c(2500, 3500, 3000),
                        New_Membership = c(500, 500, -1000),
                        stringsAsFactors = FALSE)

styleColorBar2 <- function (data, color1, color2)
{
  M <- max(abs(data), na.rm = TRUE)
  js <- c(
    "value <= 0 ? ",
    sprintf("'linear-gradient(90deg, transparent ' + (1+value/%f) * 100 + '%%, %s ' + (1+value/%f) * 100 + '%%)'",
            M, color1, M),
    " : ",
    sprintf("'linear-gradient(90deg, transparent ' + (1-value/%f) * 100 + '%%, %s ' + (1-value/%f) * 100 + '%%)'",
            M, color2, M)
  )
  JS(js)
}

datatable(
  modelData , selection = 'none', editable = TRUE
) %>% formatStyle(
  'New_Membership',
  background = styleColorBar2(modelData$New_Membership, "red", "lightblue"),
  backgroundSize = '100% 50%',
  backgroundRepeat = 'no-repeat',
  backgroundPosition = 'center'
)
</code>```

Body:
You probably used styleColorBar. With this function, the bar for the cell containing the minimum value has length 0, so the output you get is the expected one. To have a bar with a length proportional to the value, you can use my function styleColorBar2 provided below. This function accepts two colors, one for the negative values and the other one for the positive values.

library(DT)

modelData <- data.frame(Channel = c("A", "B", "C"),
                        Current = c(2000, 3000, 4000),
                        Modified = c(2500, 3500, 3000),
                        New_Membership = c(500, 500, -1000),
                        stringsAsFactors = FALSE)

styleColorBar2 <- function (data, color1, color2)
{
  M <- max(abs(data), na.rm = TRUE)
  js <- c(
    "value <= 0 ? ",
    sprintf("'linear-gradient(90deg, transparent ' + (1+value/%f) * 100 + '%%, %s ' + (1+value/%f) * 100 + '%%)'",
            M, color1, M),
    " : ",
    sprintf("'linear-gradient(90deg, transparent ' + (1-value/%f) * 100 + '%%, %s ' + (1-value/%f) * 100 + '%%)'",
            M, color2, M)
  )
  JS(js)
}

datatable(
  modelData , selection = 'none', editable = TRUE
) %>% formatStyle(
  'New_Membership',
  background = styleColorBar2(modelData$New_Membership, "red", "lightblue"),
  backgroundSize = '100% 50%',
  backgroundRepeat = 'no-repeat',
  backgroundPosition = 'center'
)


问:
Why would one ever want to compile with -O2 instead of -O3
We usually compile with -O2 because -O3 would "trigger subtle bugs".

For our GCC version -O3 enables more aggressive inlining which would actually reveal bugs otherwise unnoticed (e.g. use of uninitialized values from functions taking them as reference arguments or out-of-bounds access for arrays). It seems to me this aggressive inlining also allows a more expressive way of coding with smaller functions and -funswitch-loops helps keeping variable definitions more local in loops.

Given that bugs in our code are orders of magnitude more likely than compiler bugs and that we use -Wall -Wextra without any issues what kind of bugs should we be looking for?

If it matters we use gcc-4.3.2. Compile time is not a major issue for us.

答: Don't kid yourself that compiler bugs aren't lurking out there to make your life hell.  Here's a nasty one which cropped up in Debian last year, and where the fix was to fall back to -O2. </p>


问:
How to route ASP.Net Core api return value to appropriate observable based on data type returned
I have created an ASP.NET Core Web Api backend with an Angular 7 frontend. One of the methods in the Api can return either an object or an array to an Angular service. How do I route to specific observable, based on the data type returned? I am a noob to Angular, so any kind assistance would be appreciated.</p>

```<code>Angular service call to Api:

getLinksFromSitus(situs: any) {
    this.http.post(this.baseUrl + 'getLinksFromSitus', situs).subscribe(data =>
    this.apiData.next(data)
    );
  }

Portion of Web Api that returns array if more than one APN present:

// if more than one item in list, get status information for each and return list to user to select appropriate apn
            if (propApn.Count > 1)
            {
                return Ok(propApn);
            }

Portion of same method to return object if only one value for APN:

var resultsModel = new Results
            {
                ArcGisLink = arcGisLink,
                HistInfoLink = histInfoLink,
                PropInfoLink = propInfoLink
            };

            return Ok(resultsModel);
</code>```

答:
I was able to find a solution that worked...

```<code>getLinksFromSitus(situs: any) {
    this.http.post(this.baseUrl + 'getLinksFromSitus', situs).subscribe(data => {
    if (data.hasOwnProperty('arcGisLink')) {
      this.apiData.next(data);
    } else {
      let vals = [];
      vals = this.apiPropApn.getValue();
      const item = vals.concat(data);
      this.apiPropApn.next(item);
      }
    });
  }
</code>```

So, after subscribing to the HttpResponse, I am able to check if the data in the response contains a known property. If it doesn't contain the known property, then it concatenates the data to a BehaviorSubject array. It works perfectly.

Body:
I have created an ASP.NET Core Web Api backend with an Angular 7 frontend. One of the methods in the Api can return either an object or an array to an Angular service. How do I route to specific observable, based on the data type returned? I am a noob to Angular, so any kind assistance would be appreciated.

Angular service call to Api:

getLinksFromSitus(situs: any) {
    this.http.post(this.baseUrl + 'getLinksFromSitus', situs).subscribe(data =>
    this.apiData.next(data)
    );
  }

Portion of Web Api that returns array if more than one APN present:

// if more than one item in list, get status information for each and return list to user to select appropriate apn
            if (propApn.Count > 1)
            {
                return Ok(propApn);
            }

Portion of same method to return object if only one value for APN:

var resultsModel = new Results
            {
                ArcGisLink = arcGisLink,
                HistInfoLink = histInfoLink,
                PropInfoLink = propInfoLink
            };

            return Ok(resultsModel);

Body:
I was able to find a solution that worked...

getLinksFromSitus(situs: any) {
    this.http.post(this.baseUrl + 'getLinksFromSitus', situs).subscribe(data => {
    if (data.hasOwnProperty('arcGisLink')) {
      this.apiData.next(data);
    } else {
      let vals = [];
      vals = this.apiPropApn.getValue();
      const item = vals.concat(data);
      this.apiPropApn.next(item);
      }
    });
  }

So, after subscribing to the HttpResponse, I am able to check if the data in the response contains a known property. If it doesn't contain the known property, then it concatenates the data to a BehaviorSubject array. It works perfectly.


问:
How to use dispose to prevent memory leak
I've this init state method:

```<code>@override
  void initState() {
    super.initState();

    getNumber(index).then((number) {
      if (number> 1000) {
        number = number/ 1000;
        setState(() {
          flag = true;
          _num = number.toInt().toString();
        });
      } else {
        setState(() {
          _num = number.toInt().toString();
        });
      }
    });
  }
</code>```

And i got this error:

This error happens if you call setState() on a State object for a
  widget that no longer appears in the widget tree (e.g., whose parent
  widget no longer includes the widget in its build). This error can
  occur when code calls setState() from a timer or an animation
  callback. The preferred solution is to cancel the timer or stop
  listening to the animation in the dispose() callback. Another solution
  is to check the "mounted" property of this object before calling
  setState() to ensure the object is still in the tree.

This error might indicate a memory leak if setState() is being called
  because another object is retaining a reference to this State object
  after it has been removed from the tree. To avoid memory leaks,
  consider breaking the reference to this object during dispose().

How i use dispose  in the right way?

答:
I can't account for this being a standard, but in my code I usually check for mounted in every Future event; whether it's .then, .catchError, or .whenComplete callbacks.

@override
void initState() {
  super.initState();

  getNumber(index).then((number) {
    if (!mounted) {
      return; // Just do nothing if the widget is disposed.
    }
    // ...
  });
}
```

Body:
I've this init state method:

@override
  void initState() {
    super.initState();

    getNumber(index).then((number) {
      if (number> 1000) {
        number = number/ 1000;
        setState(() {
          flag = true;
          _num = number.toInt().toString();
        });
      } else {
        setState(() {
          _num = number.toInt().toString();
        });
      }
    });
  }

And i got this error:

This error happens if you call setState() on a State object for a
  widget that no longer appears in the widget tree (e.g., whose parent
  widget no longer includes the widget in its build). This error can
  occur when code calls setState() from a timer or an animation
  callback. The preferred solution is to cancel the timer or stop
  listening to the animation in the dispose() callback. Another solution
  is to check the "mounted" property of this object before calling
  setState() to ensure the object is still in the tree.

This error might indicate a memory leak if setState() is being called
  because another object is retaining a reference to this State object
  after it has been removed from the tree. To avoid memory leaks,
  consider breaking the reference to this object during dispose().

How i use dispose  in the right way?


问:
Titanium Alloy ImageView from applicationDataDirectory
I am developing an app that needs to function in an offline mode.
The app has a shop for which I have to download and store product images.
In the 'shop view' I have a collection of products in a ListView.
How can I bind the downloaded images to the alloy ImageView?
The downloaded images are in the applicationDataDirectory.
So somehow I need to be able to access applicationDataDirectory in the Alloy xml.</p>

答: You can use the transform function of the Collection (https://docs.axway.com/bundle/Alloy_allOS_en/page/alloy_collection_and_model_objects.html). There I would check if you are in offline/online mode and change the image path (e.g. online images with URL vs. local images with Ti.Filesystem.applicationDataDirectory + "image-name.jpg")


问:
MIPS using different register types but same solution wise
I am wondering is there any difference when you use different register such as the code below:

Here the correct answer uses register $v0 all the way:

```<code>get_status:
        lui $t0,0xabab
        ori $t0, $t0, 0x0020

        lw $v0,0($t0)
        andi $v0,$v0,0x4
        srl $v0,$v0,2

        jr $ra
</code>```

I used $t1 instead of $v0 above, notice I have a extra sw:

```<code>get_status:
        lui $t0,0xabab
        ori $t0, $t0, 0x0020

        lw $t1,0($t0)
        andi $t1,$t1,0x4
        srl $t1,$t1,2
        sw $t1, 0($t0)

        jr $ra
</code>```

I think both code works the same, what you guys think?

答:
$v0 and $t1 are both call-clobbered general-purpose integer registers.  They're not "different types".

But in the standard MIPS calling convention, $v0 (and sometimes $v1) is where callers expect to find integer return values.  That's why get_status calculates a result in $v0.

I think both code works the same, what you guys think?

Your code modifies the static storage that it loaded from!!!  It's not a get_status anymore.

It's either void update_status(void) or int update_status(void) with a non-standard calling convention (returning in $t1).

This is inefficient:

```<code>lui ...
ori $t0, $t0, 0x0020
lw  $v0,0($t0)
</code>```

Use the immediate offset space of lw to hold the low 16 bits of the static address.  (It's sign extended, vs. ori zero-extending its immediate, but in this case you don't need to adjust the lui because the offset is signed positive.)

```<code>lui ...
lw  $v0, 0x0020($t0)
</code>```

Body:
I am wondering is there any difference when you use different register such as the code below:

Here the correct answer uses register $v0 all the way:

get_status:
        lui $t0,0xabab
        ori $t0, $t0, 0x0020

        lw $v0,0($t0)
        andi $v0,$v0,0x4
        srl $v0,$v0,2

        jr $ra

I used $t1 instead of $v0 above, notice I have a extra sw:

get_status:
        lui $t0,0xabab
        ori $t0, $t0, 0x0020

        lw $t1,0($t0)
        andi $t1,$t1,0x4
        srl $t1,$t1,2
        sw $t1, 0($t0)

        jr $ra

I think both code works the same, what you guys think?

Body:
$v0 and $t1 are both call-clobbered general-purpose integer registers.  They're not "different types".

But in the standard MIPS calling convention, $v0 (and sometimes $v1) is where callers expect to find integer return values.  That's why get_status calculates a result in $v0.

I think both code works the same, what you guys think?

Your code modifies the static storage that it loaded from!!!  It's not a get_status anymore.

It's either void update_status(void) or int update_status(void) with a non-standard calling convention (returning in $t1).

This is inefficient:

lui ...
ori $t0, $t0, 0x0020
lw  $v0,0($t0)

Use the immediate offset space of lw to hold the low 16 bits of the static address.  (It's sign extended, vs. ori zero-extending its immediate, but in this case you don't need to adjust the lui because the offset is signed positive.)

lui ...
lw  $v0, 0x0020($t0)


问:
Why *this* is not *this*?
I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

```<code><html>
<head>
<script type="text/javascript">
var EpisodeFeedParser = function(url){
    this.url = url;
    this.didStartCallback = null;
};
EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
};

var EpisodeController = function(){
    this.episodes = new Array();
    this.parser = null; //lazy
};
EpisodeController.prototype.parserDidStart = function(parser){
    console.log("here *this* is not of type EpisodeController but it is EpisodeFeedParser Why?");
    this.testEpi(); //**********ERROR HERE!***********
};
EpisodeController.prototype.fetchEpisodes = function(urlString){
    if(urlString !== undefined){
        if(parser === undefined){
            var parser = new EpisodeFeedParser(urlString);
            parser.didStartCallback = this.parserDidStart;
            this.parser = parser;
        }
        this.parser.parse();
    }
};
EpisodeController.prototype.testEpi = function(){
console.log("it worked!");
};

function testEpisode(){
    var controller = new EpisodeController();
    controller.fetchEpisodes("myurl");
}
</script>
</head>
<body>
<button type="button" onclick="testEpisode()">press me</button>
</body>
</html>
</code>```

答:
Try:

```<code>var that = this;
parser.didStartCallback = function(parser) {
  that.parserDidStart(parser);
};
</code>```

This creates a closure that passes in the correct scope to parserDidStart. Currently, when you call this.parser.parse(), it passes the EpisodeFeedParser as context, as that's where it's called from. It's one of the quirks of scope in JavaScript, and can be pretty frustrating.

Title: Why *this* is not *this*?

Body:
I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

<button type="button" onclick="testEpisode()">press me</button>

Body:
Try:

var that = this;
parser.didStartCallback = function(parser) {
  that.parserDidStart(parser);
};

This creates a closure that passes in the correct scope to parserDidStart. Currently, when you call this.parser.parse(), it passes the EpisodeFeedParser as context, as that's where it's called from. It's one of the quirks of scope in JavaScript, and can be pretty frustrating.


答:
Try to refresh existing composer files:

composer dump-autoload
```

Also, check your "autoload" section in composer.json.

Title: [PHP][LARAVEL] "Class 'App\User' not found" but there is clearly 'use App\User;' in the code

Body:
Try to refresh existing composer files:

composer dump-autoload

Also, check your "autoload" section in composer.json.


问:
Resources that don't persist data
JSON-API expects me to provide an id with the resources we create and move around. But how do we handle cases where the resource doesn't have a natural ID?

A good example is a quote system where the price needs to be determined server side. In this case, we don't give the client the price-book to work out the price themselves, the client needs to submit something to the API so the server can determine the price.

However, we don't want the quote to be persisted to a DB yet because it is not technically "locked in", the client is just playing with options before proceeding"

One way I thought of is to create a UUID for the quote in the pending state

For example

```<code>POST /quotes
{ "data": { "type": "quotes", "attributes": {
    "state": "pending", <all the items>
    } }
returns
{ "data": { "type": "quotes", "id": <UUID>, "attributes": {
    "price": 900, "state": "pending", <all the items>
    } }
</code>```

Now I have the price in the response but I can't get it at a defined url like /quote/1234 yet.

Then once state updates to "quoted" I can physically save to DB, get a proper ID and the client can GET /quote/1234 to see the submitted quote and its price.

The alternative is to create intent resources that model the intention to get a price or fulfil some workflow. I just don't know how you would implement that within a JSON-API context because, again, there aren't IDs.

How should one handle these dynamic/calculated/ephemeral resource endpoints?

答:
I would create a separate table for these pre-quote requests. I can think of several reasons why you would want these captured in a DB, you can have all sorts of metrics like how many times they played with the options, during what time, how long did it take them to create an actual quote etc etc. You can then limit those requests, you can stop the spam of such requests etc.

Once a pre-quote becomes an actual quote, at that point you can move the data to your Quotes table and can use the API properly, because you now have IDs from pre-quotes you can work with. It seems to me that you simplify everything if you just store those in the DB and assign them a proper ID from the beginning.

Title: Resources that don't persist data

Body:
JSON-API expects me to provide an id with the resources we create and move around. But how do we handle cases where the resource doesn't have a natural ID?

A good example is a quote system where the price needs to be determined server side. In this case, we don't give the client the price-book to work out the price themselves, the client needs to submit something to the API so the server can determine the price.

However, we don't want the quote to be persisted to a DB yet because it is not technically "locked in", the client is just playing with options before proceeding"

One way I thought of is to create a UUID for the quote in the pending state

For example

POST /quotes
{ "data": { "type": "quotes", "attributes": {
    "state": "pending", <all the items>
    } }
returns
{ "data": { "type": "quotes", "id": <UUID>, "attributes": {
    "price": 900, "state": "pending", <all the items>
    } }

Now I have the price in the response but I can't get it at a defined url like /quote/1234 yet.

Then once state updates to "quoted" I can physically save to DB, get a proper ID and the client can GET /quote/1234 to see the submitted quote and its price.

The alternative is to create intent resources that model the intention to get a price or fulfil some workflow. I just don't know how you would implement that within a JSON-API context because, again, there aren't IDs.

How should one handle these dynamic/calculated/ephemeral resource endpoints?


问:
How to change stroke color of CAShaperLayer on button click
I am have create some custom layer and added on UIView ,i have two CAShaper Layer but i am just showing only one example here

```<code>    hexBorderOtline = CAShapeLayer()
    hexBorderOtline.name = "dhiru_border_hidden"
    hexBorderOtline.path = path2.cgPath
    hexBorderOtline.lineCap = .round
    hexBorderOtline.strokeColor = inActiveBorderColor.cgColor
    hexBorderOtline.fillColor = UIColor.clear.cgColor
    self.layer.addSublayer(hexBorderOtline)
</code>```

I want to change it's border color when button is clicked.

```<code>func btnAction()
{
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
}
</code>```

But this is not working , i am posting one reference image  what i need to do on button click .

答:
If you are having only 2 layers which shows active and inactive modes with colours you can create two separate layers with different stroke colour and add them as a sublayers into the main layer. The default layer colour which you want to show should be added afterwards. When the button is clicked then you need to only hide/show the sublayers and you will be good to go.

Hope this helps.

Body:
I am have create some custom layer and added on UIView ,i have two CAShaper Layer but i am just showing only one example here

    hexBorderOtline = CAShapeLayer()
    hexBorderOtline.name = "dhiru_border_hidden"
    hexBorderOtline.path = path2.cgPath
    hexBorderOtline.lineCap = .round
    hexBorderOtline.strokeColor = inActiveBorderColor.cgColor
    hexBorderOtline.fillColor = UIColor.clear.cgColor
    self.layer.addSublayer(hexBorderOtline)

I want to change it's border color when button is clicked.

func btnAction()
{
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
}

But this is not working , i am posting one reference image  what i need to do on button click .


问:
Debugging macro with the help of gdb
I know the that the alternative approach is to convert the macro to inline function which will allow the gdb to step into it.

But I want to know if there is any way by which I can debug through each line of a macro definition by using gdb like any other function.

e.g. in the below code snippet.

```<code>#define print_macro printf("We're inside the macro now");\
     for(int i=0; i<100; i++) \
     { \
          if(i%2 == 0) \
              printf("%d is even number", i); \
          else \
              printf("%d is odd number);\
     }

int main()
{
    print_macro;
    return 0;
}
</code>```

In the gdb prompt can we break in main and then step into print_macro and go through each line of it's definition one by one by using next

答:
The debugging difficulty is one of the reasons why macros should be avoided. No, you cannot debug macro commands line by line, you can not set breakpoint in macro, you can not see variables values in the macro etc. The reasons for this are at least two:

Technical. The compiler doesn't know anything about macros expansion at all. All macros are expanded by the preprocessor before the compiler is called. The compiler will not be able to add debugging information for addressing macro lines, compiler doesn't have it! So debugger can only assume how exactly the preprocessor performs macro expansion.

Logical. The output C++ code command does not necessarily correspond to one line of (one) macro. Structurally and syntactically, the macro code may absolutely not be like C++ code. Such line by line macro debugging seems logical only for simple examples like yours where the resulting C++ code is easily viewed (easily for you, not for debugger!). But consider a more convoluted example. At what line debugger should indicate in this example? I think ASSIGN(VAR(INT, i), 10); the only logical option.

```<code>#define INT int
#define VAR(TYPE, NAME)  TYPE NAME
#define ASSIGN(V, VAL) V = VAL

ASSIGN(VAR(INT, i), 10);
</code>```

You cannot debug macros as С++ code since they are not directly С++ code! However, you can expand a macro for debugging as advised. If you need flexibility like macros but without debugging problems, use template functions.

Title: Debugging macro with the help of gdb

Body:
I know the that the alternative approach is to convert the macro to inline function which will allow the gdb to step into it.

But I want to know if there is any way by which I can debug through each line of a macro definition by using gdb like any other function.

e.g. in the below code snippet.

#define print_macro printf("We're inside the macro now");\
     for(int i=0; i<100; i++) \
     { \
          if(i%2 == 0) \
              printf("%d is even number", i); \
          else \
              printf("%d is odd number);\
     }

int main()
{
    print_macro;
    return 0;
}

In the gdb prompt can we break in main and then step into print_macro and go through each line of it's definition one by one by using next

Body:
The debugging difficulty is one of the reasons why macros should be avoided. No, you cannot debug macro commands line by line, you can not set breakpoint in macro, you can not see variables values in the macro etc. The reasons for this are at least two:

Technical. The compiler doesn't know anything about macros expansion at all. All macros are expanded by the preprocessor before the compiler is called. The compiler will not be able to add debugging information for addressing macro lines, compiler doesn't have it! So debugger can only assume how exactly the preprocessor performs macro expansion.

Logical. The output C++ code command does not necessarily correspond to one line of (one) macro. Structurally and syntactically, the macro code may absolutely not be like C++ code. Such line by line macro debugging seems logical only for simple examples like yours where the resulting C++ code is easily viewed (easily for you, not for debugger!). But consider a more convoluted example. At what line debugger should indicate in this example? I think ASSIGN(VAR(INT, i), 10); the only logical option.

#define INT int
#define VAR(TYPE, NAME)  TYPE NAME
#define ASSIGN(V, VAL) V = VAL

ASSIGN(VAR(INT, i), 10);

You cannot debug macros as С++ code since they are not directly С++ code! However, you can expand a macro for debugging as advised. If you need flexibility like macros but without debugging problems, use template functions.


问:
Set authorization header param in interceptor.module.ts
I need to send an authorization token into every request's header and I can't find a proper way to set params into intercepetor.module.ts code.

Here's an extract from my Angular interceptor.module.ts

```<code>intercept(
        req: HttpRequest<any>,
        next: HttpHandler,
    ): Observable<HttpEvent<any>> {

        console.warn("Loader Started - HTTP request: " + req.url);

        let dupReq = req.clone({
            setHeaders:{
                'Content-Type' : 'application/json',
                'Accept'       : 'application/json',
                'Authorization': "Basic "+ myToken
            }
        });

        return next.handle(dupReq).pipe(
            map(event => {
                return event;
            }),
            catchError(error => {
                return Observable.throw(error);
            }),
            finalize(() => {

            })
        );
    }
</code>```

When I go into Chrome's Network tab in debug mode, request's header had no change and it is not showing the 'authorization' param.

I've tried to set the headers thru headers.append() method and it had no difference as well.

答:
```<code>request.clone({
     setHeaders: {
       'Authorization': `Basic ${myToken}`
     }
   });
</code>```

Body:
I need to send an authorization token into every request's header and I can't find a proper way to set params into intercepetor.module.ts code.

Here's an extract from my Angular interceptor.module.ts

intercept(
        req: HttpRequest<any>,
        next: HttpHandler,
    ): Observable<HttpEvent<any>> {

        console.warn("Loader Started - HTTP request: " + req.url);

        let dupReq = req.clone({
            setHeaders:{
                'Content-Type' : 'application/json',
                'Accept'       : 'application/json',
                'Authorization': "Basic "+ myToken
            }
        });

        return next.handle(dupReq).pipe(
            map(event => {
                return event;
            }),
            catchError(error => {
                return Observable.throw(error);
            }),
            finalize(() => {

            })
        );
    }

When I go into Chrome's Network tab in debug mode, request's header had no change and it is not showing the 'authorization' param.

I've tried to set the headers thru headers.append() method and it had no difference as well.


问:
Adding a new value into the linked list
I'm trying to implement function in linked list which will add a new note.
That new node is a sum of a previous and next node.

Here is my code, but i don't know where is mistake.

```<code>void change(Node *head){

    Node *p = head;
    Node *temp = new Node;
    temp->next = NULL;

    while(p != NULL){
        temp->data = p->data + p->next->data;
        temp->next = p->next;
        p->next = temp;
        p = p->next;
    }
}
</code>```

答:
If head is null, then this function allocates a new Node, but nothing points to the new node, so it will be leaked.

If head isn't null, but is the last (i.e. the only) node of the list, then p->next->data indirects through the null pointer, and the behaviour of the program is undefined.

Otherwise, in the first iteration, p->next = temp; p = p->next; makes p be the same as temp, and in the second iteration p->next = temp; makes the node point to itself, and the loop will never terminate.

Title: Adding a new value into the linked list

Body:
I'm trying to implement function in linked list which will add a new note.
That new node is a sum of a previous and next node.

Here is my code, but i don't know where is mistake.

void change(Node *head){

    Node *p = head;
    Node *temp = new Node;
    temp->next = NULL;

    while(p != NULL){
        temp->data = p->data + p->next->data;
        temp->next = p->next;
        p->next = temp;
        p = p->next;
    }
}


问:
My Bootstrap Nav bar forms like a Table if I use the Bootstrap link
I have a problem with my Nav bar: If I use the stylesheet link from bootstrap

```<code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</code>```

My Nav bar forms like this:
You need at least 10 reputation to post images, so I have to post it like this: https://i.imgur.com/dANnzzG.png

on every routerLink.

My Nav bar component looks like this:

```<code>
        <nav class="navbar navbar-default">
            <ul class="nav navbar-nav">
                    <li>
                            <a routerLinkActive="active" routerLink="">Home</a>
                        </li>
                <li>
                    <a routerLinkActive="active" routerLink="list">List</a>
                </li>
                <li>
                    <a routerLinkActive="active" routerLink="create">Create</a>
                </li>
                <li>
                    <a routerLinkActive="active" routerLink="calendar">Calendar</a>
                </li>
            </ul>
        </nav>
        <div>
        <section>
        <router-outlet></router-outlet>
    </section>
    </div>

</code>```

How can I fix this? Thank You!

答:
You can write this way.</p>

```<code><section class="sidebar">
<div class="collapse navbar-collapse m-0 ad-user sidebar-form" id="navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="dropdown user user-menu">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        <div id="profile_view_image"></div>
                        <span class="hidden-xs">{{ data }}</span>
                    </a>
                    <ul class="dropdown-menu" style="width: 160px; !important">
                        <li><a href="{{ route('page') }}"><i class="fa fa-user"></i> </a></li>
                        <li><a href="{{ route('page2') }}"><i class="fa fa-key"></i> </a></li>
                        <form id="logout-form" action="{{ route('page') }}" method="POST" style="display: none;">
                        </form> -->
                    </ul>
                </li>
            </ul>
        </div>
</section>
</code>```

Body:
I have a problem with my Nav bar: If I use the stylesheet link from bootstrap

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

My Nav bar forms like this:
You need at least 10 reputation to post images, so I have to post it like this: https://i.imgur.com/dANnzzG.png

on every routerLink.

My Nav bar component looks like this:

                            Home

                    List

                    Create

                    Calendar

        <router-outlet></router-outlet>

How can I fix this? Thank You!

Body:
You can write this way.

<section class="sidebar">
<div class="collapse navbar-collapse m-0 ad-user sidebar-form" id="navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="dropdown user user-menu">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        <div id="profile_view_image"></div>
                        <span class="hidden-xs">{{ data }}</span>
                    </a>
                    <ul class="dropdown-menu" style="width: 160px; !important">
                        <li><a href="{{ route('page') }}"><i class="fa fa-user"></i> </a></li>
                        <li><a href="{{ route('page2') }}"><i class="fa fa-key"></i> </a></li>
                        <form id="logout-form" action="{{ route('page') }}" method="POST" style="display: none;">
                        </form> -->
                    </ul>
                </li>
            </ul>
        </div>
</section>


问:
WordSegmentation in SymSpellPlusPlus
I'd like to use C++ version of SymSpell, which is called SymSpellPlusPlus. In C# version using WordSegmentation looks like this (from the first link):

```<code>//word segmentation and correction for multi-word input strings with/without spaces
inputTerm="thequickbrownfoxjumpsoverthelazydog";
maxEditDistance = 0;
suggestion = symSpell.WordSegmentation(input);

//display term and edit distance
Console.WriteLine(suggestion.correctedString + " " + suggestion.distanceSum.ToString("N0"));
</code>```

In C++ version method WordSegmentation returns shared pointer (from the second link):

```<code>     ...
     shared_ptr<WordSegmentationItem> WordSegmentation(const char* input)
        {
            return WordSegmentation(input, this->maxDictionaryEditDistance, this->maxDictionaryWordLength);
        }

     shared_ptr<WordSegmentationItem> WordSegmentation(const char* input, size_t maxEditDistance)
        {
            return WordSegmentation(input, maxEditDistance, this->maxDictionaryWordLength);
        }

     shared_ptr<WordSegmentationItem> WordSegmentation(const char* input, size_t maxEditDistance, size_t maxSegmentationWordLength)
        {
          // lines 1039 - 1179 under second link
          std::vector<shared_ptr<WordSegmentationItem>> compositions;
          ...
          return compositions[circularIndex];
        }
</code>```

In my code I tried among others the following code:

```<code>const char* inputTerm = "whereis th elove hehad dated forImuch of thepast who couqdn'tread in sixtgrade and ins pired him";
auto suggestions = symSpell.WordSegmentation(inputTerm);
</code>```

But it gives an error:

```<code>free() invalid next size (fast)
</code>```

It is related to memory error, but I don't know how to overcome this problem.

Class WordSegmentationItem looks as follows (lines 292-325 in second link):

```<code>class WordSegmentationItem
    {
    public:
        const char* segmentedString{ nullptr };
        const char* correctedString{ nullptr };
        u_int8_t distanceSum = 0;
        double probabilityLogSum = 0;

        WordSegmentationItem() { }
        WordSegmentationItem(const symspell::WordSegmentationItem & p)
        {
            this->segmentedString = p.segmentedString;
            this->correctedString = p.correctedString;
            this->distanceSum = p.distanceSum;
            this->probabilityLogSum = p.probabilityLogSum;
        }

        WordSegmentationItem& operator=(const WordSegmentationItem&) { return *this; }
        WordSegmentationItem& operator=(WordSegmentationItem&&) { return *this; }

        void set(const char* pSegmentedString, const char* pCorrectedString, u_int8_t pDistanceSum, double pProbabilityLogSum)
        {
            this->segmentedString = pSegmentedString;
            this->correctedString = pCorrectedString;
            this->distanceSum = pDistanceSum;
            this->probabilityLogSum = pProbabilityLogSum;
        }

        ~WordSegmentationItem()
        {
            delete[] segmentedString;
            delete[] correctedString;
        }
};
</code>```

How should I get the correctedString from the WordSegmentationItem?

答:
The library is buggy and the author needs to make some fixes.

First, compiling gives us a warning about SuggestItem::ShallowCopy, which returns a local variable by reference. Very bad! We can change that to return by value, probably.

This doesn't fix the crash, though.

If we clone the library's repo then run the following testcase in a debugger:

```<code>#include "symspell6.h"

int main()
{
    const char* inputTerm = "whereis th elove hehad dated forlmuch of thepast who couqdn'tread in sixtgrade and ins pired him";

    symspell::SymSpell symSpell;
    auto suggestions = symSpell.WordSegmentation(inputTerm);
}
</code>```

…we see that returning compositions[circularIndex] from the WordSegmentation function is causing an invalid access in the shared_ptr constructor. This suggests that circularIndex is out-of-bounds and giving us a non-existent shared_ptr. Indeed, circularIndex is 95 but compositions.size() is 0!

The function is lacking some serious error checking.

Now, only the author (or at least someone who knows what the library is supposed to do; that's not me!) can fix this properly. But as a quick patch I added the following after line 1055:

```<code>if (compositions.empty())
   return nullptr;
</code>```

…and it now at least runs.

It seems that the function assumes the dictionary is non-empty. I don't know whether that's expected behaviour or not (other than the missing error checking as detailed above).

The project is in serious need of some documentation, because no preconditions or postconditions are mentioned for these functions and there is no indication as to how the library is supposed to be used. Again, the author should fix these things.

Title: WordSegmentation in SymSpellPlusPlus

Body:
I'd like to use C++ version of SymSpell, which is called SymSpellPlusPlus. In C# version using WordSegmentation looks like this (from the first link):

//word segmentation and correction for multi-word input strings with/without spaces
inputTerm="thequickbrownfoxjumpsoverthelazydog";
maxEditDistance = 0;
suggestion = symSpell.WordSegmentation(input);

//display term and edit distance
Console.WriteLine(suggestion.correctedString + " " + suggestion.distanceSum.ToString("N0"));

In C++ version method WordSegmentation returns shared pointer (from the second link):

     ...
     shared_ptr<WordSegmentationItem> WordSegmentation(const char* input)
        {
            return WordSegmentation(input, this->maxDictionaryEditDistance, this->maxDictionaryWordLength);
        }

     shared_ptr<WordSegmentationItem> WordSegmentation(const char* input, size_t maxEditDistance)
        {
            return WordSegmentation(input, maxEditDistance, this->maxDictionaryWordLength);
        }

     shared_ptr<WordSegmentationItem> WordSegmentation(const char* input, size_t maxEditDistance, size_t maxSegmentationWordLength)
        {
          // lines 1039 - 1179 under second link
          std::vector<shared_ptr<WordSegmentationItem>> compositions;
          ...
          return compositions[circularIndex];
        }

In my code I tried among others the following code:

const char* inputTerm = "whereis th elove hehad dated forImuch of thepast who couqdn'tread in sixtgrade and ins pired him";
auto suggestions = symSpell.WordSegmentation(inputTerm);

But it gives an error:

free() invalid next size (fast)

It is related to memory error, but I don't know how to overcome this problem.

Class WordSegmentationItem looks as follows (lines 292-325 in second link):

class WordSegmentationItem
    {
    public:
        const char* segmentedString{ nullptr };
        const char* correctedString{ nullptr };
        u_int8_t distanceSum = 0;
        double probabilityLogSum = 0;

        WordSegmentationItem() { }
        WordSegmentationItem(const symspell::WordSegmentationItem & p)
        {
            this->segmentedString = p.segmentedString;
            this->correctedString = p.correctedString;
            this->distanceSum = p.distanceSum;
            this->probabilityLogSum = p.probabilityLogSum;
        }

        WordSegmentationItem& operator=(const WordSegmentationItem&) { return *this; }
        WordSegmentationItem& operator=(WordSegmentationItem&&) { return *this; }

        void set(const char* pSegmentedString, const char* pCorrectedString, u_int8_t pDistanceSum, double pProbabilityLogSum)
        {
            this->segmentedString = pSegmentedString;
            this->correctedString = pCorrectedString;
            this->distanceSum = pDistanceSum;
            this->probabilityLogSum = pProbabilityLogSum;
        }

        ~WordSegmentationItem()
        {
            delete[] segmentedString;
            delete[] correctedString;
        }
};

How should I get the correctedString from the WordSegmentationItem?

Body:
The library is buggy and the author needs to make some fixes.

First, compiling gives us a warning about SuggestItem::ShallowCopy, which returns a local variable by reference. Very bad! We can change that to return by value, probably.

This doesn't fix the crash, though.

If we clone the library's repo then run the following testcase in a debugger:

#include "symspell6.h"

int main()
{
    const char* inputTerm = "whereis th elove hehad dated forlmuch of thepast who couqdn'tread in sixtgrade and ins pired him";

    symspell::SymSpell symSpell;
    auto suggestions = symSpell.WordSegmentation(inputTerm);
}

…we see that returning compositions[circularIndex] from the WordSegmentation function is causing an invalid access in the shared_ptr constructor. This suggests that circularIndex is out-of-bounds and giving us a non-existent shared_ptr. Indeed, circularIndex is 95 but compositions.size() is 0!

The function is lacking some serious error checking.

Now, only the author (or at least someone who knows what the library is supposed to do; that's not me!) can fix this properly. But as a quick patch I added the following after line 1055:

if (compositions.empty())
   return nullptr;

…and it now at least runs.

It seems that the function assumes the dictionary is non-empty. I don't know whether that's expected behaviour or not (other than the missing error checking as detailed above).

The project is in serious need of some documentation, because no preconditions or postconditions are mentioned for these functions and there is no indication as to how the library is supposed to be used. Again, the author should fix these things.


问:
How to get many attributes data from a single tag?
I'm unable to get data from a single tag. Single tag have many data attributes like name, phone, company and url. i need to get data from many tags and all tags similar to this one.

HTML Code:

```<code> <div class="ListingDetails">
        <div class="ListingDisplayName">
            <a href="/members/jeremy.counter1/default.aspx">
                Jeremy Counter
            </a>
        </div>
                                        Mortgage Officer  -
        American Pacific Mortgage<br>

       Anchorage, Alaska  99503<br>
                                        phone: (907) 519-
       6656 | (907) 250-0766

      <div class="listingurl">
          <a rel="nofollow" href="http://www.jeremycounter.com" target="_blank">
            jeremycounter.com
          </a>
      </div>
 </div>
</code>```

Python Code:

```<code>data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find('div', class_="CommonContentBox DirectoryListings")

listing_box = page.find('div', class_="BusinessListingUser")
name  = listing_box.find('div', class_="ListingDisplayName").text
#print(name)

details  = listing_box.find('div',
class_="ListingDetails").text.strip('\n\t\r')
print(details)
</code>```

Output:

```<code>Tyler Tullis
                                          -
                                        Montgomery, Alabama  36117
                                         | (334) 322-3707
</code>```

Anyone tell me the best possible solution to get data.

Expected result:

```<code>name: Jeremy Counter

phone: (907) 519-6656

company: American Pacific Mortgage

url: jeremycounter.com
</code>```

答:
Based on your html you can try following code.

```<code>from bs4 import BeautifulSoup
data='''<div class="ListingDetails">
        <div class="ListingDisplayName">
            <a href="/members/jeremy.counter1/default.aspx">
                Jeremy Counter
            </a>
        </div>
                                        Mortgage Officer  -
        American Pacific Mortgage<br>

       Anchorage, Alaska  99503<br>
                                        phone: (907) 519-
       6656 | (907) 250-0766

      <div class="listingurl">
          <a rel="nofollow" href="http://www.jeremycounter.com" target="_blank">
            jeremycounter.com
          </a>
      </div>
 </div>'''

soup=BeautifulSoup(data,'html.parser')

items= soup.find_all('div', class_="ListingDetails")

for item in items:
    print("name: " + item.find('a').text.strip())
    print('company: ' + item.find_all('br')[0].previous_element.strip().split('-')[1].strip())
    print('Phone: ' + item.find_all('br')[1].next_element.strip().split('|')[0].strip())
    print('url: ' + item.find('div',class_='listingurl').find('a').text.strip())
</code>```

Output:

```<code>name: Jeremy Counter
company: American Pacific Mortgage
Phone: phone: (907) 519-
       6656
url: jeremycounter.com
</code>```

Body:
I'm unable to get data from a single tag. Single tag have many data attributes like name, phone, company and url. i need to get data from many tags and all tags similar to this one.

HTML Code:

                Jeremy Counter

                                        Mortgage Officer  -
        American Pacific Mortgage

       Anchorage, Alaska  99503

                                        phone: (907) 519-
       6656 | (907) 250-0766

            jeremycounter.com

Python Code:

data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find('div', class_="CommonContentBox DirectoryListings")

listing_box = page.find('div', class_="BusinessListingUser")
name  = listing_box.find('div', class_="ListingDisplayName").text
#print(name)

details  = listing_box.find('div',
class_="ListingDetails").text.strip('\n\t\r')
print(details)

Output:

Tyler Tullis
                                          -
                                        Montgomery, Alabama  36117
                                         | (334) 322-3707

Anyone tell me the best possible solution to get data.

Expected result:

name: Jeremy Counter

phone: (907) 519-6656

company: American Pacific Mortgage

url: jeremycounter.com

Body:
Based on your html you can try following code.

from bs4 import BeautifulSoup
data='''<div class="ListingDetails">
        <div class="ListingDisplayName">
            <a href="/members/jeremy.counter1/default.aspx">
                Jeremy Counter
            </a>
        </div>
                                        Mortgage Officer&nbsp; -
       &nbsp;American Pacific Mortgage<br>

       Anchorage,&nbsp;Alaska&nbsp;&nbsp;99503<br>
                                        phone:&nbsp;(907) 519-
       6656&nbsp;|&nbsp;(907) 250-0766

      <div class="listingurl">
          <a rel="nofollow" href="http://www.jeremycounter.com" target="_blank">
            jeremycounter.com
          </a>
      </div>
 </div>'''

soup=BeautifulSoup(data,'html.parser')

items= soup.find_all('div', class_="ListingDetails")

for item in items:
    print("name: " + item.find('a').text.strip())
    print('company: ' + item.find_all('br')[0].previous_element.strip().split('-')[1].strip())
    print('Phone: ' + item.find_all('br')[1].next_element.strip().split('|')[0].strip())
    print('url: ' + item.find('div',class_='listingurl').find('a').text.strip())

Output:

name: Jeremy Counter
company: American Pacific Mortgage
Phone: phone: (907) 519-
       6656
url: jeremycounter.com


问:
Expressjs: How to catch form data using POST method?
Guys.

I'm currently building a rather large project and I want to know which the best tool that I can use to catch form data using the POST method. The form is a 'sigin' and 'login' form

I read about 'body-parser' and 'busboy', but I'm a noob and I don't know which is the best choice

答:
I use body-parser. </p>

```<code>const app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
</code>```

<p>Place this before the declaration of your route in your main file. Also - ensure that the form data elements you will be submitting have a name attribute. If there is no name attribute, you will not see the data come through.
Hope this helps :) </p>

Body:
I use body-parser.

const app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

Place this before the declaration of your route in your main file. Also - ensure that the form data elements you will be submitting have a name attribute. If there is no name attribute, you will not see the data come through.
Hope this helps :)


问:
How to use bind_param for deleting from the database?
I have the following method that inserts data to a table I have in my database

```<code>function database_preparedModify($sql, $types, &$insertId, ...$value)
  {
      $statement =  mysqli_prepare(database_link(), $sql);

      $statement->bind_param($types, ...$value);

      $statement->execute();

      $insertId = $statement->insert_id;

      return $statement->affected_rows;
  }
</code>```

A valid use of this function (which works fine) is the following:

```<code>private function saveError(someError $error)
    {
        $sql = 'INSERT INTO stackoverflowErrors (dateTimeTest, errorURL, clientInfo, accountID, actions, message)
                VALUES (?, ?, ?, ?, ?, ?)';
        $insertId = 0;
        database_preparedModify($sql, 'ssssss', $insertId, $error->getTime(), $error->errorURL(), $error->getClientInfo(), $error->getAccountID(), $error->getAction(), $error->getMessage());
    }
</code>```

Where the methods getTime(), errorURL()...etc are in another class and not really relevant for this question.

My question is, how could I use the method database_preparedModify() to delete from the database instead of inserting? I've tried the following:

```<code>$filename = 'some valid filename';
$feed["id"] = $validID;
$insertId = 0;
$sql = "DELETE FROM `".$config_databaseTablePrefix."table1` WHERE filename = '".database_safe($filename)."'";

        database_preparedModify($sql,'s',$insertId, ' ');

$sql = "DELETE FROM `".$config_databaseTablePrefix."table2` WHERE id = '".database_safe($feed["id"])."'";

        database_preparedModify($sql,'s',$insertId, ' ');
</code>```

But I'm getting this error:

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement

答:
You need to use placeholders in your query.

```<code>$sql = "DELETE FROM `".$config_databaseTablePrefix."table1` WHERE filename = ?";
database_preparedModify($sql,'s',$insertId, $filename);
</code>```

and

```<code>$sql = "DELETE FROM `".$config_databaseTablePrefix."table2` WHERE id = ?";
database_preparedModify($sql,'s',$insertId, $feed["id"]);
</code>```

Body:
I have the following method that inserts data to a table I have in my database

function database_preparedModify($sql, $types, &$insertId, ...$value)
  {
      $statement =  mysqli_prepare(database_link(), $sql);

      $statement->bind_param($types, ...$value);

      $statement->execute();

      $insertId = $statement->insert_id;

      return $statement->affected_rows;
  }

A valid use of this function (which works fine) is the following:

private function saveError(someError $error)
    {
        $sql = 'INSERT INTO stackoverflowErrors (dateTimeTest, errorURL, clientInfo, accountID, actions, message)
                VALUES (?, ?, ?, ?, ?, ?)';
        $insertId = 0;
        database_preparedModify($sql, 'ssssss', $insertId, $error->getTime(), $error->errorURL(), $error->getClientInfo(), $error->getAccountID(), $error->getAction(), $error->getMessage());
    }

Where the methods getTime(), errorURL()...etc are in another class and not really relevant for this question.

My question is, how could I use the method database_preparedModify() to delete from the database instead of inserting? I've tried the following:

$filename = 'some valid filename';
$feed["id"] = $validID;
$insertId = 0;
$sql = "DELETE FROM `".$config_databaseTablePrefix."table1` WHERE filename = '".database_safe($filename)."'";

        database_preparedModify($sql,'s',$insertId, ' ');

$sql = "DELETE FROM `".$config_databaseTablePrefix."table2` WHERE id = '".database_safe($feed["id"])."'";

        database_preparedModify($sql,'s',$insertId, ' ');

But I'm getting this error:

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement

Body:
You need to use placeholders in your query.

$sql = "DELETE FROM `".$config_databaseTablePrefix."table1` WHERE filename = ?";
database_preparedModify($sql,'s',$insertId, $filename);

and

$sql = "DELETE FROM `".$config_databaseTablePrefix."table2` WHERE id = ?";
database_preparedModify($sql,'s',$insertId, $feed["id"]);


答:
If I have understood the problem correctly after reviewing the code, the changes made do not persist after the function call.

```<code>void change(Node *head ){
</code>```

to

```<code>void change(Node *& head ){
</code>```

Pls try this.

Edit:-

There are other problems in the code as pointed out by others like

1. Dereferencing a null pointer

2. Invalid memory access.

Title: Adding a new value into the linked list

Body:
If I have understood the problem correctly after reviewing the code, the changes made do not persist after the function call.

void change(Node *head ){

to

void change(Node *& head ){

Pls try this.

Edit:-

There are other problems in the code as pointed out by others like

1. Dereferencing a null pointer

2. Invalid memory access.


问:
How to authorise a role to perform "execute-api:Invoke"?
I'm attempting to move a suite of end-to-end tests so that they are fully contained within AWS. I've done this through code build and gotten everything running up to the point of running the tests, which invoke an API to reset the database before every test run. I keep running into this error message when the first test attempts to run.

StatusCodeError: 403 - "{\"Message\":\"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:eu-west-2:*:*"}"
```

<p>At first, I thought the error was being caused by a lack of permissions on the role that was being used to build everything. I tried adding the correct permissions to IAM Role being used, eventual making them more open than I would like. </p>

```"Effect": "Allow",
"Action": [
    "execute-api:Invoke",
    "execute-api:ManageConnections"
],
"Resource": "arn:aws:execute-api:*:*:*"
```

<p>Obviously didn't fix things but I did notice that the access advisor shows that the particular policy isn't being accessed.</p>

<p>Next, I went into the resource policy in API Gateway to see if there was something there. I removed some Ip Address conditions that were set up to restrict access to the office's Ip Addresses. </p>

<p>I've look inside of WAF and Shield and can't see anything that would be related to invoking the API. At this point I am at a lost on where my next investigation should start.</p>

<p><strong><em>Edit</em></strong></p>

<p>Here's the responce I'm getting back.</p>

```"requestId": "********-82f8-11e9-a732-0b550cf3fcd6",
"ip": "*.*.*.*",
"caller": "-",
"user": "-",
"requestTime": "30/May/2019:16:32:50 +0000",
"httpMethod": "GET",
"resourcePath": "/*/ref-data/{proxy+}", "status": "403", "protocol": "HTTP/1.1", "responseLength": "185"
```

答: In this case it turned out the major blocker was the API gateway IP Restrictions set in the policy were getting in the way. I did not realise that changes made didn't take affect until (re)deployment. Once I did that with updated IP restrictions the API endpoint could be invoked.</p>

Body:
I'm attempting to move a suite of end-to-end tests so that they are fully contained within AWS. I've done this through code build and gotten everything running up to the point of running the tests, which invoke an API to reset the database before every test run. I keep running into this error message when the first test attempts to run.

StatusCodeError: 403 - "{\"Message\":\"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:eu-west-2:*:*"}"

At first, I thought the error was being caused by a lack of permissions on the role that was being used to build everything. I tried adding the correct permissions to IAM Role being used, eventual making them more open than I would like.

"Effect": "Allow",
"Action": [
    "execute-api:Invoke",
    "execute-api:ManageConnections"
],
"Resource": "arn:aws:execute-api:*:*:*"

Obviously didn't fix things but I did notice that the access advisor shows that the particular policy isn't being accessed.

Next, I went into the resource policy in API Gateway to see if there was something there. I removed some Ip Address conditions that were set up to restrict access to the office's Ip Addresses.

I've look inside of WAF and Shield and can't see anything that would be related to invoking the API. At this point I am at a lost on where my next investigation should start.

Edit

Here's the responce I'm getting back.

"requestId": "********-82f8-11e9-a732-0b550cf3fcd6",
"ip": "*.*.*.*",
"caller": "-",
"user": "-",
"requestTime": "30/May/2019:16:32:50 +0000",
"httpMethod": "GET",
"resourcePath": "/*/ref-data/{proxy+}", "status": "403", "protocol": "HTTP/1.1", "responseLength": "185"


问:
Hide router in ngx-admin based on user permissions?
Hide route in ngx-admin based on user permissions?. The user chooses the plans. Based on his plan, hide some routes.</p>

答:
You can hide your routes with ngif based on user's plan and you can check if user can navigate that route with Guard.

Read the Angular documentation about that: Angular Guard


问:
ReduxForm - onSubmit method is not called for submit() function
I have a problem with onSubmit method when it is called from onChange event.

If a form below is submitted by a submit button function buttonOnSubmit is called.

But if the form is submitted by function props.submit() in onChange event, the function buttonOnSubmit is not called.

Do you have idea why? I was trying to find explanation in documentation and also on the internet but I failed.

Thank you.

```<code>  const Form = props => {
    // this method is called if submit button is clicked, it is not called from onChange event
    const buttonOnSubmit = (formData) => {
      return new Promise((resolve, reject) => {
        if (props.onSubmit) {
          props.onSubmit(formData);
        }
      });
    };

    return (
      <form onSubmit={props.handleSubmit(buttonOnSubmit)}>
        ....
      </form>
    );
  };

  return reduxForm({
    form: 'name',
    onChange: (values, dispatch, props) => {
        setTimeout(() => {
          props.submit();
        }, 0);
    }
  })(Form);
</code>```

答:
Hi Wanna help but do you have more codes to share ? This is not complete your code i guess.
reduxForm({
    form: 'name',
    onChange: (values, dispatch, props) => {
        setTimeout(() => {
          props.submit();
        }, 0);
    }
  })(Form);
What is your reduxForm ? </p>

Body:
I have a problem with onSubmit method when it is called from onChange event.

If a form below is submitted by a submit button function buttonOnSubmit is called.

But if the form is submitted by function props.submit() in onChange event, the function buttonOnSubmit is not called.

Do you have idea why? I was trying to find explanation in documentation and also on the internet but I failed.

Thank you.

  const Form = props => {
    // this method is called if submit button is clicked, it is not called from onChange event
    const buttonOnSubmit = (formData) => {
      return new Promise((resolve, reject) => {
        if (props.onSubmit) {
          props.onSubmit(formData);
        }
      });
    };

    return (
      <form onSubmit={props.handleSubmit(buttonOnSubmit)}>
        ....
      </form>
    );
  };

  return reduxForm({
    form: 'name',
    onChange: (values, dispatch, props) => {
        setTimeout(() => {
          props.submit();
        }, 0);
    }
  })(Form);


问:
Default size for database fields
What the size that you use for common database fields, like firstName, lastName, Email, password, etc? I see these common fields in a lot of databases of blogs, forums, e-commerces, etc. But I don't know if there is some reference or default for the size for that common fields. So, I want to know what the method/reference/basis that you to use for selecting size for common fields.</p>

答:
Double your estimates. And then redouble them to accomodate unicode.

Databases which have varchars (almost all do) incur a very small penalty for fields which are designed to hold longer values but do not. You can use that to your advantage.

OwnerDisplayName: Click Ok

Title: Default size for database fields

OwnerDisplayName: Learning


问:
How to display single scalar value in Telerik Report?
I need to show a single value in telerik report. I need to pass report parameters to the function that returns this single value and and display that returned value in a textbox in the body of the report.

How do I do this?

答:
I would suggest adding a property in the the partial class of the report and assign it to the control in the NeedDataSource event handler.

```<code>public partial class SimpleReport : Telerik.Reporting.Report
{
    public int ScalerValue;

    private void Report1_NeedDataSource(object sender, EventArgs e)
    {
         myTextBox.Text = ScalerValue.ToString();
    }
}
</code>```

Body:
I would suggest adding a property in the the partial class of the report and assign it to the control in the NeedDataSource event handler.

public partial class SimpleReport : Telerik.Reporting.Report
{
    public int ScalerValue;

    private void Report1_NeedDataSource(object sender, EventArgs e)
    {
         myTextBox.Text = ScalerValue.ToString();
    }
}


问:
How can i change status to 'ingedient'
I want to change status from 'Niet ingedient' to 'ingedient' with a button click.
I have created a script but I keep getting an error.
Does someone know how I can fix this error?

Error:

```<code>Reverse for '<WSGIRequest: GET '/weekstaat/indienen/26'>' not found.
'<WSGIRequest: GET '/weekstaat/indienen/26'>' is not a valid view function or pattern name.
</code>```

view.py

```<code>    def indienen(request, id):
        global Weekstaat
        weekstaat = Weekstaat.objects.get(pk=id)
        Weekstaat.status = 'Ingedient'
        weekstaat.save()
        return redirect(request, 'weekstaat/index.html')
</code>```

-model

```<code>    class Weekstaat(models.Model):
        id = models.AutoField(primary_key=True, null=False, blank=False)
        status = models.CharField(max_length=11, choices=STATUS_CHOICES, default='Niet ingediend',)
        jaar = models.ForeignKey(Jaar, default=datetime.now().year, null=False, blank=False,on_delete=models.CASCADE)
        week = models.ForeignKey(Week, default=date.today().isocalendar()[1], null=False, blank=False,on_delete=models.CASCADE)
        werknemer = models.ForeignKey(User, related_name='weekstaat_werknemer', null=False, blank=False, default=1,on_delete=models.CASCADE)
        maandag = models.FloatField(null=True, blank=True, default=0)
        dinsdag = models.FloatField(null=True, blank=True, default=0)
        woensdag = models.FloatField(null=True, blank=True, default=0)
        donderdag = models.FloatField(null=True, blank=True, default=0)
        vrijdag = models.FloatField(null=True, blank=True, default=0)
        zaterdag = models.FloatField(null=True, blank=True, default=0)
        zondag = models.FloatField(null=True, blank=True, default=0)

        def __str__(self):
            return str(self.jaar) + ' week ' + str(self.week) + str(self.werknemer) + str(self.status)
</code>```

-html

```<code>    <td class="text-center">
                    <a href="{% url 'weekstaat-indienen' Weekstaat.id  %}">
                      <button class="btn btn-success btn-sm" onclick="bevestigIndienen()">indienen </button>
                    </a>

                  </td>
                  <td class="text-center">
                      <button type="button" class="read-Contract btn btn-sm btn-primary" data-id="{% url 'read_Weekstaat' Weekstaat.id %}">
                        <span class="fa fa-eye"></span>
                      </button>
                      <button type="button" class="update-Contract btn btn-sm btn-primary" data-id="{% url 'update_Weekstaat' Weekstaat.id %}">
                        <span class="fa fa-pencil"></span>
                      </button>
                  </td>
                  </tr>
                  {% endfor %}
                </tbody>
              </table>
            {% else %}
              <p class="text-primary">U heeft nog geen Weekstaat</p>
            {% endif %}
          </div>
        </div>

      </div>
    </div>
  </div>

{% endblock content %}

{% block extrascripts %}
  <script type="text/javascript">

    function bevestigIndienen(){
        if(confirm('U staat op het punt een weekstaat in te dienen. Weet u het zeker?') != true){
            document.getElementById('formulierIndienen').action = '';
            window.location.href = "{% url 'home' %}";
        }
    }
</code>```

答:
You mean render, not redirect.

(But note, you shouldn't really be changing statuses on a GET request. Your form should submit a POST request, and your view should then redirect to another URL after processing the submission.)

Title: How can i change status to 'ingedient'

Body:
I want to change status from 'Niet ingedient' to 'ingedient' with a button click.
I have created a script but I keep getting an error.
Does someone know how I can fix this error?

Error:

Reverse for '<WSGIRequest: GET '/weekstaat/indienen/26'>' not found.
'<WSGIRequest: GET '/weekstaat/indienen/26'>' is not a valid view function or pattern name.

view.py

    def indienen(request, id):
        global Weekstaat
        weekstaat = Weekstaat.objects.get(pk=id)
        Weekstaat.status = 'Ingedient'
        weekstaat.save()
        return redirect(request, 'weekstaat/index.html')

-model

    class Weekstaat(models.Model):
        id = models.AutoField(primary_key=True, null=False, blank=False)
        status = models.CharField(max_length=11, choices=STATUS_CHOICES, default='Niet ingediend',)
        jaar = models.ForeignKey(Jaar, default=datetime.now().year, null=False, blank=False,on_delete=models.CASCADE)
        week = models.ForeignKey(Week, default=date.today().isocalendar()[1], null=False, blank=False,on_delete=models.CASCADE)
        werknemer = models.ForeignKey(User, related_name='weekstaat_werknemer', null=False, blank=False, default=1,on_delete=models.CASCADE)
        maandag = models.FloatField(null=True, blank=True, default=0)
        dinsdag = models.FloatField(null=True, blank=True, default=0)
        woensdag = models.FloatField(null=True, blank=True, default=0)
        donderdag = models.FloatField(null=True, blank=True, default=0)
        vrijdag = models.FloatField(null=True, blank=True, default=0)
        zaterdag = models.FloatField(null=True, blank=True, default=0)
        zondag = models.FloatField(null=True, blank=True, default=0)

        def __str__(self):
            return str(self.jaar) + ' week ' + str(self.week) + str(self.werknemer) + str(self.status)

-html

                      <button class="btn btn-success btn-sm" onclick="bevestigIndienen()">indienen </button>

                      <button type="button" class="read-Contract btn btn-sm btn-primary" data-id="{% url 'read_Weekstaat' Weekstaat.id %}">

                      </button>
                      <button type="button" class="update-Contract btn btn-sm btn-primary" data-id="{% url 'update_Weekstaat' Weekstaat.id %}">

                      </button>

                  {% endfor %}

            {% else %}

U heeft nog geen Weekstaat

            {% endif %}

{% endblock content %}

{% block extrascripts %}


问:
SQL to count number for each value
I have a SQL query and I want to be able to count the total number of priorities which has values set to low, medium, high or unspecified.

Currently it counts to a maximum of 13 rows, i'd expect there to be multiple columns with counts such as... 2, 4, 0

Code:

```<code> SELECT c.Name, COUNT(*) as Count_By_Priority,
 CASE WHEN cb.Priority = 0 THEN "Unspecified" WHEN cb.Priority = 1 THEN "Low" WHEN cb.Priority = 2 THEN "Medium" WHEN cb.Priority = 3 THEN "High" END as PriorityNumber
 FROM TABLE 1 cb
 LEFT JOIN Co c ON c.Id = cb.Id
 WHERE c.Name LIKE %Name%"
 GROUP BY c.Id;
</code>```

It seems to print "Unspecified" for the priority keys when I would be expecting low or alternatives.

答:
I am pretty sure that you can just change your group by clause to group by c.Id, then PriorityNumber:

```<code>SELECT
    c.Name,
    COUNT(*) as Count_By_Priority,
    CASE
        WHEN cb.Priority = 0 THEN "Unspecified"
        WHEN cb.Priority = 1 THEN "Low"
        WHEN cb.Priority = 2 THEN "Medium"
        WHEN cb.Priority = 3 THEN "High"
    END as PriorityNumber
FROM TABLE 1 cb
LEFT JOIN Co c
ON c.Id = cb.Id
WHERE c.Name LIKE %Name%"
GROUP BY c.Id, PriorityNumber;
</code>```

Title: SQL to count number for each value

Body:
I have a SQL query and I want to be able to count the total number of priorities which has values set to low, medium, high or unspecified.

Currently it counts to a maximum of 13 rows, i'd expect there to be multiple columns with counts such as... 2, 4, 0

Code:

 SELECT c.Name, COUNT(*) as Count_By_Priority,
 CASE WHEN cb.Priority = 0 THEN "Unspecified" WHEN cb.Priority = 1 THEN "Low" WHEN cb.Priority = 2 THEN "Medium" WHEN cb.Priority = 3 THEN "High" END as PriorityNumber
 FROM TABLE 1 cb
 LEFT JOIN Co c ON c.Id = cb.Id
 WHERE c.Name LIKE %Name%"
 GROUP BY c.Id;

It seems to print "Unspecified" for the priority keys when I would be expecting low or alternatives.

Body:
I am pretty sure that you can just change your group by clause to group by c.Id, then PriorityNumber:

SELECT
    c.Name,
    COUNT(*) as Count_By_Priority,
    CASE
        WHEN cb.Priority = 0 THEN "Unspecified"
        WHEN cb.Priority = 1 THEN "Low"
        WHEN cb.Priority = 2 THEN "Medium"
        WHEN cb.Priority = 3 THEN "High"
    END as PriorityNumber
FROM TABLE 1 cb
LEFT JOIN Co c
ON c.Id = cb.Id
WHERE c.Name LIKE %Name%"
GROUP BY c.Id, PriorityNumber;


问:
SVG shadow-root is closed
I have tried to animate an svg-sprite with CSS.
I’ve created a sprite and injected it from gulp:

gulp.task('svgstore', function () {
var svgs = gulp
    .src('app/svg/*.svg')
    .pipe(svgmin(function (file) {
        return {
            plugins: [{
                cleanupIDs: {
                    minify: true
                }
            }]
        }
    }))
    .pipe(svgstore({ inlineSvg: true }));

function fileContents (filePath, file) {
    return file.contents.toString();
}

return gulp
    .src('app/*.html')
    .pipe(inject(svgs, { transform: fileContents }))
    .pipe(gulp.dest('app/'))
});
```

<p>…and inserted images from the sprite to HTML:</p>

<pre class="lang-xml prettyprint-override"><code><svg class="icon-ufo" >
    <use xlink:href="img/sprite.svg#ufo" aria-hidden="true"></use>
</svg>
</code>```

And it works well, but the following image shows the shadow DOM is closed.

How I can to animate some styles of this SVG without JavaScript? But if JavaScript is the only way, how to do it better?

答:
You could use "currentColor" property in your fill attribute to styling:

and styles for "icon-ufo" class will be like

```<code>.icon-ufo {
    color: green;
}

.icon-ufo:hover {
   color: red;
}
</code>```

Title: SVG shadow-root is closed

Body:
I have tried to animate an svg-sprite with CSS.
I’ve created a sprite and injected it from gulp:

gulp.task('svgstore', function () {
var svgs = gulp
    .src('app/svg/*.svg')
    .pipe(svgmin(function (file) {
        return {
            plugins: [{
                cleanupIDs: {
                    minify: true
                }
            }]
        }
    }))
    .pipe(svgstore({ inlineSvg: true }));

function fileContents (filePath, file) {
    return file.contents.toString();
}

return gulp
    .src('app/*.html')
    .pipe(inject(svgs, { transform: fileContents }))
    .pipe(gulp.dest('app/'))
});

…and inserted images from the sprite to HTML:

<svg class="icon-ufo" >
    <use xlink:href="img/sprite.svg#ufo" aria-hidden="true"></use>
</svg>

And it works well, but the following image shows the shadow DOM is closed.

How I can to animate some styles of this SVG without JavaScript? But if JavaScript is the only way, how to do it better?

Body:
You could use "currentColor" property in your fill attribute to styling:

and styles for "icon-ufo" class will be like

.icon-ufo {
    color: green;
}

.icon-ufo:hover {
   color: red;
}


问:
How to check the date is empty using python?
The startdate and enddate values are coming from jenkin to lambda.
In this code I am trying to get value using event["start_date"] and event["end_date"] and it's working fine, but if startdate and enddate are not available then the code should automatically take today's and yesterday's date.

I am new to python, can someone help here?

I tried as below but I am getting error.
If I will mention 'startdate and enddate is none' and set both values as none then it's working but I need to implement mentioned in code as I am using AWS lambda with python.

```<code>import datetime
from datetime import timedelta

dateformat = "%Y-%m-%d"
startdate = datetime.datetime.strptime("", dateformat)
enddate = datetime.datetime.strptime("", dateformat)
# Both startdate and enddate values come from Jenkin to lambda  -
event["start_date"] and event["end_date"]
if (startdate and enddate) == "":
    startdate = datetime.date.today()
    enddate = startdate - datetime.timedelta(days = 1)
    print('yesterday : ', enddate)
    print('Today : ', startdate)
</code>```

Current Error Output:

```<code>Traceback (most recent call last):
  File "variable_value_change.py", line 10, in <module>
    startdate = datetime.datetime.strptime("", dateformat)
  File "C:\Users\336635743\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\336635743\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 359, in _strptime
   (data_string, format))
ValueError: time data '' does not match format '%Y-%m-%d'
</code>```

答:
I tried it other way as I was working on python AWS lambda and it works.</p>

```<code>  if "start_date" in event:
        startdate = datetime.datetime.strptime(event["start_date"], dateformat)
        enddate = datetime.datetime.strptime(event["end_date"], dateformat)
</code>```

Body:
The startdate and enddate values are coming from jenkin to lambda.
In this code I am trying to get value using event["start_date"] and event["end_date"] and it's working fine, but if startdate and enddate are not available then the code should automatically take today's and yesterday's date.

I am new to python, can someone help here?

I tried as below but I am getting error.
If I will mention 'startdate and enddate is none' and set both values as none then it's working but I need to implement mentioned in code as I am using AWS lambda with python.

import datetime
from datetime import timedelta

dateformat = "%Y-%m-%d"
startdate = datetime.datetime.strptime("", dateformat)
enddate = datetime.datetime.strptime("", dateformat)
# Both startdate and enddate values come from Jenkin to lambda  -
event["start_date"] and event["end_date"]
if (startdate and enddate) == "":
    startdate = datetime.date.today()
    enddate = startdate - datetime.timedelta(days = 1)
    print('yesterday : ', enddate)
    print('Today : ', startdate)

Current Error Output:

Traceback (most recent call last):
  File "variable_value_change.py", line 10, in <module>
    startdate = datetime.datetime.strptime("", dateformat)
  File "C:\Users\336635743\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\336635743\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 359, in _strptime
   (data_string, format))
ValueError: time data '' does not match format '%Y-%m-%d'

Body:
I tried it other way as I was working on python AWS lambda and it works.

  if "start_date" in event:
        startdate = datetime.datetime.strptime(event["start_date"], dateformat)
        enddate = datetime.datetime.strptime(event["end_date"], dateformat)