问:
Scala akka-http WebSocket: How to save the client connection and push message to the client when needed?
How to keep the client (web) connection in a memory variable and then send outgoing messages to the client (web) when needed?

I already have some simple code for pushing back message to the client once the server receives messages from the client. How to modify the code below for the outgoing messaging part?

```<code>implicit val actorSystem = ActorSystem("akka-system")
implicit val flowMaterializer = ActorMaterializer()
implicit val executionContext = actorSystem.dispatcher

val ip = "127.0.0.1"
val port = 32000

val route = get {
    pathEndOrSingleSlash {
        complete("Welcome to websocket server")
    }
} ~
path("hello") {
    get {
        handleWebSocketMessages(echoService)
    }
}

def sendMessageToClient(msg : String) {

    // *** How to implement this?
    // *** How to save the client connection when it is first connected?
    //     Then how to send message to this connection?

}

val echoService = Flow[Message].collect {

    // *** Here the server push back messages when receiving msg from client

    case tm : TextMessage => TextMessage(Source.single("Hello ") ++ tm.textStream)
    case _ => TextMessage("Message type unsupported")
}

val binding = Http().bindAndHandle(route, ip, port)
</code>```

答:
You can look into pipelining the sink flow via .map call. Inside the .map call you can capture the value and then return the same message. For example:

```<code>  Flow[Message].collect {
    case tm : TextMessage =>
      TextMessage(Source.single("Hello ") ++ tm.textStream.via(
        Flow[String].map((message) => {println(message) /* capture value here*/; message})))
    case _ => TextMessage("Message type unsupported")
  }
</code>```

Now, if your intention is to process those values and send out values later, what you want is not a single source-to-sink flow, but two separate streams for sink and source, for which you can use Flow.fromSinkAndSource e.g.

```<code>Flow.fromSinkAndSource[Message, Message](
  Flow[Message].collect { /* capture values */},
    // Or send stream to other sink for more processing
  source
)
</code>```

In all likelihood, this source will be either constructed out of graph DSL, a hand-rolled actor, or you can look into utilizing reusable helpers such as MergeHub.

Body:
How to keep the client (web) connection in a memory variable and then send outgoing messages to the client (web) when needed?

I already have some simple code for pushing back message to the client once the server receives messages from the client. How to modify the code below for the outgoing messaging part?

implicit val actorSystem = ActorSystem("akka-system")
implicit val flowMaterializer = ActorMaterializer()
implicit val executionContext = actorSystem.dispatcher

val ip = "127.0.0.1"
val port = 32000

val route = get {
    pathEndOrSingleSlash {
        complete("Welcome to websocket server")
    }
} ~
path("hello") {
    get {
        handleWebSocketMessages(echoService)
    }
}

def sendMessageToClient(msg : String) {

    // *** How to implement this?
    // *** How to save the client connection when it is first connected?
    //     Then how to send message to this connection?

}

val echoService = Flow[Message].collect {

    // *** Here the server push back messages when receiving msg from client

    case tm : TextMessage => TextMessage(Source.single("Hello ") ++ tm.textStream)
    case _ => TextMessage("Message type unsupported")
}

val binding = Http().bindAndHandle(route, ip, port)

Body:
You can look into pipelining the sink flow via .map call. Inside the .map call you can capture the value and then return the same message. For example:

  Flow[Message].collect {
    case tm : TextMessage =>
      TextMessage(Source.single("Hello ") ++ tm.textStream.via(
        Flow[String].map((message) => {println(message) /* capture value here*/; message})))
    case _ => TextMessage("Message type unsupported")
  }

Now, if your intention is to process those values and send out values later, what you want is not a single source-to-sink flow, but two separate streams for sink and source, for which you can use Flow.fromSinkAndSource e.g.

Flow.fromSinkAndSource[Message, Message](
  Flow[Message].collect { /* capture values */},
    // Or send stream to other sink for more processing
  source
)

In all likelihood, this source will be either constructed out of graph DSL, a hand-rolled actor, or you can look into utilizing reusable helpers such as MergeHub.


来源: stackexchange

问:
Refreshing a page in a browser yields POST or GET request?
I am learning asp.net mvc form processing now and confused with the following:

What happens if we push the refresh button on the browser?
It makes a POST or GET request?

答:
Whatever HTTP method was used to generate the page will be repeated when you hit refresh.

If you're using <% Html.BeginForm(...) %> when the form is submitted, it will create a POST, and if the resulting page is refreshed, it will repeat the POST.

ContentLicense: CC BY-SA 2.5


问:
How to get current loggedin username in vtiger tpl file
How i can get the current loggedin username in the header.tpl file of vtiger CRM. It should be for use inside {php} {/php} tags.

Header.tpl

```<code>{php} if($CURRENT_USER == 'admin') { echo "yes"; } else { echo "no"; } {/php}
</code>```

答:
Not sure if that would help, but if you need to check what user is logged in, you can get their ID via

```<code>{$smarty.session.authenticated_user_id}
</code>```

If you need the name, though, you would need to use elax's solution.

ContentLicense: CC BY-SA 3.0

Body:
How i can get the current loggedin username in the header.tpl file of vtiger CRM. It should be for use inside {php} {/php} tags.

Header.tpl

{php} if($CURRENT_USER == 'admin') { echo "yes"; } else { echo "no"; } {/php}

Body:
Not sure if that would help, but if you need to check what user is logged in, you can get their ID via

{$smarty.session.authenticated_user_id}

If you need the name, though, you would need to use elax's solution.


问:
Finding just one or more comma in a string with ColdFusion
How can I detect if a string value only consists of one or more commas and nothing else. The correct value should be something like: ABC,BVC,BNM but sometimes I get value like: , or ,,, or ,, and this is not allowed. How can I detect that a string only have one or more commas and then I can create a warning to the user and stop the process.

Thank you

答:
Depends on how much your input may vary, but as you currently describe it:

Something as simple as <cfif MyVar contains ",,"> would work.

If one comma (and nothing else) is a possibility, then

```<code><cfif MyVar contains ",," OR Len(MyVar) lt 2>
</code>```

Body:
Depends on how much your input may vary, but as you currently describe it:

Something as simple as <cfif MyVar contains ",,"> would work.

If one comma (and nothing else) is a possibility, then

<cfif MyVar contains ",," OR Len(MyVar) lt 2>


问:
Adding Image into Webpage using AngularJS
Why does my image show up as a file logo? link below

This is how my image shows up when I add it

This is my JS for the image (AngularJS)

{
    name: 'Screw',
    price: 1,
    description: 'A small item drilled into objects',
    specs: '1 centimeter',
    images: [
                {
                    full: "1024px-Phillips_screw.jpg"
                }
            ]
}
```

<p>This is my HTML for adding the image</p>

<pre class="lang-html prettyprint-override"><code><img ng-src="{{product.images[0].full}}"/>
</code>```

答:
Why not use ng-src directive? ie.

```<code><div ng-init="myVar='pic_angular.jpg'">
    <h1>Angular</h1>
    <img ng-src="{{myVar}}">
</div>
</code>```

Body:
Why does my image show up as a file logo? link below

This is how my image shows up when I add it

This is my JS for the image (AngularJS)

{
    name: 'Screw',
    price: 1,
    description: 'A small item drilled into objects',
    specs: '1 centimeter',
    images: [
                {
                    full: "1024px-Phillips_screw.jpg"
                }
            ]
}

This is my HTML for adding the image

Body:
Why not use ng-src directive? ie.

<div ng-init="myVar='pic_angular.jpg'">
    <h1>Angular</h1>
    <img ng-src="{{myVar}}">
</div>


问:
How can I tell if my app upgrade from angular 2 to angular 4 was successful?
I had a .NET WebAPI application that was using angular 2 with and decided to upgrade to angular 4.

I went through somthing like the following in the cmd for my project directory (along with a few iterations of installing missing dependencies):

```<code>npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest --save
</code>```

I recently went through the CLI to update my angular app from angular 2 to angular 4. Now, is there a way for me to confirm that my application is actually using angular 4 rather than 2?

If i type in "ng --version" into the cmd line for the directly that has my project, then I get the following result:

```<code>@angular/cli: 1.2.0
node: 6.10.2
os: win32 x64
@angular/animations: 4.2.5
@angular/common: 4.2.5
@angular/compiler: 4.2.5
@angular/compiler-cli: 4.2.5
@angular/core: 4.2.5
@angular/forms: 4.2.5
@angular/http: 4.2.5
@angular/platform-browser: 4.2.5
@angular/platform-browser-dynamic: 4.2.5
@angular/platform-server: 4.2.5
@angular/router: 4.2.5
@angular/cli: 1.2.0
</code>```

if i run my application then and look at the brower developer tools i see this in the DOM explorer:

```<code><html>
<body>
    <my-app ng-version="2.4.8" _nghost-vrp-0="">
... other stuff that isn't important
</html>
</body>
</code>```

so it looks like my app says ng-version ="2.4.8" but does my CLI say differently? Did i successfully upgrade, and if so, why does the DOM in the browser developer tools say differently?

Again, this is a .NET WebAPI application that was using angular 2 with.

答:
You can always try some of the hot new angular4 features and see if it works, or see if it compiles with a ng build --prod --aot</p>

```<code> <div *ngIf="userList | async as users; else loading">
  <user-profile *ngFor="let user of users; count as count; index as i" [user]="user">
User {{i}} of {{count}}
  </user-profile>
</div>
<ng-template #loading>Loading...</ng-template>
</code>```

Body:
I had a .NET WebAPI application that was using angular 2 with and decided to upgrade to angular 4.

I went through somthing like the following in the cmd for my project directory (along with a few iterations of installing missing dependencies):

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest --save

I recently went through the CLI to update my angular app from angular 2 to angular 4. Now, is there a way for me to confirm that my application is actually using angular 4 rather than 2?

If i type in "ng --version" into the cmd line for the directly that has my project, then I get the following result:

@angular/cli: 1.2.0
node: 6.10.2
os: win32 x64
@angular/animations: 4.2.5
@angular/common: 4.2.5
@angular/compiler: 4.2.5
@angular/compiler-cli: 4.2.5
@angular/core: 4.2.5
@angular/forms: 4.2.5
@angular/http: 4.2.5
@angular/platform-browser: 4.2.5
@angular/platform-browser-dynamic: 4.2.5
@angular/platform-server: 4.2.5
@angular/router: 4.2.5
@angular/cli: 1.2.0

if i run my application then and look at the brower developer tools i see this in the DOM explorer:

    <my-app ng-version="2.4.8" _nghost-vrp-0="">
... other stuff that isn't important

so it looks like my app says ng-version ="2.4.8" but does my CLI say differently? Did i successfully upgrade, and if so, why does the DOM in the browser developer tools say differently?

Again, this is a .NET WebAPI application that was using angular 2 with.

Body:
You can always try some of the hot new angular4 features and see if it works, or see if it compiles with a ng build --prod --aot

 <div *ngIf="userList | async as users; else loading">
  <user-profile *ngFor="let user of users; count as count; index as i" [user]="user">
User {{i}} of {{count}}
  </user-profile>
</div>
<ng-template #loading>Loading...</ng-template>


问:
Merging and deleting columns in R
I am attempting to merge all columns with different names but identical variable labels (imported from an SPSS file). The way I am trying to go about this is running a few checks to make sure the columns are neither NA nor identical, then pasting j to i and deleting j. However, this appears to be changing nothing whatsoever in my dataframe. What am I doing wrong here?

A note-- mergedSet is rows bound together from set1 and set2, each of which contain the labels.

```<code>for(i in colnames(set1)) {
    for(j in colnames(set2)){
        if(!is.na(attributes(set1)$variable.labels[i]) &&
           !is.na(attributes(set2)$variable.labels[j])) {
                if(attributes(set1)$variable.labels[i] ==
                   attributes(set2)$variable.labels[j]) {
                     if(i != j) {
                       mergedSet <- within(mergedSet, i <- paste(i,j))
                       mergedSet <- within(mergedSet, rm(j))
                       }
                  }
            }

         }
    }
</code>```

答:
If I am understanding your question correctly this code should merge the columns based on the columns having matching variable.labels and non-matching column names.</p>

```<code>mergedSet <- data.frame(c(1,3,5),c("a","b","c"))
mergedSet <- data.frame(mergedSet,c("s","","h"))
attributes(mergedSet)$variable.labels["gas"] <- "three"
attributes(mergedSet)$variable.labels["xhs"] <- "three"
attributes(mergedSet)$variable.labels["hhh"] <- "notSame"
names(mergedSet) <- c("gas","hhh","xhs")

set1 <- data.frame(c(2),c(4))
names(set1) <- c("gas","factpr")
attributes(set1)$variable.labels["gas"] <- "three"
attributes(set1)$variable.labels["factpr"] <- "nah"

set2 <- data.frame(c("asd"),c("pqr"))
names(set2) <- c("non","hhh")
attributes(set2)$variable.labels["non"] <- "something"
attributes(set2)$variable.labels["hhh"] <- "three"

for(i in colnames(set1)) {
  for(j in colnames(set2)){
    if(!is.na(attributes(set1)$variable.labels[i]) &&
       !is.na(attributes(set2)$variable.labels[j])) {
      if(attributes(set1)$variable.labels[i] ==
         attributes(set2)$variable.labels[j]) {
        if(i != j) {
          mergedSet[, i] <- paste(mergedSet[,i], mergedSet[,j])
          mergedSet[, j] <- NULL
        }
      }
    }
  }
}

mergedSet
#   gas xhs
# 1 1 a   s
# 2 3 b
# 3 5 c   h
</code>```

Title: Merging and deleting columns in R

Body:
I am attempting to merge all columns with different names but identical variable labels (imported from an SPSS file). The way I am trying to go about this is running a few checks to make sure the columns are neither NA nor identical, then pasting j to i and deleting j. However, this appears to be changing nothing whatsoever in my dataframe. What am I doing wrong here?

A note-- mergedSet is rows bound together from set1 and set2, each of which contain the labels.

for(i in colnames(set1)) {
    for(j in colnames(set2)){
        if(!is.na(attributes(set1)$variable.labels[i]) &&
           !is.na(attributes(set2)$variable.labels[j])) {
                if(attributes(set1)$variable.labels[i] ==
                   attributes(set2)$variable.labels[j]) {
                     if(i != j) {
                       mergedSet <- within(mergedSet, i <- paste(i,j))
                       mergedSet <- within(mergedSet, rm(j))
                       }
                  }
            }

         }
    }

Body:
If I am understanding your question correctly this code should merge the columns based on the columns having matching variable.labels and non-matching column names.

mergedSet <- data.frame(c(1,3,5),c("a","b","c"))
mergedSet <- data.frame(mergedSet,c("s","","h"))
attributes(mergedSet)$variable.labels["gas"] <- "three"
attributes(mergedSet)$variable.labels["xhs"] <- "three"
attributes(mergedSet)$variable.labels["hhh"] <- "notSame"
names(mergedSet) <- c("gas","hhh","xhs")

set1 <- data.frame(c(2),c(4))
names(set1) <- c("gas","factpr")
attributes(set1)$variable.labels["gas"] <- "three"
attributes(set1)$variable.labels["factpr"] <- "nah"

set2 <- data.frame(c("asd"),c("pqr"))
names(set2) <- c("non","hhh")
attributes(set2)$variable.labels["non"] <- "something"
attributes(set2)$variable.labels["hhh"] <- "three"

for(i in colnames(set1)) {
  for(j in colnames(set2)){
    if(!is.na(attributes(set1)$variable.labels[i]) &&
       !is.na(attributes(set2)$variable.labels[j])) {
      if(attributes(set1)$variable.labels[i] ==
         attributes(set2)$variable.labels[j]) {
        if(i != j) {
          mergedSet[, i] <- paste(mergedSet[,i], mergedSet[,j])
          mergedSet[, j] <- NULL
        }
      }
    }
  }
}

mergedSet
#   gas xhs
# 1 1 a   s
# 2 3 b
# 3 5 c   h


问:
Should background service and UI be one app?
I wan to create an android app which would have two different use-cases:

A background service, which would listen to a specific notification.

A UI which would present a visual way to present some information fetched from other resources.

Questions

should it be an Android APP which would have 1 service module and 1 UI module OR it would be two apps, one service and other UI?

If these are 2 apps then will user have to install 2 different apps from play or one app can complete the installation of the underlying service app?

答:
If these are 2 apps then would user has to install 2 different apps from play or one app can complete the installation of the underlying service app

If you have two apps user will always have to install and grant permissions for each one of them individually.

Shall it should be on Android APP which would have 1 service module and 1 UI module OR it would be two apps, one service and other UI.

Based on your requirements, I don't see why you need two apps.


问:
Freemarker syntax for a form for a collection of objects (Spring 3 MVC)
I have a command bean (FooList) which has a property which is a collection (a List of Foo beans).

I'm trying to create a form which can edit all the Foos at once. I have found many examples of how to do this using JSP, but I'm having trouble translating these to Freemarker syntax.

In my Freemarker template, I can easily iterate over the collection:

```<code>[#list fooList.foos as foo]
...
[/#list]
</code>```

I can also refer to a particular Foo by index:

```<code>[@spring.bind "fooList.foos[0].name" /]
<input type="text" name="${spring.status.expression}" value="${spring.status.value?default('')}"/>
</code>```

However, I haven't yet worked out how I can do both at the same time, to bind all the Foos to form elements.

Here's one naïve attempt which failed:

```<code>[#list fooList.foos as foo]
    [@spring.bind "fooList.foos[foo_index].name" /]
    ...
[/#list]
</code>```

(On its own, ${foo_index} works inside the loop.)

Can anyone point me in the right direction?

Thanks.

答:
Just had the same problem. This worked for me:</p>

```<code>[#list fooList.foos as foo]
  <#assign item>fooList.foos[${foo_index}].name</#assign>
  [@spring.bind item /]
  ...
[/#list]
</code>```

Body:
I have a command bean (FooList) which has a property which is a collection (a List of Foo beans).

I'm trying to create a form which can edit all the Foos at once. I have found many examples of how to do this using JSP, but I'm having trouble translating these to Freemarker syntax.

In my Freemarker template, I can easily iterate over the collection:

[#list fooList.foos as foo]
...
[/#list]

I can also refer to a particular Foo by index:

[@spring.bind "fooList.foos[0].name" /]
<input type="text" name="${spring.status.expression}" value="${spring.status.value?default('')}"/>

However, I haven't yet worked out how I can do both at the same time, to bind all the Foos to form elements.

Here's one naïve attempt which failed:

[#list fooList.foos as foo]
    [@spring.bind "fooList.foos[foo_index].name" /]
    ...
[/#list]

(On its own, ${foo_index} works inside the loop.)

Can anyone point me in the right direction?

Thanks.

Body:
Just had the same problem. This worked for me:

[#list fooList.foos as foo]
  <#assign item>fooList.foos[${foo_index}].name</#assign>
  [@spring.bind item /]
  ...
[/#list]


问:
android.view.InflateException - cannot find reason
This is my fragment inputtext_fragment.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/inputtextfragm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/inputtext_layout"
        android:visibility="invisible"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        ...>

        ...

    </LinearLayout>
</fragment>
</code>```

inputText fragment in java:

```<code>package de.company.android.inputtext;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class InputTextFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        try {
            return inflater.inflate(R.layout.inputtext_fragment, container, false);
        }
        catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
}
</code>```

This is the activity layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    tools:context="de.company.android.testview.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    ...

    <fragment
        android:id="@+id/console"
        android:name="de.company.android.inputtext.InputTextFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>
</code>```

I get the following error on launch, when the content view of the activity is set onCreate():

D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: de.company.android.testview, PID: 573
                    java.lang.RuntimeException: Unable to start activity ComponentInfo{de.company.android.testview/de.company.android.testview.MainActivity}: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Caused by: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                   ...

Caused by: java.lang.IllegalStateException: Fragment de.company.android.inputtext.InputTextFragment did not create a view.
                        at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2253)
                        at android.app.FragmentController.onCreateView(FragmentController.java:99)
                        at android.app.Activity.onCreateView(Activity.java:6085)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:479)
                        at android.app.Activity.setContentView(Activity.java:2400)
                        at de.company.android.testview.MainActivity.onCreate(MainActivity.java:1697)
                        at android.app.Activity.performCreate(Activity.java:6904)
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

This is the error logged inside catch:

```<code>W/System.err: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class fragment
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
W/System.err:     at de.company.android.inputtext.InputTextFragment.onCreateView(InputTextFragment.java:23)
W/System.err:     at android.app.Fragment.performCreateView(Fragment.java:2281)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1142)
W/System.err:     at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1246)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2223)
W/System.err:     at android.app.FragmentController.onCreateView(FragmentController.java:99)
W/System.err:     at android.app.Activity.onCreateView(Activity.java:6085)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
W/System.err:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
W/System.err:     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
...
W/System.err: Caused by: java.lang.NullPointerException
W/System.err:     at java.lang.VMClassLoader.findLoadedClass(Native Method)
W/System.err:     at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:620)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:598)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2214)
W/System.err:     at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:192)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:   ... 33 more
</code>```

I cannot find out what is wrong. The activity and the fragment are in different modules, but everything is configured right so that the de.company.android.inputtext utils are correctly referenced.

答: Your input_text_fragment.xml should not be inside of a Fragment tag.  It should be inside the appropriate type of Layout.  The fragment tag goes only in main_activity.xml where you want the fragment to appear.</p>

ContentLicense: CC BY-SA 4.0

Body:
This is my fragment inputtext_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/inputtextfragm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/inputtext_layout"
        android:visibility="invisible"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        ...>

        ...

    </LinearLayout>
</fragment>

inputText fragment in java:

package de.company.android.inputtext;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class InputTextFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        try {
            return inflater.inflate(R.layout.inputtext_fragment, container, false);
        }
        catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
}

This is the activity layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    tools:context="de.company.android.testview.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    ...

    <fragment
        android:id="@+id/console"
        android:name="de.company.android.inputtext.InputTextFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

I get the following error on launch, when the content view of the activity is set onCreate():

D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: de.company.android.testview, PID: 573
                    java.lang.RuntimeException: Unable to start activity ComponentInfo{de.company.android.testview/de.company.android.testview.MainActivity}: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Caused by: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                   ...

Caused by: java.lang.IllegalStateException: Fragment de.company.android.inputtext.InputTextFragment did not create a view.
                        at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2253)
                        at android.app.FragmentController.onCreateView(FragmentController.java:99)
                        at android.app.Activity.onCreateView(Activity.java:6085)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:479)
                        at android.app.Activity.setContentView(Activity.java:2400)
                        at de.company.android.testview.MainActivity.onCreate(MainActivity.java:1697)
                        at android.app.Activity.performCreate(Activity.java:6904)
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

This is the error logged inside catch:

W/System.err: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class fragment
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
W/System.err:     at de.company.android.inputtext.InputTextFragment.onCreateView(InputTextFragment.java:23)
W/System.err:     at android.app.Fragment.performCreateView(Fragment.java:2281)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1142)
W/System.err:     at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1246)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2223)
W/System.err:     at android.app.FragmentController.onCreateView(FragmentController.java:99)
W/System.err:     at android.app.Activity.onCreateView(Activity.java:6085)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
W/System.err:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
W/System.err:     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
...
W/System.err: Caused by: java.lang.NullPointerException
W/System.err:     at java.lang.VMClassLoader.findLoadedClass(Native Method)
W/System.err:     at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:620)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:598)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2214)
W/System.err:     at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:192)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:   ... 33 more

I cannot find out what is wrong. The activity and the fragment are in different modules, but everything is configured right so that the de.company.android.inputtext utils are correctly referenced.


问:
R merge multiple files into 1 dataframe and keep all values
I have 6 multiple files, each having only 1 column of names. I want to read all these files and combine them in 1 dataframe so that it looks like this:

```<code>file1  file2  file3  file4  file5  file6
adam   adam   adam   adam   adam   adam
Roy    NA     Roy    Roy    NA     NA
NA     Sam    Sam    NA     NA     NA
</code>```

The colnames of resulting dataframe should represent the actual file names. Let's say that the file I read were named file1.txt, file2.txt and so on..

Any help will be much appreciated.

What I've been trying so far:

```<code>multmerge = function(mypath){
+ filenames=list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
+ datalist = lapply(filenames, function(x){read.csv(file=x,header=F)})
+ Reduce(function(x,y) {merge(x,y, all.x=T)}, datalist)}
> mymergeddata = multmerge("/Path/To/The/Folder/Having/All/Files")
> dim(mymergeddata)
[1] 11508     1
</code>```

As seen here it is combining all values (names) in one column..

答:
Here is another version of your function that gives the output you asked for...</p>

```<code>multmerge <- function(mypath){
  filenames <- list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
  datalist <- lapply(filenames, function(x){
            df <- read.csv(file=x,header=F,stringsAsFactors = FALSE)
            df[,2] <- gsub("\\.txt","",basename(x))
            return(df)})
  namesdf <- do.call(rbind,datalist)
  output <- as.data.frame.matrix(table(namesdf$name,namesdf$file))
  for(j in 1:nrow(output)){
    output[j,] <- ifelse(as.numeric(output[j,])==0,NA,row.names(output)[j])
  }
  return(output)
}
</code>```

Body:
I have 6 multiple files, each having only 1 column of names. I want to read all these files and combine them in 1 dataframe so that it looks like this:

file1  file2  file3  file4  file5  file6
adam   adam   adam   adam   adam   adam
Roy    NA     Roy    Roy    NA     NA
NA     Sam    Sam    NA     NA     NA

The colnames of resulting dataframe should represent the actual file names. Let's say that the file I read were named file1.txt, file2.txt and so on..

Any help will be much appreciated.

What I've been trying so far:

multmerge = function(mypath){
+ filenames=list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
+ datalist = lapply(filenames, function(x){read.csv(file=x,header=F)})
+ Reduce(function(x,y) {merge(x,y, all.x=T)}, datalist)}
> mymergeddata = multmerge("/Path/To/The/Folder/Having/All/Files")
> dim(mymergeddata)
[1] 11508     1

As seen here it is combining all values (names) in one column..

Body:
Here is another version of your function that gives the output you asked for...

multmerge <- function(mypath){
  filenames <- list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
  datalist <- lapply(filenames, function(x){
            df <- read.csv(file=x,header=F,stringsAsFactors = FALSE)
            df[,2] <- gsub("\\.txt","",basename(x))
            return(df)})
  namesdf <- do.call(rbind,datalist)
  output <- as.data.frame.matrix(table(namesdf$name,namesdf$file))
  for(j in 1:nrow(output)){
    output[j,] <- ifelse(as.numeric(output[j,])==0,NA,row.names(output)[j])
  }
  return(output)
}


问:
How to debug JavaScript code with mobile browsers
I know about firebug and the developer tools for the major modern desktop browsers, but I can't find any way of debugging JavaScript code on mobile browsers.

What are some high level techniques I can use to debug code on mobile browsers?

答: On the IPhone you can go into settings>Safari>advanced and turn web inspector on</p>


问:
bootstrapTable: how to vertical align the detail-icon?
I'm using bootstrapTable and ran into the following problem:

In every row of my table a preview picture is shown so that the row height is greater than 'normal' and the content in the remaining columns is placed on top. I want to vertical-align the text/buttons/checkboxes in those columns. By using the options align: 'center' and valign: 'middle' for the columns one can achieve this - at least for the 'normal' ones. It has no effect on the columns containing the checkboxes and the detail icons ('plus'-icons).

I added

```<code>.bs-checkbox {
    text-align: center !important;
    vertical-align: middle !important;
}
</code>```

to my css file and received the desired result. But an analog way for the detail-icon class went wrong. I found similar questions on Stackoverflow - but the answers didn't help me.

Has anyone an idea to fix my problem?

Here an example:

var data = [
  {
    "id": 0,
    "name": "Item 0",
    "price": "$0",
    "preview": ''
  },
  {
    "id": 1,
    "name": "Item 1",
    "price": "$1",
    "preview": ''
  },
  {
    "id": 2,
    "name": "Item 2",
    "price": "$2",
    "preview": ''
  }
];

$(function () {
  $('#table').bootstrapTable({
      columns: [
        {
          field: 'state',
          checkbox: true,
          align: 'center',
          valign: 'middle'
        },
        {
          field: 'id',
          title: 'ID',
          align: 'center',
          valign: 'middle',
          sortable: true
        },
        {
          field: 'name',
          title: 'Name',
          sortable: true,
          align: 'center',
          valign: 'middle',
          editable: {
            type: 'text',
            title: 'Name',
            validate: function (value) {return '';}
          }
        },
        {
          field: 'price',
          title: 'Price',
          align: 'center',
          valign: 'middle',
          editable: {
            type: 'text',
            title: 'Price',
            validate: function (value) {return '';}
          }
        },
        {
          field: 'preview',
          title: 'Preview',
          align: 'center',
          valign: 'middle'
        }
      ],
      data: data
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bs-checkbox {
 text-align: center !important;
 vertical-align: middle !important;
}

/* won't work:*/
.detail-icon {
 text-align: center !important;
 vertical-align: middle !important;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.css" rel="stylesheet"/>
<link href="https://rawgit.com/vitalets/x-editable/master/dist/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>

  <button id="new_btn" class="btn btn-success">
    New
  </button>
  <button id="delete_btn" class="btn btn-danger" disabled>
    Delete
  </button>

```

答:
You are actually going to want to set those properties on the table cells themselves, not the elements in the cells.

```<code>#table td {
    vertical-align: middle;
    text-align: center;
}
</code>```

This should do the trick.

Body:
I'm using bootstrapTable and ran into the following problem:

In every row of my table a preview picture is shown so that the row height is greater than 'normal' and the content in the remaining columns is placed on top. I want to vertical-align the text/buttons/checkboxes in those columns. By using the options align: 'center' and valign: 'middle' for the columns one can achieve this - at least for the 'normal' ones. It has no effect on the columns containing the checkboxes and the detail icons ('plus'-icons).

I added

.bs-checkbox {
    text-align: center !important;
    vertical-align: middle !important;
}

to my css file and received the desired result. But an analog way for the detail-icon class went wrong. I found similar questions on Stackoverflow - but the answers didn't help me.

Has anyone an idea to fix my problem?

Here an example:

var data = [
  {
    "id": 0,
    "name": "Item 0",
    "price": "$0",
    "preview": ''
  },
  {
    "id": 1,
    "name": "Item 1",
    "price": "$1",
    "preview": ''
  },
  {
    "id": 2,
    "name": "Item 2",
    "price": "$2",
    "preview": ''
  }
];

$(function () {
  $('#table').bootstrapTable({
      columns: [
        {
          field: 'state',
          checkbox: true,
          align: 'center',
          valign: 'middle'
        },
        {
          field: 'id',
          title: 'ID',
          align: 'center',
          valign: 'middle',
          sortable: true
        },
        {
          field: 'name',
          title: 'Name',
          sortable: true,
          align: 'center',
          valign: 'middle',
          editable: {
            type: 'text',
            title: 'Name',
            validate: function (value) {return '';}
          }
        },
        {
          field: 'price',
          title: 'Price',
          align: 'center',
          valign: 'middle',
          editable: {
            type: 'text',
            title: 'Price',
            validate: function (value) {return '';}
          }
        },
        {
          field: 'preview',
          title: 'Preview',
          align: 'center',
          valign: 'middle'
        }
      ],
      data: data
  });
});

.bs-checkbox {
 text-align: center !important;
 vertical-align: middle !important;
}

/* won't work:*/
.detail-icon {
 text-align: center !important;
 vertical-align: middle !important;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.css" rel="stylesheet"/>
<link href="https://rawgit.com/vitalets/x-editable/master/dist/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>

  <button id="new_btn" class="btn btn-success">
    New
  </button>
  <button id="delete_btn" class="btn btn-danger" disabled>
    Delete
  </button>

Body:
You are actually going to want to set those properties on the table cells themselves, not the elements in the cells.

#table td {
    vertical-align: middle;
    text-align: center;
}

This should do the trick.


问:
Centering listed right-aligned paragraphs
For starters there are many reasons that I can't change the html code so any solution must be using the current html code. What I am trying to do is to right-align the paragraphs but have them centered and not be on the right side of my screen because it doesn't look nice.

```<code><ul class="ullist">
<li><p>sometext</p></li>
<li><p>somemoretext</p></li>
<li><p>somemoremoretext</p></li>
<li><p>lesstext</p></li>
<li><p>text</p></li>
</ul>
</code>```

CSS:

```<code> ul.ullist li {
    display: block !important;
    width: 100% !important;
    margin-bottom: 0;
    text-align: right;
}

ul.ullist li p {
font-size:2.4em;
color:#000;
font-weight:600;
white-space:nowrap;
display:inline-block;}
</code>```

答:
You can add margin-right to your paragraphs:

ul.ullist li {
    display: block !important;
    width: 100% !important;
    margin-bottom: 0;
    text-align: right;
}

ul.ullist li p {
    font-size:2.4em;
    color:#000;
    font-weight:600;
    white-space:nowrap;
    display:inline-block;
    margin-right: 10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="ullist">
    <li><p>sometext</p></li>
    <li><p>somemoretext</p></li>
    <li><p>somemoremoretext</p></li>
    <li><p>lesstext</p></li>
    <li><p>text</p></li>
</ul></code>```

Body:
For starters there are many reasons that I can't change the html code so any solution must be using the current html code. What I am trying to do is to right-align the paragraphs but have them centered and not be on the right side of my screen because it doesn't look nice.

sometext

somemoretext

somemoremoretext

lesstext

text

CSS:

 ul.ullist li {
    display: block !important;
    width: 100% !important;
    margin-bottom: 0;
    text-align: right;
}

ul.ullist li p {
font-size:2.4em;
color:#000;
font-weight:600;
white-space:nowrap;
display:inline-block;}

Body:
You can add margin-right to your paragraphs:

ul.ullist li {
    display: block !important;
    width: 100% !important;
    margin-bottom: 0;
    text-align: right;
}

ul.ullist li p {
    font-size:2.4em;
    color:#000;
    font-weight:600;
    white-space:nowrap;
    display:inline-block;
    margin-right: 10%;
}

<ul class="ullist">
    <li><p>sometext</p></li>
    <li><p>somemoretext</p></li>
    <li><p>somemoremoretext</p></li>
    <li><p>lesstext</p></li>
    <li><p>text</p></li>
</ul>


问:
Association analysis with duplicate transactions using arules package in R
I want to create a transaction object in basket format which I can call anytime for my analyses. The data contains comma separated items with 1001 transactions. The first 10 transactions look like this:

```<code>hering,corned_b,olives,ham,turkey,bourbon,ice_crea
baguette,soda,hering,cracker,heineken,olives,corned_b
avocado,cracker,artichok,heineken,ham,turkey,sardines
olives,bourbon,coke,turkey,ice_crea,ham,peppers
hering,corned_b,apples,olives,steak,avocado,turkey
sardines,heineken,chicken,coke,ice_crea,peppers,ham
olives,bourbon,coke,turkey,ice_crea,heineken,apples
corned_b,peppers,bourbon,cracker,chicken,ice_crea,baguette
soda,olives,bourbon,cracker,heineken,peppers,baguette
corned_b,peppers,bourbon,cracker,chicken,bordeaux,hering
...
</code>```

I observed that there are duplicated transactions in the data and removed them but each time I tried to read the transactions, I get:

Error in asMethod(object) :
  can not coerce list with transactions with duplicated items

Here is my code:

```<code>data <- read.csv("AssociationsItemList.txt",header=F)
data <-  data[!duplicated(data),]
pop <- NULL
for(i in 1:length(data)){
pop <- paste(pop, data[i],sep="\n")
}
write(pop, file = "Trans", sep = ",")
transdata <- read.transactions("Trans", format = "basket", sep=",")
</code>```

I'm sure there's something little yet important I've missed. Kindly offer your assistance.

答:
I just used the 'unique' function to remove duplicates. My data was a little different since I had a dataframe (data was too large for a CSV) and I had 2 columns: product_id and transaction_id. I know it's not your specific question, but I had to do this to create the transaction dataset and apply association rules.</p>

```<code>data # > 1 Million Transactions
data <- unique(data[ , 1:2 ] )
trans <- as(split(data[,"product_id"], data[,"trans_id"]),"transactions")
rules <- apriori(trans, parameter = list(supp = 0.001, conf = 0.2))
</code>```

Body:
I want to create a transaction object in basket format which I can call anytime for my analyses. The data contains comma separated items with 1001 transactions. The first 10 transactions look like this:

hering,corned_b,olives,ham,turkey,bourbon,ice_crea
baguette,soda,hering,cracker,heineken,olives,corned_b
avocado,cracker,artichok,heineken,ham,turkey,sardines
olives,bourbon,coke,turkey,ice_crea,ham,peppers
hering,corned_b,apples,olives,steak,avocado,turkey
sardines,heineken,chicken,coke,ice_crea,peppers,ham
olives,bourbon,coke,turkey,ice_crea,heineken,apples
corned_b,peppers,bourbon,cracker,chicken,ice_crea,baguette
soda,olives,bourbon,cracker,heineken,peppers,baguette
corned_b,peppers,bourbon,cracker,chicken,bordeaux,hering
...

I observed that there are duplicated transactions in the data and removed them but each time I tried to read the transactions, I get:

Error in asMethod(object) :
  can not coerce list with transactions with duplicated items

Here is my code:

data <- read.csv("AssociationsItemList.txt",header=F)
data <-  data[!duplicated(data),]
pop <- NULL
for(i in 1:length(data)){
pop <- paste(pop, data[i],sep="\n")
}
write(pop, file = "Trans", sep = ",")
transdata <- read.transactions("Trans", format = "basket", sep=",")

I'm sure there's something little yet important I've missed. Kindly offer your assistance.

Body:
I just used the 'unique' function to remove duplicates. My data was a little different since I had a dataframe (data was too large for a CSV) and I had 2 columns: product_id and transaction_id. I know it's not your specific question, but I had to do this to create the transaction dataset and apply association rules.

data # > 1 Million Transactions
data <- unique(data[ , 1:2 ] )
trans <- as(split(data[,"product_id"], data[,"trans_id"]),"transactions")
rules <- apriori(trans, parameter = list(supp = 0.001, conf = 0.2))


答:
Try setting some width on ul.ullist and set margin:auto on it.

ul.ullist{
min-width:200px;
width:300px; /*Change the width to suit your needs*/
margin:auto;
}
ul.ullist li {
    display: block !important;
    width: 100% !important;
    margin-bottom: 0;
    text-align: right;
}

ul.ullist li p {
font-size:2.4em;
color:#000;
font-weight:600;
white-space:nowrap;
display:inline-block;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="ullist">
<li><p>sometext</p></li>
<li><p>somemoretext</p></li>
<li><p>somemoremoretext</p></li>
<li><p>lesstext</p></li>
<li><p>text</p></li>
</ul></code>```

Title: Centering listed right-aligned paragraphs

Body:
Try setting some width on ul.ullist and set margin:auto on it.

ul.ullist{
min-width:200px;
width:300px; /*Change the width to suit your needs*/
margin:auto;
}
ul.ullist li {
    display: block !important;
    width: 100% !important;
    margin-bottom: 0;
    text-align: right;
}

ul.ullist li p {
font-size:2.4em;
color:#000;
font-weight:600;
white-space:nowrap;
display:inline-block;}

<ul class="ullist">
<li><p>sometext</p></li>
<li><p>somemoretext</p></li>
<li><p>somemoremoretext</p></li>
<li><p>lesstext</p></li>
<li><p>text</p></li>
</ul>


问:
What is an interface assertion?
I have just came across this piece of code on this blog post

```<code>type Logger interface {
    Debug(msg string, keyvals ...interface{}) error
    Info(msg string, keyvals ...interface{}) error
    Error(msg string, keyvals ...interface{}) error
}

type tmLogger struct {
    srcLogger kitlog.Logger
}

// Interface assertions
var _ Logger = (*tmLogger)(nil) // What is this?

// ... interface definition ...
</code>```

What is this "interface assertion"?

答:
It assigns a nil pointer to a concrete type to a variable of the interface type. This is a common practice to prove that the concrete type fulfills the interface - if it doesn't, that line won't compile, giving an error that the concrete type can't be assigned to a variable of the interface type and why.

As @JimB noted, "interface assertion" is a term made up by the author. Go has no such term. This is, specifically, a type conversion, converting nil to a pointer to tmLogger, then assigning the typed nil pointer to a blank identifier variable of the interface type Logger. If *tmLogger does not satisfy Logger, the assignment won't compile; but, at runtime, this takes no memory because it's using a nil value.

Presumably the author uses this term more in the unit-testing sense of "assertion" than the "type assertion" sense - that line of code asserts that the type implements the interface, and if it doesn't, the line will fail.

Given that this is purely a testing practice, personally I put these checks in _test.go files so that they're included in unit test executions, excluded from the final binary, and clearly part of the test suite and not the application logic.

Title: What is an interface assertion?

Body:
I have just came across this piece of code on this blog post

type Logger interface {
    Debug(msg string, keyvals ...interface{}) error
    Info(msg string, keyvals ...interface{}) error
    Error(msg string, keyvals ...interface{}) error
}

type tmLogger struct {
    srcLogger kitlog.Logger
}

// Interface assertions
var _ Logger = (*tmLogger)(nil) // What is this?

// ... interface definition ...

What is this "interface assertion"?


问:
How do I build Angular 2 for production using Systemjs?
Reading the various sites for building your Angular 2 project for production, there is a tool named Systemjs builder, but it doesn't seem to be a helpful, new developer friendly resource about where to start.  How do I go about building my code minified for production?  Also, will this stop the many, many node_module files from being loaded to the webpage?  Our application takes about 30 seconds to load (if not loading from the cache, where it will take around 7 seconds.  But we want to have a good first impression of our page to a new user, and waiting 30 seconds isn't a great first step!).  Any information would be greatly appreciated!

As I've had a vote to close for being unclear, I'll specify what I am asking.  I'm looking at how to build your code for production using Systemjs builder.  I've looked at online tutorials to configure your build, but these guides don't even indicate whether to add these lines to the Systemjs-config file, or create a new file instead.

答:
Is using the Angular CLI an option for you? It provides built-in features to build your app for production.

https://github.com/angular/angular-cli/wiki


问:
Clear $_SESSION variable with Javascript
I have inherited a file that adds a value to an input like this:

```<code><input type="text" id="cityOrZip" class="form-control zip-field-to-be-validated" name="cityOrZip" value="<? if($_SESSION['locationCityOrZip']) { echo $_SESSION['locationCityOrZip']; } else { ?>80401<? } ?>">
</code>```

A new functionality request for this page has led me to add a javascript function that checks for a specific query parameter in the URL and then update multiple (similar) fields in the form.  How can I ignore the session variable in my function that runs after checking the query parameter.

Here's my js which checks for the query parameter and then resets the fields:

```<code>if ( window.location.search.slice(1,8) === "movedto" ) {

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
       var pair = vars[i].split("=");
       if(pair[0] == variable){return pair[1];}
    }
    return(false);
}

var movedToLocation = getQueryVariable("movedto");

$('#cityOrZip, #filterCityOrZip').val(prettyLocation);
$('#locationType, #filterLocationType').val("Primary Care");
$( "#find-a-location-simple, #find-a-location" ).submit();
</code>```

}

The problem that I'm seeing happen is that:

When the query parameter conditional matches, the inputs are populated by my variables

The PHP $_SESSION variable causes the inputs to reset to what the $_SESSION variable has stored.

答:
I assume that in order for the session value to replace the javascript value that you are submitting the form (thus having php run).
You might need to add to your if statement to determine if a value was posted and use the posted value instead of the session value OR by replacing the stored session value.

I would suggest replacing the session value with the posted data before the form rather than adding to inline if statement.

Body:
I have inherited a file that adds a value to an input like this:

<input type="text" id="cityOrZip" class="form-control zip-field-to-be-validated" name="cityOrZip" value="<? if($_SESSION['locationCityOrZip']) { echo $_SESSION['locationCityOrZip']; } else { ?>80401<? } ?>">

A new functionality request for this page has led me to add a javascript function that checks for a specific query parameter in the URL and then update multiple (similar) fields in the form.  How can I ignore the session variable in my function that runs after checking the query parameter.

Here's my js which checks for the query parameter and then resets the fields:

if ( window.location.search.slice(1,8) === "movedto" ) {

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
       var pair = vars[i].split("=");
       if(pair[0] == variable){return pair[1];}
    }
    return(false);
}

var movedToLocation = getQueryVariable("movedto");

$('#cityOrZip, #filterCityOrZip').val(prettyLocation);
$('#locationType, #filterLocationType').val("Primary Care");
$( "#find-a-location-simple, #find-a-location" ).submit();

}

The problem that I'm seeing happen is that:

When the query parameter conditional matches, the inputs are populated by my variables

The PHP $_SESSION variable causes the inputs to reset to what the $_SESSION variable has stored.


问:
pythonic way of extracting desired substring from a bigger string
I have a string like this

```<code>msg = b'@\x06string\x083http://schemas.microsoft.com/2003/10/Serialization/\x9a\x05\x18{"PUID":"9279565","Title":"Risk Manager","Description":"<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}\x01'
</code>```

The string {"PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"} is json parsable. So I come up with the following code to remove garbage strings from the above msg

```<code>x1 =  msg.split(b'{"',1)[1]
>>>
>>> x1
b'PUID":"9279565","Title":"Risk Manager","Description":"<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}\x01'
x2 = x1[::-1].split(b'}"', 1)[1][::-1]
>>> x2
b'PUID":"9279565","Title":"Risk Manager","Description":"<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,'
>>> final_msg = b'{"%s"}'%x2
>>> final_msg
b'{"PUID":"9279565","Title":"Risk Manager","Description":"<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}'
>>> import json
>>> json.loads(final_msg)
{'Description': "<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,'", 'Title': 'Risk Manager', "b'PUID": '9279565'}
</code>```

Its a bad way of doing what is required, I would like to know a more optimized way of achieving the result. I think regex can be helpful here but I have a very limited knowledge of regular expressions.

Thanks in advance

答:
You can convert byte type to string type first

```<code>msg = str(msg)
</code>```

After which you can write a generator function along with enumeration to pull out the index of the symbol you are searching for

```<code>def gen_index(a_string):
    for i,symbol in enumerate(a_string):
        if symbol == '{':
            yield i
    for j , symbol in enumerate(a_string):
       if symbol == '}':
           yield j

 >>>a = list(gen_index(msg))  # returns the array
 >>># use array slicing to output to json. We need the first occurance of '{' and the last occurance of '}'
 import json
 json_output = json.loads(msg[a[0]:a[-1]+1])
</code>```

Body:
I have a string like this

msg = b'@\x06string\x083http://schemas.microsoft.com/2003/10/Serialization/\x9a\x05\x18{"PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}\x01'

The string {"PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"} is json parsable. So I come up with the following code to remove garbage strings from the above msg

x1 =  msg.split(b'{"',1)[1]
>>>
>>> x1
b'PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}\x01'
x2 = x1[::-1].split(b'}"', 1)[1][::-1]
>>> x2
b'PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,'
>>> final_msg = b'{"%s"}'%x2
>>> final_msg
b'{"PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}'
>>> import json
>>> json.loads(final_msg)
{'Description': "Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,'", 'Title': 'Risk Manager', "b'PUID": '9279565'}

Its a bad way of doing what is required, I would like to know a more optimized way of achieving the result. I think regex can be helpful here but I have a very limited knowledge of regular expressions.

Thanks in advance

Body:
You can convert byte type to string type first

msg = str(msg)

After which you can write a generator function along with enumeration to pull out the index of the symbol you are searching for

def gen_index(a_string):
    for i,symbol in enumerate(a_string):
        if symbol == '{':
            yield i
    for j , symbol in enumerate(a_string):
       if symbol == '}':
           yield j

 >>>a = list(gen_index(msg))  # returns the array
 >>># use array slicing to output to json. We need the first occurance of '{' and the last occurance of '}'
 import json
 json_output = json.loads(msg[a[0]:a[-1]+1])


问:
file_get_contents() - given an URL crashes WordPress
So i was putting a WordPress website live the other day and when i did so, it crashed WordPress.

The culprit was file_get_contents(). I have been using it in a few small places to load my svg inline. See the code for how i was rendering it:

```<code>echo file_get_contents( get_bloginfo('template_url') . 'Images/logo.svg');
</code>```

It worked fine on my local ubuntu apache set up and also worked fine on our staging servers which mimic the live environments.

Using a resource path instead of the web protocol path fixed the issues but isn't file_get_contents() also able to work with web resources?

Why did it happen only on the live when the staging server is the same?

Second issue (maybe related): The client whom I made the website for got their IT guy to point his A WWW towards our server, when he did and told me he had done it, i visited the site but also bought down my dedicated server and my hosting provider as well as the hosting company of the previous website!

There was a lot of traffic coming from the previous web host ip address to request the logo.svg. Does anybody have a good guess at whats happening here?

答:
There may be various reasons for this behaviour. First of all you in your wp-config.php you should

```<code>define('WP_DEBUG',true);
</code>```

in order to see error messages correctly.

As you have already stateted file_get_contents() is able to work with web resources as well as with paths (http://php.net/manual/en/function.file-get-contents.php).

The fact that the problem is solved if you are using paths limits the amount of possible errors.

Possible problems with file_get_contents() and (possibly external) URLs are well known - have a look at the following discussions:

file_get_contents is not working for some url

PHP ini file_get_contents external url

Why doesn't file_get_contents work?

With your problem description there is no possibility to answer the problem more specifically. There can be a lot of different problems which result from the server configuration.

Body:
So i was putting a WordPress website live the other day and when i did so, it crashed WordPress.

The culprit was file_get_contents(). I have been using it in a few small places to load my svg inline. See the code for how i was rendering it:

echo file_get_contents( get_bloginfo('template_url') . 'Images/logo.svg');

It worked fine on my local ubuntu apache set up and also worked fine on our staging servers which mimic the live environments.

Using a resource path instead of the web protocol path fixed the issues but isn't file_get_contents() also able to work with web resources?

Why did it happen only on the live when the staging server is the same?

Second issue (maybe related): The client whom I made the website for got their IT guy to point his A WWW towards our server, when he did and told me he had done it, i visited the site but also bought down my dedicated server and my hosting provider as well as the hosting company of the previous website!

There was a lot of traffic coming from the previous web host ip address to request the logo.svg. Does anybody have a good guess at whats happening here?

Body:
There may be various reasons for this behaviour. First of all you in your wp-config.php you should

define('WP_DEBUG',true);

in order to see error messages correctly.

As you have already stateted file_get_contents() is able to work with web resources as well as with paths (http://php.net/manual/en/function.file-get-contents.php).

The fact that the problem is solved if you are using paths limits the amount of possible errors.

Possible problems with file_get_contents() and (possibly external) URLs are well known - have a look at the following discussions:

file_get_contents is not working for some url

PHP ini file_get_contents external url

Why doesn't file_get_contents work?

With your problem description there is no possibility to answer the problem more specifically. There can be a lot of different problems which result from the server configuration.


问:
Sql Alchemy cannot run inside a transaction block
I'm trying to run a query in redshift from a python script, but I'm getting error:

```<code>sqlalchemy.exc.InternalError: (psycopg2.InternalError) ALTER EXTERNAL TABLE cannot run inside a transaction block
</code>```

This is my code:

```<code>engine = create_engine(SQL_ENGINE % urlquote(REDSHIFT_PASS))
partition_date = (date.today() - timedelta(day)).strftime("%Y%m%d")
query = """alter table  {table_name} add partition (dt={date_partition}) location 's3://dft-dwh-files/raw_data/google_analytics/revenue_per_channel/{date_partition}/';""".format(date_partition=partition_date,table_name=table_name)
conn = engine.connect()
conn.execute(query).execution_options(autocommit=True)
</code>```

How can I fix this?

答:
For PostgreSQL, you need to set the isolation level to AUTOCOMMIT, not the SQLAlchemy autocommit:

```<code>conn.execution_options(isolation_level="AUTOCOMMIT").execute(query)
</code>```

Body:
I'm trying to run a query in redshift from a python script, but I'm getting error:

sqlalchemy.exc.InternalError: (psycopg2.InternalError) ALTER EXTERNAL TABLE cannot run inside a transaction block

This is my code:

engine = create_engine(SQL_ENGINE % urlquote(REDSHIFT_PASS))
partition_date = (date.today() - timedelta(day)).strftime("%Y%m%d")
query = """alter table  {table_name} add partition (dt={date_partition}) location 's3://dft-dwh-files/raw_data/google_analytics/revenue_per_channel/{date_partition}/';""".format(date_partition=partition_date,table_name=table_name)
conn = engine.connect()
conn.execute(query).execution_options(autocommit=True)

How can I fix this?

Body:
For PostgreSQL, you need to set the isolation level to AUTOCOMMIT, not the SQLAlchemy autocommit:

conn.execution_options(isolation_level="AUTOCOMMIT").execute(query)


问:
Can't get a real value of screen width on my phone
I use @media screen and (max-width: 600) on my site. But my iPhone doesn't react on it. He displays full site like my desktop browser does. I added this snippet of code:

```<code>alert(document.documentElement.clientWidth);
alert(window.innerWidth);
</code>```

When I go to the site via my desktop browser, it shows actual width of my window. But when I do it via my iPhone, it always says that screen's width is 980, both of the alerts. Why does it happen? What of @media can I use to make my site responsible, because (max-width) and (width) dont work for me

答:
```<code><meta name="viewport" content="width=device-width, initial-scale=1"/>
</code>```

This helped me.

Body:
I use @media screen and (max-width: 600) on my site. But my iPhone doesn't react on it. He displays full site like my desktop browser does. I added this snippet of code:

alert(document.documentElement.clientWidth);
alert(window.innerWidth);

When I go to the site via my desktop browser, it shows actual width of my window. But when I do it via my iPhone, it always says that screen's width is 980, both of the alerts. Why does it happen? What of @media can I use to make my site responsible, because (max-width) and (width) dont work for me

Body:
<meta name="viewport" content="width=device-width, initial-scale=1"/>

This helped me.


问:
Encrypting in C# and Decrypting with Crypto++ does not work
Encryption :

```<code>    public static byte[] EncryptAES(Message msg)
    {

        byte[] encText; // This will keep the encrypted text
        byte[] encLength; // This will keep the length of the encrypted text
        byte[] finalEncText = null; // This keeps the encLength + encText (#####[encText] / [encLength][encText])

        // Building the plaintext message :
        string plainText = msg.MessageCode.ToString();

        if (msg.Parameters != null)
            foreach (string parameter in msg.Parameters)
                plainText += parameter;

        // Encrypting the plaintext :
        encText = EncryptAES(plainText);

        string encLen = encText.Length.ToString();
        string fittedEncLen = MessageSender.FitStringIntoSize(encLen, Globals.MESSAGE_LENGTH_LEN); // Fit the length of the encrypted text into a certain size
        encLength = Encoding.ASCII.GetBytes(fittedEncLen); // convert the length into byte[]

        finalEncText = new byte[encLength.Length + encText.Length];
        System.Buffer.BlockCopy(encLength, 0, finalEncText, 0, encLength.Length);
        System.Buffer.BlockCopy(encText, 0, finalEncText, encLength.Length, encText.Length); // Copy the byte arrays into the new byte array

        return finalEncText;
    }

    private static byte[] EncryptAES(string text)
    {
        // This function encrypts a plaintext message using the aes key we have from the server

        if (AesKey == null || IV == null) // If we dont have an aes key / iv, dont encrypt
            return Encoding.ASCII.GetBytes(text);

        byte[] encryptedText;

        try
        {
            Aes aes = Aes.Create();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            aes.Key = Encoding.ASCII.GetBytes(AesKey);
            aes.IV = Encoding.ASCII.GetBytes(IV);

            ICryptoTransform cryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            using (MemoryStream memStream = new MemoryStream())
            {
                using (CryptoStream crypotStream = new CryptoStream(memStream, cryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter writerStream = new StreamWriter(crypotStream))
                    {
                        writerStream.Write(text);
                    }
                    encryptedText = memStream.ToArray();
                }
            }

            aes.Dispose();
        }
        catch
        {
            // In case of an error while encrypting, dont encrypt
            encryptedText = Encoding.ASCII.GetBytes(text);
        }
        return encryptedText;
    }
</code>```

[The added fittedEncLen is basically a prefix of fixed length of 5 chars, that contains the length of the encrypted message following it, before decrypting the server reads those 5 chars and then it decrypts the encrypted part]

Sending the message to the server [TCPClient] [C#] :

```<code>public int Send(Message message)
        {
            /*
             * Encrpyts the message and then sends it to the network stream.
             *
             * Return code:
             *      0 on success.
             *      -1 on failure.
             */

            byte[] msg = Cryptography.EncryptAES(message); // Encrypt the message
            // Sending message

            try
            {
                this._networkStream.Write(msg, 0, msg.Length);
                this._networkStream.Flush();
            }
            catch
            {
                return -1;
            }
            return 0;
        }
</code>```

Receiving [C++] :

```<code>wstring Helper::getWideStringPartFromSocket(SOCKET sc, int bytesNum)
{
    // This function reads the message from the socket, using wide string
    std::wstringstream cls;
    cls << getPartFromSocket(sc, bytesNum, 0);
    return cls.str();
}

char* Helper::getPartFromSocket(SOCKET sc, int bytesNum, int flags)
{
    if (bytesNum == 0)
        return "";

    char* data = new char[bytesNum + 1];
    int res = recv(sc, data, bytesNum, flags);

    if (res == INVALID_SOCKET)
    {
        string s = "Error while recieving from socket: ";
        s += to_string(sc);
        throw exception(s.c_str());
    }

    data[bytesNum] = 0;

    return data;
}

BufferedString* Helper::makeBufferedString(SOCKET sc)
    {
        /*
            The socket contains <length of encrypted message (unencrypted)> <encrypted message>.

            This function will read the length of the unencrypted message, read
            the encrypted message, decrypt it, store it in a BufferedString
            object and return the object.

            Length of length number: MESSAGE_LENGTH_LEN.
        */

        int sizeOfMessage = Helper::getIntPartFromSocket(sc, MESSAGE_LENGTH_LEN);
        if (sizeOfMessage == 0)
            return NULL;

        wstring wideString = getWideStringPartFromSocket(sc, sizeOfMessage);
        string decrypted = "";

        if (wideString.length() < sizeOfMessage)
        {
            std::wstringstream cls;
            cls << wideString;
            cls << getWideStringPartFromSocket(sc, sizeOfMessage - wideString.length());
            wideString = cls.str();
        }

        SocketEncryptionKeychain* keyChain = SocketEncryptionKeychain::getKeychain(sc);

        if (keyChain != nullptr) // If the socket has a keychain, decrypt the message
            decrypted = Cryptography::decryptAES(wideString, keyChain->getKey(), keyChain->getIV()); // Try to decrypt the message
        else // If the keychain is null, just convert the widestring to a string
            decrypted = wideStringToString(wideString);

        return new BufferedString(decrypted);
    }
</code>```

SocketEncryptionKeychain basically contains the AES Key and IV for each socket
BufferedString is a class that contains the string, and you can read from it like you read from a socket [its a buffer that once you read from it, what you read is deleted] [basically a string buffer, nothing special]

Decrypting [C++]:

```<code>string Cryptography::decryptAES(wstring cipherText, byte aesKey[], byte iv[])
{
    if (aesKey == nullptr || iv == nullptr) // If the key or iv are null, dont decrypt
        return Helper::wideStringToString(cipherText);

    string plaintext;
    try
    {
        // Decrypt :
        byte* cipher = wideStringToByteArray(cipherText); // Convert the wide string to byte*

        CryptoPP::AES::Decryption aesDecryption(aesKey, 32);
        CryptoPP::CBC_Mode_ExternalCipher::Decryption ecbDecryption(aesDecryption, iv);

        CryptoPP::StreamTransformationFilter stfDecryptor(ecbDecryption, new CryptoPP::StringSink(plaintext), StreamTransformationFilter::ZEROS_PADDING);
        stfDecryptor.Put(cipher, cipherText.length());
        stfDecryptor.MessageEnd();

        Helper::safeDelete(cipher);
    }
    catch (CryptoPP::InvalidCiphertext& ex)
    {
        // In case of an error don't decrypt
        plaintext = Helper::wideStringToString(cipherText);
    }

    return plaintext;
}

byte* Cryptography::wideStringToByteArray(wstring text)
{
    // This function translates the wstring into a byte*
    byte* bytes = new byte[text.length()]; // Convert the wstring to byte*
    for (int i = 0; i < text.length(); i++)
    {
        bytes[i] = text[i];
    }
    return bytes;
}
</code>```

[Helper::safeDelete is a function that just deletes the pointer and sets it as null]

The decryption only fails once in a while

答:
You may have other problems, but here's one:

```<code>using (CryptoStream crypotStream = new CryptoStream(memStream, cryptor, CryptoStreamMode.Write))
{
    using (StreamWriter writerStream = new StreamWriter(crypotStream))
    {
        writerStream.Write(text);
    }
    encryptedText = memStream.ToArray();
}
</code>```

You drained the CryptoStream's output before telling the CryptoStream it was done.  So you've possibly lost up to 16 bytes.

You need to either:

call FlushFinalBlock() on crypotStream(sic).

don't call memStream.ToArray() until after the using for the CryptoStream has exited.

Body:
Encryption :

    public static byte[] EncryptAES(Message msg)
    {

        byte[] encText; // This will keep the encrypted text
        byte[] encLength; // This will keep the length of the encrypted text
        byte[] finalEncText = null; // This keeps the encLength + encText (#####[encText] / [encLength][encText])

        // Building the plaintext message :
        string plainText = msg.MessageCode.ToString();

        if (msg.Parameters != null)
            foreach (string parameter in msg.Parameters)
                plainText += parameter;

        // Encrypting the plaintext :
        encText = EncryptAES(plainText);

        string encLen = encText.Length.ToString();
        string fittedEncLen = MessageSender.FitStringIntoSize(encLen, Globals.MESSAGE_LENGTH_LEN); // Fit the length of the encrypted text into a certain size
        encLength = Encoding.ASCII.GetBytes(fittedEncLen); // convert the length into byte[]

        finalEncText = new byte[encLength.Length + encText.Length];
        System.Buffer.BlockCopy(encLength, 0, finalEncText, 0, encLength.Length);
        System.Buffer.BlockCopy(encText, 0, finalEncText, encLength.Length, encText.Length); // Copy the byte arrays into the new byte array

        return finalEncText;
    }

    private static byte[] EncryptAES(string text)
    {
        // This function encrypts a plaintext message using the aes key we have from the server

        if (AesKey == null || IV == null) // If we dont have an aes key / iv, dont encrypt
            return Encoding.ASCII.GetBytes(text);

        byte[] encryptedText;

        try
        {
            Aes aes = Aes.Create();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            aes.Key = Encoding.ASCII.GetBytes(AesKey);
            aes.IV = Encoding.ASCII.GetBytes(IV);

            ICryptoTransform cryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            using (MemoryStream memStream = new MemoryStream())
            {
                using (CryptoStream crypotStream = new CryptoStream(memStream, cryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter writerStream = new StreamWriter(crypotStream))
                    {
                        writerStream.Write(text);
                    }
                    encryptedText = memStream.ToArray();
                }
            }

            aes.Dispose();
        }
        catch
        {
            // In case of an error while encrypting, dont encrypt
            encryptedText = Encoding.ASCII.GetBytes(text);
        }
        return encryptedText;
    }

[The added fittedEncLen is basically a prefix of fixed length of 5 chars, that contains the length of the encrypted message following it, before decrypting the server reads those 5 chars and then it decrypts the encrypted part]

Sending the message to the server [TCPClient] [C#] :

public int Send(Message message)
        {
            /*
             * Encrpyts the message and then sends it to the network stream.
             *
             * Return code:
             *      0 on success.
             *      -1 on failure.
             */

            byte[] msg = Cryptography.EncryptAES(message); // Encrypt the message
            // Sending message

            try
            {
                this._networkStream.Write(msg, 0, msg.Length);
                this._networkStream.Flush();
            }
            catch
            {
                return -1;
            }
            return 0;
        }

Receiving [C++] :

wstring Helper::getWideStringPartFromSocket(SOCKET sc, int bytesNum)
{
    // This function reads the message from the socket, using wide string
    std::wstringstream cls;
    cls << getPartFromSocket(sc, bytesNum, 0);
    return cls.str();
}

char* Helper::getPartFromSocket(SOCKET sc, int bytesNum, int flags)
{
    if (bytesNum == 0)
        return "";

    char* data = new char[bytesNum + 1];
    int res = recv(sc, data, bytesNum, flags);

    if (res == INVALID_SOCKET)
    {
        string s = "Error while recieving from socket: ";
        s += to_string(sc);
        throw exception(s.c_str());
    }

    data[bytesNum] = 0;

    return data;
}

BufferedString* Helper::makeBufferedString(SOCKET sc)
    {
        /*
            The socket contains <length of encrypted message (unencrypted)> <encrypted message>.

            This function will read the length of the unencrypted message, read
            the encrypted message, decrypt it, store it in a BufferedString
            object and return the object.

            Length of length number: MESSAGE_LENGTH_LEN.
        */

        int sizeOfMessage = Helper::getIntPartFromSocket(sc, MESSAGE_LENGTH_LEN);
        if (sizeOfMessage == 0)
            return NULL;

        wstring wideString = getWideStringPartFromSocket(sc, sizeOfMessage);
        string decrypted = "";

        if (wideString.length() < sizeOfMessage)
        {
            std::wstringstream cls;
            cls << wideString;
            cls << getWideStringPartFromSocket(sc, sizeOfMessage - wideString.length());
            wideString = cls.str();
        }

        SocketEncryptionKeychain* keyChain = SocketEncryptionKeychain::getKeychain(sc);

        if (keyChain != nullptr) // If the socket has a keychain, decrypt the message
            decrypted = Cryptography::decryptAES(wideString, keyChain->getKey(), keyChain->getIV()); // Try to decrypt the message
        else // If the keychain is null, just convert the widestring to a string
            decrypted = wideStringToString(wideString);

        return new BufferedString(decrypted);
    }

SocketEncryptionKeychain basically contains the AES Key and IV for each socket
BufferedString is a class that contains the string, and you can read from it like you read from a socket [its a buffer that once you read from it, what you read is deleted] [basically a string buffer, nothing special]

Decrypting [C++]:

string Cryptography::decryptAES(wstring cipherText, byte aesKey[], byte iv[])
{
    if (aesKey == nullptr || iv == nullptr) // If the key or iv are null, dont decrypt
        return Helper::wideStringToString(cipherText);

    string plaintext;
    try
    {
        // Decrypt :
        byte* cipher = wideStringToByteArray(cipherText); // Convert the wide string to byte*

        CryptoPP::AES::Decryption aesDecryption(aesKey, 32);
        CryptoPP::CBC_Mode_ExternalCipher::Decryption ecbDecryption(aesDecryption, iv);

        CryptoPP::StreamTransformationFilter stfDecryptor(ecbDecryption, new CryptoPP::StringSink(plaintext), StreamTransformationFilter::ZEROS_PADDING);
        stfDecryptor.Put(cipher, cipherText.length());
        stfDecryptor.MessageEnd();

        Helper::safeDelete(cipher);
    }
    catch (CryptoPP::InvalidCiphertext& ex)
    {
        // In case of an error don't decrypt
        plaintext = Helper::wideStringToString(cipherText);
    }

    return plaintext;
}

byte* Cryptography::wideStringToByteArray(wstring text)
{
    // This function translates the wstring into a byte*
    byte* bytes = new byte[text.length()]; // Convert the wstring to byte*
    for (int i = 0; i < text.length(); i++)
    {
        bytes[i] = text[i];
    }
    return bytes;
}

[Helper::safeDelete is a function that just deletes the pointer and sets it as null]

The decryption only fails once in a while

Body:
You may have other problems, but here's one:

using (CryptoStream crypotStream = new CryptoStream(memStream, cryptor, CryptoStreamMode.Write))
{
    using (StreamWriter writerStream = new StreamWriter(crypotStream))
    {
        writerStream.Write(text);
    }
    encryptedText = memStream.ToArray();
}

You drained the CryptoStream's output before telling the CryptoStream it was done.  So you've possibly lost up to 16 bytes.

You need to either:

call FlushFinalBlock() on crypotStream(sic).

don't call memStream.ToArray() until after the using for the CryptoStream has exited.


问:
Dividing workload on several threads
I was wondering if anyone knows about a good article which describes dividing workload on to several Threads? Preferebly it would be written for C# but it's really the concept I'm after, so it's not an issue if it's written for a different, similar, language.

I have a problem where I would have to divide a large amount of computing into several threads and then Sum the generated data after one iteration completes (so I would need to know that all threads have finished) and then start a new iteration, supplying all the threads with the data generated in the last iteration (the data would be modified before the end of each iteration).

I hope this makes sense, and is possible. Either way I would appreciate some advice on how to tackle the problem of computing large amounts of data divided on to several threads (so I can use more than one processor's core).

Thank you for your answers!

答:
"Parallel Extensions" is designed for this, in particular the Parallel class (which allows you to split work up between the threads very easily). The aggregation of results is trickier; some quick searching shows some mixed results  - but I don't know what will be in the final release (i.e. it could be easier).

The CTP is  available here, or wait for .NET 4.0.

OwnerDisplayName: Rekreativc

Title: Dividing workload on several threads

OwnerDisplayName: Marc Gravell


问:
Refreshing a page in a browser yields POST or GET request?
I am learning asp.net mvc form processing now and confused with the following:

What happens if we push the refresh button on the browser?
It makes a POST or GET request?

答:
This is dependant on the last call that was made by the browser to get the current data. Eg:

a) If you submitted a form, performing a POST and then hit refresh, the browser will do another POST.

b) If you just clicked a link that took you to another page, performing a GET, you'll a refresh will perform a get.

If you're just starting out understanding the GET/POST methods, there is a nice pattern that you should understand that will help you not get in situations where data is posted again and again by users who constantly refresh the browser after a POST:

http://en.wikipedia.org/wiki/Post/Redirect/Get

and

An example specifically for asp.net MVC