问:
SIMD Program slow runtime
I'm starting with SIMD programming but i don't know what to do at this moment. I'm trying to diminish runtime but its doing it the other way.

This is my basic code:
https://codepaste.net/a8ut89

```<code>void blurr2(double * u, double * r) {

    int i;
    double dos[2] = { 2.0, 2.0 };

    for (i = 0; i < SIZE - 1; i++) {
        r[i] = u[i] + u[i + 1];
    }
}
</code>```

blurr2: 0.43s

```<code>int contarNegativos(double * u) {

    int i;
    int contador = 0;

    for (i = 0; i < SIZE; i++) {
        if (u[i] < 0) {
            contador++;
        }
    }
    return contador;
}
</code>```

negativeCount: 1.38s

```<code>void ord(double * v, double * u, double * r) {

    int i;

    for (i = 0; i < SIZE; i += 2) {
        r[i] = *(__int64*)&(v[i]) | *(__int64*)&(u[i]);
    }
}
</code>```

ord: 0.33

And this is my SIMD code:

https://codepaste.net/fbg1g5

```<code>void blurr2(double * u, double * r) {

    __m128d rp2;
    __m128d rdos;
    __m128d rr;
    int i;
    int sizeAux = SIZE % 2 == 1 ? SIZE : SIZE - 1;
    double dos[2] = { 2.0, 2.0 };

    rdos = *(__m128d*)dos;

    for (i = 0; i < sizeAux; i += 2) {
        rp2 = *(__m128d*)&u[i + 1];
        rr = _mm_add_pd(*(__m128d*)&u[i], rp2);
        *((__m128d*)&r[i]) = _mm_div_pd(rr, rdos);
    }
}
</code>```

blurr2: 0.42s

```<code>int contarNegativos(double * u) {

    __m128d rcero;
    __m128d rr;
    int i;
    double cero[2] = { 0.0, 0.0 };
    int contador = 0;

    rcero = *(__m128d*)cero;

    for (i = 0; i < SIZE; i += 2) {
        rr = _mm_cmplt_pd(*(__m128d*)&u[i], rcero);
        if (((__int64 *)&rr)[0]) {
            contador++;
        };
        if (((__int64 *)&rr)[1]) {
            contador++;
        };
    }
    return contador;
}
</code>```

negativeCount: 1.42s

```<code>void ord(double * v, double * u, double * r) {

    __m128d rr;
    int i;

    for (i = 0; i < SIZE; i += 2) {
        *((__m128d*)&r[i]) = _mm_or_pd(*(__m128d*)&v[i], *(__m128d*)&u[i]);
    }
}
</code>```

ord: 0.35s

**Differents solutions.

Can you explain me what i'm doing wrong? I'm a bit lost...

答:
Do you know that ord function with SIMD is not 1:1 to ord function without using SIMD instructions ?

In ord function without using SIMD, result of OR operation is calculated for even indexes

```<code>r[0] = v[0] | u[0],
r[2] = v[2] | u[2],
r[4] = v[4] | u[4]
</code>```

what with odd indexes? maybe, if OR operations are calculated for all indexes, it will take more time than now.

Title: SIMD Program slow runtime

Body:
I'm starting with SIMD programming but i don't know what to do at this moment. I'm trying to diminish runtime but its doing it the other way.

This is my basic code:
https://codepaste.net/a8ut89

void blurr2(double * u, double * r) {

    int i;
    double dos[2] = { 2.0, 2.0 };

    for (i = 0; i < SIZE - 1; i++) {
        r[i] = u[i] + u[i + 1];
    }
}

blurr2: 0.43s

int contarNegativos(double * u) {

    int i;
    int contador = 0;

    for (i = 0; i < SIZE; i++) {
        if (u[i] < 0) {
            contador++;
        }
    }
    return contador;
}

negativeCount: 1.38s

void ord(double * v, double * u, double * r) {

    int i;

    for (i = 0; i < SIZE; i += 2) {
        r[i] = *(__int64*)&(v[i]) | *(__int64*)&(u[i]);
    }
}

ord: 0.33

And this is my SIMD code:

https://codepaste.net/fbg1g5

void blurr2(double * u, double * r) {

    __m128d rp2;
    __m128d rdos;
    __m128d rr;
    int i;
    int sizeAux = SIZE % 2 == 1 ? SIZE : SIZE - 1;
    double dos[2] = { 2.0, 2.0 };

    rdos = *(__m128d*)dos;

    for (i = 0; i < sizeAux; i += 2) {
        rp2 = *(__m128d*)&u[i + 1];
        rr = _mm_add_pd(*(__m128d*)&u[i], rp2);
        *((__m128d*)&r[i]) = _mm_div_pd(rr, rdos);
    }
}

blurr2: 0.42s

int contarNegativos(double * u) {

    __m128d rcero;
    __m128d rr;
    int i;
    double cero[2] = { 0.0, 0.0 };
    int contador = 0;

    rcero = *(__m128d*)cero;

    for (i = 0; i < SIZE; i += 2) {
        rr = _mm_cmplt_pd(*(__m128d*)&u[i], rcero);
        if (((__int64 *)&rr)[0]) {
            contador++;
        };
        if (((__int64 *)&rr)[1]) {
            contador++;
        };
    }
    return contador;
}

negativeCount: 1.42s

void ord(double * v, double * u, double * r) {

    __m128d rr;
    int i;

    for (i = 0; i < SIZE; i += 2) {
        *((__m128d*)&r[i]) = _mm_or_pd(*(__m128d*)&v[i], *(__m128d*)&u[i]);
    }
}

ord: 0.35s

**Differents solutions.

Can you explain me what i'm doing wrong? I'm a bit lost...

Body:
Do you know that ord function with SIMD is not 1:1 to ord function without using SIMD instructions ?

In ord function without using SIMD, result of OR operation is calculated for even indexes

r[0] = v[0] | u[0],
r[2] = v[2] | u[2],
r[4] = v[4] | u[4]

what with odd indexes? maybe, if OR operations are calculated for all indexes, it will take more time than now.


来源: stackexchange

问:
How to send emails from a Java EE Batch Job
I have a requirement to process a list of large number of users daily to send them email and SMS notifications based on some scenario. I am using Java EE batch processing model for this. My Job xml is as follows:

```<code><step id="sendNotification">
    <chunk item-count="10" retry-limit="3">
        <reader ref="myItemReader"></reader>
        <processor ref="myItemProcessor"></processor>
        <writer ref="myItemWriter"></writer>
        <retryable-exception-classes>
            <include class="java.lang.IllegalArgumentException"/>
        </retryable-exception-classes>
    </chunk>
</step>
</code>```

MyItemReader's onOpen method reads all users from database, and readItem() reads one user at a time using list iterator. In myItemProcessor, the actual email notification is sent to user, and then the users are persisted in database in myItemWriter class for that chunk.

```<code>@Named
public class MyItemReader extends AbstractItemReader {

    private Iterator<User> iterator = null;
    private User lastUser;

    @Inject
    private MyService service;

    @Override
    public void open(Serializable checkpoint) throws Exception {
        super.open(checkpoint);

        List<User> users = service.getUsers();
        iterator = users.iterator();

        if(checkpoint != null) {
            User checkpointUser = (User) checkpoint;
            System.out.println("Checkpoint Found: " + checkpointUser.getUserId());
            while(iterator.hasNext() && !iterator.next().getUserId().equals(checkpointUser.getUserId())) {
                System.out.println("skipping already read users ... ");
            }
        }
    }

    @Override
    public Object readItem() throws Exception {

        User user=null;

        if(iterator.hasNext()) {
            user = iterator.next();
            lastUser = user;
        }
        return user;
    }

    @Override
    public Serializable checkpointInfo() throws Exception {
        return lastUser;
    }
}
</code>```

My problem is that checkpoint stores the last record that was executed in the previous chunk. If I have a chunk with next 10 users, and exception is thrown in myItemProcessor of the 5th user, then on retry the whole chunck will be executed and all 10 users will be processed again. I don't want notification to be sent again to the already processed users.

Is there a way to handle this? How should this be done efficiently?

Any help would be highly appreciated.
Thanks.

答:
I'm going to build on the comments from @cheng.  My credit to him here, and hopefully my answer provides additional value in organizing and presenting the options usefully.

Answer:  Queue up messages for another MDB to get dispatched to send emails

Background:

As @cheng pointed out, a failure means the entire transaction is rolled back, and the checkpoint doesn't advance.

So how to deal with the fact that your chunk has sent emails to some users but not all?  (You might say it rolled back but with "side effects".)

So we could restate your question then as: How to send email from a batch chunk step?

Well, assuming you had a way to send emails through an transactional API (implementing XAResource, etc.) you could use that API.

Assuming you don't, I would do a transactional write to a JMS queue, and then send the emails with a separate MDB (as @cheng suggested in one of his comments).

Suggested Alternative:  Use ItemWriter to send messages to JMS queue, then use separate MDB to actually send the emails

With this approach you still gain efficiency by batching the processing and the updates to your DB (you were only sending the emails one at a time anyway), and you can benefit from simple checkpointing and restart without having to write complicated error handling.

This is also likely to be reusable as a pattern across batch jobs and outside of batch even.

Other alternatives

Some other ideas that I don't think are as good, listed for the sake of discussion:

Add batch application logic tracking users emailed (with ItemProcessListener)

You could build your own list of either/both successful/failed emails using the ItemProcessListener methods: afterProcess  and onProcessError.

On restart, then, you could know which users had been emailed in the current chunk, which we are re-positioned to since the entire chunk rolled back, even though some emails have already been sent.

This certainly complicates your batch logic, and you also have to persist this success or failure list somehow.  Plus this approach is probably highly specific to this job (as opposed to queuing up for an MDB to process).

But it's simpler in that you have a single batch job without the need for a messaging provider and a separate app component.

If you go this route you might want to use a combination of both a skippable and a "no-rollback" retryable exception.

single-item chunk

If you define your chunk with item-count="1", then you avoid complicated checkpointing and error handling code.   You  sacrifice efficiency though, so this would only make sense if the other aspects of batch were very compelling:  e.g.  scheduling and management of jobs through a common interface, the ability to restart at the failing step within a job

If you were to go this route, you might want to consider defining socket and timeout exceptions as "no-rollback" exceptions (using ) since there's nothing to be gained from rolling back, and you might want to retry on a network timeout issue.

Since you specifically mentioned efficiency, I'm guessing this is a bad fit for you.

use a Transaction Synchronization

This could work perhaps, but the batch API doesn't especially make this easy, and you still could have a case where the chunk completes but one or more email sends fail.

ContentLicense: CC BY-SA 3.0

Body:
I have a requirement to process a list of large number of users daily to send them email and SMS notifications based on some scenario. I am using Java EE batch processing model for this. My Job xml is as follows:

<step id="sendNotification">
    <chunk item-count="10" retry-limit="3">
        <reader ref="myItemReader"></reader>
        <processor ref="myItemProcessor"></processor>
        <writer ref="myItemWriter"></writer>
        <retryable-exception-classes>
            <include class="java.lang.IllegalArgumentException"/>
        </retryable-exception-classes>
    </chunk>
</step>

MyItemReader's onOpen method reads all users from database, and readItem() reads one user at a time using list iterator. In myItemProcessor, the actual email notification is sent to user, and then the users are persisted in database in myItemWriter class for that chunk.

@Named
public class MyItemReader extends AbstractItemReader {

    private Iterator<User> iterator = null;
    private User lastUser;

    @Inject
    private MyService service;

    @Override
    public void open(Serializable checkpoint) throws Exception {
        super.open(checkpoint);

        List<User> users = service.getUsers();
        iterator = users.iterator();

        if(checkpoint != null) {
            User checkpointUser = (User) checkpoint;
            System.out.println("Checkpoint Found: " + checkpointUser.getUserId());
            while(iterator.hasNext() && !iterator.next().getUserId().equals(checkpointUser.getUserId())) {
                System.out.println("skipping already read users ... ");
            }
        }
    }

    @Override
    public Object readItem() throws Exception {

        User user=null;

        if(iterator.hasNext()) {
            user = iterator.next();
            lastUser = user;
        }
        return user;
    }

    @Override
    public Serializable checkpointInfo() throws Exception {
        return lastUser;
    }
}

My problem is that checkpoint stores the last record that was executed in the previous chunk. If I have a chunk with next 10 users, and exception is thrown in myItemProcessor of the 5th user, then on retry the whole chunck will be executed and all 10 users will be processed again. I don't want notification to be sent again to the already processed users.

Is there a way to handle this? How should this be done efficiently?

Any help would be highly appreciated.
Thanks.


问:
JAVA how to print out array in main using a method?
So I need to create a method which would take ints and return an array of length 3 with those three ints as they have been input.

This is what I have created, but it returns this [I@7852e922

```<code>public class IntsToArray {
  public static int[] fill(int a, int b, int c){
      int[] array = new int[3];
      array[0] = a;
      array[1] = b;
      array[2] = c;
      return (array);
  }
    public static void main(String[] args){
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int[] array = fill(a, b, c);
        System.out.println(array);
    }
}
</code>```

What am I doing wrong?

答:
When you pass the array to System.out.println() the array's toString() method is called and the resulting string is written. In the case of an array there is no specific implementation of toString() so the toString() of the super class Object is used. Object.toString() is defined as:

```<code>getClass().getName() + '@' + Integer.toHexString(hashCode());
</code>```

So that is the [I@7852e922 that you are seeing. Essentially this is an internal id for the instance of your array.

To print the contents of the array do this:

```<code>System.out.println(Arrays.toString(array));
</code>```

or this:

```<code>for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}
</code>```

Body:
So I need to create a method which would take ints and return an array of length 3 with those three ints as they have been input.

This is what I have created, but it returns this [I@7852e922

public class IntsToArray {
  public static int[] fill(int a, int b, int c){
      int[] array = new int[3];
      array[0] = a;
      array[1] = b;
      array[2] = c;
      return (array);
  }
    public static void main(String[] args){
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int[] array = fill(a, b, c);
        System.out.println(array);
    }
}

What am I doing wrong?

Body:
When you pass the array to System.out.println() the array's toString() method is called and the resulting string is written. In the case of an array there is no specific implementation of toString() so the toString() of the super class Object is used. Object.toString() is defined as:

getClass().getName() + '@' + Integer.toHexString(hashCode());

So that is the [I@7852e922 that you are seeing. Essentially this is an internal id for the instance of your array.

To print the contents of the array do this:

System.out.println(Arrays.toString(array));

or this:

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


问:
Python: How to break the loop if character limit is met?
I am creating a string that must be exactly 140 characters long. I must use  a loop with a break statement, and the string items are taken from the given list.

In the end, I managed to get to 147 characters. Is there a way to truncate the string?

```<code>headlines = ["Local Bear Eaten by Man",
             "Legislature Announces New Laws",
             "Peasant Discovers Violence Inherent in System",
             "Cat Rescues Fireman Stuck in Tree",
             "Brave Knight Runs Away",
             "Papperbok Review: Totally Triffic"]

news_ticker = ""

for headline in headlines:
    if len(str(news_ticker)) >= 140:
        break
    else:
        news_ticker = list(news_ticker)
        news_ticker.append(headline)

print(news_ticker)
print(len(str(news_ticker)))
</code>```

答:
Your answer returns news_ticker as a list, but it needs to be a string.  It allows you to use the .append function, but you can simply concatenate the string like this:</p>

```<code>for headline in headlines:
    news_ticker += headline + " "
    if len(news_ticker) >= 140:
        news_ticker = news_ticker[:140]
        break
</code>```

Body:
I am creating a string that must be exactly 140 characters long. I must use  a loop with a break statement, and the string items are taken from the given list.

In the end, I managed to get to 147 characters. Is there a way to truncate the string?

headlines = ["Local Bear Eaten by Man",
             "Legislature Announces New Laws",
             "Peasant Discovers Violence Inherent in System",
             "Cat Rescues Fireman Stuck in Tree",
             "Brave Knight Runs Away",
             "Papperbok Review: Totally Triffic"]

news_ticker = ""

for headline in headlines:
    if len(str(news_ticker)) >= 140:
        break
    else:
        news_ticker = list(news_ticker)
        news_ticker.append(headline)

print(news_ticker)
print(len(str(news_ticker)))

Body:
Your answer returns news_ticker as a list, but it needs to be a string.  It allows you to use the .append function, but you can simply concatenate the string like this:

for headline in headlines:
    news_ticker += headline + " "
    if len(news_ticker) >= 140:
        news_ticker = news_ticker[:140]
        break


问:
Recursive calling of a method as an argument in python
I'm trying to write a recursive function in python, but instead of returning an integer type it returns a nonetype. I know there are other questions smiliar to this but not a single solution there worked for me.
Here is the code:</p>

```<code>class t:
def search(self, globina, board):
    board.legals = board.legal()
    bestMove = 0
    if(globina == 0):
        return board.evaluation()
    elif board.turn == False:
        bestMove = -9999
        for i in range(0, len(board.legals)):
            board.move(board.legals[i])
            board.display()
            bestMove = max(bestMove, self.search(globina-1, board))
            board.undo()
        return bestMove

    else:
        bestMove = 9999
        for i in range(0, len(board.legals)):
            board.move(board.legals[i])
            board.display()
            bestMove = min(bestMove, self.search(globina-1, board))
            board.undo()
        return bestMove
z = t()
z.search(globina, board)
</code>```

答:
Your recursive method (as it appears in edited question) is doing the right thing, since it uses return in all of its cases.

That means that the None value must not be due to the recursive function itself, but rather it's a value being returned in the base case somewhere. For your function, that means board.evaluation() returns None at least some of the time.

In Python 3, I'd expect that to cause an exception in any of the recursive cases, as min and max will choke on a None value (since None isn't comparable to anything, including itself). In Python 2 however, all objects are comparable, though there may not be any particular meaning to comparisons between unlike types. The default behavior is to compare class names alphabetically (so all int and float instances are less than all str instances, which are less than all tuples), though if I recall correctly, None compares as less than all other values.

Body:
I'm trying to write a recursive function in python, but instead of returning an integer type it returns a nonetype. I know there are other questions smiliar to this but not a single solution there worked for me.
Here is the code:

class t:
def search(self, globina, board):
    board.legals = board.legal()
    bestMove = 0
    if(globina == 0):
        return board.evaluation()
    elif board.turn == False:
        bestMove = -9999
        for i in range(0, len(board.legals)):
            board.move(board.legals[i])
            board.display()
            bestMove = max(bestMove, self.search(globina-1, board))
            board.undo()
        return bestMove

    else:
        bestMove = 9999
        for i in range(0, len(board.legals)):
            board.move(board.legals[i])
            board.display()
            bestMove = min(bestMove, self.search(globina-1, board))
            board.undo()
        return bestMove
z = t()
z.search(globina, board)


问:
Chargify API - XML issue - '<' not found
I'm trying to run some API scripts found in this github https://github.com/abraham/chargify

with this library https://github.com/jforrest/Chargify-PHP-Client/

When I run the subscriptions.php file, I get this error:

Warning:  SimpleXMLElement::__construct() [simplexmlelement.--construct]: Entity: line 1: parser error : Start tag expected, '<' not found in /Applications/MAMP/htdocs/abraham-chargify-ace5a40/lib/ChargifyConnector.php on line 557

What is causing this error/How do I get rid of it?

答: Well sorry to say this problem turned out to be a settings problem.  If the customer doesn't submit a shipping address (required) then that apparently generates the above error.  Just input an address or remove the shipping address requirement if you fall into this error with Chargify.</p>

ContentLicense: CC BY-SA 2.5


问:
Bulk import CSV file into a single sheet in a Google Sheet file
I'm trying to write a Google Sheet App script that bulk import CSV files into a single sheet in a google sheet.

Every week my server is sending me a CSV file reporting with some updated data from my database. Each CSV file has exactly the same structure, since it's the same report and only date is changing.

I automatically download all the csv in a single Folder on Google Drive
Is there a way to build a script that scans the folder, open the first CSV file fills a Google sheet with the data (and the date of the CSV report) deletes the current CSV from the folder then moves to the next CSV files.

答:
if you dont want to mess around with code, you might as well us this add-on: https://www.sheetgo.com/

Worked well for us. :)


问:
Helm: Extra newline when using "include" for templating
I get a weird new line when my chart is rendered that templates from another file using {{ include }}. For instance, my manifest looks like this

```<code>      containers:
      - name: {{ .Release.Name }}
        image: {{ .Values.global.image}}:{{ .Values.global.imageTag }}
        imagePullPolicy: {{ .Values.global.pullPolicy }}
        ports:
          - containerPort: {{ .Values.gloabl.containerPort }}
{{ include "common_deployment" . }}
</code>```

and my common_deployment is defined as

```<code>{{- define "common_deployment" }}
        envFrom:
          - secretRef:
              name: {{ .Release.Name }}-secret
{{- end -}}
</code>```

when I look at my manifest after doing a dry run on Helm, my template looks something like this

```<code> containers:
  - name: test
    image: myrepo/myimage:latest
    imagePullPolicy: Always
    ports:
      - containerPort: 4444

envFrom:
  - secretRef:
      name: test-secret
</code>```

Notice how there is a new lie between the ports and the envFrom. I'm wondering if this will affect how my pods will turn out because there are issues with volumes being mounted and I want to be able to make sure that this templating problem is the culprit before going down another rabbit hole.

答:
You can use a hyphen to suppress the newline on template commands. You're already using it for define and end.

Similarly, you should use {{- include ... -}}.

Body:
I get a weird new line when my chart is rendered that templates from another file using {{ include }}. For instance, my manifest looks like this

      containers:
      - name: {{ .Release.Name }}
        image: {{ .Values.global.image}}:{{ .Values.global.imageTag }}
        imagePullPolicy: {{ .Values.global.pullPolicy }}
        ports:
          - containerPort: {{ .Values.gloabl.containerPort }}
{{ include "common_deployment" . }}

and my common_deployment is defined as

{{- define "common_deployment" }}
        envFrom:
          - secretRef:
              name: {{ .Release.Name }}-secret
{{- end -}}

when I look at my manifest after doing a dry run on Helm, my template looks something like this

 containers:
  - name: test
    image: myrepo/myimage:latest
    imagePullPolicy: Always
    ports:
      - containerPort: 4444

envFrom:
  - secretRef:
      name: test-secret

Notice how there is a new lie between the ports and the envFrom. I'm wondering if this will affect how my pods will turn out because there are issues with volumes being mounted and I want to be able to make sure that this templating problem is the culprit before going down another rabbit hole.


问:
Barplot by R, the scale (mark, correspond to labels) does not correspond to each bar?
But they are same length vector, I have tried many part of code, just can't let the "city name" correspond each bar? The problem of pdf width? Or I shouldn't axis(1, c(1:47)? Tried but don't solve...Reminder also will be grateful.

```<code>pdf("barplot1.pdf", width = 8.6, height = 8)

matrix_tem <- t(matrix(each_bar_number))    #each_bar_number is a vector, length(each_bar_number) is 47
barplot(matrix_tem, ylim = c(0, 150), xaxt="n", border=NA, space = NULL, beside=F)
axis(1, c(1:47), labels=as.character(cityname_vector), las = 2,cex.axis = 0.6) #length(cityname_vector) is 47

dev.off()
</code>```

答:
barplot() expects the names to be in the names.arg parameter inside the call to barplot. See here for an example. Not sure why the axis labelling fails.

## Default S3 method:

```<code> barplot(height, width = 1, space = NULL,
    names.arg = NULL, legend.text = NULL, beside = FALSE,
    horiz = FALSE, density = NULL, angle = 45,
    col = NULL, border = par("fg"),
    main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
    xlim = NULL, ylim = NULL, xpd = TRUE, log = "",
    axes = TRUE, axisnames = TRUE,
    cex.axis = par("cex.axis"), cex.names = par("cex.axis"),
    inside = TRUE, plot = TRUE, axis.lty = 0, offset = 0,
    add = FALSE, args.legend = NULL, ...)
</code>```

Arguments

```<code> names.arg
   a vector of names to be plotted below each bar or group of bars.
   If this argument is omitted, then the names are taken from the
   names attribute of height if this is a vector, or the column
   names if it is a matrix.
</code>```

Body:
But they are same length vector, I have tried many part of code, just can't let the "city name" correspond each bar? The problem of pdf width? Or I shouldn't axis(1, c(1:47)? Tried but don't solve...Reminder also will be grateful.

pdf("barplot1.pdf", width = 8.6, height = 8)

matrix_tem <- t(matrix(each_bar_number))    #each_bar_number is a vector, length(each_bar_number) is 47
barplot(matrix_tem, ylim = c(0, 150), xaxt="n", border=NA, space = NULL, beside=F)
axis(1, c(1:47), labels=as.character(cityname_vector), las = 2,cex.axis = 0.6) #length(cityname_vector) is 47

dev.off()

Body:
barplot() expects the names to be in the names.arg parameter inside the call to barplot. See here for an example. Not sure why the axis labelling fails.

## Default S3 method:

 barplot(height, width = 1, space = NULL,
    names.arg = NULL, legend.text = NULL, beside = FALSE,
    horiz = FALSE, density = NULL, angle = 45,
    col = NULL, border = par("fg"),
    main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
    xlim = NULL, ylim = NULL, xpd = TRUE, log = "",
    axes = TRUE, axisnames = TRUE,
    cex.axis = par("cex.axis"), cex.names = par("cex.axis"),
    inside = TRUE, plot = TRUE, axis.lty = 0, offset = 0,
    add = FALSE, args.legend = NULL, ...)

Arguments

 names.arg
   a vector of names to be plotted below each bar or group of bars.
   If this argument is omitted, then the names are taken from the
   names attribute of height if this is a vector, or the column
   names if it is a matrix.


Title: javascript: Fast way to find connected components in array (looking for speed up / alternative way)

Body:
I have an matrix (1d array, x&y-axe) like this:

var matrix=[
'00000000000000000000000000000000000000000000000000000000000000000000111111111',
'11111100000000000000000000001000000000000000000000000000000000000000000001111',
'00000000000000000000000000000000001000000000000000000000000000000000000000011',
'11111000000000000000000000000000000000000001111110000000000000000000000000001',
'11111000000000000111000000000000000000111111000000000000000000000000000000000',
'00000000000111111111111100000000000000111111000000000000000000000000000000000',
'00000000000000000110000000000000000000111111000000000000000000010000000000000',
'00000000000000000000000000000001111111000000000000000000000000000000000000000',
'00000100000000000000000000000000000000000000000000000000000000000010000000000',
'00000010010000000000000000000000000000111111110000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000100000000000000',
'00000000000000000000000000000000000000000000000000000100000000000000000000000'
]

and I'D like to find all connected groups of '1'-characters and extract all of their positions to get something like this as result:

[{"0": [[68,0],[69,0],[70,0],[71,0],[72,0],[73,0],[73,1],[74,1],[75,1],[75,2],[76,2],[76,3],[76,1],[76,0],[75,0],[74,0]],"1": [[0,1],[1,1],[2,1],[3,1],[4,1],[5,1]],"2": [[28,1]],"3": [[34,2]],"4": [[0,3],[0,4],[1,4],[2,4],[3,4],[4,4],[4,3],[3,3],[2,3],[1,3]],"5": [[43,3],[43,4],[43,5],[43,6],[42,6],[42,5],[42,4],[41,4],[41,5],[41,6],[40,6],[40,5],[40,4],[39,4],[39,5],[39,6],[38,6],[38,5],[38,4],[44,3],[45,3],[46,3],[47,3],[48,3]],"6": [[17,4],[17,5],[17,6],[18,6],[18,5],[19,5],[20,5],[21,5],[22,5],[23,5],[19,4],[18,4],[16,5],[15,5],[14,5],[13,5],[12,5],[11,5]],"7": [[63,6]],"8": [[31,7],[32,7],[33,7],[34,7],[35,7],[36,7],[37,7]],"9": [[5,8]],"10": [[66,8]],"11": [[6,9]],"12": [[9,9]],"13": [[38,9],[39,9],[40,9],[41,9],[42,9],[43,9],[44,9],[45,9]],"14": [[62,11]],"15": [[53,12]]}]

I have already developed some kind of a flood fill algorithm that is working quiet well with the matrix above.

But there must be a way more efficient & fast way to find connected components in a bigger matrix (e.g 10 or even 100 times bigger).
  --> My idea was maybe this result could be also achieved with some kind of regex expression combined with javascript code, but I'm absolutely not sure how to code this, so I hope somebody has an good idea to fast up my little algorithm below so that I can avoid Overflow Errors :

var matrix=[
'00000000000000000000000000000000000000000000000000000000000000000000111111111',
'11111100000000000000000000001000000000000000000000000000000000000000000001111',
'00000000000000000000000000000000001000000000000000000000000000000000000000011',
'11111000000000000000000000000000000000000001111110000000000000000000000000001',
'11111000000000000111000000000000000000111111000000000000000000000000000000000',
'00000000000111111111111100000000000000111111000000000000000000000000000000000',
'00000000000000000110000000000000000000111111000000000000000000010000000000000',
'00000000000000000000000000000001111111000000000000000000000000000000000000000',
'00000100000000000000000000000000000000000000000000000000000000000010000000000',
'00000010010000000000000000000000000000111111110000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000100000000000000',
'00000000000000000000000000000000000000000000000000000100000000000000000000000'
]

Array.prototype.extract_components_positions = function(offset) {
 var array = this.map(item => item.split('')).map(str => Array.from(str, Number)),
  default_value = 0,
  result_object = {}

 function test_connection(array, i, j) {
  if (array[i] && array[i][j] === -1) {
   if (!result_object[default_value]) result_object[default_value] = [];
   result_object[default_value].push([j, i]);
   array[i][j] = 1;
   for (var k = offset; k > 0; k--) {
    test_connection(array, i + k, j); // left - right
    test_connection(array, i, j + k); // top - bottom
    test_connection(array, i - k, j); // right - left
    test_connection(array, i, j - k); // bottom - top
   }
   return true
  }
 }
 array.forEach(function(a) {
  a.forEach(function(b, i, bb) {
   bb[i] = -b
  })
 });
 array.forEach(function(a, i, aa) {
  a.forEach(function(b, j, bb) {
   test_connection(aa, i, j) && default_value++
  })
 })
 return [result_object];
}

var result = matrix.extract_components_positions(1);
console.log((result))

.as-console-wrapper { max-height: 100% !important; top: 0; }

Edit 1.0 BTW It would be also not that bad if the algorithm is just able to connect bigger components (e.g minimum group of 5 connected characters)

Body:
Code

This is the method I figured out. I'm sure it can be optimized, but I feel it's at least a big step in the right direction.

I've also taken information from the following answers and applied it.

Finding all indexes of a specified character within a string

Check whether an array exists in an array of arrays

var matrix=[
'00000000000000000000000000000000000000000000000000000000000000000000111111111',
'11111100000000000000000000001000000000000000000000000000000000000000000001111',
'00000000000000000000000000000000001000000000000000000000000000000000000000011',
'11111000000000000000000000000000000000000001111110000000000000000000000000001',
'11111000000000000111000000000000000000111111000000000000000000000000000000000',
'00000000000111111111111100000000000000111111000000000000000000000000000000000',
'00000000000000000110000000000000000000111111000000000000000000010000000000000',
'00000000000000000000000000000001111111000000000000000000000000000000000000000',
'00000100000000000000000000000000000000000000000000000000000000000010000000000',
'00000010010000000000000000000000000000111111110000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000100000000000000',
'00000000000000000000000000000000000000000000000000000100000000000000000000000'
]

var results = [];

function charPos(str, char) {
  return str
         .split("")
         .map(function (c, i) { if (c == char) return i; })
         .filter(function (v) { return v >= 0; });
}

matrix.forEach(function(s, i) {
  var p = charPos(s, '1');
  results[i] = [];
  matrix.forEach(function(s2, i2) {
    var p2;
    if((p2 = charPos(s2, '1').filter((n) => p.includes(n))).length) {
      p2.forEach(function(v) {
        if(JSON.stringify(results).indexOf(JSON.stringify([v, i2])) === -1)
          results[i].push([v, i2]);
      });
    }
  });
});

console.log(results.filter(v => v.length > 0));


问:
Use Camel 2.18.x version with Jboss-fuse-karaf-6.3.0.redhat-187
I am using camel-salesforce component in jboss-fuse-karaf-6.3.0.redhat-187. Camel version 2.18.x provide replay with push-topic. If the client subscription got lost we can replay the old notification.

As per Red hat component details page , JBoss Fuse 6.3 support camel version 2.17.0.

https://access.redhat.com/articles/348423

Is there any way we can use camel 2.18.x version with jboss-fuse-karaf-6.3.0.redhat-187, so we use salesforce replay.

Will highlty appreciate if someone could provide any link , document or any red hat jira issue.

We already tried different stuff

1.) Try to merge 2.18 replay classes with 2.17 , there is lot of changes in 30-40 classes so tough doable.

2.) Try to build with 2.18 classes with 2.17 jars .Still not worked with karaf

3.) Fuse 6.3 not support camel 2.18.x so directly using 2.18 not making sense.

Kindly let me know if need any further information.

Thank you so much in advance.

答: No you should use the version that is shipped with JBoss Fuse, that is the certified version. Use Red Hat customer portal to get help/support with your fuse product. If there is a bug/feature in camel-salesforce you are looking for in JBoss Fuse 6.3 that is only available in later Camel release, then the Red Hat team can help you by looking into whether that can be backported and provided to you or what else you can do.</p>


答:
As you've mentioned about not to use library, you can extract the code from class Arrays:

```<code>public static String stringify(int[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(a[i]);
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}
</code>```

And use it as follow:

```<code>public class IntsToArray {
    public static int[] fill(int a, int b, int c){
      int[] array = new int[3];
      array[0] = a;
      array[1] = b;
      array[2] = c;
      return (array);
    }
    public static void main(String[] args){
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int[] array = fill(a, b, c);

        System.out.println(stringify(array));
    }
}
</code>```

Title: JAVA how to print out array in main using a method?

Body:
As you've mentioned about not to use library, you can extract the code from class Arrays:

public static String stringify(int[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(a[i]);
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

And use it as follow:

public class IntsToArray {
    public static int[] fill(int a, int b, int c){
      int[] array = new int[3];
      array[0] = a;
      array[1] = b;
      array[2] = c;
      return (array);
    }
    public static void main(String[] args){
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int[] array = fill(a, b, c);

        System.out.println(stringify(array));
    }
}


问:
jquery html($("").attr("src", this.href)); not working in Safari
I'm  using a simple jquery function for an image gallery. There is a div of thumbnails, then the target div where the large images are loaded into after one clicks on a thumbnail.

It's working fine in all browsers, with the exception of Safari, where the image's absolute url is loaded, opposed to being loaded inside of the div.

Here's the jquery code:

```<code>$("#thumbnails a").click(function() {
    $("#work").html($("<img>").attr("src", this.href));

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

Any thoughts? Thanks

答:
this.href is not safe!

Use $(this).attr('href') and it will work.

Check out my question here: Retrieving HTML attribute values "the DOM 0 way"

It explains that there are several HTML attributes (href among them) that are problematical, so one should use jQuery's attr() to retrieve their values.

Quote from an answer on that page:

For example, the href property of an
   element always reports a fully
  qualified URL while
  getAttribute("href") will return the
  string specified in the HTML href
  attribute verbatim. Except, of course,
  in IE. jQuery's attr() does attempt to
  normalize this kind of inconsistency.

UPDATE

I figured it out. You didn't ensure that the jQuery code runs after the DOM is ready. Always place all your jQuery code inside the ready handler:

```<code>$(function() {

    // place all jQuery code here

});
</code>```

UPDATE 2

Try this code:

```<code>$('#thumbnails a').click(function() {
    $('#work').empty().html( '<img src="' + $(this).attr('href') + '">' );
    return false;
});
</code>```

I should have seen this earlier. The argument of the html() function has to be a string.

UPDATE 3

It could be that Safari (at least) does not execute JavaScript code that is on a page which is loaded entirely via jQuery's load() method.

However, I think that I figured out how to deal with it!

On the 1776.php page, move the SCRIPT element from the HEAD to the BODY of the document.

```<code><body>
    <script> ... the code ... </script>
    <div> ... </div>
</body>
</code>```

Title: jquery html($("<img>").attr("src", this.href)); not working in Safari

Body:
I'm  using a simple jquery function for an image gallery. There is a div of thumbnails, then the target div where the large images are loaded into after one clicks on a thumbnail.

It's working fine in all browsers, with the exception of Safari, where the image's absolute url is loaded, opposed to being loaded inside of the div.

Here's the jquery code:

$("#thumbnails a").click(function() {
    $("#work").html($("").attr("src", this.href));

    return false;
});

Any thoughts? Thanks

Body:
this.href is not safe!

Use $(this).attr('href') and it will work.

Check out my question here: Retrieving HTML attribute values "the DOM 0 way"

It explains that there are several HTML attributes (href among them) that are problematical, so one should use jQuery's attr() to retrieve their values.

Quote from an answer on that page:

For example, the href property of an
   element always reports a fully
  qualified URL while
  getAttribute("href") will return the
  string specified in the HTML href
  attribute verbatim. Except, of course,
  in IE. jQuery's attr() does attempt to
  normalize this kind of inconsistency.

UPDATE

I figured it out. You didn't ensure that the jQuery code runs after the DOM is ready. Always place all your jQuery code inside the ready handler:

$(function() {

    // place all jQuery code here

});

UPDATE 2

Try this code:

$('#thumbnails a').click(function() {
    $('#work').empty().html( '<img src="' + $(this).attr('href') + '">' );
    return false;
});

I should have seen this earlier. The argument of the html() function has to be a string.

UPDATE 3

It could be that Safari (at least) does not execute JavaScript code that is on a page which is loaded entirely via jQuery's load() method.

However, I think that I figured out how to deal with it!

On the 1776.php page, move the SCRIPT element from the HEAD to the BODY of the document.

<body>
    <script> ... the code ... </script>
    <div> ... </div>
</body>


问:
Eliminating Blank White Space in JTable After Setting Width
I am trying to set the size of a table in Java.

```<code>    pTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    pTable.getColumnModel().getColumn(0).setPreferredWidth(120);
    pTable.getColumnModel().getColumn(1).setPreferredWidth(100);
</code>```

The table is in the correct position in my frame but there is this unnecessary blank space to the right of the last column.
This is what I get:

I would just like to eliminate that blank white space that is to the right of the first name column.

Please don't lock this question, there is a similar one out there but it did not have any info that was of any help to me.

答:
A JTable has a predefined preferred size.

You can reset this by doing something like:

```<code>JTable table = new JTable(5, 2);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(120);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
</code>```

Now the width will be the width of the columns, but of course the height will be the height of all the rows as well.

But if you add the scrollpane to the frame using BorderLayout.LINE_START as the constraint, then the width of the table will be preserved and the height will vary with the height of the frame.

Body:
I am trying to set the size of a table in Java.

    pTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    pTable.getColumnModel().getColumn(0).setPreferredWidth(120);
    pTable.getColumnModel().getColumn(1).setPreferredWidth(100);

The table is in the correct position in my frame but there is this unnecessary blank space to the right of the last column.
This is what I get:

I would just like to eliminate that blank white space that is to the right of the first name column.

Please don't lock this question, there is a similar one out there but it did not have any info that was of any help to me.

Body:
A JTable has a predefined preferred size.

You can reset this by doing something like:

JTable table = new JTable(5, 2);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(120);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.setPreferredScrollableViewportSize(table.getPreferredSize());

Now the width will be the width of the columns, but of course the height will be the height of all the rows as well.

But if you add the scrollpane to the frame using BorderLayout.LINE_START as the constraint, then the width of the table will be preserved and the height will vary with the height of the frame.


问:
Network Error: req.headers.forEach Apollo Client Angular4
Trying to query my graphql endpoint, which is accessible with a postman call, using the ApolloClient.Query call provided by the Apollo Client and return results.  Following the guidelines from the docs here, I should be able to do something quick and crude like the following in a custom angular 4 component:

```<code>import { Component } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { User } from '../models/user';

import { Apollo } from 'apollo-angular';

import gql from 'graphql-tag';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent  {
  user: User = new User();
  constructor(private auth: AuthService, private apollo: Apollo) {}
  onLogin(): void {

    this.apollo.query({
      context: {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
        opts: {

          mode: 'no-cors',
        }
      },
      query: gql`{
  allUsers {
    id
    emailAddress
    password
  }
}`}).subscribe(
      (response) => console.log(response),
      (error) => console.log(error),
      () => console.log('completed!')
    );
  }
}
</code>```

with the following Apollo Client creation in my main app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import {HttpClientModule} from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { LoginComponent } from './login/login.component';
import { AuthService } from './services/auth.service';
import { RegisterComponent } from './register/register.component';
import { StatusComponent } from './status/status.component';

import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    LoginComponent,
    RegisterComponent,
    StatusComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    ApolloModule,
    HttpLinkModule,
    RouterModule.forRoot([
      { path: 'login', component: LoginComponent },
      { path: 'register', component: RegisterComponent },
      { path: 'status', component: StatusComponent }
    ])

  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule {

  constructor(
    apollo: Apollo,
    httpLink: HttpLink
  ) {
    apollo.create({
      link: httpLink.create({ withCredentials: false,
        uri: 'http://localhost:8080/graphql'}),
      cache: new InMemoryCache()
    });
  }
}
</code>```

However, in my debug console I am getting the following error. Thoughts? Scroll below to see the versioning of my javascript libraries

```<code>Error: Network error: req.headers.forEach is not a function
    at new ApolloError (ApolloError.js:34)
    at QueryManager.js:277
    at QueryManager.js:655
    at Array.forEach (<anonymous>)
    at QueryManager.js:654
    at Map.forEach (<anonymous>)
    at QueryManager.webpackJsonp.../../../../apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (QueryManager.js:649)
    at QueryManager.js:226
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:392)
</code>```

package.json

```<code>{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "apollo-angular": "^1.0.0",
    "apollo-angular-link-http": "^1.0.1",
    "apollo-cache-inmemory": "^1.1.1",
    "apollo-client": "^2.0.3",
    "core-js": "^2.4.1",
    "graphql": "^0.11.7",
    "graphql-tag": "^2.5.0",
    "rxjs": "^5.4.1",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.2.3",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}
</code>```

答:
I had the same problem.  What solved it for me was to swap out the headers to be inserted into the middleware instead, and then pass the middleware as a concat() result into link.

https://www.apollographql.com/docs/angular/basics/network-layer.html

```<code>const authMiddleware = new ApolloLink((operation, forward) => {
    // add the authorization to the headers
    operation.setContext({
        headers: new HttpHeaders().set('Authorization', yourToken)
    });

    return forward(operation);
});

... <other code>

apollo.create({
    link: concat(authMiddleware, http),
    cache: new InMemoryCache()
});
</code>```

Of course, you can probably swap Authorization for Content-Type and any other header you want.

Body:
Trying to query my graphql endpoint, which is accessible with a postman call, using the ApolloClient.Query call provided by the Apollo Client and return results.  Following the guidelines from the docs here, I should be able to do something quick and crude like the following in a custom angular 4 component:

import { Component } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { User } from '../models/user';

import { Apollo } from 'apollo-angular';

import gql from 'graphql-tag';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent  {
  user: User = new User();
  constructor(private auth: AuthService, private apollo: Apollo) {}
  onLogin(): void {

    this.apollo.query({
      context: {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
        opts: {

          mode: 'no-cors',
        }
      },
      query: gql`{
  allUsers {
    id
    emailAddress
    password
  }
}`}).subscribe(
      (response) => console.log(response),
      (error) => console.log(error),
      () => console.log('completed!')
    );
  }
}

with the following Apollo Client creation in my main app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import {HttpClientModule} from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { LoginComponent } from './login/login.component';
import { AuthService } from './services/auth.service';
import { RegisterComponent } from './register/register.component';
import { StatusComponent } from './status/status.component';

import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    LoginComponent,
    RegisterComponent,
    StatusComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    ApolloModule,
    HttpLinkModule,
    RouterModule.forRoot([
      { path: 'login', component: LoginComponent },
      { path: 'register', component: RegisterComponent },
      { path: 'status', component: StatusComponent }
    ])

  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule {

  constructor(
    apollo: Apollo,
    httpLink: HttpLink
  ) {
    apollo.create({
      link: httpLink.create({ withCredentials: false,
        uri: 'http://localhost:8080/graphql'}),
      cache: new InMemoryCache()
    });
  }
}

However, in my debug console I am getting the following error. Thoughts? Scroll below to see the versioning of my javascript libraries

Error: Network error: req.headers.forEach is not a function
    at new ApolloError (ApolloError.js:34)
    at QueryManager.js:277
    at QueryManager.js:655
    at Array.forEach (<anonymous>)
    at QueryManager.js:654
    at Map.forEach (<anonymous>)
    at QueryManager.webpackJsonp.../../../../apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (QueryManager.js:649)
    at QueryManager.js:226
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:392)

package.json

{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "apollo-angular": "^1.0.0",
    "apollo-angular-link-http": "^1.0.1",
    "apollo-cache-inmemory": "^1.1.1",
    "apollo-client": "^2.0.3",
    "core-js": "^2.4.1",
    "graphql": "^0.11.7",
    "graphql-tag": "^2.5.0",
    "rxjs": "^5.4.1",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.2.3",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

Body:
I had the same problem.  What solved it for me was to swap out the headers to be inserted into the middleware instead, and then pass the middleware as a concat() result into link.

https://www.apollographql.com/docs/angular/basics/network-layer.html

const authMiddleware = new ApolloLink((operation, forward) => {
    // add the authorization to the headers
    operation.setContext({
        headers: new HttpHeaders().set('Authorization', yourToken)
    });

    return forward(operation);
});

... <other code>

apollo.create({
    link: concat(authMiddleware, http),
    cache: new InMemoryCache()
});

Of course, you can probably swap Authorization for Content-Type and any other header you want.


问:
not able to see activities to deliver in clearcase ucm
I had to deliver some code(a folder and some files inside) from an activity A from dev stream to int stream in ucm clearcase. before delivering I renamed the folder using another activity B and changed some files inside. Now, While delivering from dev to int, I cannot find A and B as undelivered work.

Please advise how to resolve. let me know if any other information is required.

答:
The usual workaround would be to a non-UCM merge by activity, instead of an UCM deliver (which is not listing the expected activities), using cleartool findmerge.

See "How to merge changes from a specific UCM activity from one ClearCase stream to another"

```<code>cd /path/to/myView/myFolder
ct findmerge activity:B@\pvob -fcsets -c "deliver B" -merge -gmerge
</code>```

See also "how to merge new folder from a sub branch to the main branch in clearcase?".

Body:
The usual workaround would be to a non-UCM merge by activity, instead of an UCM deliver (which is not listing the expected activities), using cleartool findmerge.

See "How to merge changes from a specific UCM activity from one ClearCase stream to another"

cd /path/to/myView/myFolder
ct findmerge activity:B@\pvob -fcsets -c "deliver B" -merge -gmerge

See also "how to merge new folder from a sub branch to the main branch in clearcase?".


问:
MongoDB: Deserializing complex object returns NULL
Using C# Mongo DB Driver version, 2.4.4 and I try to deserialize a complex class. It has been stored correctly in the MongoDB, but when being deserialized it is null.

This is my datamodel:

```<code>public abstract class Document
{
    public DocumentId Id { get; private set; }

    public DocumentProperty TestProperty { get; private set; }

    protected Document() { }

    public void SetId(string value)
    {
        if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("value");
        Id = new DocumentId(value);
    }

    public void AddProperty(DocumentProperty property)
    {
        if (property == null) throw new ArgumentNullException("property");
        TestProperty = property;
    }
}

public class DocumentId
{
    public string Value { get; }

    public DocumentId(string value)
    {
        Value = value;
    }
}

public abstract class DocumentProperty
{
    public string Value { get; }

    protected DocumentProperty()
    {
    }

    protected DocumentProperty(string value)
    {
        Value = value;
    }
}

public class TitleDocumentProperty : DocumentProperty
{
    public TitleDocumentProperty() { }

    public TitleDocumentProperty(string value) : base(value)
    {
    }
}
</code>```

This is my mapping code:

```<code>public class MongoClassMapper
{
    public static void InitializeMap()
    {
        BsonClassMap.RegisterClassMap<DocumentProperty>(map =>
        {
            map.MapProperty(property => property.Value).SetDefaultValue("123");
            map.SetIsRootClass(true);
        });

        BsonClassMap.RegisterClassMap<TitleDocumentProperty>(map =>
        {
        });

        BsonClassMap.RegisterClassMap<Document>(map =>
        {
            map.MapProperty(document => document.Id);
            map.MapProperty(document => document.TestProperty);
            map.SetIsRootClass(true);
        });

    }
}
</code>```

This is my methods for adding and retrieving data from Mongo:

```<code>public async Task<string> Add(Document document)
    {
        await _documents.InsertOneAsync(document);
        return document.Id.Value;
    }

    public async Task<Document> Get(DocumentId id)
    {
        var mongoDocuments = await _documents.Find(document => document.Id == id)
            .ToListAsync();

        return mongoDocuments.SingleOrDefault();
    }
</code>```

This is the code that I use for testing:

```<code>private static MongoCache _cache;

    static void Main(string[] args)
    {
        MongoClassMapper.InitializeMap();
        _cache = new MongoCache(ConfigurationManager.ConnectionStrings["connName"].ConnectionString, "dbName");
        string id = ItShouldCreateRecord().Result;
        var doc = ItShouldGetRecord(id).Result;
    }

    private static Task<string> ItShouldCreateRecord()
    {
        //Arrange
        Document document = new FakeDocument();
        document.SetId(Guid.NewGuid().ToString());
        document.AddProperty(new TitleDocumentProperty("this is a title"));

        //Act
        string id = _cache.Add(document).Result;

        //Assert
        //Assert.NotEmpty(id);
        return Task.FromResult(id);
    }

    private static Task<Document> ItShouldGetRecord(string id)
    {
        //Arrange

        //Act
        return _cache.Get(new DocumentId(id));

        //Assert
        //Assert.NotNull(doc);
    }
}

[BsonIgnoreExtraElements]
public class FakeDocument : Document
{
}
</code>```

I expected that when I retrieve the document (using _cache.Get()) from the DB, that the property TestProperty would have an actual value. Currently, it is NULL.

答:
The problem is the absence of a setter on your Value property which will cause MongoDB to not deserialize this property:

```<code>public abstract class DocumentProperty
{
    public string Value { get; /* no setter*/ }
}
</code>```

You can fix this by simply adding the setter (using any accessibility setting, even private works):

```<code>public abstract class DocumentProperty
{
    public string Value { get; /* private if you want */ set; }
}
</code>```

I have captured a JIRA issue and a pull request to get that fixed.

Body:
Using C# Mongo DB Driver version, 2.4.4 and I try to deserialize a complex class. It has been stored correctly in the MongoDB, but when being deserialized it is null.

This is my datamodel:

public abstract class Document
{
    public DocumentId Id { get; private set; }

    public DocumentProperty TestProperty { get; private set; }

    protected Document() { }

    public void SetId(string value)
    {
        if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("value");
        Id = new DocumentId(value);
    }

    public void AddProperty(DocumentProperty property)
    {
        if (property == null) throw new ArgumentNullException("property");
        TestProperty = property;
    }
}

public class DocumentId
{
    public string Value { get; }

    public DocumentId(string value)
    {
        Value = value;
    }
}

public abstract class DocumentProperty
{
    public string Value { get; }

    protected DocumentProperty()
    {
    }

    protected DocumentProperty(string value)
    {
        Value = value;
    }
}

public class TitleDocumentProperty : DocumentProperty
{
    public TitleDocumentProperty() { }

    public TitleDocumentProperty(string value) : base(value)
    {
    }
}

This is my mapping code:

public class MongoClassMapper
{
    public static void InitializeMap()
    {
        BsonClassMap.RegisterClassMap<DocumentProperty>(map =>
        {
            map.MapProperty(property => property.Value).SetDefaultValue("123");
            map.SetIsRootClass(true);
        });

        BsonClassMap.RegisterClassMap<TitleDocumentProperty>(map =>
        {
        });

        BsonClassMap.RegisterClassMap<Document>(map =>
        {
            map.MapProperty(document => document.Id);
            map.MapProperty(document => document.TestProperty);
            map.SetIsRootClass(true);
        });

    }
}

This is my methods for adding and retrieving data from Mongo:

public async Task<string> Add(Document document)
    {
        await _documents.InsertOneAsync(document);
        return document.Id.Value;
    }

    public async Task<Document> Get(DocumentId id)
    {
        var mongoDocuments = await _documents.Find(document => document.Id == id)
            .ToListAsync();

        return mongoDocuments.SingleOrDefault();
    }

This is the code that I use for testing:

private static MongoCache _cache;

    static void Main(string[] args)
    {
        MongoClassMapper.InitializeMap();
        _cache = new MongoCache(ConfigurationManager.ConnectionStrings["connName"].ConnectionString, "dbName");
        string id = ItShouldCreateRecord().Result;
        var doc = ItShouldGetRecord(id).Result;
    }

    private static Task<string> ItShouldCreateRecord()
    {
        //Arrange
        Document document = new FakeDocument();
        document.SetId(Guid.NewGuid().ToString());
        document.AddProperty(new TitleDocumentProperty("this is a title"));

        //Act
        string id = _cache.Add(document).Result;

        //Assert
        //Assert.NotEmpty(id);
        return Task.FromResult(id);
    }

    private static Task<Document> ItShouldGetRecord(string id)
    {
        //Arrange

        //Act
        return _cache.Get(new DocumentId(id));

        //Assert
        //Assert.NotNull(doc);
    }
}

[BsonIgnoreExtraElements]
public class FakeDocument : Document
{
}

I expected that when I retrieve the document (using _cache.Get()) from the DB, that the property TestProperty would have an actual value. Currently, it is NULL.

Body:
The problem is the absence of a setter on your Value property which will cause MongoDB to not deserialize this property:

public abstract class DocumentProperty
{
    public string Value { get; /* no setter*/ }
}

You can fix this by simply adding the setter (using any accessibility setting, even private works):

public abstract class DocumentProperty
{
    public string Value { get; /* private if you want */ set; }
}

I have captured a JIRA issue and a pull request to get that fixed.


答:
If you want to print an array you should iterate over all of it's members and print each one. What you are doing at this moment is trying to print the array object which prints  it's memory address uses the default toString() method of the object base class, as pointed out by bhspencer, to print the array.

Try this:

```<code>public class IntsToArray {
  public static int[] fill(int a, int b, int c){
      int[] array = new int[3];
      array[0] = a;
      array[1] = b;
      array[2] = c;
      return (array);
  }
    public static void main(String[] args){
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int[] array = fill(a, b, c);

        for(int i = 0; i < array.length; i++)
        {
            System.out.println(array[i]);
        }
    }
}
</code>```

Body:
So I need to create a method which would take ints and return an array of length 3 with those three ints as they have been input.

This is what I have created, but it returns this [I@7852e922

public class IntsToArray {
  public static int[] fill(int a, int b, int c){
      int[] array = new int[3];
      array[0] = a;
      array[1] = b;
      array[2] = c;
      return (array);
  }
    public static void main(String[] args){
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int[] array = fill(a, b, c);
        System.out.println(array);
    }
}

What am I doing wrong?

Body:
If you want to print an array you should iterate over all of it's members and print each one. What you are doing at this moment is trying to print the array object which prints  it's memory address uses the default toString() method of the object base class, as pointed out by bhspencer, to print the array.

Try this:

public class IntsToArray {
  public static int[] fill(int a, int b, int c){
      int[] array = new int[3];
      array[0] = a;
      array[1] = b;
      array[2] = c;
      return (array);
  }
    public static void main(String[] args){
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int[] array = fill(a, b, c);

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


问:
what's wrong with string contains match
Sorry, I don't want to post this question here. Other questions like mine have been posted before, but I haven't found an answer yet.

I am trying to do a simple string match using string.contains

```<code> If Not dataRow("Name").ToString().Contains(UserName) Then
  --do something--
End If
</code>```

but that's not working in my condition

```<code>dataRow("Name").ToString()= "Steve Cook"
UserName="Cook Steve"
</code>```

I want to find the %like match (like SQL) but .contains not what I was expecting it to do?

答:
You can solve the problem by using Regex. Regex is comparable to using wildcards but allows you to express much more complex search patterns. Google for Regex tutorials. You will find lots of them.

```<code>Dim s As String = dataRow("Name").ToString()
If Not Regex.IsMatch(s, "\bSteve\s+Cook\b|\bCook\s+Steve\b") Then
    ' do something
End If
</code>```

Requires

```<code>Imports System.Text.RegularExpressions
</code>```

The meaning of this Regex expression is: find the whole words (i.e. not only parts of words imbedded in a longer word) "Steve Cook" OR "Cook Steve" that are separated by at least one space character.

Title: what's wrong with string contains match

Body:
Sorry, I don't want to post this question here. Other questions like mine have been posted before, but I haven't found an answer yet.

I am trying to do a simple string match using string.contains

 If Not dataRow("Name").ToString().Contains(UserName) Then
  --do something--
End If

but that's not working in my condition

dataRow("Name").ToString()= "Steve Cook"
UserName="Cook Steve"

I want to find the %like match (like SQL) but .contains not what I was expecting it to do?

Body:
You can solve the problem by using Regex. Regex is comparable to using wildcards but allows you to express much more complex search patterns. Google for Regex tutorials. You will find lots of them.

Dim s As String = dataRow("Name").ToString()
If Not Regex.IsMatch(s, "\bSteve\s+Cook\b|\bCook\s+Steve\b") Then
    ' do something
End If

Requires

Imports System.Text.RegularExpressions

The meaning of this Regex expression is: find the whole words (i.e. not only parts of words imbedded in a longer word) "Steve Cook" OR "Cook Steve" that are separated by at least one space character.

ContentLicense: CC BY-SA 4.0


问:
Replace callbacks with observables from RxJava
Im using listeners as callbacks to observe asynchronous operations with Android, but I think that could be great replacing this listeners with RxJava, Im new using this library but I really like it and Im always using it with Android projects.

Here is my code to refactor:

```<code>public void getData( final OnResponseListener listener ){
   if(data!=null && !data.isEmpty()){
       listener.onSuccess();
   }
   else{
       listener.onError();
   }
}
</code>```

A simple callback:

```<code>public interface OnResponseListener {
   public void onSuccess();
   public void onError();
}
</code>```

And the "observer":

```<code>object.getData( new OnResponseListener() {
    @Override
    public void onSuccess() {
       Log.w(TAG," on success");
    }

    @Override
    public void onError() {
       Log.e(TAG," on error");
    }
});
</code>```

Thanks!

答:
```<code>Maybe.<String>create(new MaybeOnSubscribe<String>() {
      @Override
      public void subscribe(MaybeEmitter<String> e) throws Exception {
        OnSuccessListener(uri->{
          e.onSuccess(uri));
        })
        .addOnFailureListener(throwable -> {
          e.onError(throwable);
        });
      }
    });
</code>```

Body:
Im using listeners as callbacks to observe asynchronous operations with Android, but I think that could be great replacing this listeners with RxJava, Im new using this library but I really like it and Im always using it with Android projects.

Here is my code to refactor:

public void getData( final OnResponseListener listener ){
   if(data!=null && !data.isEmpty()){
       listener.onSuccess();
   }
   else{
       listener.onError();
   }
}

A simple callback:

public interface OnResponseListener {
   public void onSuccess();
   public void onError();
}

And the "observer":

object.getData( new OnResponseListener() {
    @Override
    public void onSuccess() {
       Log.w(TAG," on success");
    }

    @Override
    public void onError() {
       Log.e(TAG," on error");
    }
});

Thanks!


问:
Elegant solution to remove trailing 0's with precision set
Is there any elegant solution using the std C++ or Boost libraries to output a double to std::cout in a way that the following conditions are met:

scientific notation is disabled

the precision for the decimal part is 6

however, trailing 0's (for the decimal part) are not printed out

For example:

```<code>double d = 200000779998;
std::cout << `[something]` << d;
</code>```

should print out exactly 200000779998. [something] should possibly be a noexcept combination of some existing manipulators.

This is not a solution to the problem:

```<code>std::cout << std::setprecision(6) << std::fixed << d;
</code>```

because it prints out 200000779998.000000 with trailing 0's

答:
Hard to prove a negative, but I would assume no.

The requirements are inconsistent with any normal use. Space efficiency dictates a binary format.  6 digits (decimal) of precision suggests a format intended for human readers, who can't churn through lots of data. And humans have no issue dealing with a consistent 6 digit format.

So, you're basically targeting a format that has no obvious audience, and that is why I would be surprised if there is support for that.

Body:
Is there any elegant solution using the std C++ or Boost libraries to output a double to std::cout in a way that the following conditions are met:

scientific notation is disabled

the precision for the decimal part is 6

however, trailing 0's (for the decimal part) are not printed out

For example:

double d = 200000779998;
std::cout << `[something]` << d;

should print out exactly 200000779998. [something] should possibly be a noexcept combination of some existing manipulators.

This is not a solution to the problem:

std::cout << std::setprecision(6) << std::fixed << d;

because it prints out 200000779998.000000 with trailing 0's


问:
I implemented card views in XML on Android Studios. How can I have this act as buttons?
I'm new to Android and recently created a dashboard for my app. I followed a tutorial but it only covered the front end. I created a layout called content_main.xml with three Cardviews. Each of these Cardviews contains the code

```<code>android:clickable="true"
</code>```

Beginning the back end of things, I created a java receiver class called DashboardActivity (as seen below). I want to make my Cardviews clickable so that when one is clicked, I am taken to another screen within my app. The other screens in my app I am trying to get to are fragments. Each of these screens has its own java class in my "Fragments" folder. One of them, of which I try calling on in the code that follows is called SettingsViewFragment().

So far, I have tried the following. It does nothing.

```<code>public class DashboardActivity  extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        cd1 = (CardView) findViewById(R.id.dash_settings);
        cd2 = (CardView) findViewById(R.id.dash_profile);
        cd3 = (CardView) findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment1 = new SettingsViewFragment();
            }

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

UPDATE: FULL CODE

```<code>public class DashboardActivity extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        cd1 = findViewById(R.id.dash_settings);
        cd2 = findViewById(R.id.dash_profile);
        cd3 = findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Testing 123 123 123");
            }

        });

    }
}
</code>```

And my XML: (it continues for 3 cards this way)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.newproject.DashboardActivity"
    tools:showIn="@layout/toolbar">

    <FrameLayout
        android:id="@+id/dashframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.CardView
            android:id="@+id/dash_settings"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:focusable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/bg_circle1"
                    android:src="@drawable/ic_settingspicture"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="View your settings"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightgray"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Follow along with guided tutorials"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>
</code>```

答:
Change Fragment fragment1 = new SettingsViewFragment (); by Toast.makeText (mActivity, "onCLick", Toast.LENGTH_LONG) .show ();

//if show toast The problem is not the onClick, the problem is when loading the fragment

Body:
I'm new to Android and recently created a dashboard for my app. I followed a tutorial but it only covered the front end. I created a layout called content_main.xml with three Cardviews. Each of these Cardviews contains the code

android:clickable="true"

Beginning the back end of things, I created a java receiver class called DashboardActivity (as seen below). I want to make my Cardviews clickable so that when one is clicked, I am taken to another screen within my app. The other screens in my app I am trying to get to are fragments. Each of these screens has its own java class in my "Fragments" folder. One of them, of which I try calling on in the code that follows is called SettingsViewFragment().

So far, I have tried the following. It does nothing.

public class DashboardActivity  extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        cd1 = (CardView) findViewById(R.id.dash_settings);
        cd2 = (CardView) findViewById(R.id.dash_profile);
        cd3 = (CardView) findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment1 = new SettingsViewFragment();
            }

        });
    }
}

UPDATE: FULL CODE

public class DashboardActivity extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        cd1 = findViewById(R.id.dash_settings);
        cd2 = findViewById(R.id.dash_profile);
        cd3 = findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Testing 123 123 123");
            }

        });

    }
}

And my XML: (it continues for 3 cards this way)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.newproject.DashboardActivity"
    tools:showIn="@layout/toolbar">

    <FrameLayout
        android:id="@+id/dashframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.CardView
            android:id="@+id/dash_settings"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:focusable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/bg_circle1"
                    android:src="@drawable/ic_settingspicture"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="View your settings"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightgray"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Follow along with guided tutorials"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>


问:
Object Normalization
In the same line as Database Normalization - is there an approach to object normalization, not design pattern, but the same mathematical like approach to normalizing object creation.  For example: first normal form: no repeating fields....
here's some links to DB Normalization:

http://en.wikipedia.org/wiki/Database_normalization
  http://databases.about.com/od/specificproducts/a/normalization.htm

Would this make object creation and self-documentation better?

Here's a link to a book about class normalization (guess we're really talking about classes)
http://www.agiledata.org/essays/classNormalization.html

答:
I guess the Single Responsible Principle is at least related to this. Or at least, violation of the SRP is similar to a lack of normalization in some ways.

(It's possible I'm talking rubbish. I'm pretty tired.)

OwnerDisplayName: meade

Title: Object Normalization

LastEditorDisplayName: meade

OwnerDisplayName: Jon Skeet


问:
About Kotlin and functions
So Ive started learning Kotlin and I have a question about functions.

In Kotlin you can do the javascript thing of creating a variable that can hold any type. But functions need to have their parameters typed.

So is the practice in Kotlin to type all variables anyway?
Is it not kind of pointless allowing the variables to be untyped but forcing types for the parameters and return values of functions?

答:
When you write

```<code>val x = "Pizza"
</code>```

kotlin infers from the declaration that 'x' is a string, there isn't some magic going on, if you try

```<code>var x = "Pizza"
x = 42
</code>```

it won't work, because x is of a type String.

kotlin translates to java, and java is a "Statically typed language", which means the type of a field have to be known at runtime,
other languages, like Javascript are a "Dynamically typed languages", which in them the variables types doesn't have to be known at runtime, so it can make the developer life a bit easier ( or harder ).

Title: About Kotlin and functions

Body:
When you write

val x = "Pizza"

kotlin infers from the declaration that 'x' is a string, there isn't some magic going on, if you try

var x = "Pizza"
x = 42

it won't work, because x is of a type String.

kotlin translates to java, and java is a "Statically typed language", which means the type of a field have to be known at runtime,
other languages, like Javascript are a "Dynamically typed languages", which in them the variables types doesn't have to be known at runtime, so it can make the developer life a bit easier ( or harder ).


问:
Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)
I just upgraded my MacMini Server from Lion Server to Mountain Lion using OS X Server.  I am having the same problem with PostgreSQL that I did last year when I first installed Lion Server.

When I try to do any kind of PostgreSQL terminal command I get the following notorious error message that many have gotten over the years:

```<code>psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
</code>```

I was attempting to change the password for _postgres when I got the error.  I tried several commands but got the same error.  I just rebooted my server but no luck.  I logged in as root to look at /var/pgsql_socket and the folder is empty.  Folder /var/pgsql_socket_alt is also empty.

I have checked online about this.  However just about all of the solutions I have read, including on Stack Overflow, suggest a removal and reinstall of PostgreSQL.  I do not know but this does not seem like a plausible option because several options on the Server App use PostgreSQL.  I contacted Apple Enterprise Support (no agreement) and I was told that my issue would have to be solved by the developers which would cost $695.

I have a website that is down right now because I cannot rebuild it.  I don't know where to turn for help with this at this point.  I will continue looking online to see if I can find something.  However I hope that someone can give me an answer quick so I can rebuild my database.

Update: 12/13/2012 15:33 GMT-6

Here is my output for ps auwx|grep postg:

```<code>_postgres      28123   0.0  0.1  2479696   7724   ??  Ss    3:01PM   0:00.04 /Applications/Server.app/Contents/ServerRoot/usr/bin/postgres_real -D /Library/Server/PostgreSQL For Server Services/Data -c listen_addresses= -c log_connections=on -c log_directory=/Library/Logs/PostgreSQL -c log_filename=PostgreSQL_Server_Services.log -c log_line_prefix=%t  -c log_lock_waits=on -c log_statement=ddl -c logging_collector=on -c unix_socket_directory=/Library/Server/PostgreSQL For Server Services/Socket -c unix_socket_group=_postgres -c unix_socket_permissions=0770
server1        28216   0.0  0.0  2432768    620 s000  R+    3:02PM   0:00.00 grep postg
_postgres      28138   0.0  0.0  2439388    752   ??  Ss    3:01PM   0:00.01 postgres: stats collector process
_postgres      28137   0.0  0.0  2479828   1968   ??  Ss    3:01PM   0:00.00 postgres: autovacuum launcher process
_postgres      28136   0.0  0.0  2479696    544   ??  Ss    3:01PM   0:00.00 postgres: wal writer process
_postgres      28135   0.0  0.0  2479696    732   ??  Ss    3:01PM   0:00.01 postgres: writer process
_postgres      28134   0.0  0.0  2479696    592   ??  Ss    3:01PM   0:00.00 postgres: checkpointer process
_postgres      28131   0.0  0.0  2439388    368   ??  Ss    3:01PM   0:00.00 postgres: logger process
</code>```

Update: 12/13/2012 18:10 GMT-6

After intense web searching this video was found.  I was able to get PostgreSQL working and remove the error.  I am able to connect using pgadmin and phppgadmin.  I was about to go back to Lion Server because of sheer frustration.  Now I will not have to.

http://www.youtube.com/watch?v=y1c7WFMMkZ4

答:
I just created a new cluster and that worked for me, I was using (PostgreSQL) 9.3.20:</p>

```<code>sudo pg_createcluster 9.3 main --start
</code>```

Body:
I just upgraded my MacMini Server from Lion Server to Mountain Lion using OS X Server.  I am having the same problem with PostgreSQL that I did last year when I first installed Lion Server.

When I try to do any kind of PostgreSQL terminal command I get the following notorious error message that many have gotten over the years:

psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

I was attempting to change the password for _postgres when I got the error.  I tried several commands but got the same error.  I just rebooted my server but no luck.  I logged in as root to look at /var/pgsql_socket and the folder is empty.  Folder /var/pgsql_socket_alt is also empty.

I have checked online about this.  However just about all of the solutions I have read, including on Stack Overflow, suggest a removal and reinstall of PostgreSQL.  I do not know but this does not seem like a plausible option because several options on the Server App use PostgreSQL.  I contacted Apple Enterprise Support (no agreement) and I was told that my issue would have to be solved by the developers which would cost $695.

I have a website that is down right now because I cannot rebuild it.  I don't know where to turn for help with this at this point.  I will continue looking online to see if I can find something.  However I hope that someone can give me an answer quick so I can rebuild my database.

Update: 12/13/2012 15:33 GMT-6

Here is my output for ps auwx|grep postg:

_postgres      28123   0.0  0.1  2479696   7724   ??  Ss    3:01PM   0:00.04 /Applications/Server.app/Contents/ServerRoot/usr/bin/postgres_real -D /Library/Server/PostgreSQL For Server Services/Data -c listen_addresses= -c log_connections=on -c log_directory=/Library/Logs/PostgreSQL -c log_filename=PostgreSQL_Server_Services.log -c log_line_prefix=%t  -c log_lock_waits=on -c log_statement=ddl -c logging_collector=on -c unix_socket_directory=/Library/Server/PostgreSQL For Server Services/Socket -c unix_socket_group=_postgres -c unix_socket_permissions=0770
server1        28216   0.0  0.0  2432768    620 s000  R+    3:02PM   0:00.00 grep postg
_postgres      28138   0.0  0.0  2439388    752   ??  Ss    3:01PM   0:00.01 postgres: stats collector process
_postgres      28137   0.0  0.0  2479828   1968   ??  Ss    3:01PM   0:00.00 postgres: autovacuum launcher process
_postgres      28136   0.0  0.0  2479696    544   ??  Ss    3:01PM   0:00.00 postgres: wal writer process
_postgres      28135   0.0  0.0  2479696    732   ??  Ss    3:01PM   0:00.01 postgres: writer process
_postgres      28134   0.0  0.0  2479696    592   ??  Ss    3:01PM   0:00.00 postgres: checkpointer process
_postgres      28131   0.0  0.0  2439388    368   ??  Ss    3:01PM   0:00.00 postgres: logger process

Update: 12/13/2012 18:10 GMT-6

After intense web searching this video was found.  I was able to get PostgreSQL working and remove the error.  I am able to connect using pgadmin and phppgadmin.  I was about to go back to Lion Server because of sheer frustration.  Now I will not have to.

http://www.youtube.com/watch?v=y1c7WFMMkZ4

Body:
I just created a new cluster and that worked for me, I was using (PostgreSQL) 9.3.20:

sudo pg_createcluster 9.3 main --start


问:
Run R.NET in and Azure Function
I am trying to integrate R into an Azure Function.

Instead of just calling the R exe - I want to be able to try the R.NET library to make it easier to pass and collect data between .NET and R. For example, respond to an event.

It runs fine locally, but once deployed as an Azure function, I get various errors.  The latest ": This engine is not running. You may have forgotten to call Initialize"

For anyone else wanting to try this, I had to force the Azure function to run as 64bit, and also install the R extension library to the function. at RDotNet.REngine.CheckEngineIsRunning()

Has anyone had any success?  Is anyone with R.NET experience wanting to help getting to work as an Azure function environment?

答:
Looking at the code in R.NET for the functions RDotNet.REngine.GetInstance(), RDotNet.REngine.CheckEngineIsRunning(), and RDotNet.REngine.Initialize(), it appears as though creating the engine instance via RDotNet.REngine.GetInstance() should help you avoid this issue, as after calling that the method should be running, and you should not be encountering this area.

It is possible that you are encountering some error in creating this instance. Looking at the code comments about usage in the above link, it looks like an environment variable needs to be set for PATH. It is possible that the code you used to set this up does not work in Azure Functions. You can manually set environment variables in Azure Functions by using App Settings.

Title: Run R.NET in and Azure Function