问:
Why would you ever call .call() on Observable functions?
I am a relative beginner in Angular, and I am struggling to understand some source I am reading from the ng-bootstrap project. The source code can be found here.

I am very confused by the code in ngOnInit:

```<code>ngOnInit(): void {
    const inputValues$ = _do.call(this._valueChanges, value => {
      this._userInput = value;
      if (this.editable) {
        this._onChange(value);
      }
    });
    const results$ = letProto.call(inputValues$, this.ngbTypeahead);
    const processedResults$ = _do.call(results$, () => {
      if (!this.editable) {
        this._onChange(undefined);
      }
    });
    const userInput$ = switchMap.call(this._resubscribeTypeahead, () => processedResults$);
    this._subscription = this._subscribeToUserInput(userInput$);
  }
</code>```

What is the point of calling .call(...) on these Observable functions? What kind of behaviour is this trying to achieve? Is this a normal pattern?

I've done a lot of reading/watching about Observables (no pun intended) as part of my Angular education but I have never come across anything like this. Any explanation would be appreciated

答:
My personal opinion is that they were using this for RxJS prior 5.5 which introduced lettable operators. The same style is used internally by Angular. For example: https://github.com/angular/angular/blob/master/packages/router/src/router_preloader.ts#L91.

The reason for this is that by default they would have to patch the Observable class with rxjs/add/operators/XXX. The disadvantage of this is that some 3rd party library is modifying a global object that might unexpectedly cause problems somewhere else in your app. See https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md#why.

You can see at the beginning of the file that they import each operator separately https://github.com/ng-bootstrap/ng-bootstrap/blob/master/src/typeahead/typeahead.ts#L22-L25.

So by using .call() they can use any operator and still avoid patching the Observable class.

Body:
I am a relative beginner in Angular, and I am struggling to understand some source I am reading from the ng-bootstrap project. The source code can be found here.

I am very confused by the code in ngOnInit:

ngOnInit(): void {
    const inputValues$ = _do.call(this._valueChanges, value => {
      this._userInput = value;
      if (this.editable) {
        this._onChange(value);
      }
    });
    const results$ = letProto.call(inputValues$, this.ngbTypeahead);
    const processedResults$ = _do.call(results$, () => {
      if (!this.editable) {
        this._onChange(undefined);
      }
    });
    const userInput$ = switchMap.call(this._resubscribeTypeahead, () => processedResults$);
    this._subscription = this._subscribeToUserInput(userInput$);
  }

What is the point of calling .call(...) on these Observable functions? What kind of behaviour is this trying to achieve? Is this a normal pattern?

I've done a lot of reading/watching about Observables (no pun intended) as part of my Angular education but I have never come across anything like this. Any explanation would be appreciated


来源: stackexchange

问:
Visual Basic FtpWebRequest downloading files?
What I have:

```<code>Dim ftploader As System.Net.FtpWebRequest =
    DirectCast(System.Net.WebRequest.Create(
        "ftp://ftp.cabbageee.host-ed.me/nim/Vardelatestmessage.txt"),
        System.Net.FtpWebRequest)

ftploader.Credentials =
    New System.Net.NetworkCredential("Insert Username here", "Insert password here")
</code>```

I am trying to download this .txt file to my c: drive. I already have a connection, so how can I save that .txt file? Also, how can I upload a file? I already tried My.Computer.Network.DownloadFile, but it is only possible to download/upload once, as I have no idea of how to get rid of that connection.

答:
The most trivial way to download a binary file from an FTP server using VB.NET is using WebClient.DownloadFile:

```<code>Dim client As WebClient = New WebClient()
client.Credentials = New NetworkCredential("username", "password")
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")
</code>```

If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, resuming transfers, etc), use FtpWebRequest. Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

```<code>Dim request As FtpWebRequest =
    WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.DownloadFile

Using ftpStream As Stream = request.GetResponse().GetResponseStream(),
      fileStream As Stream = File.Create("C:\local\path\file.zip")
    ftpStream.CopyTo(fileStream)
End Using
</code>```

If you need to monitor a download progress, you have to copy the contents by chunks yourself:

```<code>Dim request As FtpWebRequest =
    WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.DownloadFile

Using ftpStream As Stream = request.GetResponse().GetResponseStream(),
      fileStream As Stream = File.Create("C:\local\path\file.zip")
    Dim buffer As Byte() = New Byte(10240 - 1) {}
    Dim read As Integer
    Do
        read = ftpStream.Read(buffer, 0, buffer.Length)
        If read > 0 Then
            fileStream.Write(buffer, 0, read)
            Console.WriteLine("Downloaded {0} bytes", fileStream.Position)
        End If
    Loop While read > 0
End Using
</code>```

For GUI progress (WinForms ProgressBar), see (C#):

FtpWebRequest FTP download with ProgressBar

If you want to download all files from a remote folder, see

How to download directories from FTP using VB.NET

ContentLicense: CC BY-SA 3.0

Body:
What I have:

Dim ftploader As System.Net.FtpWebRequest =
    DirectCast(System.Net.WebRequest.Create(
        "ftp://ftp.cabbageee.host-ed.me/nim/Vardelatestmessage.txt"),
        System.Net.FtpWebRequest)

ftploader.Credentials =
    New System.Net.NetworkCredential("Insert Username here", "Insert password here")

I am trying to download this .txt file to my c: drive. I already have a connection, so how can I save that .txt file? Also, how can I upload a file? I already tried My.Computer.Network.DownloadFile, but it is only possible to download/upload once, as I have no idea of how to get rid of that connection.

Body:
The most trivial way to download a binary file from an FTP server using VB.NET is using WebClient.DownloadFile:

Dim client As WebClient = New WebClient()
client.Credentials = New NetworkCredential("username", "password")
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")

If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, resuming transfers, etc), use FtpWebRequest. Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

Dim request As FtpWebRequest =
    WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.DownloadFile

Using ftpStream As Stream = request.GetResponse().GetResponseStream(),
      fileStream As Stream = File.Create("C:\local\path\file.zip")
    ftpStream.CopyTo(fileStream)
End Using

If you need to monitor a download progress, you have to copy the contents by chunks yourself:

Dim request As FtpWebRequest =
    WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.DownloadFile

Using ftpStream As Stream = request.GetResponse().GetResponseStream(),
      fileStream As Stream = File.Create("C:\local\path\file.zip")
    Dim buffer As Byte() = New Byte(10240 - 1) {}
    Dim read As Integer
    Do
        read = ftpStream.Read(buffer, 0, buffer.Length)
        If read > 0 Then
            fileStream.Write(buffer, 0, read)
            Console.WriteLine("Downloaded {0} bytes", fileStream.Position)
        End If
    Loop While read > 0
End Using

For GUI progress (WinForms ProgressBar), see (C#):

FtpWebRequest FTP download with ProgressBar

If you want to download all files from a remote folder, see

How to download directories from FTP using VB.NET

ContentLicense: CC BY-SA 4.0


问:
downgrade directive component from angular 2 to angularJS is not working as expected
Here is my angular 2 component:

```<code>@Component({
  selector: '[my-component]',
  template:`<ng-content></ng-content>`
})
export class MyComponentClass {
  @Input() myComponent: string;

...
</code>```

This allows me in angular 2 app use this as directive on any html tag, for example:

```<code><div [myComponent]="'my text string'"></div>
<span [myComponent]="'my text string'"></span>
</code>```

But when taking the same component downgrade to be used in angularJs app:

```<code>angular.module('myApp')
    .directive('myComponent', downgradeComponent({component: MyComponentClass , inputs: ['myComponent']}) as angular.IDirectiveFactory);
</code>```

Now this will not work:

```<code> <div [myComponent]="'my text string'"></div> // or
<div [my-component]="'my text string'"></div>
</code>```

Only if I use it as component like

```<code><my-component [my-component]="'some text'"></my-component>
</code>```

What have I done wrong?
I don't want it to be used as a new html tag, but as a directive that can be added to any html element (directive).

答: I've met the same issue and found a word around at: https://github.com/angular/angular/issues/16695#issuecomment-336456199</p>

Body:
Here is my angular 2 component:

@Component({
  selector: '[my-component]',
  template:`<ng-content></ng-content>`
})
export class MyComponentClass {
  @Input() myComponent: string;

...

This allows me in angular 2 app use this as directive on any html tag, for example:

But when taking the same component downgrade to be used in angularJs app:

angular.module('myApp')
    .directive('myComponent', downgradeComponent({component: MyComponentClass , inputs: ['myComponent']}) as angular.IDirectiveFactory);

Now this will not work:

 // or

Only if I use it as component like

<my-component [my-component]="'some text'"></my-component>

What have I done wrong?
I don't want it to be used as a new html tag, but as a directive that can be added to any html element (directive).


问:
How to find S3 connected to a cloudfront URL
The client has a site running on PHP deployed over AWS infrastructure. I have access to AWS console of a client.

There are some images in his site that is loading from cloudfront (which I understand is mapped to an S3 bucket). I need to update these images, but I do not know which S3 bucket they are in, since client has a lot of S3 buckets configured. How do I figure this one from the console?

答:
First, you will need to find the CloudFront distribution that is serving the content. Find the distribution with the same cloudfront.net URL that you're using to access the images.

Then, look at the behaviors and origins of the distribution to determine when it is going to each origin, and which origin is serving the path. This will then tell you which Amazon S3 bucket is being used.


问:
How new Java.util.Date() works while other classes return just reference?
I am curious as to why new Java.util.Date() returns Date object but not address(reference) to itself on heap:

```<code>System.out.println(new Date()); //Should print address(reference)
</code>```

of object on   heap?

like every other class I've been learning about for example:

```<code>Cat cat = new Cat();  //new Cat() returns reference which is stored in cat;
</code>```

how can I implement it in my classes?

答:
java.util.Date, like a lot of other classes in the JDK, overrides toString(), which allows you to control the string representation of your objects.

You can, of course, do this for your own classes too.

Body:
I am curious as to why new Java.util.Date() returns Date object but not address(reference) to itself on heap:

System.out.println(new Date()); //Should print address(reference)

of object on   heap?

like every other class I've been learning about for example:

Cat cat = new Cat();  //new Cat() returns reference which is stored in cat;

how can I implement it in my classes?


问:
Pandas deleting my zero index when groupby
I am doing a very basic groupby on a column to have counts for n different columns of the dataframe :

```<code>counts = (dataframe.groupby(['label'])[best_features_names_ordered[i]].sum() for i in indices)
</code>```

Here is the column 'label' of the dataframe :

The other columns are words.

My best_features_names_ordered variable is a basic list containing words
:

The groupby works well, excepted when one of the values of the column 'labels' is equal to 0!

Here an example, the labels are equal to {-2, -1, 0, 1, 2} but the 0 has disappeared:

However, the labels have the 0 ...:

Does pandas delete my 0 index when grouping ? Why ? How can I solve this ?
Thanks !

答:
The problem was indeed that the 0 is removed by pandas when indexing the result of groupby.

I soluced the problem by using string classes (therefore string indexes) which prevent pandas from deleting tha value '0'.

However, if anybody has a better solution, please don't hesitate.

Body:
I am doing a very basic groupby on a column to have counts for n different columns of the dataframe :

counts = (dataframe.groupby(['label'])[best_features_names_ordered[i]].sum() for i in indices)

Here is the column 'label' of the dataframe :

The other columns are words.

My best_features_names_ordered variable is a basic list containing words
:

The groupby works well, excepted when one of the values of the column 'labels' is equal to 0!

Here an example, the labels are equal to {-2, -1, 0, 1, 2} but the 0 has disappeared:

However, the labels have the 0 ...:

Does pandas delete my 0 index when grouping ? Why ? How can I solve this ?
Thanks !


问:
Output labels sticking to same value in vgg16
I am trying to run VGG16 model for digit detection on svhn dataset

http://ufldl.stanford.edu/housenumbers/train_32x32.mat

However, the values of prediction are always same.
I tried to feed images with -

scaling from 0-255 to 0-1

subtracting mean from each image

divide by std

Here is how I am running it:

Initialising VGG16:

```<code>vgg = tf.keras._impl.keras.applications.vgg16.VGG16
    (include_top=True,
    weights=None,
    input_tensor=None,
    input_shape=(64,64,3),
    pooling='max',
    classes=10)

vgg.compile(loss=tf.keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.SGD(lr=1e-4, momentum=0.9, nesterov=True),metrics=['mae', 'acc'])
#Here train_data shape is (None,64,64,3) and labels_data shape is (None,10) and are one hot like labels
vgg.fit(train_data, labels_data, epochs=5, batch_size=96)
</code>```

Train data can be read and preprocessed like this:

```<code>train_data = sio.loadmat('datasets/housing/train_32x32.mat')
</code>```

Below two functions I am using to preprocess train_data:

```<code>import numpy as np
import cv2
import tensorflow as tf
import os
import scipy
from skimage import data, io, filters
import scipy.io as sio
from utils import *
import h5py

from tensorflow.python.keras._impl.keras import backend as K
from tensorflow.python.keras._impl.keras.applications.imagenet_utils         import _obtain_input_shape
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import decode_predictions  # pylint: disable=unused-import
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import preprocess_input  # pylint: disable=unused-import
from tensorflow.python.keras._impl.keras.engine.topology import get_source_inputs
from tensorflow.python.keras._impl.keras.layers import Conv2D
from tensorflow.python.keras._impl.keras.layers import Dense
from tensorflow.python.keras._impl.keras.layers import Flatten
from tensorflow.python.keras._impl.keras.layers import GlobalAveragePooling2D
from tensorflow.python.keras._impl.keras.layers import     GlobalMaxPooling2D
from tensorflow.python.keras._impl.keras.layers import Input
from tensorflow.python.keras._impl.keras.layers import MaxPooling2D
from tensorflow.python.keras._impl.keras.models import Model
from tensorflow.python.keras._impl.keras.utils import layer_utils
from tensorflow.python.keras._impl.keras.utils.data_utils import get_file
from tensorflow.python.keras._impl.keras.engine import Layer

def reshape_mat_vgg (QUANTITY,matfilepath='datasets/housing/train_32x32.mat', type="non-quantized", size=(64,64)):
data = read_mat_file (matfilepath)
train = data['X'][:,:,:,0:QUANTITY]
train = np.swapaxes(np.swapaxes(np.swapaxes(train,2,3),1,2),0,1)
labels = data['y'][0:QUANTITY]
labels_data = []; labels_data = np.array(labels_data)
train_data = np.zeros((QUANTITY,size[0],size[1],3))
print "Reorganizing Data..."
for i in range(QUANTITY):
    image_i = np.copy(train[i,:,:,:])
    image_i = preprocess_small_vgg16 (image_i, new_size=size, type=type)
    train_data[i,:,:,:] = image_i
    label_i = np.zeros((10)); label_i[labels[i]-1] = 1.0; label_i = label_i.reshape(1,10)
    if i == 0:
        labels_data = np.vstack(( label_i ))
    else:
        labels_data = np.vstack(( labels_data, label_i ))
    if i % 1000 == 0:
        print i*100/(QUANTITY-1),"percent done..."
print "100 percent done..."
return train_data, labels_data

def preprocess_small_vgg16 (image, new_size=(64,64), type="non-quantized"):
img = np.copy (image)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#Whitening
imgnorm = img * 255.0/np.max(img)
#Normalisation
gray = imgnorm
borderless  = gray[:,5:gray.shape[1]-5,:] # centering
final_img = (cv2.resize (borderless, new_size))
final_img = final_img/np.max(final_img) #scaling 0-1
stddev = np.std(final_img); mn = np.mean (final_img)
final_img = (final_img - mn) / stddev #standardizing
return final_img
</code>```

Output :

```<code>Epoch 1/10
5000/5000 [==============================] - 1346s - loss: 3.2877 -
mean_absolute_error: 0.0029 - acc: 0.1850
Epoch 2/10
</code>```

Running over multiple epochs does not help. I tried with 5 epochs.

When I check output or predictions, it shows same results for all inputs e.g.(converted using np.argmax(pred, axis=-1)):

```<code>[3 3 3 . . . 3 3 3]
</code>```

Please mark the problem in my model.

答:
I think most of your problem is that 5 epochs are far from enough for VGG weights to converge. In VGG original paper, authors said that they trained 370k iterations (74 epochs) to get the best results, so you may consider giving it more time to converge.

I have fed your dataset to on of tensorflow tutorial nets and you can see how the total loss decreases after thousands of iterations.

Of course you can fine tune learning rate decay to prevent time spent on plateaus.

Body:
I am trying to run VGG16 model for digit detection on svhn dataset

http://ufldl.stanford.edu/housenumbers/train_32x32.mat

However, the values of prediction are always same.
I tried to feed images with -

scaling from 0-255 to 0-1

subtracting mean from each image

divide by std

Here is how I am running it:

Initialising VGG16:

vgg = tf.keras._impl.keras.applications.vgg16.VGG16
    (include_top=True,
    weights=None,
    input_tensor=None,
    input_shape=(64,64,3),
    pooling='max',
    classes=10)

vgg.compile(loss=tf.keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.SGD(lr=1e-4, momentum=0.9, nesterov=True),metrics=['mae', 'acc'])
#Here train_data shape is (None,64,64,3) and labels_data shape is (None,10) and are one hot like labels
vgg.fit(train_data, labels_data, epochs=5, batch_size=96)

Train data can be read and preprocessed like this:

train_data = sio.loadmat('datasets/housing/train_32x32.mat')

Below two functions I am using to preprocess train_data:

import numpy as np
import cv2
import tensorflow as tf
import os
import scipy
from skimage import data, io, filters
import scipy.io as sio
from utils import *
import h5py

from tensorflow.python.keras._impl.keras import backend as K
from tensorflow.python.keras._impl.keras.applications.imagenet_utils         import _obtain_input_shape
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import decode_predictions  # pylint: disable=unused-import
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import preprocess_input  # pylint: disable=unused-import
from tensorflow.python.keras._impl.keras.engine.topology import get_source_inputs
from tensorflow.python.keras._impl.keras.layers import Conv2D
from tensorflow.python.keras._impl.keras.layers import Dense
from tensorflow.python.keras._impl.keras.layers import Flatten
from tensorflow.python.keras._impl.keras.layers import GlobalAveragePooling2D
from tensorflow.python.keras._impl.keras.layers import     GlobalMaxPooling2D
from tensorflow.python.keras._impl.keras.layers import Input
from tensorflow.python.keras._impl.keras.layers import MaxPooling2D
from tensorflow.python.keras._impl.keras.models import Model
from tensorflow.python.keras._impl.keras.utils import layer_utils
from tensorflow.python.keras._impl.keras.utils.data_utils import get_file
from tensorflow.python.keras._impl.keras.engine import Layer

def reshape_mat_vgg (QUANTITY,matfilepath='datasets/housing/train_32x32.mat', type="non-quantized", size=(64,64)):
data = read_mat_file (matfilepath)
train = data['X'][:,:,:,0:QUANTITY]
train = np.swapaxes(np.swapaxes(np.swapaxes(train,2,3),1,2),0,1)
labels = data['y'][0:QUANTITY]
labels_data = []; labels_data = np.array(labels_data)
train_data = np.zeros((QUANTITY,size[0],size[1],3))
print "Reorganizing Data..."
for i in range(QUANTITY):
    image_i = np.copy(train[i,:,:,:])
    image_i = preprocess_small_vgg16 (image_i, new_size=size, type=type)
    train_data[i,:,:,:] = image_i
    label_i = np.zeros((10)); label_i[labels[i]-1] = 1.0; label_i = label_i.reshape(1,10)
    if i == 0:
        labels_data = np.vstack(( label_i ))
    else:
        labels_data = np.vstack(( labels_data, label_i ))
    if i % 1000 == 0:
        print i*100/(QUANTITY-1),"percent done..."
print "100 percent done..."
return train_data, labels_data

def preprocess_small_vgg16 (image, new_size=(64,64), type="non-quantized"):
img = np.copy (image)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#Whitening
imgnorm = img * 255.0/np.max(img)
#Normalisation
gray = imgnorm
borderless  = gray[:,5:gray.shape[1]-5,:] # centering
final_img = (cv2.resize (borderless, new_size))
final_img = final_img/np.max(final_img) #scaling 0-1
stddev = np.std(final_img); mn = np.mean (final_img)
final_img = (final_img - mn) / stddev #standardizing
return final_img

Output :

Epoch 1/10
5000/5000 [==============================] - 1346s - loss: 3.2877 -
mean_absolute_error: 0.0029 - acc: 0.1850
Epoch 2/10

Running over multiple epochs does not help. I tried with 5 epochs.

When I check output or predictions, it shows same results for all inputs e.g.(converted using np.argmax(pred, axis=-1)):

[3 3 3 . . . 3 3 3]

Please mark the problem in my model.


问:
What am I doing wrong with this modulus?
I wrote a c++ program that receives from user a number and Print 1 if positive and even, Print 2 if positive and odd, Print 3 if negative and even, Print 4 if negative and odd, Print 0 if zero.
Here's my code: </p>

```<code>#include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
if (n>0 && n%2==0)
    cout <<"1";
else if (n>0 && n%2==!0)
    cout <<"2";
else if (n<0 &&  n%2==0)
    cout <<"3";
else if (n<0 && n%2==!0)
    cout <<"4";
else if (n==0)
cout <<"0";
return 0;

}
</code>```

<p>Everything run pretty well except the 4th case whenever I enter negative and odd it prints nothing on the screen and that means nothing of all these cases are true, What am I doing wrong with the 4th, Isn't there a modulus to a negative number or what?  </p>

答:
Replace n%2==!0 with n % 2 != 0. The extra spacing is my personal taste.

n%2==!0 is evaluated as n%2==(!0) due to operator precedence, and !0 is equal to 1. Maddeningly, the way you have it works perfectly for the positive n case, but it breaks the negative n % 2 case which, for odd negative n, returns -1 from C++11 onwards. (Prior to that the result was implementation defined.)

Body:
I wrote a c++ program that receives from user a number and Print 1 if positive and even, Print 2 if positive and odd, Print 3 if negative and even, Print 4 if negative and odd, Print 0 if zero.
Here's my code:

#include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
if (n>0 && n%2==0)
    cout <<"1";
else if (n>0 && n%2==!0)
    cout <<"2";
else if (n<0 &&  n%2==0)
    cout <<"3";
else if (n<0 && n%2==!0)
    cout <<"4";
else if (n==0)
cout <<"0";
return 0;

}

Everything run pretty well except the 4th case whenever I enter negative and odd it prints nothing on the screen and that means nothing of all these cases are true, What am I doing wrong with the 4th, Isn't there a modulus to a negative number or what?


问:
How to concat two tensors different shape
I have two tensors, get_shape = [?, 400] and [?, 1176]. I want to concat them into one tensor of size [?, 1576].

I tried concat, but it requires both to be the same dimension.

How to do so?

答:
Hopefully, you are passing same dimension of input via batch size.</p>

```<code>import tensorflow as tf
import numpy as np

t1 = tf.placeholder(tf.float32, [None, 400])
t2 = tf.placeholder(tf.float32, [None, 1176])
t3 = tf.concat([t1, t2], axis = 1)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    t3_val = sess.run(t3, feed_dict = {t1: np.ones((300, 400)), t2: np.ones((300, 1176))})

    print(t3_val.shape)
    # (300, 1576)
</code>```

Body:
Hopefully, you are passing same dimension of input via batch size.

import tensorflow as tf
import numpy as np

t1 = tf.placeholder(tf.float32, [None, 400])
t2 = tf.placeholder(tf.float32, [None, 1176])
t3 = tf.concat([t1, t2], axis = 1)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    t3_val = sess.run(t3, feed_dict = {t1: np.ones((300, 400)), t2: np.ones((300, 1176))})

    print(t3_val.shape)
    # (300, 1576)


问:
"Could not locate the included file" error
I am practicing with Jekyll building a little website from scratch. Unfortunately, the following command returns error:

```<code>rodolfocangiotti.github.io rodolfo$ bundle exec jekyll serve --incremental --host=0.0.0.0
</code>```

Here is what is printed to stdout:

```<code>Configuration file: /Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io/_config.yml
Source: /Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io
Destination: /Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io/_site
Incremental build: enabled
Generating...
Liquid Exception: Could not locate the included file 'bodyheader.html' in any of ["/Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io/_includes", "/usr/local/lib/ruby/gems/2.4.0/gems/minima-2.1.1/_includes"]. Ensure it exists in one of those directories and, if it is a symlink, does not point outside your site source. in /_layouts/default.html
jekyll 3.6.2 | Error:  Could not locate the included file 'bodyheader.html' in any of ["/Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io/_includes", "/usr/local/lib/ruby/gems/2.4.0/gems/minima-2.1.1/_includes"]. Ensure it exists in one of those directories and, if it is a symlink, does not point outside your site source.
</code>```

Actually, the bodyheader.html file is inside the _include folder. Is anyone able to explain why Jekyll is unable to locate that file and how to solve the issue?

UPDATE:

The bodyheader.html file is included inside the default.html file, which is located inside the _layouts folder. Here is the content of that file:

```<code><!DOCTYPE html>
<html>
{% include head.html %}
<body>
{% include bodyheader.html %}
{{ content }}
</body>
</html>
</code>```

答: Try to rename _include folder to _includes.

Body:
I am practicing with Jekyll building a little website from scratch. Unfortunately, the following command returns error:

rodolfocangiotti.github.io rodolfo$ bundle exec jekyll serve --incremental --host=0.0.0.0

Here is what is printed to stdout:

Configuration file: /Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io/_config.yml
Source: /Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io
Destination: /Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io/_site
Incremental build: enabled
Generating...
Liquid Exception: Could not locate the included file 'bodyheader.html' in any of ["/Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io/_includes", "/usr/local/lib/ruby/gems/2.4.0/gems/minima-2.1.1/_includes"]. Ensure it exists in one of those directories and, if it is a symlink, does not point outside your site source. in /_layouts/default.html
jekyll 3.6.2 | Error:  Could not locate the included file 'bodyheader.html' in any of ["/Volumes/Data HD/Jekyll Folder/rodolfocangiotti.github.io/_includes", "/usr/local/lib/ruby/gems/2.4.0/gems/minima-2.1.1/_includes"]. Ensure it exists in one of those directories and, if it is a symlink, does not point outside your site source.

Actually, the bodyheader.html file is inside the _include folder. Is anyone able to explain why Jekyll is unable to locate that file and how to solve the issue?

UPDATE:

The bodyheader.html file is included inside the default.html file, which is located inside the _layouts folder. Here is the content of that file:

<!DOCTYPE html>

{% include head.html %}

{% include bodyheader.html %}
{{ content }}


问:
Scroll not working for multiple RecyclerView in BottomSheet
I implemented BottomSheet using the DialogFragment approach. I have a TabLayout and ViewPager in the BottomSheet. The ViewPager is hosting 2 pages, each inflates a RecyclerView. The first(Coffee tab) RecyclerView scrolls fine. The problem I'm having now is that for the 2nd(Milk tab) the scroll is not working. Any idea how can I fix this? Thanks!

You can test out with the demo project I created here: https://github.com/choongyouqi/bottomsheet`

答:
you can use 2 RecyclerView in CoordinatorLayout.

```<code><android.support.design.widget.CoordinatorLayout
         android:id="@+id/mainBottomSheet"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="@color/white">

         <android.support.v7.widget.RecyclerView
                  android:id="@+id/recyclerViewRight"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent" />

         <android.support.v7.widget.RecyclerView
                  android:id="@+id/recyclerViewLeft"
                  android:layout_width="200dp"
                  android:layout_height="match_parent" />

</android.support.design.widget.CoordinatorLayout>
</code>```

check this post link

Body:
you can use 2 RecyclerView in CoordinatorLayout.

<android.support.design.widget.CoordinatorLayout
         android:id="@+id/mainBottomSheet"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="@color/white">

         <android.support.v7.widget.RecyclerView
                  android:id="@+id/recyclerViewRight"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent" />

         <android.support.v7.widget.RecyclerView
                  android:id="@+id/recyclerViewLeft"
                  android:layout_width="200dp"
                  android:layout_height="match_parent" />

</android.support.design.widget.CoordinatorLayout>

check this post link


问:
In UI-Router how to set component property to child state parameter value
I have these two route definitions, product list and product detail:

```<code>{
  name: "product",
  url: "/product",
  component: ProductListComponent,
  resolve: [
    {
      token: "Products",
      deps: [ApiService],
      resolveFn: (api: ApiService) => api.getProducts().toPromise()
    }
  ]
},
{
  name: "product.detail",
  url: "/:productcode",
  component: ProductDetailComponent,
  resolve: [
    {
      token: "Product",
      deps: [Transition, ApiService],
      resolveFn: (transition: Transition, api: ApiService) =>
        api.getProduct(transition.params().productcode).toPromise()
    }
  ]
}
</code>```

Inside the product list component I have a set of radio buttons to indicate which product is selected, while the ui-view displays the product detail component:

```<code><div *ngFor="let product of Products" class="radio">
    <label>
        <input [(ngModel)]="SelectedProduct"
            [value]="product"
            (change)="RefreshDetail()"
            name="selectedProduct"
            type="radio">
            {{product.Name}} {{product.Code}}
    </label>
</div>
<ui-view></ui-view>
</code>```

When the user clicks the radio button, the URL, the product detail component, and the radio button are synchronized correctly.

But when the user goes directly to a certain product URL, the URL and product detail component display the correct product, but the radio button doesn't. What I mean by going directly to a certain product URL is the user inputs the URL to the browser address bar and press enter.

I tried to get the value of :productcode from the Transition object in ngOnInit:

```<code>ngOnInit() {
    let prodcode = this.transition.params().productcode;
    this.SelectedProduct = !!prodcode
        ? this.Products.find(product => product.Code == prodcode)
        : null;
}
</code>```

It works for browser refresh, the right product is selected in the radio button. But doesn't work on browser back button, no radio buttons are selected. (maybe because this parent state is not reinitialized?)

Anyway I'm not sure that this is the idiomatic way to get the parameter values of a child state.

What is the proper way to set component property value based on child state parameter value?

答:
You need to implements the Resolver. You can have a look here :

https://angular.io/api/router/Resolve

The Resolve perform route data retrieval before route activation. So you can assign & manage your data before anything else happen.

This is mine resolver when certain actions are called :

```<code>resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<something> {
        return this.myService.getTitle(route.params[something.property])
            .do(result => {
                if (result && !!Object.keys(result).length) {
                    //action to update what you want
                } else {
                    this.notificationsService.addNotification(<Notification>{
                        text: this.localizationKeys.deletedOrNotExisting,
                        type: MessageColorType.warning
                    });
                    this.router.navigate([...])]);
                    // tell the router where to go if there is any error
                }
            });

    }
</code>```

You can Inject a service in your component that keeps track about every change and use it to get access to your child parameter. As the resolver's logic is called even if you don't do a refresh, you can add few line of code to 'save' your current state.

Body:
I have these two route definitions, product list and product detail:

{
  name: "product",
  url: "/product",
  component: ProductListComponent,
  resolve: [
    {
      token: "Products",
      deps: [ApiService],
      resolveFn: (api: ApiService) => api.getProducts().toPromise()
    }
  ]
},
{
  name: "product.detail",
  url: "/:productcode",
  component: ProductDetailComponent,
  resolve: [
    {
      token: "Product",
      deps: [Transition, ApiService],
      resolveFn: (transition: Transition, api: ApiService) =>
        api.getProduct(transition.params().productcode).toPromise()
    }
  ]
}

Inside the product list component I have a set of radio buttons to indicate which product is selected, while the ui-view displays the product detail component:

        <input [(ngModel)]="SelectedProduct"
            [value]="product"
            (change)="RefreshDetail()"
            name="selectedProduct"
            type="radio">
            {{product.Name}} {{product.Code}}

<ui-view></ui-view>

When the user clicks the radio button, the URL, the product detail component, and the radio button are synchronized correctly.

But when the user goes directly to a certain product URL, the URL and product detail component display the correct product, but the radio button doesn't. What I mean by going directly to a certain product URL is the user inputs the URL to the browser address bar and press enter.

I tried to get the value of :productcode from the Transition object in ngOnInit:

ngOnInit() {
    let prodcode = this.transition.params().productcode;
    this.SelectedProduct = !!prodcode
        ? this.Products.find(product => product.Code == prodcode)
        : null;
}

It works for browser refresh, the right product is selected in the radio button. But doesn't work on browser back button, no radio buttons are selected. (maybe because this parent state is not reinitialized?)

Anyway I'm not sure that this is the idiomatic way to get the parameter values of a child state.

What is the proper way to set component property value based on child state parameter value?

Body:
You need to implements the Resolver. You can have a look here :

https://angular.io/api/router/Resolve

The Resolve perform route data retrieval before route activation. So you can assign & manage your data before anything else happen.

This is mine resolver when certain actions are called :

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<something> {
        return this.myService.getTitle(route.params[something.property])
            .do(result => {
                if (result && !!Object.keys(result).length) {
                    //action to update what you want
                } else {
                    this.notificationsService.addNotification(<Notification>{
                        text: this.localizationKeys.deletedOrNotExisting,
                        type: MessageColorType.warning
                    });
                    this.router.navigate([...])]);
                    // tell the router where to go if there is any error
                }
            });

    }

You can Inject a service in your component that keeps track about every change and use it to get access to your child parameter. As the resolver's logic is called even if you don't do a refresh, you can add few line of code to 'save' your current state.


问:
Integrate MS botframework in android app
I have created a basic Q&A bot using the MS bot framework. Now I want to integrate this chatbot in an android app as a feature. Can you tell me how do i do this.
Point me in the right direction.
Thanks.</p>

答:
There are several ways to achieve your requirement.

You can try to WebView in android to embed your bot application's endpoint. Which I think is the simplest method. Please refer to https://learn.microsoft.com/en-us/bot-framework/bot-design-pattern-embed-app for the similar scenario. Also which will leverage the repo https://github.com/Microsoft/BotFramework-WebChat, you can refer this for more info.

You can try to implement Direct Line in Android. You can refer to the unofficial repo https://github.com/brijrajsingh/DirectLineAndroidSample for hint.

Hope it helps.


问:
Vlookup to the right of a column
I am trying to vlookup the value to the right of the column.

df1

```<code>       EW  WE   DA  dd     AA
0  cheese   0  300   T      T
1  dwadaw   3  400  21  31232
</code>```

df 2

```<code>       AD   FA      BA  DA    daw ddwad
0  dddddd    1     300   T      T     T
1  cheese    1     400  21  31232   NaN
2  chees   dwa  waddcv   3    NaN   NaN
</code>```

Desired:

```<code>       AD   FA
0  cheese    1
</code>```

I try:

```<code>    df3 = df2[['AD', 'FA']].copy()
    df3.FA=np.where(df2.AD.isin(df1.EW),df3.FA,np.nan)
    print (df3)
</code>```

I get output identical to AD and FA in df2

df3 = df2[df2.AD.isin(df1.EW)]  gives: df3 = df2[df2.AD.isin(df1.EW)]   cheese  1.0  300  T   T

答:
I think you need:</p>

```<code>df3 = df2[df2.AD.isin(df1.EW)]
df3 = df3[['AD','FA']]
print (df3)
       AD FA
1  cheese  1
</code>```

Title: Vlookup to the right of a column

Body:
I am trying to vlookup the value to the right of the column.

df1

       EW  WE   DA  dd     AA
0  cheese   0  300   T      T
1  dwadaw   3  400  21  31232

df 2

       AD   FA      BA  DA    daw ddwad
0  dddddd    1     300   T      T     T
1  cheese    1     400  21  31232   NaN
2  chees   dwa  waddcv   3    NaN   NaN

Desired:

       AD   FA
0  cheese    1

I try:

    df3 = df2[['AD', 'FA']].copy()
    df3.FA=np.where(df2.AD.isin(df1.EW),df3.FA,np.nan)
    print (df3)

I get output identical to AD and FA in df2

df3 = df2[df2.AD.isin(df1.EW)]  gives: df3 = df2[df2.AD.isin(df1.EW)]   cheese  1.0  300  T   T

Body:
I think you need:

df3 = df2[df2.AD.isin(df1.EW)]
df3 = df3[['AD','FA']]
print (df3)
       AD FA
1  cheese  1


问:
How to retrieve a value from JSON Object Swift 4
I am trying to decode JSON object using Codable with Swift 4:

```<code>{
USD: {
"15m": 9977.49,
last: 9977.49,
buy: 9979.36,
sell: 9975.62,
symbol: "$"
    },
AUD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
    },
TBD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
    }
}
</code>```

This is what I've done so far with a model of an object:

```<code>struct Currency: Codable {

    let fifteenMin: Double?
    let last: Double?
    let buy: Double
    let sell: Double
    let symbol: String

    enum CodingKeys: String, CodingKey {
        case fifteenMin = "15m"
        case last
        case buy
        case sell
        case symbol
    }
}
</code>```

And this is how I decode that:

```<code>var currencyName = [String]()
var currenciesArray = [Currency]()

func fetchCurrencyData() {
    guard let urlString = API.RateURL.absoluteString else { return }
    guard let url = URL(string: urlString) else { return }
    let jsonData = try! Data(contentsOf: url)
    let decoder = JSONDecoder()
    do {
        let currenciesData = try decoder.decode([String: Currency].self, from: jsonData)
        for currency in currenciesData {
            self.currencyName.append(currency.key)
            self.currenciesArray.append(currency.value)
        }
    } catch let err {
        print(err.localizedDescription)
    }
}
</code>```

So when I want to populate rows in tableView with that Data I use "for loop" and append "USD", "AUD" and so on in one array and Currency object in another array.

What is the better way of fetching data and populating Currency object. Cuz I am pretty sure that fetching and appending the same object of JSON into two separate arrays isn't good practice I assume.

If my question isn't clear I can explain in more details what I would like to achieve.

Thank you.

答:
It's quite annoying (and error-prone) to maintain multiple arrays. I recommend to include the name in the struct.

Add this line in Currency

```<code>var name = ""
</code>```

After decoding the JSON sort the keys, get the corresponding value and set the name to the key

```<code>var currenciesArray = [Currency]()

let currencies = try decoder.decode([String: Currency].self, from: jsonData)

for key in currencies.keys.sorted() {
    var currency = currencies[key]!
    currency.name = key
    currenciesArray.append(currency)
}
print(currenciesArray)
</code>```

Body:
I am trying to decode JSON object using Codable with Swift 4:

{
USD: {
"15m": 9977.49,
last: 9977.49,
buy: 9979.36,
sell: 9975.62,
symbol: "$"
    },
AUD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
    },
TBD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
    }
}

This is what I've done so far with a model of an object:

struct Currency: Codable {

    let fifteenMin: Double?
    let last: Double?
    let buy: Double
    let sell: Double
    let symbol: String

    enum CodingKeys: String, CodingKey {
        case fifteenMin = "15m"
        case last
        case buy
        case sell
        case symbol
    }
}

And this is how I decode that:

var currencyName = [String]()
var currenciesArray = [Currency]()

func fetchCurrencyData() {
    guard let urlString = API.RateURL.absoluteString else { return }
    guard let url = URL(string: urlString) else { return }
    let jsonData = try! Data(contentsOf: url)
    let decoder = JSONDecoder()
    do {
        let currenciesData = try decoder.decode([String: Currency].self, from: jsonData)
        for currency in currenciesData {
            self.currencyName.append(currency.key)
            self.currenciesArray.append(currency.value)
        }
    } catch let err {
        print(err.localizedDescription)
    }
}

So when I want to populate rows in tableView with that Data I use "for loop" and append "USD", "AUD" and so on in one array and Currency object in another array.

What is the better way of fetching data and populating Currency object. Cuz I am pretty sure that fetching and appending the same object of JSON into two separate arrays isn't good practice I assume.

If my question isn't clear I can explain in more details what I would like to achieve.

Thank you.

Body:
It's quite annoying (and error-prone) to maintain multiple arrays. I recommend to include the name in the struct.

Add this line in Currency

var name = ""

After decoding the JSON sort the keys, get the corresponding value and set the name to the key

var currenciesArray = [Currency]()

let currencies = try decoder.decode([String: Currency].self, from: jsonData)

for key in currencies.keys.sorted() {
    var currency = currencies[key]!
    currency.name = key
    currenciesArray.append(currency)
}
print(currenciesArray)


问:
Python ctypes pass pointer in structure field to Fortran derived types
I want to make a variable-size array to pass to a Fortran DLL and get the result (by reference), so that I can get value directly.

In the Fortran code, I use allocatable variables, which I think is like a pointer to point allocated address.

I can do as following but I don't know how to do it in structure:

```<code>test = POINTER(c_double)()

sim.structtest(input, byref(test))
</code>```

the definition of test in Fortran is

```<code>real(kind=8), allocatable, dimension (:) :: test

allocate(test(1))
</code>```

The original code:

Python code (structtest.py):

```<code>from ctypes import *
import sys
import os

sim = cdll.LoadLibrary("struct.so")

class Input( Structure ):
    _fields_ = [( "a", c_double * 1 ),
                ( "b", c_double )]

class Output( Structure ):
    _fields_ = [( "a", c_double ),
                ( "b", POINTER(c_double) )] #-> don't know how to do

def main():
    input = Input()
    output = Output()
    input.a[0] = 1
    input.b = 2

    sim.structtest(input, byref(output))
</code>```

Fortran code (struct.f90):

```<code>subroutine structtest(input, output) bind(c, name='structtest')

    USE ISO_C_BINDING
    IMPLICIT NONE

    !define input structure
    TYPE T_INPUT
        !real*8, allocatable :: a(:)
        real(kind=8) :: a(1)
        real(kind=8) :: b
    END TYPE T_INPUT

    !define output structure
    TYPE T_OUTPUT
        real(kind=8) :: a
        real(kind=8), allocatable, dimension (:) :: b
    END TYPE T_OUTPUT

    !define a variable "input" with structure "INPUT"
    TYPE (T_INPUT), value :: input

    TYPE (T_OUTPUT) :: output

    allocate(output%d(1))

    output%b(1) = 5
    PRINT *, output%d(1)
</code>```

I compile the Fortran to DLL like:

```<code>ifort -shared -fPIC -static-intel -o struct.so struct.f90
</code>```

I execute the Python as:

```<code>python structtest.py
</code>```

I get the result:

```<code>*** Error in `python': free(): corrupted unsorted chunks: 0x0000000001f7af00 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fc9027f57e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fc9027fe37a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fc90280253c]
/lib/x86_64-linux-gnu/libc.so.6(__open_catalog+0xe8)[0x7fc9027b2008]
/lib/x86_64-linux-gnu/libc.so.6(catopen+0x4c)[0x7fc9027b1c2c]
/home/mingster/simGeo.docker/simgeo/lib/struct.so(for__issue_diagnostic+0x11e)[0x7fc90147a77e]
/home/mingster/simGeo.docker/simgeo/lib/struct.so(for_allocate+0x303)[0x7fc90146b9a3]
/home/mingster/simGeo.docker/simgeo/lib/struct.so(structtest+0xae)[0x7fc90146b16e]
/usr/lib/x86_64-linux-gnu/libffi.so.6(ffi_call_unix64+0x4c)[0x7fc901757e40]
/usr/lib/x86_64-linux-gnu/libffi.so.6(ffi_call+0x2eb)[0x7fc9017578ab]
/usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so(_ctypes_callproc+0x48f)[0x7fc9019673df]
/usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so(+0x11d82)[0x7fc90196bd82]
python(PyObject_Call+0x43)[0x4b0c93]
python(PyEval_EvalFrameEx+0x602f)[0x4c9f9f]
python(PyEval_EvalFrameEx+0x5e0f)[0x4c9d7f]
python(PyEval_EvalCodeEx+0x255)[0x4c2705]
python(PyEval_EvalCode+0x19)[0x4c24a9]
python[0x4f19ef]
python(PyRun_FileExFlags+0x82)[0x4ec372]
python(PyRun_SimpleFileExFlags+0x191)[0x4eaaf1]
python(Py_Main+0x6c8)[0x49e208]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fc90279e830]
python(_start+0x29)[0x49da59]
======= Memory map: ========
00400000-006e9000 r-xp 00000000 08:01 525090                             /usr/bin/python2.7
008e8000-008ea000 r--p 002e8000 08:01 525090                             /usr/bin/python2.7
008ea000-00961000 rw-p 002ea000 08:01 525090                             /usr/bin/python2.7
00961000-00984000 rw-p 00000000 00:00 0
01f10000-01ff6000 rw-p 00000000 00:00 0                                  [heap]
7fc8fc000000-7fc8fc021000 rw-p 00000000 00:00 0
7fc8fc021000-7fc900000000 ---p 00000000 00:00 0
7fc901246000-7fc90125c000 r-xp 00000000 08:01 38797837                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fc90125c000-7fc90145b000 ---p 00016000 08:01 38797837                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fc90145b000-7fc90145c000 rw-p 00015000 08:01 38797837                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fc90145c000-7fc901504000 r-xp 00000000 08:01 51643749                   /home/mingster/simGeo.docker/simgeo/lib/struct.so
7fc901504000-7fc901704000 ---p 000a8000 08:01 51643749                   /home/mingster/simGeo.docker/simgeo/lib/struct.so
7fc901704000-7fc90170a000 rw-p 000a8000 08:01 51643749                   /home/mingster/simGeo.docker/simgeo/lib/struct.so
7fc90170a000-7fc901752000 rw-p 00000000 00:00 0
7fc901752000-7fc901759000 r-xp 00000000 08:01 526635                     /usr/lib/x86_64-linux-gnu/libffi.so.6.0.4
7fc901759000-7fc901958000 ---p 00007000 08:01 526635                     /usr/lib/x86_64-linux-gnu/libffi.so.6.0.4
7fc901958000-7fc901959000 r--p 00006000 08:01 526635                     /usr/lib/x86_64-linux-gnu/libffi.so.6.0.4
7fc901959000-7fc90195a000 rw-p 00007000 08:01 526635                     /usr/lib/x86_64-linux-gnu/libffi.so.6.0.4
7fc90195a000-7fc901978000 r-xp 00000000 08:01 30543353                   /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
7fc901978000-7fc901b77000 ---p 0001e000 08:01 30543353                   /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
7fc901b77000-7fc901b78000 r--p 0001d000 08:01 30543353                   /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
7fc901b78000-7fc901b7c000 rw-p 0001e000 08:01 30543353                   /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
7fc901b7c000-7fc901e54000 r--p 00000000 08:01 529135                     /usr/lib/locale/locale-archive
7fc901e54000-7fc901f5c000 r-xp 00000000 08:01 38797852                   /lib/x86_64-linux-gnu/libm-2.23.so
7fc901f5c000-7fc90215b000 ---p 00108000 08:01 38797852                   /lib/x86_64-linux-gnu/libm-2.23.so
7fc90215b000-7fc90215c000 r--p 00107000 08:01 38797852                   /lib/x86_64-linux-gnu/libm-2.23.so
7fc90215c000-7fc90215d000 rw-p 00108000 08:01 38797852                   /lib/x86_64-linux-gnu/libm-2.23.so
7fc90215d000-7fc902176000 r-xp 00000000 08:01 38797934                   /lib/x86_64-linux-gnu/libz.so.1.2.8
7fc902176000-7fc902375000 ---p 00019000 08:01 38797934                   /lib/x86_64-linux-gnu/libz.so.1.2.8
7fc902375000-7fc902376000 r--p 00018000 08:01 38797934                   /lib/x86_64-linux-gnu/libz.so.1.2.8
7fc902376000-7fc902377000 rw-p 00019000 08:01 38797934                   /lib/x86_64-linux-gnu/libz.so.1.2.8
7fc902377000-7fc902379000 r-xp 00000000 08:01 38797927                   /lib/x86_64-linux-gnu/libutil-2.23.so
7fc902379000-7fc902578000 ---p 00002000 08:01 38797927                   /lib/x86_64-linux-gnu/libutil-2.23.so
7fc902578000-7fc902579000 r--p 00001000 08:01 38797927                   /lib/x86_64-linux-gnu/libutil-2.23.so
7fc902579000-7fc90257a000 rw-p 00002000 08:01 38797927                   /lib/x86_64-linux-gnu/libutil-2.23.so
7fc90257a000-7fc90257d000 r-xp 00000000 08:01 38797825                   /lib/x86_64-linux-gnu/libdl-2.23.so
7fc90257d000-7fc90277c000 ---p 00003000 08:01 38797825                   /lib/x86_64-linux-gnu/libdl-2.23.so
7fc90277c000-7fc90277d000 r--p 00002000 08:01 38797825                   /lib/x86_64-linux-gnu/libdl-2.23.so
7fc90277d000-7fc90277e000 rw-p 00003000 08:01 38797825                   /lib/x86_64-linux-gnu/libdl-2.23.so
7fc90277e000-7fc90293e000 r-xp 00000000 08:01 38797811                   /lib/x86_64-linux-gnu/libc-2.23.so
7fc90293e000-7fc902b3e000 ---p 001c0000 08:01 38797811                   /lib/x86_64-linux-gnu/libc-2.23.so
7fc902b3e000-7fc902b42000 r--p 001c0000 08:01 38797811                   /lib/x86_64-linux-gnu/libc-2.23.so
7fc902b42000-7fc902b44000 rw-p 001c4000 08:01 38797811                   /lib/x86_64-linux-gnu/libc-2.23.so
7fc902b44000-7fc902b48000 rw-p 00000000 00:00 0
7fc902b48000-7fc902b60000 r-xp 00000000 08:01 38797898                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fc902b60000-7fc902d5f000 ---p 00018000 08:01 38797898                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fc902d5f000-7fc902d60000 r--p 00017000 08:01 38797898                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fc902d60000-7fc902d61000 rw-p 00018000 08:01 38797898                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fc902d61000-7fc902d65000 rw-p 00000000 00:00 0
7fc902d65000-7fc902d8b000 r-xp 00000000 08:01 38797787                   /lib/x86_64-linux-gnu/ld-2.23.so
7fc902dc5000-7fc902f7b000 rw-p 00000000 00:00 0
7fc902f86000-7fc902f87000 rw-p 00000000 00:00 0
7fc902f87000-7fc902f88000 rwxp 00000000 00:00 0
7fc902f88000-7fc902f8a000 rw-p 00000000 00:00 0
7fc902f8a000-7fc902f8b000 r--p 00025000 08:01 38797787                   /lib/x86_64-linux-gnu/ld-2.23.so
7fc902f8b000-7fc902f8c000 rw-p 00026000 08:01 38797787                   /lib/x86_64-linux-gnu/ld-2.23.so
7fc902f8c000-7fc902f8d000 rw-p 00000000 00:00 0
7ffc38bde000-7ffc38bff000 rw-p 00000000 00:00 0                          [stack]
7ffc38cd8000-7ffc38cda000 r--p 00000000 00:00 0                          [vvar]
7ffc38cda000-7ffc38cdc000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted (core dumped)
</code>```

答:
Thanks All,

belows is the working example for Python to pass multi-dimension array to Fortran

python code:

```<code>from ctypes import *
import ctypes
import sys
import os
import numpy as np

sim = cdll.LoadLibrary(os.path.dirname(os.path.abspath(__file__)) + "/lib/struct.so")

class Param( Structure ):
    pass

class Result( Structure ):
    pass

def main():

    x = 2
    y = 3
    z = 4
    Param._fields_ = [( "len_x", c_int ),
                ( "len_y", c_int ),
                ( "len_z", c_int ),
                ( "c", POINTER(c_double)),
                ( "d", POINTER(c_double * x)),
                ( "e", POINTER(c_double * x * y))]

    Result._fields_ = [( "len_x", c_int ),
                ( "len_y", c_int ),
                ( "len_z", c_int ),
                ( "f", POINTER(c_double)),
                ( "g", POINTER(c_double * x)),
                ( "h", POINTER(c_double * x * y))]

    param = Param()
    result = Result()

    cc = (c_double * x)()
    dd = ( (c_double * x) * y )()
    ee = ( ( ( (c_double * x) * y ) * z ) )()

    #[x]
    cc[0] = 10.0
    cc[1] = 20.0

    #[y][x]
    dd[0][0] = 10.0
    dd[1][0] = 20.0
    dd[2][0] = 30.0
    dd[0][1] = 40.0
    dd[1][1] = 50.0
    dd[2][1] = 60.0

    #[z][y][x]
    ee[0][0][0] = 1.0
    ee[1][0][0] = 2.0
    ee[2][0][0] = 3.0
    ee[0][1][0] = 4.0
    ee[1][1][0] = 5.0
    ee[2][1][0] = 6.0

    param.len_x = x
    param.len_y = y
    param.len_z = z

    param.c = cc
    param.d = dd
    param.e = ee

    sim.structtest(byref(param), byref(result))

    #[x]
    print "1D"
    print result.f[0]
    print result.f[1]

    #[y][x]
    print "2D"
    print result.g[0][0]
    print result.g[1][0]
    print result.g[2][0]
    print result.g[0][1]
    print result.g[1][1]
    print result.g[2][1]

    #[z][y][x]
    print "3D"
    print result.h[0][0][0]
    print result.h[1][0][0]
    print result.h[2][0][0]
    print result.h[0][1][0]
    print result.h[1][1][0]
    print result.h[2][1][0]

if __name__ == "__main__":
    result = main()
</code>```

fortran code:

```<code>subroutine structtest(param, result) bind(c, name="structtest")

    use, intrinsic :: ISO_C_BINDING
    implicit none

    type, BIND(C) :: args
        integer (C_INT) :: len_x
        integer (C_INT) :: len_y
        integer (C_INT) :: len_z
        type (C_PTR) :: c
        type (C_PTR) :: d
        type (C_PTR) :: e
    end type args

    type, BIND(C) :: output
        integer (C_INT) :: len_x
        integer (C_INT) :: len_y
        integer (C_INT) :: len_z
        type (C_PTR) :: f
        type (C_PTR) :: g
        type (C_PTR) :: h
    end type output

    type (args), intent(in):: param
    type (output), intent(out):: result

    real (C_DOUBLE), pointer :: arg_array_c(:)
    real (C_DOUBLE), pointer :: arg_array_d(:,:)
    real (C_DOUBLE), pointer :: arg_array_e(:,:,:)
    real (C_DOUBLE), ALLOCATABLE, target, save :: result_array_f(:)
    real (C_DOUBLE), ALLOCATABLE, target, save :: result_array_g(:,:)
    real (C_DOUBLE), ALLOCATABLE, target, save :: result_array_h(:,:,:)

    ! Associate c_array with an array allocated in C
    call C_F_POINTER (param%c, arg_array_c, [param%len_x] )
    call C_F_POINTER (param%d, arg_array_d, [param%len_x,param%len_y] )
    call C_F_POINTER (param%e, arg_array_e, [param%len_x,param%len_y,param%len_z] )

    ![x]
    print *,"1D"
    print *,arg_array_c(1)
    print *,arg_array_c(2)

    ![x][y]
    print *,"2D"
    print *,arg_array_d(1,1)
    print *,arg_array_d(1,2)
    print *,arg_array_d(1,3)
    print *,arg_array_d(2,1)
    print *,arg_array_d(2,2)
    print *,arg_array_d(2,3)

    ![x][y][z]
    print *,"3D"
    print *,arg_array_e(1,1,1)
    print *,arg_array_e(1,1,2)
    print *,arg_array_e(1,1,3)
    print *,arg_array_e(1,2,1)
    print *,arg_array_e(1,2,2)
    print *,arg_array_e(1,2,3)

    ! Allocate an array and make it available in C

    result%len_x = param%len_x
    result%len_y = param%len_y
    result%len_z = param%len_z

    ALLOCATE (result_array_f(result%len_x))
    ALLOCATE (result_array_g(result%len_x, result%len_y))
    ALLOCATE (result_array_h(result%len_x, result%len_y, result%len_z))

    result%f = c_loc(result_array_f)
    result%g = c_loc(result_array_g)
    result%h = c_loc(result_array_h)

    ![x]
    result_array_f(1) = arg_array_c(1)
    result_array_f(2) = arg_array_c(2)

    ![x][y]
    result_array_g(1,1) = arg_array_d(1,1)
    result_array_g(1,2) = arg_array_d(1,2)
    result_array_g(1,3) = arg_array_d(1,3)
    result_array_g(2,1) = arg_array_d(2,1)
    result_array_g(2,2) = arg_array_d(2,2)
    result_array_g(2,3) = arg_array_d(2,3)

    ![x][y][z]
    result_array_h(1,1,1) = arg_array_e(1,1,1)
    result_array_h(1,1,2) = arg_array_e(1,1,2)
    result_array_h(1,1,3) = arg_array_e(1,1,3)
    result_array_h(1,2,1) = arg_array_e(1,2,1)
    result_array_h(1,2,2) = arg_array_e(1,2,2)
    result_array_h(1,2,3) = arg_array_e(1,2,3)

end
</code>```

output:

```<code> 1D
   10.0000000000000
   20.0000000000000
 2D
   10.0000000000000
   20.0000000000000
   30.0000000000000
   40.0000000000000
   50.0000000000000
   60.0000000000000
 3D
   1.00000000000000
   2.00000000000000
   3.00000000000000
   4.00000000000000
   5.00000000000000
   6.00000000000000
1D
10.0
20.0
2D
10.0
20.0
30.0
40.0
50.0
60.0
3D
1.0
2.0
3.0
4.0
5.0
6.0
</code>```

Body:
I want to make a variable-size array to pass to a Fortran DLL and get the result (by reference), so that I can get value directly.

In the Fortran code, I use allocatable variables, which I think is like a pointer to point allocated address.

I can do as following but I don't know how to do it in structure:

test = POINTER(c_double)()

sim.structtest(input, byref(test))

the definition of test in Fortran is

real(kind=8), allocatable, dimension (:) :: test

allocate(test(1))

The original code:

Python code (structtest.py):

from ctypes import *
import sys
import os

sim = cdll.LoadLibrary("struct.so")

class Input( Structure ):
    _fields_ = [( "a", c_double * 1 ),
                ( "b", c_double )]

class Output( Structure ):
    _fields_ = [( "a", c_double ),
                ( "b", POINTER(c_double) )] #-> don't know how to do

def main():
    input = Input()
    output = Output()
    input.a[0] = 1
    input.b = 2

    sim.structtest(input, byref(output))

Fortran code (struct.f90):

subroutine structtest(input, output) bind(c, name='structtest')

    USE ISO_C_BINDING
    IMPLICIT NONE

    !define input structure
    TYPE T_INPUT
        !real*8, allocatable :: a(:)
        real(kind=8) :: a(1)
        real(kind=8) :: b
    END TYPE T_INPUT

    !define output structure
    TYPE T_OUTPUT
        real(kind=8) :: a
        real(kind=8), allocatable, dimension (:) :: b
    END TYPE T_OUTPUT

    !define a variable "input" with structure "INPUT"
    TYPE (T_INPUT), value :: input

    TYPE (T_OUTPUT) :: output

    allocate(output%d(1))

    output%b(1) = 5
    PRINT *, output%d(1)

I compile the Fortran to DLL like:

ifort -shared -fPIC -static-intel -o struct.so struct.f90

I execute the Python as:

python structtest.py

I get the result:

*** Error in `python': free(): corrupted unsorted chunks: 0x0000000001f7af00 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fc9027f57e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fc9027fe37a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fc90280253c]
/lib/x86_64-linux-gnu/libc.so.6(__open_catalog+0xe8)[0x7fc9027b2008]
/lib/x86_64-linux-gnu/libc.so.6(catopen+0x4c)[0x7fc9027b1c2c]
/home/mingster/simGeo.docker/simgeo/lib/struct.so(for__issue_diagnostic+0x11e)[0x7fc90147a77e]
/home/mingster/simGeo.docker/simgeo/lib/struct.so(for_allocate+0x303)[0x7fc90146b9a3]
/home/mingster/simGeo.docker/simgeo/lib/struct.so(structtest+0xae)[0x7fc90146b16e]
/usr/lib/x86_64-linux-gnu/libffi.so.6(ffi_call_unix64+0x4c)[0x7fc901757e40]
/usr/lib/x86_64-linux-gnu/libffi.so.6(ffi_call+0x2eb)[0x7fc9017578ab]
/usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so(_ctypes_callproc+0x48f)[0x7fc9019673df]
/usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so(+0x11d82)[0x7fc90196bd82]
python(PyObject_Call+0x43)[0x4b0c93]
python(PyEval_EvalFrameEx+0x602f)[0x4c9f9f]
python(PyEval_EvalFrameEx+0x5e0f)[0x4c9d7f]
python(PyEval_EvalCodeEx+0x255)[0x4c2705]
python(PyEval_EvalCode+0x19)[0x4c24a9]
python[0x4f19ef]
python(PyRun_FileExFlags+0x82)[0x4ec372]
python(PyRun_SimpleFileExFlags+0x191)[0x4eaaf1]
python(Py_Main+0x6c8)[0x49e208]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fc90279e830]
python(_start+0x29)[0x49da59]
======= Memory map: ========
00400000-006e9000 r-xp 00000000 08:01 525090                             /usr/bin/python2.7
008e8000-008ea000 r--p 002e8000 08:01 525090                             /usr/bin/python2.7
008ea000-00961000 rw-p 002ea000 08:01 525090                             /usr/bin/python2.7
00961000-00984000 rw-p 00000000 00:00 0
01f10000-01ff6000 rw-p 00000000 00:00 0                                  [heap]
7fc8fc000000-7fc8fc021000 rw-p 00000000 00:00 0
7fc8fc021000-7fc900000000 ---p 00000000 00:00 0
7fc901246000-7fc90125c000 r-xp 00000000 08:01 38797837                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fc90125c000-7fc90145b000 ---p 00016000 08:01 38797837                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fc90145b000-7fc90145c000 rw-p 00015000 08:01 38797837                   /lib/x86_64-linux-gnu/libgcc_s.so.1
7fc90145c000-7fc901504000 r-xp 00000000 08:01 51643749                   /home/mingster/simGeo.docker/simgeo/lib/struct.so
7fc901504000-7fc901704000 ---p 000a8000 08:01 51643749                   /home/mingster/simGeo.docker/simgeo/lib/struct.so
7fc901704000-7fc90170a000 rw-p 000a8000 08:01 51643749                   /home/mingster/simGeo.docker/simgeo/lib/struct.so
7fc90170a000-7fc901752000 rw-p 00000000 00:00 0
7fc901752000-7fc901759000 r-xp 00000000 08:01 526635                     /usr/lib/x86_64-linux-gnu/libffi.so.6.0.4
7fc901759000-7fc901958000 ---p 00007000 08:01 526635                     /usr/lib/x86_64-linux-gnu/libffi.so.6.0.4
7fc901958000-7fc901959000 r--p 00006000 08:01 526635                     /usr/lib/x86_64-linux-gnu/libffi.so.6.0.4
7fc901959000-7fc90195a000 rw-p 00007000 08:01 526635                     /usr/lib/x86_64-linux-gnu/libffi.so.6.0.4
7fc90195a000-7fc901978000 r-xp 00000000 08:01 30543353                   /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
7fc901978000-7fc901b77000 ---p 0001e000 08:01 30543353                   /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
7fc901b77000-7fc901b78000 r--p 0001d000 08:01 30543353                   /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
7fc901b78000-7fc901b7c000 rw-p 0001e000 08:01 30543353                   /usr/lib/python2.7/lib-dynload/_ctypes.x86_64-linux-gnu.so
7fc901b7c000-7fc901e54000 r--p 00000000 08:01 529135                     /usr/lib/locale/locale-archive
7fc901e54000-7fc901f5c000 r-xp 00000000 08:01 38797852                   /lib/x86_64-linux-gnu/libm-2.23.so
7fc901f5c000-7fc90215b000 ---p 00108000 08:01 38797852                   /lib/x86_64-linux-gnu/libm-2.23.so
7fc90215b000-7fc90215c000 r--p 00107000 08:01 38797852                   /lib/x86_64-linux-gnu/libm-2.23.so
7fc90215c000-7fc90215d000 rw-p 00108000 08:01 38797852                   /lib/x86_64-linux-gnu/libm-2.23.so
7fc90215d000-7fc902176000 r-xp 00000000 08:01 38797934                   /lib/x86_64-linux-gnu/libz.so.1.2.8
7fc902176000-7fc902375000 ---p 00019000 08:01 38797934                   /lib/x86_64-linux-gnu/libz.so.1.2.8
7fc902375000-7fc902376000 r--p 00018000 08:01 38797934                   /lib/x86_64-linux-gnu/libz.so.1.2.8
7fc902376000-7fc902377000 rw-p 00019000 08:01 38797934                   /lib/x86_64-linux-gnu/libz.so.1.2.8
7fc902377000-7fc902379000 r-xp 00000000 08:01 38797927                   /lib/x86_64-linux-gnu/libutil-2.23.so
7fc902379000-7fc902578000 ---p 00002000 08:01 38797927                   /lib/x86_64-linux-gnu/libutil-2.23.so
7fc902578000-7fc902579000 r--p 00001000 08:01 38797927                   /lib/x86_64-linux-gnu/libutil-2.23.so
7fc902579000-7fc90257a000 rw-p 00002000 08:01 38797927                   /lib/x86_64-linux-gnu/libutil-2.23.so
7fc90257a000-7fc90257d000 r-xp 00000000 08:01 38797825                   /lib/x86_64-linux-gnu/libdl-2.23.so
7fc90257d000-7fc90277c000 ---p 00003000 08:01 38797825                   /lib/x86_64-linux-gnu/libdl-2.23.so
7fc90277c000-7fc90277d000 r--p 00002000 08:01 38797825                   /lib/x86_64-linux-gnu/libdl-2.23.so
7fc90277d000-7fc90277e000 rw-p 00003000 08:01 38797825                   /lib/x86_64-linux-gnu/libdl-2.23.so
7fc90277e000-7fc90293e000 r-xp 00000000 08:01 38797811                   /lib/x86_64-linux-gnu/libc-2.23.so
7fc90293e000-7fc902b3e000 ---p 001c0000 08:01 38797811                   /lib/x86_64-linux-gnu/libc-2.23.so
7fc902b3e000-7fc902b42000 r--p 001c0000 08:01 38797811                   /lib/x86_64-linux-gnu/libc-2.23.so
7fc902b42000-7fc902b44000 rw-p 001c4000 08:01 38797811                   /lib/x86_64-linux-gnu/libc-2.23.so
7fc902b44000-7fc902b48000 rw-p 00000000 00:00 0
7fc902b48000-7fc902b60000 r-xp 00000000 08:01 38797898                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fc902b60000-7fc902d5f000 ---p 00018000 08:01 38797898                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fc902d5f000-7fc902d60000 r--p 00017000 08:01 38797898                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fc902d60000-7fc902d61000 rw-p 00018000 08:01 38797898                   /lib/x86_64-linux-gnu/libpthread-2.23.so
7fc902d61000-7fc902d65000 rw-p 00000000 00:00 0
7fc902d65000-7fc902d8b000 r-xp 00000000 08:01 38797787                   /lib/x86_64-linux-gnu/ld-2.23.so
7fc902dc5000-7fc902f7b000 rw-p 00000000 00:00 0
7fc902f86000-7fc902f87000 rw-p 00000000 00:00 0
7fc902f87000-7fc902f88000 rwxp 00000000 00:00 0
7fc902f88000-7fc902f8a000 rw-p 00000000 00:00 0
7fc902f8a000-7fc902f8b000 r--p 00025000 08:01 38797787                   /lib/x86_64-linux-gnu/ld-2.23.so
7fc902f8b000-7fc902f8c000 rw-p 00026000 08:01 38797787                   /lib/x86_64-linux-gnu/ld-2.23.so
7fc902f8c000-7fc902f8d000 rw-p 00000000 00:00 0
7ffc38bde000-7ffc38bff000 rw-p 00000000 00:00 0                          [stack]
7ffc38cd8000-7ffc38cda000 r--p 00000000 00:00 0                          [vvar]
7ffc38cda000-7ffc38cdc000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted (core dumped)

Body:
Thanks All,

belows is the working example for Python to pass multi-dimension array to Fortran

python code:

from ctypes import *
import ctypes
import sys
import os
import numpy as np

sim = cdll.LoadLibrary(os.path.dirname(os.path.abspath(__file__)) + "/lib/struct.so")

class Param( Structure ):
    pass

class Result( Structure ):
    pass

def main():

    x = 2
    y = 3
    z = 4
    Param._fields_ = [( "len_x", c_int ),
                ( "len_y", c_int ),
                ( "len_z", c_int ),
                ( "c", POINTER(c_double)),
                ( "d", POINTER(c_double * x)),
                ( "e", POINTER(c_double * x * y))]

    Result._fields_ = [( "len_x", c_int ),
                ( "len_y", c_int ),
                ( "len_z", c_int ),
                ( "f", POINTER(c_double)),
                ( "g", POINTER(c_double * x)),
                ( "h", POINTER(c_double * x * y))]

    param = Param()
    result = Result()

    cc = (c_double * x)()
    dd = ( (c_double * x) * y )()
    ee = ( ( ( (c_double * x) * y ) * z ) )()

    #[x]
    cc[0] = 10.0
    cc[1] = 20.0

    #[y][x]
    dd[0][0] = 10.0
    dd[1][0] = 20.0
    dd[2][0] = 30.0
    dd[0][1] = 40.0
    dd[1][1] = 50.0
    dd[2][1] = 60.0

    #[z][y][x]
    ee[0][0][0] = 1.0
    ee[1][0][0] = 2.0
    ee[2][0][0] = 3.0
    ee[0][1][0] = 4.0
    ee[1][1][0] = 5.0
    ee[2][1][0] = 6.0

    param.len_x = x
    param.len_y = y
    param.len_z = z

    param.c = cc
    param.d = dd
    param.e = ee

    sim.structtest(byref(param), byref(result))

    #[x]
    print "1D"
    print result.f[0]
    print result.f[1]

    #[y][x]
    print "2D"
    print result.g[0][0]
    print result.g[1][0]
    print result.g[2][0]
    print result.g[0][1]
    print result.g[1][1]
    print result.g[2][1]

    #[z][y][x]
    print "3D"
    print result.h[0][0][0]
    print result.h[1][0][0]
    print result.h[2][0][0]
    print result.h[0][1][0]
    print result.h[1][1][0]
    print result.h[2][1][0]

if __name__ == "__main__":
    result = main()

fortran code:

subroutine structtest(param, result) bind(c, name="structtest")

    use, intrinsic :: ISO_C_BINDING
    implicit none

    type, BIND(C) :: args
        integer (C_INT) :: len_x
        integer (C_INT) :: len_y
        integer (C_INT) :: len_z
        type (C_PTR) :: c
        type (C_PTR) :: d
        type (C_PTR) :: e
    end type args

    type, BIND(C) :: output
        integer (C_INT) :: len_x
        integer (C_INT) :: len_y
        integer (C_INT) :: len_z
        type (C_PTR) :: f
        type (C_PTR) :: g
        type (C_PTR) :: h
    end type output

    type (args), intent(in):: param
    type (output), intent(out):: result

    real (C_DOUBLE), pointer :: arg_array_c(:)
    real (C_DOUBLE), pointer :: arg_array_d(:,:)
    real (C_DOUBLE), pointer :: arg_array_e(:,:,:)
    real (C_DOUBLE), ALLOCATABLE, target, save :: result_array_f(:)
    real (C_DOUBLE), ALLOCATABLE, target, save :: result_array_g(:,:)
    real (C_DOUBLE), ALLOCATABLE, target, save :: result_array_h(:,:,:)

    ! Associate c_array with an array allocated in C
    call C_F_POINTER (param%c, arg_array_c, [param%len_x] )
    call C_F_POINTER (param%d, arg_array_d, [param%len_x,param%len_y] )
    call C_F_POINTER (param%e, arg_array_e, [param%len_x,param%len_y,param%len_z] )

    ![x]
    print *,"1D"
    print *,arg_array_c(1)
    print *,arg_array_c(2)

    ![x][y]
    print *,"2D"
    print *,arg_array_d(1,1)
    print *,arg_array_d(1,2)
    print *,arg_array_d(1,3)
    print *,arg_array_d(2,1)
    print *,arg_array_d(2,2)
    print *,arg_array_d(2,3)

    ![x][y][z]
    print *,"3D"
    print *,arg_array_e(1,1,1)
    print *,arg_array_e(1,1,2)
    print *,arg_array_e(1,1,3)
    print *,arg_array_e(1,2,1)
    print *,arg_array_e(1,2,2)
    print *,arg_array_e(1,2,3)

    ! Allocate an array and make it available in C

    result%len_x = param%len_x
    result%len_y = param%len_y
    result%len_z = param%len_z

    ALLOCATE (result_array_f(result%len_x))
    ALLOCATE (result_array_g(result%len_x, result%len_y))
    ALLOCATE (result_array_h(result%len_x, result%len_y, result%len_z))

    result%f = c_loc(result_array_f)
    result%g = c_loc(result_array_g)
    result%h = c_loc(result_array_h)

    ![x]
    result_array_f(1) = arg_array_c(1)
    result_array_f(2) = arg_array_c(2)

    ![x][y]
    result_array_g(1,1) = arg_array_d(1,1)
    result_array_g(1,2) = arg_array_d(1,2)
    result_array_g(1,3) = arg_array_d(1,3)
    result_array_g(2,1) = arg_array_d(2,1)
    result_array_g(2,2) = arg_array_d(2,2)
    result_array_g(2,3) = arg_array_d(2,3)

    ![x][y][z]
    result_array_h(1,1,1) = arg_array_e(1,1,1)
    result_array_h(1,1,2) = arg_array_e(1,1,2)
    result_array_h(1,1,3) = arg_array_e(1,1,3)
    result_array_h(1,2,1) = arg_array_e(1,2,1)
    result_array_h(1,2,2) = arg_array_e(1,2,2)
    result_array_h(1,2,3) = arg_array_e(1,2,3)

end

output:

 1D
   10.0000000000000
   20.0000000000000
 2D
   10.0000000000000
   20.0000000000000
   30.0000000000000
   40.0000000000000
   50.0000000000000
   60.0000000000000
 3D
   1.00000000000000
   2.00000000000000
   3.00000000000000
   4.00000000000000
   5.00000000000000
   6.00000000000000
1D
10.0
20.0
2D
10.0
20.0
30.0
40.0
50.0
60.0
3D
1.0
2.0
3.0
4.0
5.0
6.0


问:
Android: optimal way to find shortest distance between Point and Rect?
Seems like there should be some convenient way to do this?

I couldn't find one, so I threw together the below algorithm.  Is it memory/computationally optimal?

Thanks:

Edit: Original algorithm was stupidly wrong, maybe this is better?

```<code>public static float minDistance(RectF rect, PointF point)
{
    if(rect.contains(point.x, point.y))
    {
        //North line
        float distance = point.y - rect.top;

        //East line
        distance = Math.min(distance, point.x - rect.left);

        //South line
        distance = Math.min(distance, rect.bottom - point.y);

        //West line
        distance = Math.min(distance, rect.right - point.x);

        return distance;
    }
    else
    {
        float minX, minY;

        if (point.x < rect.left)
        {
            minX = rect.left;
        }
        else if (point.x > rect.right)
        {
            minX = rect.right;
        }
        else
        {
            minX = point.x;
        }

        if (point.y < rect.top)
        {
            minY = rect.top;
        }
        else if (point.y > rect.bottom)
        {
            minY = rect.bottom;
        }
        else
        {
            minY = point.y;
        }

        float vectorX = point.x - minX;
        float vectorY = point.y - minY;

        float distance = (float) Math.sqrt((vectorX * vectorX) + (vectorY * vectorY));

        return distance;
    }
}
</code>```

答:
One optimization is to not use the square root until the end. If you just compare distance squared and then return the sqrt of the smallest distance squared, you only have to do one sqrt.

Edit: Here is a good example of the distance from a point to a line segment (edge of the rect). You can use it, and modify it so that it returns the distance squared instead. Then compare them all and return the sqrt of the min distance squared.

Distance Between Point and Segment

ContentLicense: CC BY-SA 2.5

Body:
Seems like there should be some convenient way to do this?

I couldn't find one, so I threw together the below algorithm.  Is it memory/computationally optimal?

Thanks:

Edit: Original algorithm was stupidly wrong, maybe this is better?

public static float minDistance(RectF rect, PointF point)
{
    if(rect.contains(point.x, point.y))
    {
        //North line
        float distance = point.y - rect.top;

        //East line
        distance = Math.min(distance, point.x - rect.left);

        //South line
        distance = Math.min(distance, rect.bottom - point.y);

        //West line
        distance = Math.min(distance, rect.right - point.x);

        return distance;
    }
    else
    {
        float minX, minY;

        if (point.x < rect.left)
        {
            minX = rect.left;
        }
        else if (point.x > rect.right)
        {
            minX = rect.right;
        }
        else
        {
            minX = point.x;
        }

        if (point.y < rect.top)
        {
            minY = rect.top;
        }
        else if (point.y > rect.bottom)
        {
            minY = rect.bottom;
        }
        else
        {
            minY = point.y;
        }

        float vectorX = point.x - minX;
        float vectorY = point.y - minY;

        float distance = (float) Math.sqrt((vectorX * vectorX) + (vectorY * vectorY));

        return distance;
    }
}


问:
How we can handle Multiple Type UITableViewCell
I have multiple type cell to show in UITableView.

I have five type of cell in UITableView. all cell show according the different service response data, if service data nil or empty then we will not need to show the cell. so how i can check the number of row and show the cell according the service response.

答:
you can insert type in your array .. and in cellforRow function of tableView

```<code>if type == 1{
  // your first cell code
   }
else if type == 2
{
//your second cell
}
</code>```

and so - on...

Body:
you can insert type in your array .. and in cellforRow function of tableView

if type == 1{
  // your first cell code
   }
else if type == 2
{
//your second cell
}

and so - on...


问:
Parse a different kind of json object and list the data in recyclerview
I am a newbie to json parsing. I know how to parse a normal json object but I have no idea how to parse the kind of json I am listing below. Can someone help me on this?

I know how to parse this kind of json

```<code>[{"id":"1","image_title":"Android 1.5 Cupcake","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"2","image_title":"Android 1.6 Donut","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"3","image_title":"Android 2.0 Eclair","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"4","image_title":"Android 2.2 Froyo","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"5","image_title":"Android 2.3 GingerBread","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"6","image_title":"Android 3.0 HoneyComb","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"7","image_title":"Android 4.0 Ice Cream Sandwich","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"8","image_title":"Android 4.1 Jelly Bean","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"9","image_title":"Android 4.4 KitKat","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"}]
</code>```

But I have no Idea on how to parse this and append the values in recyclerview.

```<code>    {
    "id": {
        "0": "1",
        "5": "2",
        "6": "3",
        "10": "4",
        "12": "5"
    },
    "image_title": {
        "0": "Blue",
        "5": "Black",
        "6": "Yellow",
        "10": "Orange",
        "12": "Voilet"
    }
}
</code>```

My Full JSON Response

```<code>    {
  "Store EAN Number": {
    "0": null,
    "5": null,
    "6": null,
    "10": null,
    "12": null
  },
  "SKU Code": {
    "0": null,
    "5": null,
    "6": null,
    "10": null,
    "12": null
  },
  "Mihu EAN Number": {
    "0": 9999922000001,
    "5": 9999922000006,
    "6": 9999922000007,
    "10": 9999922000011,
    "12": 9999922000013
  },
  "Style Code": {
    "0": "Vico0001",
    "5": "Vico0006",
    "6": "Vico0007",
    "10": "Vico0011",
    "12": "Vico0013"
  },
  "Store": {
    "0": "Vision Colour",
    "5": "Vision Colour",
    "6": "Vision Colour",
    "10": "Vision Colour",
    "12": "Vision Colour"
  },
  "Store Code": {
    "0": 22,
    "5": 22,
    "6": 22,
    "10": 22,
    "12": 22
  },
  "Category": {
    "0": "Shirt",
    "5": "Shirt",
    "6": "Shirt",
    "10": "Shirt",
    "12": "Shirt"
  },
  "Gender": {
    "0": "Male",
    "5": "Male",
    "6": "Male",
    "10": "Male",
    "12": "Male"
  },
  "Sleeves Type": {
    "0": "Full Sleeve",
    "5": "Full Sleeve",
    "6": "Full Sleeve",
    "10": "Full Sleeve",
    "12": "Full Sleeve"
  },
  "Collection": {
    "0": "Casual",
    "5": "Casual",
    "6": "Casual",
    "10": "Casual",
    "12": "Casual"
  },
  "Fitting Type": {
    "0": "Slim",
    "5": "Slim",
    "6": "Slim",
    "10": "Slim",
    "12": "Slim"
  },
  " Size ": {
    "0": "M",
    "5": "M",
    "6": "M",
    "10": "M",
    "12": "M"
  },
  "Pocket Type": {
    "0": "No Pocket",
    "5": "V Shape",
    "6": "V Shape",
    "10": "V Shape",
    "12": "V Shape"
  },
  "Fabric Type": {
    "0": "100% cotton",
    "5": "100% cotton",
    "6": "100% cotton",
    "10": "100% cotton",
    "12": "100% cotton"
  },
  "Colour": {
    "0": "White",
    "5": "White",
    "6": "White",
    "10": "White",
    "12": "White"
  },
  "Fabric Design": {
    "0": "Printed",
    "5": "Printed",
    "6": "Printed",
    "10": "Printed",
    "12": "Printed"
  },
  "garment_description": {
    "0": null,
    "5": null,
    "6": null,
    "10": null,
    "12": null
  },
  "garment_name": {
    "0": "White Full Sleeve Printed Shirt",
    "5": "White Full Sleeve Printed Shirt",
    "6": "White Full Sleeve Printed Shirt",
    "10": "White Full Sleeve Printed Shirt",
    "12": "White Full Sleeve Printed Shirt"
  },
  "mrp_price": {
    "0": 450,
    "5": 450,
    "6": 450,
    "10": 450,
    "12": 450
  },
  "discount_price": {
    "0": null,
    "5": null,
    "6": null,
    "10": null,
    "12": null
  }

}
</code>```

答:
Parse like this:</p>

```<code>JsonObject jsonObj = new JsonObject(response);

JsonObject id_jsonObj = jsonObj.getJsonObject("id");

String first = id_jsonObj.getString("0");

String second = id_jsonObj.getString("5");

//and so on

JsonObject image_jsonObj = jsonObj.getJsonObject("image_title");

String title1 = image_jsonObj.getString("0");

String title2 = image_jsonObj.getString("5");

//and so on
</code>```

Body:
I am a newbie to json parsing. I know how to parse a normal json object but I have no idea how to parse the kind of json I am listing below. Can someone help me on this?

I know how to parse this kind of json

[{"id":"1","image_title":"Android 1.5 Cupcake","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"2","image_title":"Android 1.6 Donut","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"3","image_title":"Android 2.0 Eclair","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"4","image_title":"Android 2.2 Froyo","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"5","image_title":"Android 2.3 GingerBread","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"6","image_title":"Android 3.0 HoneyComb","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"7","image_title":"Android 4.0 Ice Cream Sandwich","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"8","image_title":"Android 4.1 Jelly Bean","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"},{"id":"9","image_title":"Android 4.4 KitKat","image_url":"https://firebasestorage.googleapis.com/v0/b/sukshichat.appspot.com/o/Wrangler%2FIMG_20171102_141451.jpg?alt=media&token=ce3f2747-a36f-416d-9dfc-ecfb6be4b447"}]

But I have no Idea on how to parse this and append the values in recyclerview.

    {
    "id": {
        "0": "1",
        "5": "2",
        "6": "3",
        "10": "4",
        "12": "5"
    },
    "image_title": {
        "0": "Blue",
        "5": "Black",
        "6": "Yellow",
        "10": "Orange",
        "12": "Voilet"
    }
}

My Full JSON Response

    {
  "Store EAN Number": {
    "0": null,
    "5": null,
    "6": null,
    "10": null,
    "12": null
  },
  "SKU Code": {
    "0": null,
    "5": null,
    "6": null,
    "10": null,
    "12": null
  },
  "Mihu EAN Number": {
    "0": 9999922000001,
    "5": 9999922000006,
    "6": 9999922000007,
    "10": 9999922000011,
    "12": 9999922000013
  },
  "Style Code": {
    "0": "Vico0001",
    "5": "Vico0006",
    "6": "Vico0007",
    "10": "Vico0011",
    "12": "Vico0013"
  },
  "Store": {
    "0": "Vision Colour",
    "5": "Vision Colour",
    "6": "Vision Colour",
    "10": "Vision Colour",
    "12": "Vision Colour"
  },
  "Store Code": {
    "0": 22,
    "5": 22,
    "6": 22,
    "10": 22,
    "12": 22
  },
  "Category": {
    "0": "Shirt",
    "5": "Shirt",
    "6": "Shirt",
    "10": "Shirt",
    "12": "Shirt"
  },
  "Gender": {
    "0": "Male",
    "5": "Male",
    "6": "Male",
    "10": "Male",
    "12": "Male"
  },
  "Sleeves Type": {
    "0": "Full Sleeve",
    "5": "Full Sleeve",
    "6": "Full Sleeve",
    "10": "Full Sleeve",
    "12": "Full Sleeve"
  },
  "Collection": {
    "0": "Casual",
    "5": "Casual",
    "6": "Casual",
    "10": "Casual",
    "12": "Casual"
  },
  "Fitting Type": {
    "0": "Slim",
    "5": "Slim",
    "6": "Slim",
    "10": "Slim",
    "12": "Slim"
  },
  " Size ": {
    "0": "M",
    "5": "M",
    "6": "M",
    "10": "M",
    "12": "M"
  },
  "Pocket Type": {
    "0": "No Pocket",
    "5": "V Shape",
    "6": "V Shape",
    "10": "V Shape",
    "12": "V Shape"
  },
  "Fabric Type": {
    "0": "100% cotton",
    "5": "100% cotton",
    "6": "100% cotton",
    "10": "100% cotton",
    "12": "100% cotton"
  },
  "Colour": {
    "0": "White",
    "5": "White",
    "6": "White",
    "10": "White",
    "12": "White"
  },
  "Fabric Design": {
    "0": "Printed",
    "5": "Printed",
    "6": "Printed",
    "10": "Printed",
    "12": "Printed"
  },
  "garment_description": {
    "0": null,
    "5": null,
    "6": null,
    "10": null,
    "12": null
  },
  "garment_name": {
    "0": "White Full Sleeve Printed Shirt",
    "5": "White Full Sleeve Printed Shirt",
    "6": "White Full Sleeve Printed Shirt",
    "10": "White Full Sleeve Printed Shirt",
    "12": "White Full Sleeve Printed Shirt"
  },
  "mrp_price": {
    "0": 450,
    "5": 450,
    "6": 450,
    "10": 450,
    "12": 450
  },
  "discount_price": {
    "0": null,
    "5": null,
    "6": null,
    "10": null,
    "12": null
  }

}

Body:
Parse like this:

JsonObject jsonObj = new JsonObject(response);

JsonObject id_jsonObj = jsonObj.getJsonObject("id");

String first = id_jsonObj.getString("0");

String second = id_jsonObj.getString("5");

//and so on

JsonObject image_jsonObj = jsonObj.getJsonObject("image_title");

String title1 = image_jsonObj.getString("0");

String title2 = image_jsonObj.getString("5");

//and so on


问:
Joomla and K2 Soft404 errors
We are using Joomla for a public site and we are getting a ton of soft 404 errors that all look similar to

```<code>/?option=com_k2&view=itemlist&task=user&id=xxx
</code>```

where xxx = some numeric id.  Obviously this is some soft of spamming but how do I turn it off in Joomla/K2?

I'm not particularly Joomla oriented but this seems a task I should be able to accomplish if I can get an idea of "where" to fix the code.  The page shows a warning instead of an error

Warning
  JUser: :_load: Unable to load user with ID: 35414

so it seems the "page" is actually there but with no content.  I'm guessing some internal handler is spitting this dynamic content out but I want to return 404 in this case.  Any ideas would be appreciated.

答:
I'm trying to understand the nature of your problem. What do you mean with "Soft 404" errors? Do you have 404 errors or not?

On my K2 websites, I have sometimes "visitors" who try to find holes in K2. I then have many, many accesses of the same page. These visitors try to post comments or somethings else on the articles or user profiles.

Is this a similar thing that is happening on your site?

Is there a (Joomla) user on your site with ID 35414? If not, you can be pretty sure that someone is trying to hack your site.

Is the URL always requested by the same user? You can find this in the log files of the Apache server. In such cases I add a "deny from" statement to my .htaccess file.

In case you seriously expect a K2 related issue, I would recommend to post the issue in the K2 forum. This forum is quite knowledgeable and JoomlaWorks makes a serious effort to bring good K2 customer support.

Title: Joomla and K2 Soft404 errors

Body:
We are using Joomla for a public site and we are getting a ton of soft 404 errors that all look similar to

/?option=com_k2&view=itemlist&task=user&id=xxx

where xxx = some numeric id.  Obviously this is some soft of spamming but how do I turn it off in Joomla/K2?

I'm not particularly Joomla oriented but this seems a task I should be able to accomplish if I can get an idea of "where" to fix the code.  The page shows a warning instead of an error

Warning
  JUser: :_load: Unable to load user with ID: 35414

so it seems the "page" is actually there but with no content.  I'm guessing some internal handler is spitting this dynamic content out but I want to return 404 in this case.  Any ideas would be appreciated.


问:
how to name mutation in apollo with optimistic response config?
this is my wrapped component:

```<code>export default compose(
    graphql(VOTE_MUTATION, {
        name: 'voteMutation',
        props: ({ ownProps, mutate }) => ({
          submit({ commentId, commentContent }) {
            return mutate({
              variables: { input },
              optimisticResponse: {
                __typename: 'Mutation',
                updateComment: {
                  id: input.activeNews.id,
                  __typename: 'News',
                  ...input.activeNews
                },
              }
            });
          },
        }),
      }),
    graphql(ALL_NEWS_QUERY, { name: 'allNewsQuery' })
)(withApollo(withRouter(NewsFeed)))
</code>```

however when i try to invoke the mutation, i have an error that states this.props.voteMutation is not a function? so i do not have an idea how to call specifically the name.

I have done a simple signup and login mutation like this that works fine:

```<code>export default compose(
    graphql(CREATE_USER_MUTATION, { name: 'createUserMutation' }),
    graphql(AUTHENTICATE_USER_MUTATION, { name: 'signinUserMutation' })
)(Login)
</code>```

I call it with this.props.createUserMutation(), however, calling this.props.voteMutation is not a function. Help?

答:
You're supposed to use voteMutation instead of mutate. Customizing the prop names kicks in before the mapping. Also, the correct way to destructure is { voteMutation, ...ownProps }, even so, you are not using ownProps anywhere

So, replace mutate with voteMutation in your snippet:

```<code>export default compose(
    graphql(VOTE_MUTATION, {
        name: 'voteMutation',
        props: ({ voteMutation }) => ({
          submit({ commentId, commentContent }) {
            return voteMutation({
              variables: { input },
              optimisticResponse: {
                __typename: 'Mutation',
                updateComment: {
                  id: input.activeNews.id,
                  __typename: 'News',
                  ...input.activeNews
                },
              }
            });
          },
        }),
      }),
    graphql(ALL_NEWS_QUERY, { name: 'allNewsQuery' })
)(withApollo(withRouter(NewsFeed)))
</code>```

Body:
this is my wrapped component:

export default compose(
    graphql(VOTE_MUTATION, {
        name: 'voteMutation',
        props: ({ ownProps, mutate }) => ({
          submit({ commentId, commentContent }) {
            return mutate({
              variables: { input },
              optimisticResponse: {
                __typename: 'Mutation',
                updateComment: {
                  id: input.activeNews.id,
                  __typename: 'News',
                  ...input.activeNews
                },
              }
            });
          },
        }),
      }),
    graphql(ALL_NEWS_QUERY, { name: 'allNewsQuery' })
)(withApollo(withRouter(NewsFeed)))

however when i try to invoke the mutation, i have an error that states this.props.voteMutation is not a function? so i do not have an idea how to call specifically the name.

I have done a simple signup and login mutation like this that works fine:

export default compose(
    graphql(CREATE_USER_MUTATION, { name: 'createUserMutation' }),
    graphql(AUTHENTICATE_USER_MUTATION, { name: 'signinUserMutation' })
)(Login)

I call it with this.props.createUserMutation(), however, calling this.props.voteMutation is not a function. Help?

Body:
You're supposed to use voteMutation instead of mutate. Customizing the prop names kicks in before the mapping. Also, the correct way to destructure is { voteMutation, ...ownProps }, even so, you are not using ownProps anywhere

So, replace mutate with voteMutation in your snippet:

export default compose(
    graphql(VOTE_MUTATION, {
        name: 'voteMutation',
        props: ({ voteMutation }) => ({
          submit({ commentId, commentContent }) {
            return voteMutation({
              variables: { input },
              optimisticResponse: {
                __typename: 'Mutation',
                updateComment: {
                  id: input.activeNews.id,
                  __typename: 'News',
                  ...input.activeNews
                },
              }
            });
          },
        }),
      }),
    graphql(ALL_NEWS_QUERY, { name: 'allNewsQuery' })
)(withApollo(withRouter(NewsFeed)))


问:
how to make trial version of win and web application in .Net technology
how to develop a trial version of window or web application in dotnet technology. as a result user can use that windows or web apps for certain day and also will not be able to use after resetting his system clock.how could make this type of trial version both in window and web.
please give me the concept in detail.

thanks

答:
It all depends on how critical your software is. In order to make a trial version of a web app, you could incorporate the following mechanisms.

Obfuscate assemblies - This
prevents users from
decompiling\reverse engineering your
code and looking into how the trial
version logic is implemented.

Release different versions -Maintain two different versions of the product i.e. Full version and a demo version, by using compiler directives. This prevents the trial version from being cracked.

Limit features - Say if its a payroll application, limit the number of users, say something between 10 or 20. Suppose if its a BI app, then embed watermarks on generated graphs and reports. Next what you could limit the number of logins per day or put restriction on major features from being used more than a specific number of times per day.

Configuration Storage - Store trial version counter related data in a encrypted file and keep the hash of that file separately. Each time after writing to the file update the hash and also verify the hash before reading from the file. Also make sure the trial version configuration file's creation date is same as that of any other program file, so as to prevent it from being replaced with a new one, so as to reset the counters.

Here are couple of links from SO on this same query.

Implementing a 30 day time trial

https://stackoverflow.com/questions/981294/copy-protection-tool-to-limit-number-of-units/2025926#2025926