问:
App works on emulator but crashes on S8
I am using 2 images for my app's splash screen. The logo in my ImageView (src) and the background in the layout(:background) and although my app works fine on the emulator it crashes on my phone(S8). Below you can see my xml file responsible for my splashScreen and the exception. From what I understand one of those images(or both?) are considered too large for my phone's memory? Their dimension however, are :
logo(1305x641)
background(1688x1125).

Any ideas on how to fix this? I thought of providing different resolution versions of the images but I get lost in the process.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:gravity="center_horizontal|center_vertical"
    tools:context="com.spdesigns.funfacts.SplashScreen">

<ImageView
    android:id="@+id/logoImageView"
    android:layout_width="377dp"
    android:layout_height="293dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:src="@drawable/logo"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>```

Exception:

```<code>11-16 00:11:01.529 3688-3688/com.spdesigns.funfacts E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.spdesigns.funfacts, PID: 3688
                                                                  java.lang.RuntimeException: Canvas: trying to draw too large(120362760bytes) bitmap.
                                                                      at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
                                                                      at android.graphics.Canvas.drawBitmap(Canvas.java:1420)
                                                                      at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
                                                                      at android.widget.ImageView.onDraw(ImageView.java:1286)
                                                                      at android.view.View.draw(View.java:18394)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17372)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.draw(View.java:18397)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17372)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17367)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17367)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17367)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17367)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.draw(View.java:18397)
                                                                      at com.android.internal.policy.DecorView.draw(DecorView.java:967)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17372)
                                                                      at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:722)
                                                                      at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:728)
                                                                      at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:836)
                                                                      at android.view.ViewRootImpl.draw(ViewRootImpl.java:3181)
                                                                      at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2977)
                                                                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2565)
                                                                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1550)
                                                                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7189)
                                                                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:959)
                                                                      at android.view.Choreographer.doCallbacks(Choreographer.java:734)
                                                                      at android.view.Choreographer.doFrame(Choreographer.java:670)
                                                                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:945)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

答:
You're trying to load a 120 MB image into memory.
That's about 20 times bigger than any image that should ever be loaded.

It works fine on emulators, as they can utilize your computers memory, and perhaps have looser rules on memory consumption. But real devices are much stricter.

You should do the following:

1) Scale down the image further

2) Run PNGCrush on all images in your app. It's a program that reduces memory size of images without loosing quality (read their documentation for specifics)

3) Provide different size images for hdpi, xhdpi, xxhdpi and xxxhdpi densities. This way the system loads the appropriate image according to the screen size.

Title: App works on emulator but crashes on S8

Body:
I am using 2 images for my app's splash screen. The logo in my ImageView (src) and the background in the layout(:background) and although my app works fine on the emulator it crashes on my phone(S8). Below you can see my xml file responsible for my splashScreen and the exception. From what I understand one of those images(or both?) are considered too large for my phone's memory? Their dimension however, are :
logo(1305x641)
background(1688x1125).

Any ideas on how to fix this? I thought of providing different resolution versions of the images but I get lost in the process.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:gravity="center_horizontal|center_vertical"
    tools:context="com.spdesigns.funfacts.SplashScreen">

<ImageView
    android:id="@+id/logoImageView"
    android:layout_width="377dp"
    android:layout_height="293dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:src="@drawable/logo"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Exception:

11-16 00:11:01.529 3688-3688/com.spdesigns.funfacts E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.spdesigns.funfacts, PID: 3688
                                                                  java.lang.RuntimeException: Canvas: trying to draw too large(120362760bytes) bitmap.
                                                                      at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
                                                                      at android.graphics.Canvas.drawBitmap(Canvas.java:1420)
                                                                      at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
                                                                      at android.widget.ImageView.onDraw(ImageView.java:1286)
                                                                      at android.view.View.draw(View.java:18394)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17372)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.draw(View.java:18397)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17372)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17367)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17367)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17367)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17367)
                                                                      at android.view.View.draw(View.java:18156)
                                                                      at android.view.ViewGroup.drawChild(ViewGroup.java:3969)
                                                                      at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3755)
                                                                      at android.view.View.draw(View.java:18397)
                                                                      at com.android.internal.policy.DecorView.draw(DecorView.java:967)
                                                                      at android.view.View.updateDisplayListIfDirty(View.java:17372)
                                                                      at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:722)
                                                                      at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:728)
                                                                      at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:836)
                                                                      at android.view.ViewRootImpl.draw(ViewRootImpl.java:3181)
                                                                      at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2977)
                                                                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2565)
                                                                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1550)
                                                                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7189)
                                                                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:959)
                                                                      at android.view.Choreographer.doCallbacks(Choreographer.java:734)
                                                                      at android.view.Choreographer.doFrame(Choreographer.java:670)
                                                                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:945)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)


来源: stackexchange

问:
How to configure MuleSoft with Maven?
I am trying to create my first MuleSoft application using Maven. I have used CMD to confirm that both Java and Maven are installed. I've also configured my environment variables.

I then open the MuleSoft Anypoint Studio, and create my first named "mulesoft-sample" I select to use Maven, and leave all default settings as they are.

Once I click finish, the Console begins to download a number of files
These continue to be downloaded until after it would seem the near end of the files, it throws an error:

There was an error running the studio:studio goal on project mulesoft-sample

In Console, I see the errors listed below.

I was originally trying to use the latest version of Maven (3.5.0). However, I found a video tutorial that said 3.3.9 was a verified version for MuleSoft. So I thought perhaps the newest version wasn't supported and instead used 3.3.9. However, it is still failing. I've also tried changing the environment variable to other options, such as going straight to \bin, rather than the complete directory (taking shots in the dark here). Unfortunately, nothing has worked and I'm running out of option.

Can anyone tell me why I'm getting these errors, and my build will not succeed? How to correct the error?

答:
Mule Maven Plugin configuration.
1.1. Use mule mule-app-maven-plugin to build the application.

```<code><plugin>
        <groupId>org.mule.tools.maven</groupId>
        <artifactId>mule-app-maven-plugin</artifactId>
        <version>${mule.tools.version}</version>
        <extensions>true</extensions>
        <configuration>
        <copyToAppsDirectory>false</copyToAppsDirectory>
        </configuration>
    </plugin>
</code>```

No need for additional Mule Maven plugins.
  This is the default mule plugin set when creating your Mule project on AnyPoint (AP) Studio.

```<code>1.2. Make sure you set flag copyToAppsDirectory to false.
       This flag is set to true by default so you must change it manually.
</code>```

Maven Dependency Plugin Configuration.
2.1. Now we need to add a plugin to copy the generated artifact to the MULE_HOME/apps directory, i.e. to deploy the application to the standalone local mule server.
       We will use the maven-dependency-plugin.
       Just add these plugin after the mule maven plugin section in your application pom.xml.

```<code>              <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>2.10</version>
                    <executions>
                        <execution>
                            <id>copy</id>
                            <phase>deploy</phase>
                            <goals>
                                <goal>copy</goal>
                            </goals>
                            <configuration>
                                <artifactItems>
                                    <artifactItem>
                                        <groupId>com.mule.support.ba</groupId>
                                        <artifactId>bonmarche-case-00145615</artifactId>
                                        <version>1.0.0</version>
                                        <type>zip</type>
                                        <overWrite>false</overWrite>
                                        <outputDirectory>C:/mule-home/apps</outputDirectory>
                                        <destFileName>bonmarche-case.zip</destFileName>
                                    </artifactItem>
                                </artifactItems>
                                <overWriteReleases>false</overWriteReleases>
                                <overWriteSnapshots>true</overWriteSnapshots>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
</code>```

2.2. Update the attributes within the  tag (in grey) with the corresponding values on your environment.
 2.3. As you see in 2.1, we are configuring the deployment to apps folder on Maven 'deploy' phase. You may choose a different phase to copy the artifact, but it must be bound to any phase after the package phase, so that the artifact exists in the repository.

Disable the default execution of Maven Deploy Plugin to prevent deploying the generated artifact to an external repository. This may be changed depending on your project needs.
Add this plugin after maven-dependency-plugin:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-deploy-plugin</artifactId>
    <version>2.8.2</version>
    <configuration>
        <skip>true</skip>
    </configuration>
</plugin>
</code>```

Build your application and verify the generated ZIP file is copied to MULE_HOME/apps directory.
        $> mvn clean deploy

ContentLicense: CC BY-SA 3.0

Title: How to configure MuleSoft with Maven?

Body:
Mule Maven Plugin configuration.
1.1. Use mule mule-app-maven-plugin to build the application.

<plugin>
        <groupId>org.mule.tools.maven</groupId>
        <artifactId>mule-app-maven-plugin</artifactId>
        <version>${mule.tools.version}</version>
        <extensions>true</extensions>
        <configuration>
        <copyToAppsDirectory>false</copyToAppsDirectory>
        </configuration>
    </plugin>

No need for additional Mule Maven plugins.
  This is the default mule plugin set when creating your Mule project on AnyPoint (AP) Studio.

1.2. Make sure you set flag copyToAppsDirectory to false.
       This flag is set to true by default so you must change it manually.

Maven Dependency Plugin Configuration.
2.1. Now we need to add a plugin to copy the generated artifact to the MULE_HOME/apps directory, i.e. to deploy the application to the standalone local mule server.
       We will use the maven-dependency-plugin.
       Just add these plugin after the mule maven plugin section in your application pom.xml.

              <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>2.10</version>
                    <executions>
                        <execution>
                            <id>copy</id>
                            <phase>deploy</phase>
                            <goals>
                                <goal>copy</goal>
                            </goals>
                            <configuration>
                                <artifactItems>
                                    <artifactItem>
                                        <groupId>com.mule.support.ba</groupId>
                                        <artifactId>bonmarche-case-00145615</artifactId>
                                        <version>1.0.0</version>
                                        <type>zip</type>
                                        <overWrite>false</overWrite>
                                        <outputDirectory>C:/mule-home/apps</outputDirectory>
                                        <destFileName>bonmarche-case.zip</destFileName>
                                    </artifactItem>
                                </artifactItems>
                                <overWriteReleases>false</overWriteReleases>
                                <overWriteSnapshots>true</overWriteSnapshots>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

2.2. Update the attributes within the  tag (in grey) with the corresponding values on your environment.
 2.3. As you see in 2.1, we are configuring the deployment to apps folder on Maven 'deploy' phase. You may choose a different phase to copy the artifact, but it must be bound to any phase after the package phase, so that the artifact exists in the repository.

Disable the default execution of Maven Deploy Plugin to prevent deploying the generated artifact to an external repository. This may be changed depending on your project needs.
Add this plugin after maven-dependency-plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-deploy-plugin</artifactId>
    <version>2.8.2</version>
    <configuration>
        <skip>true</skip>
    </configuration>
</plugin>

Build your application and verify the generated ZIP file is copied to MULE_HOME/apps directory.
        $> mvn clean deploy


问:
How to Read / Improve C.R.A.P Index Calculated by PHP
I just started working with PHPUnit and its colorful code coverage reports. I understand all the numbers and percentages save one: The C.R.A.P index. Can anyone offer me a solid explanation of what it means, how to analyze it and how to lower it?</p>

答:
Basically it wants to be a predictor of the risk of change for a method.

It has two factors in it:

code complexity of the method (cyclomatic complexity) aka how many decisions paths exists in said method: comp(m).

how testable is that method (via automated tests, provided by a code coverage tool). Basically this measures how many decisions in said code are automatically testable.

If the method has 100% coverage than the risk of change is considered to be equivalent only with the complexity of the method: C.R.A.P.(m) = comp(m).

If the method has 0% coverage than the risk of change is considered to be a second degree polinomial in the complexity measure (reasoning being that if you can't test a code path changing it increases risk of breakage): C.R.A.P.(m) = comp(m)^2 + comp(m)

Hopefully this will help you.

I just noticed that I only provide the half answer (the read part). The how to improve it should be pretty clear if you understand the reasoning of the index. But a much more clear explanation is given in @edorian's answer.

The short story is: write tests until you have near 100% coverage and after that refactor the methods to decrease the cyclomatic complexity. You can try to refactor before having tests but depending on the actual method complexity you risk introducing breakage if you can't reason (because of the complexity involved) all the consequences of the change you are doing.


问:
Flattening Nested Observable in object property
I am new to RxJs and trying to use it in my node app. Following code expects to return array of objects and each object should have nested array in one of its property.

Now the problem is it returns expected array of Objects, except the inner observable (that is supposed to be an array) is still not flattened in the subscribe.

```<code>createPlanOffers = (groupPlans) => {
    const groupPlan1 = groupPlans.filter(PREDICATE_1);
    return groupPlans
        .filter(PREDICATE_2)
        .reduce((offers, plan2) => {
            const plans_1 = groupPlan1.filter(PREDICATE_1_1);
            const plan1Details = plans_1.flatMap(plan1 => ({
                id: plan1.ID
            }));
            const offer = {
                groupKey: plan2.KEY,
                plan1Details: plan1Details
            };
            offers.push(offer);
            return offers;
        }, []);
};

const classPlans = query()
    .groupBy(group => group.KEY)
    .flatMap(groupPlans => createPlanOffers(groupPlans))
    .subscribe(group => console.log(group),
        err => console.log(err),
        () => console.log('complete'));
</code>```

Expected Result:

```<code>[
 { groupKey: 1111,
   plan1Details: [{id: xyz}]
 },
 { groupKey: 2222,
   plan1Details: [{id: xyz}]
 },
 { groupKey: 2222,
   plan1Details: [{id: abc}]
 }
]
</code>```

Actual Result :(

```<code>[
 { groupKey: 1111,
   plan1Details:
     Observable {
     _isScalar: false,
     source: [Observable],
     operator: [MergeMapOperator] } },
   { groupKey: 2222,
     plan1Details:
       Observable {
       _isScalar: false,
       source: [Observable],
       operator: [MergeMapOperator] } },
   { groupKey: 2222,
     plan1Details:
       Observable {
       _isScalar: false,
       source: [Observable],
       operator: [MergeMapOperator] } }
]
</code>```

This query will return something like:

```<code>const query = () => Rx.Observable.from([
    { KEY: 1111,
        id: 'xyz',
        category: 'A', // predicates are using these categories for filters
    }
    { GRGR_CK: 2222,
        id: 'xyz',
        category: 'A',
    }
    { GRGR_CK: 2222,
        id: 'ABC',
        category: 'B',
    }
])
</code>```

答:
This is because flatMap does not recursively resolve Observables from my understanding. What you could do is add another flatMap and resolve the inner one before returning:

```<code>query()
    .groupBy(group => group.KEY)
    .flatMap(groupPlans => createPlanOffers (groupPlans))
    .flatMap(obj => // could destruct the values you want instead
       obj.plan1Details.map(
         val => Object.assign({}, obj, { plan1Details: val})
       )
    )
    .subscribe(group => console.log(group),
        err => console.log(err),
        () => console.log('complete'));
</code>```

I don't like the way that looks/reads so I would look into resolving this higher up but not sure without looking at the full code where.

Body:
I am new to RxJs and trying to use it in my node app. Following code expects to return array of objects and each object should have nested array in one of its property.

Now the problem is it returns expected array of Objects, except the inner observable (that is supposed to be an array) is still not flattened in the subscribe.

createPlanOffers = (groupPlans) => {
    const groupPlan1 = groupPlans.filter(PREDICATE_1);
    return groupPlans
        .filter(PREDICATE_2)
        .reduce((offers, plan2) => {
            const plans_1 = groupPlan1.filter(PREDICATE_1_1);
            const plan1Details = plans_1.flatMap(plan1 => ({
                id: plan1.ID
            }));
            const offer = {
                groupKey: plan2.KEY,
                plan1Details: plan1Details
            };
            offers.push(offer);
            return offers;
        }, []);
};

const classPlans = query()
    .groupBy(group => group.KEY)
    .flatMap(groupPlans => createPlanOffers(groupPlans))
    .subscribe(group => console.log(group),
        err => console.log(err),
        () => console.log('complete'));

Expected Result:

[
 { groupKey: 1111,
   plan1Details: [{id: xyz}]
 },
 { groupKey: 2222,
   plan1Details: [{id: xyz}]
 },
 { groupKey: 2222,
   plan1Details: [{id: abc}]
 }
]

Actual Result :(

[
 { groupKey: 1111,
   plan1Details:
     Observable {
     _isScalar: false,
     source: [Observable],
     operator: [MergeMapOperator] } },
   { groupKey: 2222,
     plan1Details:
       Observable {
       _isScalar: false,
       source: [Observable],
       operator: [MergeMapOperator] } },
   { groupKey: 2222,
     plan1Details:
       Observable {
       _isScalar: false,
       source: [Observable],
       operator: [MergeMapOperator] } }
]

This query will return something like:

const query = () => Rx.Observable.from([
    { KEY: 1111,
        id: 'xyz',
        category: 'A', // predicates are using these categories for filters
    }
    { GRGR_CK: 2222,
        id: 'xyz',
        category: 'A',
    }
    { GRGR_CK: 2222,
        id: 'ABC',
        category: 'B',
    }
])

Body:
This is because flatMap does not recursively resolve Observables from my understanding. What you could do is add another flatMap and resolve the inner one before returning:

query()
    .groupBy(group => group.KEY)
    .flatMap(groupPlans => createPlanOffers (groupPlans))
    .flatMap(obj => // could destruct the values you want instead
       obj.plan1Details.map(
         val => Object.assign({}, obj, { plan1Details: val})
       )
    )
    .subscribe(group => console.log(group),
        err => console.log(err),
        () => console.log('complete'));

I don't like the way that looks/reads so I would look into resolving this higher up but not sure without looking at the full code where.


问:
GET request returning different result in different browsers
I'm having a problem with API requests giving inconsistent results.

I'm trying to send the following request to the Reddit API: https://www.reddit.com/search.json?q=url:https://www.youtube.com/watch?v=a7Sf_H2cFdM. This should return a list of all threads that link to that video specified by the url, of which there should be two (I checked manually). However, I don't get any threads returned at all.

Chrome Request

I thought it might be just a bug with the Reddit API that I couldn't fix, but then I tried the same request across different browsers. As it turns out, the request does return the correct results, but strangely only in Firefox Developer Edition.

Firefox Developer Edition Request

I have no idea why the results are different, and my only guess is that it might be because the request headers are different, but even still, I don't know how that would change anything. If anyone has any guess as to what might be causing this, I'm all ears.

答: I can't imagine anyone actually running into the same problem in the future, but if that's you, u/ketralnis on reddit left an awesome reply in an r/bugs thread that explains the issue and a solution: https://www.reddit.com/r/bugs/comments/7d0hg0/inconsistent_reddit_api_results/</p>


问:
How to overwrite an item with a different schema but same key in DynamoDB using nodejs on lambda
I am trying to overwrite an item in DynamoDB (that uses a primary key called username) by using put as shown below:

```<code>        console.log('writing commands',existingCommands,message.username);
        var t2 = performance();
        var writeParams = {
            Item: {
                username: message.username,
                commands: existingCommands // Sorry for the confusing name, due to deepExtend existingCommands are the new commands
            },

            TableName: TableName
        };

        docClient.put(writeParams, function(err, data){
            if(err){
                console.error('error',err);
            } else {
                console.log('write result',data);
                var t3 = performance();
                console.info('delete & write performance',(t3-t2).toFixed(3));
            }
            // End function
            context.done();
        });
</code>```

That works for:

Inserting a new item where the username doesn't exist.

Updating an item that matches the schema of the Item i'm trying to insert, for example, I'm trying to insert that item:

```<code>{
   "username":"ausin441062133",
    "commands": {
      "command1":"command",
      "command2":"command"
    }
}
</code>```

and if there's an item that matches the schema and the username it'll get overwritten, i.e.

```<code>    {
       "username":"ausin441062133",
        "commands": {
          "command1":"I will be overwritten",
          "command2":"I will be overwritten"
        }
    }
</code>```

But when there's an item with the exact username but different schema, it doesn't work, i.e.

```<code>    {
       "username":"ausin441062133",
        "commands": {
          "command1":"I will NOT be overwritten"
        }
    }
</code>```

What command do I need to use to overwrite an existing item if it matches the username?

答:
Eventually as Dmitry suggested update works but it needs some different params as opposed to put here's my code:

```<code>        // Step 3 write command back
        console.log('writing commands',existingCommands,message.username);
        var t2 = performance();
        var updateParams = {
            Key: {
                username: message.username
            },
            UpdateExpression: "set commands = :c",
            ExpressionAttributeValues: {
                ":c":existingCommands
            },
            ReturnValues: "UPDATED_NEW",
            TableName: TableName
        };

        docClient.update(updateParams, function(err, data){
            if(err){
                console.error('error',err);
            } else {
                console.log('write result',data);
                var t3 = performance();
                console.info('delete & write performance',(t3-t2).toFixed(3));
            }
            // End function
            context.done();
        });
</code>```

Body:
I am trying to overwrite an item in DynamoDB (that uses a primary key called username) by using put as shown below:

        console.log('writing commands',existingCommands,message.username);
        var t2 = performance();
        var writeParams = {
            Item: {
                username: message.username,
                commands: existingCommands // Sorry for the confusing name, due to deepExtend existingCommands are the new commands
            },

            TableName: TableName
        };

        docClient.put(writeParams, function(err, data){
            if(err){
                console.error('error',err);
            } else {
                console.log('write result',data);
                var t3 = performance();
                console.info('delete & write performance',(t3-t2).toFixed(3));
            }
            // End function
            context.done();
        });

That works for:

Inserting a new item where the username doesn't exist.

Updating an item that matches the schema of the Item i'm trying to insert, for example, I'm trying to insert that item:

{
   "username":"ausin441062133",
    "commands": {
      "command1":"command",
      "command2":"command"
    }
}

and if there's an item that matches the schema and the username it'll get overwritten, i.e.

    {
       "username":"ausin441062133",
        "commands": {
          "command1":"I will be overwritten",
          "command2":"I will be overwritten"
        }
    }

But when there's an item with the exact username but different schema, it doesn't work, i.e.

    {
       "username":"ausin441062133",
        "commands": {
          "command1":"I will NOT be overwritten"
        }
    }

What command do I need to use to overwrite an existing item if it matches the username?

Body:
Eventually as Dmitry suggested update works but it needs some different params as opposed to put here's my code:

        // Step 3 write command back
        console.log('writing commands',existingCommands,message.username);
        var t2 = performance();
        var updateParams = {
            Key: {
                username: message.username
            },
            UpdateExpression: "set commands = :c",
            ExpressionAttributeValues: {
                ":c":existingCommands
            },
            ReturnValues: "UPDATED_NEW",
            TableName: TableName
        };

        docClient.update(updateParams, function(err, data){
            if(err){
                console.error('error',err);
            } else {
                console.log('write result',data);
                var t3 = performance();
                console.info('delete & write performance',(t3-t2).toFixed(3));
            }
            // End function
            context.done();
        });


问:
Cordova - cordova-uglify plugin changes content to 'undefined' when uglified
After installing,

```<code>npm install cordova-uglify --save-dev
</code>```

and when running,

```<code>cordova build android --release
</code>```

all the css are minified correctly.

But, JS files contents are replaced with 'undefined'.

What might be the issue?

What kind of information should I give you to solve it?

Please help guys?

SOLUTION:

Reinstall cordova-uglify with the version 0.2.9 (or) follow the accepted answer.

答:
Turns out we had an old uglify-config.json. Specifically this property was causing the output to be undefined:

```<code>"uglifyJsOptions": { "fromString": true }
</code>```

More info on GitHub:
https://github.com/rossmartin/cordova-uglify/issues/35#issuecomment-344738718

Body:
After installing,

npm install cordova-uglify --save-dev

and when running,

cordova build android --release

all the css are minified correctly.

But, JS files contents are replaced with 'undefined'.

What might be the issue?

What kind of information should I give you to solve it?

Please help guys?

SOLUTION:

Reinstall cordova-uglify with the version 0.2.9 (or) follow the accepted answer.

Body:
Turns out we had an old uglify-config.json. Specifically this property was causing the output to be undefined:

"uglifyJsOptions": { "fromString": true }

More info on GitHub:
https://github.com/rossmartin/cordova-uglify/issues/35#issuecomment-344738718


问:
While loop starts from beginning in tic tac toe game
I am trying to write a tic tac toe game with java. In this game there are two player as A and B. Player A always starts the game(X),
and Player B is (O). I used random method to generate move numbers.

So, I created a while loop but it always start from beginning but I want to print a new board with latest move.

There's code below if you look at it and say what is the point that I am missing I will be glad.

Also singular numbers are belong to player A, plurals are belong to player B
I have to add +1 to whoseTurn for correct move(if random method tries to write X or O to a position has already taken, it must generate another row and column number but I couldn't figure it out as well)

```<code>import java.util.Random;

public class TicTacToe {

final static int SIZE = 5;
private static int row;
private static int column;

static Random number = new Random();
static char [][] array = new char[SIZE][SIZE];

public static void createBoard(){
    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            array[i][j] = '#';
        }
    }

    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            System.out.print(array[i][j] + " ");
        }
        System.out.println();
    }
    System.out.println();
    System.out.println("--------------");
}

public static void move(){
    int whoseTurn =1;
    while(whoseTurn <= (SIZE * SIZE)) {
        row = number.nextInt(6-1) + 1;
        column = number.nextInt(6-1) + 1;
        if ((whoseTurn % 2) != 0) {
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    array[i][j] = '#';
                    array[row-1][column-1] = 'X';
                }
            }
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    System.out.print(array[i][j] + " ");
                }
                System.out.println();
            }
            System.out.println("--------------");
            whoseTurn +=1;
        } else if((whoseTurn % 2) == 0){
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    array[i][j] = '#';
                    array[row-1][column-1] = 'O';
                    System.out.print(array[i][j] + " ");
                }
                System.out.println();
            }
            whoseTurn += 1;
        }
    }
}
</code>```

答:
Here is the simple solution that works, and checks if the field is already taken(placed 'X' or 'Y') so it doesn't overwrite the existing X and O.

It is based on @melanzane's answer:

```<code>import java.util.Random;

public class TicTacToe {

    final static int SIZE = 5;
    private static int row;
    private static int column;

    static Random number = new Random();
    static char[][] array = new char[SIZE][SIZE];

    public static void createBoard() {

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array.length; j++) {

                array[i][j] = '#';
            }

        }

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array.length; j++) {

                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
        System.out.println("--------------");
    }

    public static void move() {

        int whoseTurn = 1;

        while (whoseTurn <= (SIZE * SIZE)) {

            do {

                row = number.nextInt(6 - 1) + 1;

                column = number.nextInt(6 - 1) + 1;

            } while (array[row][column] == 'X' || array[row][column] == 'Y');

            if ((whoseTurn % 2) != 0) {

                array[row - 1][column - 1] = 'X';

                for (int i = 0; i < array.length; i++) {

                    for (int j = 0; j < array.length; j++) {
                        System.out.print(array[i][j] + " ");
                    }

                    System.out.println();
                }
                System.out.println("--------------");

                whoseTurn += 1;

            } else if ((whoseTurn % 2) == 0) {

                array[row - 1][column - 1] = 'O';

                for (int i = 0; i < array.length; i++) {

                    for (int j = 0; j < array.length; j++) {
                        System.out.print(array[i][j] + " ");
                    }

                    System.out.println();
                }
                System.out.println("--------------");

                whoseTurn += 1;
            }

        }
    }

}
</code>```

Body:
I am trying to write a tic tac toe game with java. In this game there are two player as A and B. Player A always starts the game(X),
and Player B is (O). I used random method to generate move numbers.

So, I created a while loop but it always start from beginning but I want to print a new board with latest move.

There's code below if you look at it and say what is the point that I am missing I will be glad.

Also singular numbers are belong to player A, plurals are belong to player B
I have to add +1 to whoseTurn for correct move(if random method tries to write X or O to a position has already taken, it must generate another row and column number but I couldn't figure it out as well)

import java.util.Random;

public class TicTacToe {

final static int SIZE = 5;
private static int row;
private static int column;

static Random number = new Random();
static char [][] array = new char[SIZE][SIZE];

public static void createBoard(){
    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            array[i][j] = '#';
        }
    }

    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            System.out.print(array[i][j] + " ");
        }
        System.out.println();
    }
    System.out.println();
    System.out.println("--------------");
}

public static void move(){
    int whoseTurn =1;
    while(whoseTurn <= (SIZE * SIZE)) {
        row = number.nextInt(6-1) + 1;
        column = number.nextInt(6-1) + 1;
        if ((whoseTurn % 2) != 0) {
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    array[i][j] = '#';
                    array[row-1][column-1] = 'X';
                }
            }
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    System.out.print(array[i][j] + " ");
                }
                System.out.println();
            }
            System.out.println("--------------");
            whoseTurn +=1;
        } else if((whoseTurn % 2) == 0){
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                    array[i][j] = '#';
                    array[row-1][column-1] = 'O';
                    System.out.print(array[i][j] + " ");
                }
                System.out.println();
            }
            whoseTurn += 1;
        }
    }
}

Body:
Here is the simple solution that works, and checks if the field is already taken(placed 'X' or 'Y') so it doesn't overwrite the existing X and O.

It is based on @melanzane's answer:

import java.util.Random;

public class TicTacToe {

    final static int SIZE = 5;
    private static int row;
    private static int column;

    static Random number = new Random();
    static char[][] array = new char[SIZE][SIZE];

    public static void createBoard() {

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array.length; j++) {

                array[i][j] = '#';
            }

        }

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array.length; j++) {

                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
        System.out.println("--------------");
    }

    public static void move() {

        int whoseTurn = 1;

        while (whoseTurn <= (SIZE * SIZE)) {

            do {

                row = number.nextInt(6 - 1) + 1;

                column = number.nextInt(6 - 1) + 1;

            } while (array[row][column] == 'X' || array[row][column] == 'Y');

            if ((whoseTurn % 2) != 0) {

                array[row - 1][column - 1] = 'X';

                for (int i = 0; i < array.length; i++) {

                    for (int j = 0; j < array.length; j++) {
                        System.out.print(array[i][j] + " ");
                    }

                    System.out.println();
                }
                System.out.println("--------------");

                whoseTurn += 1;

            } else if ((whoseTurn % 2) == 0) {

                array[row - 1][column - 1] = 'O';

                for (int i = 0; i < array.length; i++) {

                    for (int j = 0; j < array.length; j++) {
                        System.out.print(array[i][j] + " ");
                    }

                    System.out.println();
                }
                System.out.println("--------------");

                whoseTurn += 1;
            }

        }
    }

}


问:
Will using LINQ to SQL help prevent SQL injection
I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?

This example is creating the user account.

```<code>Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
profile.UserName = userName;
profile.Password = password;
profile.EmailAddress = email;
profile.QuestionID = qID;
profile.QuestionResponse = securityAnswer;
profile.LastModDt = DateTime.Now;
profile.LastModBy = "web";
context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
context.SubmitChanges();
</code>```

This example is changing the password

```<code>   MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
   var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
   mProfileRecord.Password = sNewPassword;
   dc.SubmitChanges();
</code>```

Are these safe? Does LINQ parameterize the SQL it generates automatically?

答:
You're good to go.  Linq does parameterize the data it sends to the database.

Use the Log property to check out what's happening: dc.Log = Console.Out;

Body:
I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?

This example is creating the user account.

Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
profile.UserName = userName;
profile.Password = password;
profile.EmailAddress = email;
profile.QuestionID = qID;
profile.QuestionResponse = securityAnswer;
profile.LastModDt = DateTime.Now;
profile.LastModBy = "web";
context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
context.SubmitChanges();

This example is changing the password

   MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
   var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
   mProfileRecord.Password = sNewPassword;
   dc.SubmitChanges();

Are these safe? Does LINQ parameterize the SQL it generates automatically?

OwnerDisplayName: David B

ContentLicense: CC BY-SA 2.5


问:
Which HTTP verb is appropriate for setting a boolean?
I have a RESTful web service which exposes a resource that enables you (the logged in user) to like or unlike a blog post. My question is: what is the RESTfully correct way to express this resource?

My first stab looks like:

```<code>PUT    /likes/<blog_entry_id> # marks this blog entry as liked
DELETE /likes/<blog_entry_id> # marks this blog entry as not liked
</code>```

This semantic is at least consistent with the idempotency requirements of PUT and DELETE (i.e. repeated calls to PUT have no effect unless interspersed with DELETEs, and vice versa).

Is there a more conventional design for the management of a boolean HTTP resource?

答:
I would step away from using verbs in resource URLs and use the following schemes:

POST /blog/<id>/fan  Send the user-id and other data for the resource you want to create as part of the 'Like' action. I'm supposing JSON here, so this could be an example { "user": "http://..../user/34343", "timestamp": 234353443 }

you could then use
GET /blog/<id>/fan to get a list of all users that like the blog post. I would probably send a JSON presentation of the resource that makes it easy to list those users and follow a link the the data of the like action (if there is any)

GET /blog/<id>/fan/<user-id>  to get the data of the like action (if there is any)

Body:
I have a RESTful web service which exposes a resource that enables you (the logged in user) to like or unlike a blog post. My question is: what is the RESTfully correct way to express this resource?

My first stab looks like:

PUT    /likes/<blog_entry_id> # marks this blog entry as liked
DELETE /likes/<blog_entry_id> # marks this blog entry as not liked

This semantic is at least consistent with the idempotency requirements of PUT and DELETE (i.e. repeated calls to PUT have no effect unless interspersed with DELETEs, and vice versa).

Is there a more conventional design for the management of a boolean HTTP resource?


问:
How to get a fraction from a float number?
I have a floating point number:

```<code>var f = 0.1457;
</code>```

Or:

```<code>var f = 4.7005
</code>```

How do I get just the fraction remainder as integer?

I.e. in the first example I want to get:

```<code>var remainder = 1457;
</code>```

In the second example:

```<code>var remainder = 7005;
</code>```

答:
I would argue that, assuming we want to display these values to the user, treating these numbers as strings would be the best approach. This gets round the issue of fractional values such as 0.002. </p>

<p>I came accross this issue when trying to display prices with the cents in superscript. </p>

```<code>let price = 23.43; // 23.43
let strPrice = price.toFixed(2) + ''; // "23.43"
let integer = strPrice.split(".")[0] // "23"
let fractional = strPrice.split(".")[1] // "43"
</code>```

Body:
I have a floating point number:

var f = 0.1457;

Or:

var f = 4.7005

How do I get just the fraction remainder as integer?

I.e. in the first example I want to get:

var remainder = 1457;

In the second example:

var remainder = 7005;

Body:
I would argue that, assuming we want to display these values to the user, treating these numbers as strings would be the best approach. This gets round the issue of fractional values such as 0.002.

I came accross this issue when trying to display prices with the cents in superscript.

let price = 23.43; // 23.43
let strPrice = price.toFixed(2) + ''; // "23.43"
let integer = strPrice.split(".")[0] // "23"
let fractional = strPrice.split(".")[1] // "43"


问:
Docker - in docker-compose.override.yml, prevent a service being executed or immediately stop the service
I use the docker-compose.override.yml to override my docker services in development and specifically reference the docker-compose.yml file when deploying to more production like environments much like this workflow.

If I have a service say my-job-scheduler, I don't want that to run in development so would prefer to include something in my docker-compose.override.yml file that tells docker-compose:

Dont start this service; or

Immediately stop this service

Is there a good pattern to do this?

答:
Use a combination of a single simple command such as echo and flagging restart as "no":

```<code>services:
  my-job-scheduler:
    command: echo "do nothing"
    restart: "no"
</code>```

Body:
Use a combination of a single simple command such as echo and flagging restart as "no":

services:
  my-job-scheduler:
    command: echo "do nothing"
    restart: "no"


问:
Center align text while there are other texts on div
I know this may sound like a silly question but here goes
I'd Like to Center Align a text while there are other text inside a div.

HTML

```<code> <div class="divisions" id="lightsBox">
    <h1> Lights Status </h1>

    <p class="divisionsText">Number of Lights On: </p> <p id="nLightsOn"></p> <br>
    <p class="divisionsText">Number of Lights Off: </p> <p id="nLightsOff"></p>

 </div>
</code>```

Javascript

```<code> document.getElementById("lightsBox").style.opacity = 0.6;
 document.getElementById("lightsBox").style.backgroundColor = "grey";
 var h = document.createElement("H1")

 h.appendChild(document.createTextNode("Feature not avaliable"));
 h.style.verticleAlign = "middle";
 h.style.textAlign = "center";
 h.style.color ="red";
</code>```

I want to Align the "Feature not available" text, in the middle of the div on top of other texts to look like this, (edited with ms paint :P)

答:
You should target one of the paragraphs and then createTextNode for "
Feature not available
" in between them. Or you can always have the  there but with a display: none; and then show it once you need too.

Body:
I know this may sound like a silly question but here goes
I'd Like to Center Align a text while there are other text inside a div.

HTML

 Lights Status

Number of Lights On:

Number of Lights Off:

Javascript

 document.getElementById("lightsBox").style.opacity = 0.6;
 document.getElementById("lightsBox").style.backgroundColor = "grey";
 var h = document.createElement("H1")

 h.appendChild(document.createTextNode("Feature not avaliable"));
 h.style.verticleAlign = "middle";
 h.style.textAlign = "center";
 h.style.color ="red";

I want to Align the "Feature not available" text, in the middle of the div on top of other texts to look like this, (edited with ms paint :P)

Body: You should target one of the paragraphs and then createTextNode for "<h1>Feature not available</h1>" in between them. Or you can always have the  there but with a display: none; and then show it once you need too.


问:
Install confluent-kafka avro with pip
I'm trying to install the avro package for confluent-kafka with python3 on macOs Sierra.

Installing the confluent-kafka package works fine, no issues. The problem is when I try to install the avro package:

```<code>pip install confluent-kafka[avro]
</code>```

I just get an error message from the bash, saying:

```<code>no matches found: confluent-kafka[avro]
</code>```

How can I install this package? Anyone else that have managed to do it on mac?

答:
Try installing directly from github</p>

```<code>pip install git+git://github.com/confluentinc/confluent-kafka-python.git
</code>```

Title: Install confluent-kafka avro with pip

Body:
I'm trying to install the avro package for confluent-kafka with python3 on macOs Sierra.

Installing the confluent-kafka package works fine, no issues. The problem is when I try to install the avro package:

pip install confluent-kafka[avro]

I just get an error message from the bash, saying:

no matches found: confluent-kafka[avro]

How can I install this package? Anyone else that have managed to do it on mac?

Body:
Try installing directly from github

pip install git+git://github.com/confluentinc/confluent-kafka-python.git


问:
React router Link not causing component to update within nested routes
This is driving me crazy. When I try to use React Router's Link within a nested route, the link updates in the browser but the view isn't changing. Yet if I refresh the page to the link, it does. Somehow, the component isn't updating when it should (or at least that's the goal).

Here's what my links look like (prev/next-item are really vars):

```<code><Link to={'/portfolio/previous-item'}>
    <button className="button button-xs">Previous</button>
</Link>
<Link to={'/portfolio/next-item'}>
    <button className="button button-xs">Next</button>
</Link>
</code>```

A hacky solution is to manaully call a forceUpate() like:

```<code><Link onClick={this.forceUpdate} to={'/portfolio/next-item'}>
    <button className="button button-xs">Next</button>
</Link>
</code>```

That works, but causes a full page refresh, which I don't want and an error:

```<code>ReactComponent.js:85 Uncaught TypeError: Cannot read property 'enqueueForceUpdate' of undefined
</code>```

I've searched high and low for an answer and the closest I could come is this: https://github.com/reactjs/react-router/issues/880. But it's old and I'm not using the pure render mixin.

Here are my relevant routes:

```<code><Route component={App}>
    <Route path='/' component={Home}>
        <Route path="/index:hashRoute" component={Home} />
    </Route>
    <Route path="/portfolio" component={PortfolioDetail} >
        <Route path="/portfolio/:slug" component={PortfolioItemDetail} />
    </Route>
    <Route path="*" component={NoMatch} />
</Route>
</code>```

For whatever reason, calling Link is not causing the component to remount which needs to happen in order to fetch the content for the new view. It does call componentDidUpdate, and I'm sure I could check for a url slug change and then trigger my ajax call/view update there, but it seems like this shouldn't be needed.

EDIT (more of the relevant code):

PortfolioDetail.js

```<code>import React, {Component} from 'react';
import { browserHistory } from 'react-router'
import {connect} from 'react-redux';
import Loader from '../components/common/loader';
import PortfolioItemDetail from '../components/portfolio-detail/portfolioItemDetail';
import * as portfolioActions  from '../actions/portfolio';

export default class PortfolioDetail extends Component {

    static readyOnActions(dispatch, params) {
        // this action fires when rendering on the server then again with each componentDidMount.
        // but not firing with Link...
        return Promise.all([
            dispatch(portfolioActions.fetchPortfolioDetailIfNeeded(params.slug))
        ]);
    }

    componentDidMount() {
        // react-router Link is not causing this event to fire
        const {dispatch, params} = this.props;
        PortfolioDetail.readyOnActions(dispatch, params);
    }

    componentWillUnmount() {
        // react-router Link is not causing this event to fire
        this.props.dispatch(portfolioActions.resetPortfolioDetail());
    }

    renderPortfolioItemDetail(browserHistory) {
        const {DetailReadyState, item} = this.props.portfolio;
        if (DetailReadyState === 'WORK_DETAIL_FETCHING') {
            return <Loader />;
        } else if (DetailReadyState === 'WORK_DETAIL_FETCHED') {
            return <PortfolioItemDetail />; // used to have this as this.props.children when the route was nested
        } else if (DetailReadyState === 'WORK_DETAIL_FETCH_FAILED') {
            browserHistory.push('/not-found');
        }
    }

    render() {
        return (
            <div id="interior-page">
                {this.renderPortfolioItemDetail(browserHistory)}
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        portfolio: state.portfolio
    };
}
function mapDispatchToProps(dispatch) {
    return {
        dispatch: dispatch
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(PortfolioDetail);
</code>```

PortfolioItemDetail.js

```<code>import React, {Component} from 'react';
import {connect} from 'react-redux';
import Gallery from './gallery';

export default class PortfolioItemDetail extends React.Component {

    makeGallery(gallery) {
        if (gallery) {
            return gallery
                .split('|')
                .map((image, i) => {
                    return <li key={i}><img src={'/images/portfolio/' + image} alt="" /></li>
            })
        }
    }

    render() {
        const { item } = this.props.portfolio;

        return (
            <div className="portfolio-detail container-fluid">
                <Gallery
                    makeGallery={this.makeGallery.bind(this)}
                    item={item}
                />
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        portfolio: state.portfolio
    };
}

export default connect(mapStateToProps)(PortfolioItemDetail);
</code>```

gallery.js

```<code>import React, { Component } from 'react';
import { Link } from 'react-router';

const Gallery = (props) => {

    const {gallery, prev, next} = props.item;
    const prevButton = prev ? <Link to={'/portfolio/' + prev}><button className="button button-xs">Previous</button></Link> : '';
    const nextButton = next ? <Link to={'/portfolio/' + next}><button className="button button-xs">Next</button></Link> : '';

    return (
        <div>
            <ul className="gallery">
                {props.makeGallery(gallery)}
            </ul>
            <div className="next-prev-btns">
                {prevButton}
                {nextButton}
            </div>
        </div>
    );
};

export default Gallery;
</code>```

New routes, based on Anoop's suggestion:

```<code><Route component={App}>
    <Route path='/' component={Home}>
        <Route path="/index:hashRoute" component={Home} />
    </Route>
    <Route path="/portfolio/:slug" component={PortfolioDetail} />
    <Route path="*" component={NoMatch} />
</Route>
</code>```

答:
I got stuck on this also in React 16.

My solution was as follows:

```<code>componentWillMount() {
    const { id } = this.props.match.params;
    this.props.fetchCategory(id); // Fetch data and set state
}

componentWillReceiveProps(nextProps) {
    const { id } = nextProps.match.params;
    const { category } = nextProps;

    if(!category) {
        this.props.fetchCategory(id); // Fetch data and set state
    }
}
</code>```

I am using redux to manage state but the concept is the same I think.

Set the state as per normal on the WillMount method and when the WillReceiveProps is called you can check if the state has been updated if it hasn't you can recall the method that sets your state, this should re-render your component.

Body:
This is driving me crazy. When I try to use React Router's Link within a nested route, the link updates in the browser but the view isn't changing. Yet if I refresh the page to the link, it does. Somehow, the component isn't updating when it should (or at least that's the goal).

Here's what my links look like (prev/next-item are really vars):

<Link to={'/portfolio/previous-item'}>
    <button className="button button-xs">Previous</button>
</Link>
<Link to={'/portfolio/next-item'}>
    <button className="button button-xs">Next</button>
</Link>

A hacky solution is to manaully call a forceUpate() like:

<Link onClick={this.forceUpdate} to={'/portfolio/next-item'}>
    <button className="button button-xs">Next</button>
</Link>

That works, but causes a full page refresh, which I don't want and an error:

ReactComponent.js:85 Uncaught TypeError: Cannot read property 'enqueueForceUpdate' of undefined

I've searched high and low for an answer and the closest I could come is this: https://github.com/reactjs/react-router/issues/880. But it's old and I'm not using the pure render mixin.

Here are my relevant routes:

<Route component={App}>
    <Route path='/' component={Home}>
        <Route path="/index:hashRoute" component={Home} />
    </Route>
    <Route path="/portfolio" component={PortfolioDetail} >
        <Route path="/portfolio/:slug" component={PortfolioItemDetail} />
    </Route>
    <Route path="*" component={NoMatch} />
</Route>

For whatever reason, calling Link is not causing the component to remount which needs to happen in order to fetch the content for the new view. It does call componentDidUpdate, and I'm sure I could check for a url slug change and then trigger my ajax call/view update there, but it seems like this shouldn't be needed.

EDIT (more of the relevant code):

PortfolioDetail.js

import React, {Component} from 'react';
import { browserHistory } from 'react-router'
import {connect} from 'react-redux';
import Loader from '../components/common/loader';
import PortfolioItemDetail from '../components/portfolio-detail/portfolioItemDetail';
import * as portfolioActions  from '../actions/portfolio';

export default class PortfolioDetail extends Component {

    static readyOnActions(dispatch, params) {
        // this action fires when rendering on the server then again with each componentDidMount.
        // but not firing with Link...
        return Promise.all([
            dispatch(portfolioActions.fetchPortfolioDetailIfNeeded(params.slug))
        ]);
    }

    componentDidMount() {
        // react-router Link is not causing this event to fire
        const {dispatch, params} = this.props;
        PortfolioDetail.readyOnActions(dispatch, params);
    }

    componentWillUnmount() {
        // react-router Link is not causing this event to fire
        this.props.dispatch(portfolioActions.resetPortfolioDetail());
    }

    renderPortfolioItemDetail(browserHistory) {
        const {DetailReadyState, item} = this.props.portfolio;
        if (DetailReadyState === 'WORK_DETAIL_FETCHING') {
            return <Loader />;
        } else if (DetailReadyState === 'WORK_DETAIL_FETCHED') {
            return <PortfolioItemDetail />; // used to have this as this.props.children when the route was nested
        } else if (DetailReadyState === 'WORK_DETAIL_FETCH_FAILED') {
            browserHistory.push('/not-found');
        }
    }

    render() {
        return (

                {this.renderPortfolioItemDetail(browserHistory)}

        );
    }
}

function mapStateToProps(state) {
    return {
        portfolio: state.portfolio
    };
}
function mapDispatchToProps(dispatch) {
    return {
        dispatch: dispatch
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(PortfolioDetail);

PortfolioItemDetail.js

import React, {Component} from 'react';
import {connect} from 'react-redux';
import Gallery from './gallery';

export default class PortfolioItemDetail extends React.Component {

    makeGallery(gallery) {
        if (gallery) {
            return gallery
                .split('|')
                .map((image, i) => {
                    return

            })
        }
    }

    render() {
        const { item } = this.props.portfolio;

        return (

                <Gallery
                    makeGallery={this.makeGallery.bind(this)}
                    item={item}
                />

        );
    }
}

function mapStateToProps(state) {
    return {
        portfolio: state.portfolio
    };
}

export default connect(mapStateToProps)(PortfolioItemDetail);

gallery.js

import React, { Component } from 'react';
import { Link } from 'react-router';

const Gallery = (props) => {

    const {gallery, prev, next} = props.item;
    const prevButton = prev ? <Link to={'/portfolio/' + prev}><button className="button button-xs">Previous</button></Link> : '';
    const nextButton = next ? <Link to={'/portfolio/' + next}><button className="button button-xs">Next</button></Link> : '';

    return (

                {props.makeGallery(gallery)}

                {prevButton}
                {nextButton}

    );
};

export default Gallery;

New routes, based on Anoop's suggestion:

<Route component={App}>
    <Route path='/' component={Home}>
        <Route path="/index:hashRoute" component={Home} />
    </Route>
    <Route path="/portfolio/:slug" component={PortfolioDetail} />
    <Route path="*" component={NoMatch} />
</Route>

Body:
I got stuck on this also in React 16.

My solution was as follows:

componentWillMount() {
    const { id } = this.props.match.params;
    this.props.fetchCategory(id); // Fetch data and set state
}

componentWillReceiveProps(nextProps) {
    const { id } = nextProps.match.params;
    const { category } = nextProps;

    if(!category) {
        this.props.fetchCategory(id); // Fetch data and set state
    }
}

I am using redux to manage state but the concept is the same I think.

Set the state as per normal on the WillMount method and when the WillReceiveProps is called you can check if the state has been updated if it hasn't you can recall the method that sets your state, this should re-render your component.


答: Your problem is with auto res = Decomp::decompose(n); it returns a res object with junk values. Consider this output 8: [5 4 3 2 1 0 72405692564177152 72340172838076673..... after 0 all are seems to be junk value. So put some condition and break loop for (long long i: res) or correct Decomp::decompose(n).

Title: Why does assigning a vector from a factory function and iterating over it inside a loop cause a segfault?

Body:
I wrote a function that decomposes a number into a sequence of smaller numbers such that the sum of the squared sequence elements equals the square of the input number. The declaration of this function looks like this: std::vector<long long> Decomp::decompose(long long n);. To test the output of the function, I use the following main function:

int main()
{
    for (long long n = 1; n <= 65; ++n)
    {
        auto res = Decomp::decompose(n);
        if (res.empty())
            std::cout << n << ": No solution.\n";
        else
        {
            std::cout << n << ": [";
            for (long long i: res)
                std::cout << i << ' ';
            std::cout << "\b]\n";
        }
    }
}

However, this leads to a segmentation fault for n=8:

Output:
1: No solution.
2: No solution.
3: No solution.
4: No solution.
5: [3 4]
6: No solution.
7: [2 3 6]
8: [5 4 3 2 1 0 72405692564177152 72340172838076673 281474993553665 130961 139767842405240 139767842405240 4366240942559068160 72340172838076673 72340172838076673 282578800148737 1099511628033 256 72340168526266368 72340172838091928 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72057594054770689 72340173837828353 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72405692564177153 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72340172838076673 16843009 240 32 17817984 4 272 32 0 3 304 48 0 4 3 2 72339069014704384 130609 257 130593 0 0 0 0 0 0 282574488404224 72340168543109376 0 0 0 0 0 0 72339069031481344 72339073326448640 72058697861300225 257 0 0 0 0 72057598349672448 72058697861300225 72340172838011137 72058697861366017 282578783305985 65793 0 0 1103806595072 282578783305985 72340172821299457 282578800148737 72340168526332161 72340168543109376 72340172838076673 72339069031481600 282578800148481 72340168526332160 72340168543109376 72340172838076673 72339069031481600 72340172838076673 72340172838076673 72340172838076673 72340172838076673 72339069031481344 72339073326448641 72340172838076673 72057598349737985 72340172838076673 72340172838076673 72340172838076673 282578800148737 130145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (whole lot of zeros...)  Segmentation fault

I suspect something in above main function is causing the segfault, since the following main function seems to work fine:

int main()
{
    long long n = 8;
    auto res = Decomp::decompose(n);
    if (res.empty())
        std::cout << n << ": No solution.\n";
    else
    {
        std::cout << n << ": [";
        for (long long i: res)
            std::cout << i << ' ';
        std::cout << "\b]\n";
    }
}

Output:
8: No solution.

Edit:
gdb says the following:

Core was generated by `./test'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x00000000004026e3 in main ()

Decomp::decompose looks like this:

std::vector<long long> Decomp::decompose(long long n)
{
    if (n <= 1)
        return std::vector<long long>();

    size_t rows = n - 1, cols = n * n + 1;
    bool *table = new bool[rows * cols];
    std::vector<long long> ret;

    for (size_t i = 0; i < rows; ++i)
        table[i * cols] = true;

    table[1] = true;

    for (size_t i = 1; i < rows; ++i)
        for (size_t j = 1; j < cols; ++j)
        {
            table[i * cols + j] = (j < (i + 1) * (i + 1)) ?
                                  table[(i - 1) * cols + j] :
                                  table[(i - 1) * cols + j] ||
                                  table[(i - 1) * cols + j - (i + 1) * (i + 1)];
        }

    if ( table[rows * cols - 1] )
    {
        backtrace(n, rows - 1, cols - 1, table, ret);
        std::reverse(ret.begin(), ret.end());
    }

    delete[] table;
    return ret;
}

Decomp::backtrace is a recursive function that extracts the sequence from the table created in decompose, just adding it here for reference:

bool Decomp::backtrace(long long n, size_t i, size_t j, bool table[], std::vector<long long> &seq)
{
    if (std::inner_product(seq.begin(), seq.end(), seq.begin(), 0LL) == n * n)
        return true;

    size_t cols = n * n + 1;

    if (table[i * cols + j])
    {
        if ((i + 1) * (i + 1) <= j)
        {
            seq.push_back(i + 1);
            if (backtrace(n, i - 1, j - (i + 1) * (i + 1), table, seq))
                return true;

            return backtrace(n, i - 1, j, table, seq);
        }
        else
        {
            while (table[i * cols + j] and (i + 1) * (i + 1) > j)
                --i;

            if (table[i * cols + j])
            {
                seq.push_back(i + 1);

                if (backtrace(n, i - 1, j - (i + 1) * (i + 1), table, seq))
                    return true;

                return backtrace(n, i - 1, j, table, seq);
            }
            else
            {
                std::cout << "case found\n";
                seq.pop_back();
                return false;
            }
        }
    }
    else
    {
        seq.pop_back();
        return false;
    }
}

And the class header for reference:

public:
    static std::vector<long long> decompose(long long n);
private:
    static bool backtrace(long long n, size_t i, size_t j, bool table[], std::vector<long long> &seq);


问:
Chrome: Notifications not working, permission not requested
I have been struggling for hours on trying to enable notifications on chrome, on firefox it works perfectly and it works ok as well on localhost url address. But when it comes to non-localhost url address it just doesn't work.

i have been checking on the permissions that are displayed left next to the url input box where you see the website's information and it shows that notifications are permitted, but on advanced settings it shows block with a message "Blocked to protect your privacy" and i am not entirely sure what does that mean.

the code i am trying to execute first is simple:

```<code>if(Notifications.permission == "default"){
    Notification.requestPermission()
        .then(permission => {
            console.log(`Permission given is: ${permission}`);
        });

}

else{
    console.log("Notification permission is: ${Notification.permission}`);
}
</code>```

The result of this code is Notification permission is: denied meaning that else statement was executed but permission is given as if permission was already requested and denied was the answer of the request.

Can someone explain why does this happen?

答:
I figured out that the problem was comming from loading the website with no TLS https, making some features in chrome to be disabled by design..

I was unabled to figure this out sooner because the host testing i was using was being accessed with 0.0.0.0 instead of localhost which is the one that chrome whitelists for features

Body:
I have been struggling for hours on trying to enable notifications on chrome, on firefox it works perfectly and it works ok as well on localhost url address. But when it comes to non-localhost url address it just doesn't work.

i have been checking on the permissions that are displayed left next to the url input box where you see the website's information and it shows that notifications are permitted, but on advanced settings it shows block with a message "Blocked to protect your privacy" and i am not entirely sure what does that mean.

the code i am trying to execute first is simple:

if(Notifications.permission == "default"){
    Notification.requestPermission()
        .then(permission => {
            console.log(`Permission given is: ${permission}`);
        });

}

else{
    console.log("Notification permission is: ${Notification.permission}`);
}

The result of this code is Notification permission is: denied meaning that else statement was executed but permission is given as if permission was already requested and denied was the answer of the request.

Can someone explain why does this happen?


问:
Removing "." from Spark DataFrame column names
How do I remove the "." from a Spark DataFrame column name?

The DataFrame.select(F.col().alias()) method to rename column names that have a "." in them throws an error.

The following code is reproducible.

```<code># import Spark libraries, configuration, Contexts, and types.
import pyspark
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
#############
# Start Spark.
spark = SparkSession.builder.appName("test").getOrCreate()

testdf = spark.createDataFrame([
    (1, "Julie", "CEO"),
    (2, "Janice", "CFO"),
    (3, "Jake", "CTO")],
    ["ID", "First Name", "Title Initial."])

# this works just fine.
testdf.select(F.col('First Name').alias('first_name')).show(3)

# This throws an error.
testdf.select(F.col('Title Initial.').alias('title')).show(3)
</code>```

Error:

```<code>AnalysisException: u'syntax error in attribute name: Title Initial.;'
</code>```

What is an alternative method to change DataFrame column names that have a "." in them?

答:
Surround the column name with `

```<code>testdf.select(F.col('`Title Initial.`').alias('title')).show(3)
</code>```

Body:
How do I remove the "." from a Spark DataFrame column name?

The DataFrame.select(F.col().alias()) method to rename column names that have a "." in them throws an error.

The following code is reproducible.

# import Spark libraries, configuration, Contexts, and types.
import pyspark
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
#############
# Start Spark.
spark = SparkSession.builder.appName("test").getOrCreate()

testdf = spark.createDataFrame([
    (1, "Julie", "CEO"),
    (2, "Janice", "CFO"),
    (3, "Jake", "CTO")],
    ["ID", "First Name", "Title Initial."])

# this works just fine.
testdf.select(F.col('First Name').alias('first_name')).show(3)

# This throws an error.
testdf.select(F.col('Title Initial.').alias('title')).show(3)

Error:

AnalysisException: u'syntax error in attribute name: Title Initial.;'

What is an alternative method to change DataFrame column names that have a "." in them?

Body:
Surround the column name with `

testdf.select(F.col('`Title Initial.`').alias('title')).show(3)


问:
TWILIO - why the actual response returned does not match with documented
I have integrated Twilio and it works fine. Now I want to capture all the intermediate message statuses. I referred to Sending Messages.

My code looks like -

```<code>require __DIR__ . '/vendor/autoload.php';
      // Use the REST API Client to make requests to the Twilio REST API
      use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$sid = '****************';
$token = '*****************';
$client = new Client($sid, $token);

// send message
$message = $client->messages->create(
    // the number you'd like to send the message to
    '+1xxxxxxxxx',
    array(
        'from' => '+1xxxxxxxx',
        'body' => 'Test web hook message '.date('h:i'),
        'statusCallback' => "https://xxxxxx/xxxx.php",
    )
);
</code>```

But the output/response returned to statusCallback is different as -

```<code>"{\"SmsSid\":\"SM72478c1ea61f467dbc33338123c0ad0\",\"SmsStatus\":\"sent\",\"MessageStatus\":\"sent\",\"To\":\"+1xxxxxxxx\",\"MessageSid\":\"SM72478c1ea612222dbc3b7858123c0ad0\",\"AccountSid\":\"ACb655a10c1c2222e4af158c5395d64beb\",\"From\":\"+1xxxxxxx\",\"ApiVersion\":\"2010-04-01\"}"
</code>```

But I need the response as it is defined at Sending Messages

EDIT

If checked at Sending Messages, we can see the fields returned in the output are - account_sid, api_version, body, num_segments, num_media, date_created, date_sent, date_updated, direction, error_code, error_message, from, price, sid, status, to and uri.
But I receive fields as - SmsSid, SmsStatus, MessageStatus, To, MessageSid, AccountSid, From and ApiVersion.

For me, the fields - num_segments, date_sent, direction, error_code, error_message are important which I am not receiving. Do I need to use another API of TWILIO to retrieve this information ?

Why am I getting different response ?

答:
What does your code for your callback url script look like?

What you have is just an escaped JSON string, so to match what you see on the documentation you just have to do this:

```<code>$json = '{\"SmsSid\":\"SM72478c1ea61f467dbc33338123c0ad0\",\"SmsStatus\":\"sent\",\"MessageStatus\":\"sent\",\"To\":\"+1xxxxxxxx\",\"MessageSid\":\"SM72478c1ea612222dbc3b7858123c0ad0\",\"AccountSid\":\"ACb655a10c1c2222e4af158c5395d64beb\",\"From\":\"+1xxxxxxx\",\"ApiVersion\":\"2010-04-01\"}';
echo stripslashes($json);
</code>```

Body:
I have integrated Twilio and it works fine. Now I want to capture all the intermediate message statuses. I referred to Sending Messages.

My code looks like -

require __DIR__ . '/vendor/autoload.php';
      // Use the REST API Client to make requests to the Twilio REST API
      use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$sid = '****************';
$token = '*****************';
$client = new Client($sid, $token);

// send message
$message = $client->messages->create(
    // the number you'd like to send the message to
    '+1xxxxxxxxx',
    array(
        'from' => '+1xxxxxxxx',
        'body' => 'Test web hook message '.date('h:i'),
        'statusCallback' => "https://xxxxxx/xxxx.php",
    )
);

But the output/response returned to statusCallback is different as -

"{\"SmsSid\":\"SM72478c1ea61f467dbc33338123c0ad0\",\"SmsStatus\":\"sent\",\"MessageStatus\":\"sent\",\"To\":\"+1xxxxxxxx\",\"MessageSid\":\"SM72478c1ea612222dbc3b7858123c0ad0\",\"AccountSid\":\"ACb655a10c1c2222e4af158c5395d64beb\",\"From\":\"+1xxxxxxx\",\"ApiVersion\":\"2010-04-01\"}"

But I need the response as it is defined at Sending Messages

EDIT

If checked at Sending Messages, we can see the fields returned in the output are - account_sid, api_version, body, num_segments, num_media, date_created, date_sent, date_updated, direction, error_code, error_message, from, price, sid, status, to and uri.
But I receive fields as - SmsSid, SmsStatus, MessageStatus, To, MessageSid, AccountSid, From and ApiVersion.

For me, the fields - num_segments, date_sent, direction, error_code, error_message are important which I am not receiving. Do I need to use another API of TWILIO to retrieve this information ?

Why am I getting different response ?

Body:
What does your code for your callback url script look like?

What you have is just an escaped JSON string, so to match what you see on the documentation you just have to do this:

$json = '{\"SmsSid\":\"SM72478c1ea61f467dbc33338123c0ad0\",\"SmsStatus\":\"sent\",\"MessageStatus\":\"sent\",\"To\":\"+1xxxxxxxx\",\"MessageSid\":\"SM72478c1ea612222dbc3b7858123c0ad0\",\"AccountSid\":\"ACb655a10c1c2222e4af158c5395d64beb\",\"From\":\"+1xxxxxxx\",\"ApiVersion\":\"2010-04-01\"}';
echo stripslashes($json);


问:
Redis Client Maxlimit
I am using the redis pub/sub mechanism in my application and would like to do a benchmark test. I have an I-7 machine with 32 GB RAM and ulimit set to 1024. Redis server is of same configuration except for ulimit set to 65535. How many simultaneous connections I can make without redis complaining about MAXClient reached exception. I tried tuning the connection with connection pooling etc but number of simultaneous request does not seem to go beyond 25K requests.

Thanks \

答:
Solution that worked for me:
Edited /etc/systemd/system/redis.service
Added the following line to the [Service] section</p>

```<code>LimitNOFILE=110000
</code>```

Title: Redis Client Maxlimit

Body:
Solution that worked for me:
Edited /etc/systemd/system/redis.service
Added the following line to the [Service] section

LimitNOFILE=110000


问:
How can I get some model's objects and its associated model's objects conditionally through an intermediary model object, using ActiveRecord
How can I get some model's objects and its associated model's objects conditionally through an intermediary model object? This will then be used to generate JSON (via to_json).

Here is the setup made more generic:

```<code>class JobSet < ActiveRecord::Base
  belongs_to :job_system
  has_many :resources, through => :job_system
  has_many :jobs
  ...
end

class JobSystem < ActiveRecord::Base
  has_many :job_sets
  has_many :resources
  ...
end

class Resource < ActiveRecord::Base
  belongs_to :job_system
  has_many_and_belongs_to_many :jobs
  ...
end

class Job < ActiveRecord::Base
  belongs_to :job_system
  belongs_to :job_set
  has_many_and_belongs_to_many :resources
  ...
end
</code>```

What I want to do is get all of the resources with their corresponding jobs, but only the jobs that are part of a particular job set.

UPDATE: even if a resource doesn't have any jobs associated with it I still want to get it with the rest of the resources. The purpose is to display all resources with any jobs assigned to them.

It looks like I can set conditions when using through, but I can't seem to figure out how to do that when it is the next objects associations I am after...

Is there a good name for this type of problem? Is there any easy way to do this?

UPDATE 2: There seem to be solutions that work well within the controller, but I am using to_json in the view to preload for a canvas element. It seems to automatically include all jobs when I do this:

```<code>var resources = <%= @resources.to_json(:include => {:jobs => {:only => :id}}) %>;
</code>```

Would a manual SQL JOIN even help with this?

答:
I think I know what you are after. The only thing I would ask you for is, if a resource does not have any jobs in this particular job set, should it still be included?

Anyway, here is one way to do it:

```<code>@resources = Resource.all(:include => :jobs,
                          :conditions => ["jobs.job_set_id = ?", @job_set.id])
</code>```

This will NOT include the resources that has no jobs associated with @job_set

So, am I totally wrong in my assumptions, or was this what you where after?

Edit

Okay, this was more difficult then I thought. There are several solutions but none I really like. You could do like this:

```<code>@resources = Resource.all

@resources.each do |resource|
  resource.jobs.all(:conditions => ["jobs.job_set_id = ?", @job_set_id])
end
</code>```

But that will result in the 1+n number-of-queries-problem putting pressure on your db.

You could also do like this:

```<code>@resources = Resource.all(:include => :jobs)

@resources.each do |resource|
  resource.jobs.select{ |job| job.job_set_id == @job_set_id }
end
</code>```

But that will result in more memory consumption on the server side since all jobs are loaded eagerly and then looped through to see which matches the job_set_id.

The problem with finding a better solution in my opinion is that this is something that should be specified in the SQL JOIN condition but I don't think that ActiveRecord lets us modify that in combination with eager loading.

Body:
How can I get some model's objects and its associated model's objects conditionally through an intermediary model object? This will then be used to generate JSON (via to_json).

Here is the setup made more generic:

class JobSet < ActiveRecord::Base
  belongs_to :job_system
  has_many :resources, through => :job_system
  has_many :jobs
  ...
end

class JobSystem < ActiveRecord::Base
  has_many :job_sets
  has_many :resources
  ...
end

class Resource < ActiveRecord::Base
  belongs_to :job_system
  has_many_and_belongs_to_many :jobs
  ...
end

class Job < ActiveRecord::Base
  belongs_to :job_system
  belongs_to :job_set
  has_many_and_belongs_to_many :resources
  ...
end

What I want to do is get all of the resources with their corresponding jobs, but only the jobs that are part of a particular job set.

UPDATE: even if a resource doesn't have any jobs associated with it I still want to get it with the rest of the resources. The purpose is to display all resources with any jobs assigned to them.

It looks like I can set conditions when using through, but I can't seem to figure out how to do that when it is the next objects associations I am after...

Is there a good name for this type of problem? Is there any easy way to do this?

UPDATE 2: There seem to be solutions that work well within the controller, but I am using to_json in the view to preload for a canvas element. It seems to automatically include all jobs when I do this:

var resources = <%= @resources.to_json(:include => {:jobs => {:only => :id}}) %>;

Would a manual SQL JOIN even help with this?

Body:
I think I know what you are after. The only thing I would ask you for is, if a resource does not have any jobs in this particular job set, should it still be included?

Anyway, here is one way to do it:

@resources = Resource.all(:include => :jobs,
                          :conditions => ["jobs.job_set_id = ?", @job_set.id])

This will NOT include the resources that has no jobs associated with @job_set

So, am I totally wrong in my assumptions, or was this what you where after?

Edit

Okay, this was more difficult then I thought. There are several solutions but none I really like. You could do like this:

@resources = Resource.all

@resources.each do |resource|
  resource.jobs.all(:conditions => ["jobs.job_set_id = ?", @job_set_id])
end

But that will result in the 1+n number-of-queries-problem putting pressure on your db.

You could also do like this:

@resources = Resource.all(:include => :jobs)

@resources.each do |resource|
  resource.jobs.select{ |job| job.job_set_id == @job_set_id }
end

But that will result in more memory consumption on the server side since all jobs are loaded eagerly and then looped through to see which matches the job_set_id.

The problem with finding a better solution in my opinion is that this is something that should be specified in the SQL JOIN condition but I don't think that ActiveRecord lets us modify that in combination with eager loading.