问:
Preparing feeding data to 1D CNN
I am getting into a similar problem with reshaping data for 1-D CNN:

I am loading data (training and testing data sets ) from a csv file with 24,325 lines. Each line is a vector of 256 numbers - independent variables plus 11 numbers of expected outcome ( labels ) [0,0,0,0,1,0,0,0,0,0,0]

I am using TensorFlow backend.

The code looks like that:

```<code>    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np

   #Importing training set
   training_set = pd.read_csv("Data30.csv")
   X_train = training_set.iloc[:20000, 3 :-11].values
   y_train = training_set.iloc[:20000, -11:-1].values

   #Importing test set
   test_set = pd.read_csv("Data30.csv")
   X_test = training_set.iloc[ 20001:, 3 :-11].values
   y_test = training_set.iloc[ 20001:, -11:].values

    X_train /= np.max(X_train) # Normalise data to [0, 1] range
    X_test /= np.max(X_test) # Normalise data to [0, 1] range

    print("X_train.shape[0] = " + str(X_train.shape[0]))
    print("X_train.shape[1] = " + str(X_train.shape[1]))
    print("y_train.shape[0] = " + str(y_train.shape[0]))
    print("y_train.shape[1] = " + str(y_train.shape[1]))
    print("X_test.shape[0] = " + str(X_test.shape[0]))
    print("X_test.shape[1] = " + str(X_test.shape[1]))
</code>```

This is what I get:

X_train.shape[0] = 20000

X_train.shape1 = 256

y_train.shape[0] = 20000

y_train.shape1 = 11

X_test.shape[0] = 4325

X_test.shape1 = 256

```<code> #Convert data into 3d tensor
# Old Version
# X_train = np.reshape(X_train,(1,X_train.shape[0],X_train.shape[1]))
# X_test = np.reshape(X_test,(1,X_test.shape[0],X_test.shape[1]))

**# New Correct Version based on the Answer:**
X_train = np.reshape(X_train,( X_train.shape[0],X_train.shape[1], 1 ))
X_test = np.reshape(X_test,( X_test.shape[0],X_test.shape[1], 1 ))

print("X_train.shape[0] = " + str(X_train.shape[0]))
print("X_train.shape[1] = " + str(X_train.shape[1]))
print("X_test.shape[0] = " + str(X_test.shape[0]))
print("X_test.shape[1] = " + str(X_test.shape[1]))
</code>```

This is result of the reshaping:

X_train.shape[0] = 1

X_train.shape1 = 20000

X_test.shape[0] = 1

X_test.shape1 = 4325

```<code>   #Importing convolutional layers
   from keras.models import Sequential
   from keras.layers import Convolution1D
   from keras.layers import MaxPooling1D
   from keras.layers import Flatten
   from keras.layers import Dense
   from keras.layers import Dropout
   from keras.layers.normalization import BatchNormalization

#Initialising the CNN
classifier = Sequential()

#1.Multiple convolution and max pooling
classifier.add(Convolution1D(filters=8, kernel_size=11, activation="relu", input_shape=( 256, 1 )))
classifier.add(MaxPooling1D(strides=4))
classifier.add(BatchNormalization())
classifier.add(Convolution1D(filters=16, kernel_size=11, activation='relu'))
classifier.add(MaxPooling1D(strides=4))
classifier.add(BatchNormalization())
classifier.add(Convolution1D(filters=32, kernel_size=11, activation='relu'))
classifier.add(MaxPooling1D(strides=4))
classifier.add(BatchNormalization())
#classifier.add(Convolution1D(filters=64, kernel_size=11,activation='relu'))
    #classifier.add(MaxPooling1D(strides=4))

#2.Flattening
classifier.add(Flatten())

#3.Full Connection
classifier.add(Dropout(0.5))
classifier.add(Dense(64, activation='relu'))
classifier.add(Dropout(0.25))
classifier.add(Dense(64, activation='relu'))
classifier.add(Dense(1, activation='sigmoid'))

#Configure the learning process
classifier.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])

#Train!
classifier.fit_generator(training_set,
                     steps_per_epoch= 100,
                     nb_epoch = 200,
                     validation_data = (X_test,y_test),
                     validation_steps = 40)

score = classifier.evaluate(X_test, y_test)
</code>```

This is the error I get:

Traceback (most recent call last):

File "C:/Conda/ML_Folder/CNN Data30.py", line 85, in
    classifier.fit_generator(X_train, steps_per_epoch=10, epochs=10, validation_data=(X_test,y_test))

File "C:\Conda\lib\site-packages\keras\legacy\interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)

File "C:\Conda\lib\site-packages\keras\models.py", line 1121, in fit_generator
    initial_epoch=initial_epoch)

File "C:\Conda\lib\site-packages\keras\legacy\interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)

File "C:\Conda\lib\site-packages\keras\engine\training.py", line 1978, in fit_generator
    val_x, val_y, val_sample_weight)

File "C:\Conda\lib\site-packages\keras\engine\training.py", line 1378, in _standardize_user_data
    exception_prefix='input')

File "C:\Conda\lib\site-packages\keras\engine\training.py", line 144, in _standardize_input_data
    str(array.shape))

ValueError: Error when checking input: expected conv1d_1_input to have shape (None, 256, 1) but got array with shape (1, 4325, 256)

Can you please help me to fix the code?

答:
Shapes should be (batchSize, length, channels)

So: (20000,256,1) and (20000,11)

Detail: your last Dense must output 11, so: Dense(11,...)

Title: Preparing feeding data to 1D CNN

Body:
I am getting into a similar problem with reshaping data for 1-D CNN:

I am loading data (training and testing data sets ) from a csv file with 24,325 lines. Each line is a vector of 256 numbers - independent variables plus 11 numbers of expected outcome ( labels ) [0,0,0,0,1,0,0,0,0,0,0]

I am using TensorFlow backend.

The code looks like that:

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np

   #Importing training set
   training_set = pd.read_csv("Data30.csv")
   X_train = training_set.iloc[:20000, 3 :-11].values
   y_train = training_set.iloc[:20000, -11:-1].values

   #Importing test set
   test_set = pd.read_csv("Data30.csv")
   X_test = training_set.iloc[ 20001:, 3 :-11].values
   y_test = training_set.iloc[ 20001:, -11:].values

    X_train /= np.max(X_train) # Normalise data to [0, 1] range
    X_test /= np.max(X_test) # Normalise data to [0, 1] range

    print("X_train.shape[0] = " + str(X_train.shape[0]))
    print("X_train.shape[1] = " + str(X_train.shape[1]))
    print("y_train.shape[0] = " + str(y_train.shape[0]))
    print("y_train.shape[1] = " + str(y_train.shape[1]))
    print("X_test.shape[0] = " + str(X_test.shape[0]))
    print("X_test.shape[1] = " + str(X_test.shape[1]))

This is what I get:

X_train.shape[0] = 20000

X_train.shape1 = 256

y_train.shape[0] = 20000

y_train.shape1 = 11

X_test.shape[0] = 4325

X_test.shape1 = 256

 #Convert data into 3d tensor
# Old Version
# X_train = np.reshape(X_train,(1,X_train.shape[0],X_train.shape[1]))
# X_test = np.reshape(X_test,(1,X_test.shape[0],X_test.shape[1]))

**# New Correct Version based on the Answer:**
X_train = np.reshape(X_train,( X_train.shape[0],X_train.shape[1], 1 ))
X_test = np.reshape(X_test,( X_test.shape[0],X_test.shape[1], 1 ))

print("X_train.shape[0] = " + str(X_train.shape[0]))
print("X_train.shape[1] = " + str(X_train.shape[1]))
print("X_test.shape[0] = " + str(X_test.shape[0]))
print("X_test.shape[1] = " + str(X_test.shape[1]))

This is result of the reshaping:

X_train.shape[0] = 1

X_train.shape1 = 20000

X_test.shape[0] = 1

X_test.shape1 = 4325

   #Importing convolutional layers
   from keras.models import Sequential
   from keras.layers import Convolution1D
   from keras.layers import MaxPooling1D
   from keras.layers import Flatten
   from keras.layers import Dense
   from keras.layers import Dropout
   from keras.layers.normalization import BatchNormalization

#Initialising the CNN
classifier = Sequential()

#1.Multiple convolution and max pooling
classifier.add(Convolution1D(filters=8, kernel_size=11, activation="relu", input_shape=( 256, 1 )))
classifier.add(MaxPooling1D(strides=4))
classifier.add(BatchNormalization())
classifier.add(Convolution1D(filters=16, kernel_size=11, activation='relu'))
classifier.add(MaxPooling1D(strides=4))
classifier.add(BatchNormalization())
classifier.add(Convolution1D(filters=32, kernel_size=11, activation='relu'))
classifier.add(MaxPooling1D(strides=4))
classifier.add(BatchNormalization())
#classifier.add(Convolution1D(filters=64, kernel_size=11,activation='relu'))
    #classifier.add(MaxPooling1D(strides=4))

#2.Flattening
classifier.add(Flatten())

#3.Full Connection
classifier.add(Dropout(0.5))
classifier.add(Dense(64, activation='relu'))
classifier.add(Dropout(0.25))
classifier.add(Dense(64, activation='relu'))
classifier.add(Dense(1, activation='sigmoid'))

#Configure the learning process
classifier.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])

#Train!
classifier.fit_generator(training_set,
                     steps_per_epoch= 100,
                     nb_epoch = 200,
                     validation_data = (X_test,y_test),
                     validation_steps = 40)

score = classifier.evaluate(X_test, y_test)

This is the error I get:

Traceback (most recent call last):

File "C:/Conda/ML_Folder/CNN Data30.py", line 85, in
    classifier.fit_generator(X_train, steps_per_epoch=10, epochs=10, validation_data=(X_test,y_test))

File "C:\Conda\lib\site-packages\keras\legacy\interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)

File "C:\Conda\lib\site-packages\keras\models.py", line 1121, in fit_generator
    initial_epoch=initial_epoch)

File "C:\Conda\lib\site-packages\keras\legacy\interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)

File "C:\Conda\lib\site-packages\keras\engine\training.py", line 1978, in fit_generator
    val_x, val_y, val_sample_weight)

File "C:\Conda\lib\site-packages\keras\engine\training.py", line 1378, in _standardize_user_data
    exception_prefix='input')

File "C:\Conda\lib\site-packages\keras\engine\training.py", line 144, in _standardize_input_data
    str(array.shape))

ValueError: Error when checking input: expected conv1d_1_input to have shape (None, 256, 1) but got array with shape (1, 4325, 256)

Can you please help me to fix the code?


来源: stackexchange

问:
Fortran derived datatype used before defined
How to include the derived datatype (the type, not variable) between modules with use module, ONLY: statement?

More description: In my module1 I defined a derived datatype (let's call it my_datatype) and some data (let's call it my_data) of this datatype. In my module2 I need to use my_data. Since my module1 contains many procedures that module2 does not need, I want to use the ONLY statement to only include my_data. However, without including the datatype it will give me the error:

```<code>Derive datatype 'my_type' is used before defined at "type(my_type),intent(out)::A"
</code>```

It is obvious that module2 does not recognize my_datatype defined in module1 because I did not pass it. But what is the syntax to include a derived type in 'use module, only' statement? I am using Fortran 2003.

```<code>  module step1
  implicit none
     type my_type
        integer::id
        integer,dimension(2)::my_data
     end type my_type

     type(my_type)::A
  end module step1

  module step2
  use step1,only:A
  implicit none
  contains
     subroutine change_A(A)
        type(my_type),intent(inout)::A
        A%id = 1
        A%my_data(1) = 1
        A%my_data(2) = 2
     end subroutine change_A
  end module step2

  program test
  ! program is in a different folder
  use step1
  use step2
     implicit none
     call change_A(A)
  end program test
</code>```

答:
Given your updated question, here is how to implement the fix suggested by others:

(EDIT: implementing suggestions from the comments:

Only import the type from module step1 in module step2.

Only import A from step1 and change_A from step2 in the main program.

Do take note that the dummy argument "A" in the routine "change_A" bears no relation to the "A" from module step1 in the definition in the routine. I change the name of the dummy to illustrate this point.

)

```<code>module step1
  implicit none
  type my_type
     integer::id
     integer,dimension(2)::my_data
  end type my_type

  type(my_type)::A

end module step1

module step2
  use step1, only: my_type
  implicit none
contains
  subroutine change_A(dummy)
    type(my_type),intent(inout) :: dummy
    dummy%id = 1
    dummy%my_data(1) = 1
    dummy%my_data(2) = 2
  end subroutine change_A
end module step2

program test
  ! program is in a different folder
  use step1, only: A
  use step2, only: change_A
  implicit none

  call change_A(A)
  write(*,*) A

end program test
</code>```

I have added my_type to the 'use' statement.

ContentLicense: CC BY-SA 3.0

Body:
How to include the derived datatype (the type, not variable) between modules with use module, ONLY: statement?

More description: In my module1 I defined a derived datatype (let's call it my_datatype) and some data (let's call it my_data) of this datatype. In my module2 I need to use my_data. Since my module1 contains many procedures that module2 does not need, I want to use the ONLY statement to only include my_data. However, without including the datatype it will give me the error:

Derive datatype 'my_type' is used before defined at "type(my_type),intent(out)::A"

It is obvious that module2 does not recognize my_datatype defined in module1 because I did not pass it. But what is the syntax to include a derived type in 'use module, only' statement? I am using Fortran 2003.

  module step1
  implicit none
     type my_type
        integer::id
        integer,dimension(2)::my_data
     end type my_type

     type(my_type)::A
  end module step1

  module step2
  use step1,only:A
  implicit none
  contains
     subroutine change_A(A)
        type(my_type),intent(inout)::A
        A%id = 1
        A%my_data(1) = 1
        A%my_data(2) = 2
     end subroutine change_A
  end module step2

  program test
  ! program is in a different folder
  use step1
  use step2
     implicit none
     call change_A(A)
  end program test

Body:
Given your updated question, here is how to implement the fix suggested by others:

(EDIT: implementing suggestions from the comments:

Only import the type from module step1 in module step2.

Only import A from step1 and change_A from step2 in the main program.

Do take note that the dummy argument "A" in the routine "change_A" bears no relation to the "A" from module step1 in the definition in the routine. I change the name of the dummy to illustrate this point.

)

module step1
  implicit none
  type my_type
     integer::id
     integer,dimension(2)::my_data
  end type my_type

  type(my_type)::A

end module step1

module step2
  use step1, only: my_type
  implicit none
contains
  subroutine change_A(dummy)
    type(my_type),intent(inout) :: dummy
    dummy%id = 1
    dummy%my_data(1) = 1
    dummy%my_data(2) = 2
  end subroutine change_A
end module step2

program test
  ! program is in a different folder
  use step1, only: A
  use step2, only: change_A
  implicit none

  call change_A(A)
  write(*,*) A

end program test

I have added my_type to the 'use' statement.


问:
How to increase the value of a fraction in a loop with Python
Im was trying to do a loop, increasing the numerator by 1 each iteration, but I got this error:

ZeroDivisionError: Fraction(1, 0)

My code is something like this:

```<code>from fractions import Fraction
x = Fraction(0,48)
z = x.numerator
limit = (48,48)
while x == limit:
    print("cycle " + str(z))
    x += Fraction(1,0)
print("loop finished!")
</code>```

答:
it looks like you increment x from zero to one, in steps of 1/48

try this

```<code>from fractions import Fraction
m_denominator = 48
x = Fraction(0,m_denominator)
z = 0
limit = Fraction(m_denominator,m_denominator)    #notice limit is now a Fraction object
while x <= limit: #notice, i changed this
    print("cycle " + str(z))
    z = z+1
    x += Fraction(1,m_denominator)
print("loop finished!")
</code>```

Body:
Im was trying to do a loop, increasing the numerator by 1 each iteration, but I got this error:

ZeroDivisionError: Fraction(1, 0)

My code is something like this:

from fractions import Fraction
x = Fraction(0,48)
z = x.numerator
limit = (48,48)
while x == limit:
    print("cycle " + str(z))
    x += Fraction(1,0)
print("loop finished!")

Body:
it looks like you increment x from zero to one, in steps of 1/48

try this

from fractions import Fraction
m_denominator = 48
x = Fraction(0,m_denominator)
z = 0
limit = Fraction(m_denominator,m_denominator)    #notice limit is now a Fraction object
while x <= limit: #notice, i changed this
    print("cycle " + str(z))
    z = z+1
    x += Fraction(1,m_denominator)
print("loop finished!")


问:
How to call a models database query in a javascript function in a view?
On my user inbox from my user messaging system I am building a feature where a user can make an email message a favourite message.

I have created 2 methods in my messages model. One updates the 0 in the 'messages' table, 'favourite' column to 1 which would mean the user wants the message to be a favourite. Also the image the user clicks on to make the message a favourite turns from grey to colour.

Then I do this same process again if a user wants to make the message not a favourite. The 1 is updated to a 0 and the image turns greyed out again.

Below is my jquery/javascript that basically does something if the box is checked  (image is in colour) and something else if the box is not unchecked (image greyed out).

```<code>// favourite check box
    $('input.favourite:checkbox').simpleImageCheck({
  image: '<?php echo base_url()?>images/messages/check.png',
  imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
  afterCheck: function(isChecked) {
    if (isChecked) {
  //query to db from php to update favourite number to 1
    }
    else (!isChecked)
        {
            //query to db from php to update favourite number to 0
        }
  }
});
</code>```

What I am trying to figure out is the best way to called my 2 db queries in my model:

```<code>public function favourite_checked($message_id)
{
    $username = $this->session->userdata('username');
    return $this->db->query("UPDATE messages SET favourite = 1 WHERE id = $message_id AND to_user = '$username'");
}

    public function favourite_unchecked($message_id)
{
    $username = $this->session->userdata('username');
    return $this->db->query("UPDATE messages SET favourite = 0 WHERE id = $message_id AND to_user = '$username'");
}
</code>```

What would be the best way to do this? Calling a model directly in a view is bad practice isn't it?

So how could I achieve what I would like to achieve?

Could a controller act as a middle man?

If so how would I even call a controller in a javascript function?

I always appreciate the advice given on here. Thanks in advance

答:
In the jQuery, you would use an Ajax get request to a CodeIgniter controller.  Say your controller is called users, and your function is called update_favorites.  The jQuery call might look like this:

```<code>$.get('http://mysite.com/users/update_favorites/user_id/message_id');
</code>```

Your controller would then find the URL arguments for user_id and message_id, and load your model with those arguments.  The model would make changes to the database.

Good luck!

ContentLicense: CC BY-SA 2.5

Body:
On my user inbox from my user messaging system I am building a feature where a user can make an email message a favourite message.

I have created 2 methods in my messages model. One updates the 0 in the 'messages' table, 'favourite' column to 1 which would mean the user wants the message to be a favourite. Also the image the user clicks on to make the message a favourite turns from grey to colour.

Then I do this same process again if a user wants to make the message not a favourite. The 1 is updated to a 0 and the image turns greyed out again.

Below is my jquery/javascript that basically does something if the box is checked  (image is in colour) and something else if the box is not unchecked (image greyed out).

// favourite check box
    $('input.favourite:checkbox').simpleImageCheck({
  image: '<?php echo base_url()?>images/messages/check.png',
  imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
  afterCheck: function(isChecked) {
    if (isChecked) {
  //query to db from php to update favourite number to 1
    }
    else (!isChecked)
        {
            //query to db from php to update favourite number to 0
        }
  }
});

What I am trying to figure out is the best way to called my 2 db queries in my model:

public function favourite_checked($message_id)
{
    $username = $this->session->userdata('username');
    return $this->db->query("UPDATE messages SET favourite = 1 WHERE id = $message_id AND to_user = '$username'");
}

    public function favourite_unchecked($message_id)
{
    $username = $this->session->userdata('username');
    return $this->db->query("UPDATE messages SET favourite = 0 WHERE id = $message_id AND to_user = '$username'");
}

What would be the best way to do this? Calling a model directly in a view is bad practice isn't it?

So how could I achieve what I would like to achieve?

Could a controller act as a middle man?

If so how would I even call a controller in a javascript function?

I always appreciate the advice given on here. Thanks in advance

Body:
In the jQuery, you would use an Ajax get request to a CodeIgniter controller.  Say your controller is called users, and your function is called update_favorites.  The jQuery call might look like this:

$.get('http://mysite.com/users/update_favorites/user_id/message_id');

Your controller would then find the URL arguments for user_id and message_id, and load your model with those arguments.  The model would make changes to the database.

Good luck!


问:
UIViewController controller not recognizing delegate
my first time creating a UIControlerView and it seems that the delegates are never activated. Please tell me where I am going wrong.

Thank you!
By the way I created the IBOutlet by dragging from the storyboard...

.h

```<code>#import <UIKit/UIKit.h>

@interface CollectionController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UICollectionView *controllerTableView;

@end
</code>```

.m

```<code>#import "CollectionController.h"
#import "CollectionVIewCell.h"

@interface CollectionController ()

@end

@implementation CollectionController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[self controllerTableView]setDelegate:self];
    [[self controllerTableView]setDataSource:self];
    // Do any additional setup after loading the view.
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellIdentifier=@"Cell";
    CollectionVIewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    cell.labelDisplay.text=@"hi";
    //set up data in images

    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

答: check this inherit module is selected or not

Body:
my first time creating a UIControlerView and it seems that the delegates are never activated. Please tell me where I am going wrong.

Thank you!
By the way I created the IBOutlet by dragging from the storyboard...

.h

#import <UIKit/UIKit.h>

@interface CollectionController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UICollectionView *controllerTableView;

@end

.m

#import "CollectionController.h"
#import "CollectionVIewCell.h"

@interface CollectionController ()

@end

@implementation CollectionController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[self controllerTableView]setDelegate:self];
    [[self controllerTableView]setDataSource:self];
    // Do any additional setup after loading the view.
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellIdentifier=@"Cell";
    CollectionVIewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    cell.labelDisplay.text=@"hi";
    //set up data in images

    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


问:
Plugin execution not covered by lifecycle configuration: org.jetbrains.kotlin:kotlin-maven-plugin:1.1.51:test-compile
I cloned the spring-boot Git repository into Eclipse and I get the following error. I have not made any code changes.

```<code>Plugin execution not covered by lifecycle configuration:
org.jetbrains.kotlin:kotlin-maven-plugin:1.1.51:test-compile (execution:
test-compile, phase: test-compile)
</code>```

When I attempt to "auto-fix" the error I see this:

```<code>No marketplace entries found to handle kotlin-maven-plugin:1.1.51:test-
compile in Eclipse.  Please see Help for more information.
</code>```

Here's my POM:

```<code><plugin>
  <groupId>org.jetbrains.kotlin</groupId>
  <artifactId>kotlin-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>compile</id>
      <phase>compile</phase>
      <goals>
        <goal>compile</goal>
      </goals>
      <configuration>
        <sourceDirs>
          <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
          <sourceDir>${project.basedir}/src/main/java</sourceDir>
        </sourceDirs>
      </configuration>
    </execution>
    <execution>
      <id>test-compile</id>
      <phase>test-compile</phase>
      <goals>
        <goal>test-compile</goal>
      </goals>
      <configuration>
        <sourceDirs>
          <sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
          <sourceDir>${project.basedir}/src/test/java</sourceDir>
        </sourceDirs>
      </configuration>
    </execution>
  </executions>
</plugin>
</code>```

Error In Eclipse

答:
Try

```<code>Quick Fix -> Mark goal compile as ignore in pom.xml
</code>```

Choose both phases: compile & test-compile if coming from Markers list. In popup window quick fix shows only two rows with title pom.xml with line numbers respectively, check both.

It will create you block starting:

```<code>   <pluginManagement>
      <plugins>
         <!--This plugin's configuration is used to store Eclipse m2e settings only.
             It has no influence on the Maven build itself.-->
      ...
</code>```

And just to stress read the comment in block: it does not affect the maven build

In case quick fix fails below is the whole plugin management section I managed to generate.

```<code><pluginManagement>
   <plugins>
      <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
      <plugin>
         <groupId>org.eclipse.m2e</groupId>
         <artifactId>lifecycle-mapping</artifactId>
         <version>1.0.0</version>
         <configuration>
            <lifecycleMappingMetadata>
               <pluginExecutions>
                  <pluginExecution>
                     <pluginExecutionFilter>
                        <groupId>org.jetbrains.kotlin</groupId>
                        <artifactId>kotlin-maven-plugin</artifactId>
                        <versionRange>[1.1.60,)</versionRange>
                        <goals>
                           <goal>compile</goal>
                           <goal>test-compile</goal>
                        </goals>
                     </pluginExecutionFilter>
                     <action>
                        <ignore></ignore>
                     </action>
                  </pluginExecution>
               </pluginExecutions>
            </lifecycleMappingMetadata>
         </configuration>
      </plugin>
   </plugins>
</pluginManagement>
</code>```

Body:
I cloned the spring-boot Git repository into Eclipse and I get the following error. I have not made any code changes.

Plugin execution not covered by lifecycle configuration:
org.jetbrains.kotlin:kotlin-maven-plugin:1.1.51:test-compile (execution:
test-compile, phase: test-compile)

When I attempt to "auto-fix" the error I see this:

No marketplace entries found to handle kotlin-maven-plugin:1.1.51:test-
compile in Eclipse.  Please see Help for more information.

Here's my POM:

<plugin>
  <groupId>org.jetbrains.kotlin</groupId>
  <artifactId>kotlin-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>compile</id>
      <phase>compile</phase>
      <goals>
        <goal>compile</goal>
      </goals>
      <configuration>
        <sourceDirs>
          <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
          <sourceDir>${project.basedir}/src/main/java</sourceDir>
        </sourceDirs>
      </configuration>
    </execution>
    <execution>
      <id>test-compile</id>
      <phase>test-compile</phase>
      <goals>
        <goal>test-compile</goal>
      </goals>
      <configuration>
        <sourceDirs>
          <sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
          <sourceDir>${project.basedir}/src/test/java</sourceDir>
        </sourceDirs>
      </configuration>
    </execution>
  </executions>
</plugin>

Error In Eclipse

Body:
Try

Quick Fix -> Mark goal compile as ignore in pom.xml

Choose both phases: compile & test-compile if coming from Markers list. In popup window quick fix shows only two rows with title pom.xml with line numbers respectively, check both.

It will create you block starting:

   <pluginManagement>
      <plugins>
         <!--This plugin's configuration is used to store Eclipse m2e settings only.
             It has no influence on the Maven build itself.-->
      ...

And just to stress read the comment in block: it does not affect the maven build

In case quick fix fails below is the whole plugin management section I managed to generate.

<pluginManagement>
   <plugins>
      <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
      <plugin>
         <groupId>org.eclipse.m2e</groupId>
         <artifactId>lifecycle-mapping</artifactId>
         <version>1.0.0</version>
         <configuration>
            <lifecycleMappingMetadata>
               <pluginExecutions>
                  <pluginExecution>
                     <pluginExecutionFilter>
                        <groupId>org.jetbrains.kotlin</groupId>
                        <artifactId>kotlin-maven-plugin</artifactId>
                        <versionRange>[1.1.60,)</versionRange>
                        <goals>
                           <goal>compile</goal>
                           <goal>test-compile</goal>
                        </goals>
                     </pluginExecutionFilter>
                     <action>
                        <ignore></ignore>
                     </action>
                  </pluginExecution>
               </pluginExecutions>
            </lifecycleMappingMetadata>
         </configuration>
      </plugin>
   </plugins>
</pluginManagement>


问:
Keyword matching involving integers without leading zeros using sed and awk
Assume a multi-line textfile (file1) that contains one keyword per line, where each keyword has the format StringInteger. The order of the lines is fixed.

```<code>$cat file1
foo1
foo2
foo4
foo10
</code>```

Assume further a multi-line textfile (file2) whose lines contain several whitespace-delimited words, one of which may be one of the above-mentioned keywords. Every line can only contain one keyword, and the keyword may be located anywhere within the line, except as the last word. If a keyword exists in the line, then the term baz=() also exists in the line. The order of the lines is not fixed.

```<code>$cat file2
foo1 bar baz=()
bar foo4 baz=()
foo10 qux baz=()
foo2 baz=()
</code>```

If a line in file2 contains keyword n, I want to add the line number that keyword n has in file1 in the term baz=().

```<code>$sought_commands file1 file2
foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(4)
foo2 baz=(2)
</code>```

I came up with the following code, which has the flaw that keyword foo1 masks the term baz=() for keyword foo10:

```<code>for kw in $(cat file1); do
    lineNumbr=$(cat file1 | awk '/'$kw'/{print NR; exit}')
    sed -i "/$kw/ s/baz\=()/baz\=($lineNumbr)/" file2
done
</code>```

.

```<code>$cat file2
foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(1) # ERROR!
foo2 baz=(2)
</code>```

Edit 1: I considered using the circumstance that the keywords are always followed by a whitespace in file2 as a delimiter, but then the awk-command fails:

```<code>for kw in $(cat file1); do
    kw_adj="$kw "
    lineNumbr=$(cat file1 | awk '/'$kw_adj'/{print NR; exit}')
    sed -i "/$kw_adj/ s/baz\=()/baz\=($lineNumbr)/" file2
done

awk: cmd. line:1: /foo1
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo2
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo4
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo10
awk: cmd. line:1:  ^ unterminated regexp
</code>```

答:
awk to the rescue!

```<code>$ awk 'NR==FNR {a[$1]=NR; next}
   /baz=\(\)$/ {for(i=1;i<NF;i++)
                  if($i in a) sub(/\(\)$/,"(" a[$i] ")")}1' file{1,2}

foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(4)
foo2 baz=(2)
</code>```

Body:
Assume a multi-line textfile (file1) that contains one keyword per line, where each keyword has the format StringInteger. The order of the lines is fixed.

$cat file1
foo1
foo2
foo4
foo10

Assume further a multi-line textfile (file2) whose lines contain several whitespace-delimited words, one of which may be one of the above-mentioned keywords. Every line can only contain one keyword, and the keyword may be located anywhere within the line, except as the last word. If a keyword exists in the line, then the term baz=() also exists in the line. The order of the lines is not fixed.

$cat file2
foo1 bar baz=()
bar foo4 baz=()
foo10 qux baz=()
foo2 baz=()

If a line in file2 contains keyword n, I want to add the line number that keyword n has in file1 in the term baz=().

$sought_commands file1 file2
foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(4)
foo2 baz=(2)

I came up with the following code, which has the flaw that keyword foo1 masks the term baz=() for keyword foo10:

for kw in $(cat file1); do
    lineNumbr=$(cat file1 | awk '/'$kw'/{print NR; exit}')
    sed -i "/$kw/ s/baz\=()/baz\=($lineNumbr)/" file2
done

.

$cat file2
foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(1) # ERROR!
foo2 baz=(2)

Edit 1: I considered using the circumstance that the keywords are always followed by a whitespace in file2 as a delimiter, but then the awk-command fails:

for kw in $(cat file1); do
    kw_adj="$kw "
    lineNumbr=$(cat file1 | awk '/'$kw_adj'/{print NR; exit}')
    sed -i "/$kw_adj/ s/baz\=()/baz\=($lineNumbr)/" file2
done

awk: cmd. line:1: /foo1
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo2
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo4
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo10
awk: cmd. line:1:  ^ unterminated regexp

Body:
awk to the rescue!

$ awk 'NR==FNR {a[$1]=NR; next}
   /baz=\(\)$/ {for(i=1;i<NF;i++)
                  if($i in a) sub(/\(\)$/,"(" a[$i] ")")}1' file{1,2}

foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(4)
foo2 baz=(2)


问:
How to include one header for every page in different folders
How can I use one header.php file for every html page in different folders?

For example:

My header.php file is in homepage/includes folder.

And i include like this include "includes/header.php";

up to now, everything is okay.

And i have a diffent folder on my homepage called "users"

And i wanna include my header.php file, which is on homepage/includes folder, on homepage/users/index.php file.

And i include like this "include "../includes/header.php", but I have errors.

Cause on my header.php file I call my css files like <link href="assets/css/demo.css"/>

So I need to copy my header.php file to users folder.

And I need to change href="assets/...." like href="../assets/...."

Isn't there any way to solve it?? Thank you.

答:
The problem you are facing is relative vs absolute paths.

When using require_once you can use a constant defined in your index.php or inside a config.php or setup.php depending on your application. It would look something like:

```<code>require_once APP_PATH . 'includes/header.php';
</code>```

In your case APP_PATH could be defined as the full path before the include, ie. define('APP_PATH', dirname(__FILE__) . '/'); or if you want to hardcode it define('APP_PATH', '/home/www/my-app/');

You can use the absolute path to your css files for the assets to work,

```<code><link href="/assets/css/demo.css"/>
</code>```

OR for better portability you can create a little function to wrap all style calls:

```<code><link href="<?php echo css_asset('demo.css'); ?>"/>

// Then the possible definition of css could be
function css_asset($style)
{
    return '/assets/css/' . $style;
}
</code>```

Body:
The problem you are facing is relative vs absolute paths.

When using require_once you can use a constant defined in your index.php or inside a config.php or setup.php depending on your application. It would look something like:

require_once APP_PATH . 'includes/header.php';

In your case APP_PATH could be defined as the full path before the include, ie. define('APP_PATH', dirname(__FILE__) . '/'); or if you want to hardcode it define('APP_PATH', '/home/www/my-app/');

You can use the absolute path to your css files for the assets to work,

<link href="/assets/css/demo.css"/>

OR for better portability you can create a little function to wrap all style calls:

<link href="<?php echo css_asset('demo.css'); ?>"/>

// Then the possible definition of css could be
function css_asset($style)
{
    return '/assets/css/' . $style;
}


问:
Filtering a string from email body with Python
I am attempting to filter out only the text in the body of the email message using Python.
I need to get that "Needed Content" part of the mail.
Here's a string that I get when receiving a mail:

```<code>'--001a1144b8cc8e9a67055ddfb9ec
Content-Type: text/plain; charset="UTF-8"

Needed Content

--001a1144b8cc8e9a67055ddfb9ec
Content-Type: text/html; charset="UTF-8"

<div dir="ltr">Off</div>

--001a1144b8cc8e9a67055ddfb9ec--
'
</code>```

I have tried something like that but failed:

```<code>re.findall(r'/\r/\n(.+?)/\r/\n', body)
</code>```

To filter out between the line breaks but failed..
Thanks in advance!

答:
You can use lookahead assertion(?=).</p>

```<code>>>> import re
>>> body='--001a1144b8cc8e9a67055ddfb9ec\nContent-Type: text/plain; charset="UTF-8'
>>> re.findall(".+(?=\nContent-Type)",body)                                   ['--001a1144b8cc8e9a67055ddfb9ec']
</code>```

Body:
I am attempting to filter out only the text in the body of the email message using Python.
I need to get that "Needed Content" part of the mail.
Here's a string that I get when receiving a mail:

'--001a1144b8cc8e9a67055ddfb9ec
Content-Type: text/plain; charset="UTF-8"

Needed Content

--001a1144b8cc8e9a67055ddfb9ec
Content-Type: text/html; charset="UTF-8"

Off

--001a1144b8cc8e9a67055ddfb9ec--
'

I have tried something like that but failed:

re.findall(r'/\r/\n(.+?)/\r/\n', body)

To filter out between the line breaks but failed..
Thanks in advance!

Body:
You can use lookahead assertion(?=).

>>> import re
>>> body='--001a1144b8cc8e9a67055ddfb9ec\nContent-Type: text/plain; charset="UTF-8'
>>> re.findall(".+(?=\nContent-Type)",body)                                   ['--001a1144b8cc8e9a67055ddfb9ec']


问:
Access Value of a Control
On access, I have a navigation form (Stage) with a dropdown list (Modifiable84). How can I collect the value of these controls in each tabs (tabX, tabY ...) of my navigation form?

I've tried in a variable: X_var = Modifiable84.Value but I've got an error.

答:
If you want to refer to a control on a specific subform, you need to use the subform name. E.g. X_var = Form1.Form.Modifiable84.Value where Form1 is the subform control name, not the form name.

Note that if you're using a navigation control, the form needs to be loaded.

Title: Access Value of a Control


问:
Allocating unmanaged memory in managed .NET code
Hi I have a unmanaged function that takes a chunk of memory allocated by malloc and deallocates it later on in async manner. I want to wrap it into managed wrapper. Is following code OK?</p>

```<code>void managed_fx (byte data __gc[], size_t size)
{
    //  Pin the data
    byte __pin *pinned_data = &data [0];

    //  Copy data to the unmanaged buffer.
    void *unmanaged_data = malloc (size);
    memcpy (unmanaged_data, (byte*) pinned_data, size);

    //  Forward the call
    fx (unmanaged_data, size);
}
</code>```

答:
You are

assuming that the data array is at least as big a size. This is a possible bug waiting to happen

Not checking the result of malloc()

You may not need to do this anyway, simply passing the pinned byte pointer should be fine (unless the called fx() function in some way changes the data in which case the copy is perhaps a requirement). Based on the memory being freed later it is likely that this is not a possibility though.

With that in mind here is a fixed up version

```<code>void managed_fx (byte data __gc[], size_t size)
{
    if (data.Length < size)
        throw gcnew System.IndexOutOfRangeException(
            "the unmanaged buffer is not big enough");
    //  Pin the data
    byte __pin *pinned_data = &data [0];

    //  Copy data to the unmanaged buffer.
    void *unmanaged_data = malloc (size);
    if (unmanaged_data == NULL)
        throw gcnew OutOfMemoryException(
            "could not allocate memory for the unmanaged buffer");
    memcpy (unmanaged_data, (byte*) pinned_data, size);

    //  Forward the call
    fx (unamanged_data, size);
}
</code>```

To answer the further questions:

The pinning is necessary to do the memcpy. It does not prevent the deletion of the memory by the GC runtime (well technically it does but so does simply holding of a reference to it) it prevents it moving in memory. Since memcpy is an unmanaged function - it cannot handle the pointers it is manipulating being moved about in memory.
malloc is entirely unmanaged (though the runtime libraries are free to use reserved areas of the managed heap to do this).

There is no clear distinction in source C++/CLI as to whether 'code' is managed or unmanaged. On compilation some parts will be CIL intermediate code, others plain native code the important thing is whether the variables used are managed or unmanaged. A managed reference (anything with the ^) can only be manipulated/used by code which is itself managed. This means the runtime is free to alter the values of the underlying pointers used as it sees fit if it alters the location of the managed object in memory. It does this in a way that is safe to managed functions (they are paused while the world is changed around them).
Since many useful functions exist with no knowledge of how to handle such managed references you may end up needing to take a simple pointer to them.
Since this operation is unsafe (if the GC kicks in a moves the reference about) the pinning pointer exists to make this safe and simple to do since it both takes a pointer and for the life of that pointer prevents the runtime moving the pointed to variable.

OwnerDisplayName: martin

LastEditorDisplayName: MSalters

Body:
Hi I have a unmanaged function that takes a chunk of memory allocated by malloc and deallocates it later on in async manner. I want to wrap it into managed wrapper. Is following code OK?

void managed_fx (byte data __gc[], size_t size)
{
    //  Pin the data
    byte __pin *pinned_data = &data [0];

    //  Copy data to the unmanaged buffer.
    void *unmanaged_data = malloc (size);
    memcpy (unmanaged_data, (byte*) pinned_data, size);

    //  Forward the call
    fx (unmanaged_data, size);
}

Body:
You are

assuming that the data array is at least as big a size. This is a possible bug waiting to happen

Not checking the result of malloc()

You may not need to do this anyway, simply passing the pinned byte pointer should be fine (unless the called fx() function in some way changes the data in which case the copy is perhaps a requirement). Based on the memory being freed later it is likely that this is not a possibility though.

With that in mind here is a fixed up version

void managed_fx (byte data __gc[], size_t size)
{
    if (data.Length < size)
        throw gcnew System.IndexOutOfRangeException(
            "the unmanaged buffer is not big enough");
    //  Pin the data
    byte __pin *pinned_data = &data [0];

    //  Copy data to the unmanaged buffer.
    void *unmanaged_data = malloc (size);
    if (unmanaged_data == NULL)
        throw gcnew OutOfMemoryException(
            "could not allocate memory for the unmanaged buffer");
    memcpy (unmanaged_data, (byte*) pinned_data, size);

    //  Forward the call
    fx (unamanged_data, size);
}

To answer the further questions:

The pinning is necessary to do the memcpy. It does not prevent the deletion of the memory by the GC runtime (well technically it does but so does simply holding of a reference to it) it prevents it moving in memory. Since memcpy is an unmanaged function - it cannot handle the pointers it is manipulating being moved about in memory.
malloc is entirely unmanaged (though the runtime libraries are free to use reserved areas of the managed heap to do this).

There is no clear distinction in source C++/CLI as to whether 'code' is managed or unmanaged. On compilation some parts will be CIL intermediate code, others plain native code the important thing is whether the variables used are managed or unmanaged. A managed reference (anything with the ^) can only be manipulated/used by code which is itself managed. This means the runtime is free to alter the values of the underlying pointers used as it sees fit if it alters the location of the managed object in memory. It does this in a way that is safe to managed functions (they are paused while the world is changed around them).
Since many useful functions exist with no knowledge of how to handle such managed references you may end up needing to take a simple pointer to them.
Since this operation is unsafe (if the GC kicks in a moves the reference about) the pinning pointer exists to make this safe and simple to do since it both takes a pointer and for the life of that pointer prevents the runtime moving the pointed to variable.


问:
SQL Server : query that doesn't work with parameters
I am not sure why this query works one way and not the other.

If I use the following query:

```<code>Select
    dlb.referenceid, dlb.partnum,
    pd.width, pd.length,
    dlb.partqty,
    Convert(date, dlb.entrydatetime, 101) as entrydatetime,
    dlb.status, dlb.material
From
    tbl_dlbase dlb
Join
    tbl_partdetails pd On dlb.referenceid = pd.referenceid
Where
    (pd.Spacing = 3)
    And ((dlb.status = 'Available') or (dlb.status = 'Reserved'))
Order By
    dlb.status
</code>```

It returns one result as it should.

If I use the exact same query but with parameters:

```<code>Select
    dlb.referenceid, dlb.partnum,
    pd.width, pd.length,
    dlb.partqty,
    Convert(date, dlb.entrydatetime, 101) as entrydatetime,
    dlb.status, dlb.material
From
    tbl_dlbase dlb
Join
    tbl_partdetails pd On dlb.referenceid = pd.referenceid
Where
    (@parameter1 = @Criteria1)
    And ((dlb.status = 'Available') or (dlb.status = 'Reserved'))
Order By
    dlb.status
</code>```

And have the following parameters declared and set as follows:

```<code>Declare @parameter1 varchar(50)
Declare @Criteria1 varchar(50)
Set @parameter1 = 'pd.Spacing'
Set @Criteria1 = 3
</code>```

The query returns no results.

I have used this type parameter query many times before but for some reason this time it won't work. Can anyone tell me what stupid thing I am missing or screwed up? I can't seem to see anything wrongs with it.

答:
You can't use parameters as object names without dynamic sql. Here is a fix... just change the print to exec(@sql) when you are happy with it...

```<code>Declare @parameter1 varchar(50)
Declare @Criteria1 varchar(50)
Set @parameter1 = 'pd.Spacing'
Set @Criteria1 = '3'

declare @sql varchar(max)
set @sql =
'Select
    dlb.referenceid,
    dlb.partnum,
    pd.width,
    pd.length,
    dlb.partqty,
    Convert(date, dlb.entrydatetime, 101) as entrydatetime,
    dlb.status,
    dlb.material
From tbl_dlbase dlb
Join tbl_partdetails pd On
dlb.referenceid = pd.referenceid
Where (' + @parameter1 + ' = ' + @Criteria1 + ')
AND ((dlb.status = ''Available'') OR (dlb.status = ''Reserved''))
Order By dlb.status'

print @sql
--exec(@sql)
--sp_executesql @sql
</code>```

This makes your where clause Where (pd.Spacing = 3) otherwise  the where clause is simply comparing the parameters, which obviously aren't the same since they aren't set to the same thing. It's the same thing as writing:

```<code>Select 'True'
where @parameter1 = @Criteria1
</code>```

which is interpreted as

```<code>Select 'True'
where 'pd.Spacing'= '3'    --string literals, not column names.
</code>```

Body:
I am not sure why this query works one way and not the other.

If I use the following query:

Select
    dlb.referenceid, dlb.partnum,
    pd.width, pd.length,
    dlb.partqty,
    Convert(date, dlb.entrydatetime, 101) as entrydatetime,
    dlb.status, dlb.material
From
    tbl_dlbase dlb
Join
    tbl_partdetails pd On dlb.referenceid = pd.referenceid
Where
    (pd.Spacing = 3)
    And ((dlb.status = 'Available') or (dlb.status = 'Reserved'))
Order By
    dlb.status

It returns one result as it should.

If I use the exact same query but with parameters:

Select
    dlb.referenceid, dlb.partnum,
    pd.width, pd.length,
    dlb.partqty,
    Convert(date, dlb.entrydatetime, 101) as entrydatetime,
    dlb.status, dlb.material
From
    tbl_dlbase dlb
Join
    tbl_partdetails pd On dlb.referenceid = pd.referenceid
Where
    (@parameter1 = @Criteria1)
    And ((dlb.status = 'Available') or (dlb.status = 'Reserved'))
Order By
    dlb.status

And have the following parameters declared and set as follows:

Declare @parameter1 varchar(50)
Declare @Criteria1 varchar(50)
Set @parameter1 = 'pd.Spacing'
Set @Criteria1 = 3

The query returns no results.

I have used this type parameter query many times before but for some reason this time it won't work. Can anyone tell me what stupid thing I am missing or screwed up? I can't seem to see anything wrongs with it.

Body:
You can't use parameters as object names without dynamic sql. Here is a fix... just change the print to exec(@sql) when you are happy with it...

Declare @parameter1 varchar(50)
Declare @Criteria1 varchar(50)
Set @parameter1 = 'pd.Spacing'
Set @Criteria1 = '3'

declare @sql varchar(max)
set @sql =
'Select
    dlb.referenceid,
    dlb.partnum,
    pd.width,
    pd.length,
    dlb.partqty,
    Convert(date, dlb.entrydatetime, 101) as entrydatetime,
    dlb.status,
    dlb.material
From tbl_dlbase dlb
Join tbl_partdetails pd On
dlb.referenceid = pd.referenceid
Where (' + @parameter1 + ' = ' + @Criteria1 + ')
AND ((dlb.status = ''Available'') OR (dlb.status = ''Reserved''))
Order By dlb.status'

print @sql
--exec(@sql)
--sp_executesql @sql

This makes your where clause Where (pd.Spacing = 3) otherwise  the where clause is simply comparing the parameters, which obviously aren't the same since they aren't set to the same thing. It's the same thing as writing:

Select 'True'
where @parameter1 = @Criteria1

which is interpreted as

Select 'True'
where 'pd.Spacing'= '3'    --string literals, not column names.


问:
Deep find in Immutable.js
I want to be able to find the keyPath for a deeply nested value in Immutable.js. How could I fill out this function deepFind to get what I want?

```<code>const map = Immutable.fromJS({
    a: {
        a1: 1,
        b1: 2
    },
    b: {
        b1: 3
        b2: 4,
        b3: 5
    }
});

function deepFind(map, value) {
    /* ??? */
}

deepFind(map, 4); // returns ['b', 'b2']
</code>```

答:
It doesn't look like there's any built-in way to do this, so I decided to go with a depth-first search. I used .toKeyedSeq() to search through all the collection types with the same code.

NOTE: This function will hang forever if your collections contain themselves.

```<code>import Immutable from 'immutable';

function deepFind(root, value, path = Immutable.List()) {
  if (root === value) {
    return path;
  }

  if (!Immutable.isImmutable(root)) {
    // this is a leaf node, and it's not the value we want.
    return undefined;
  }

  for (const [key, child] of root.toKeyedSeq()) {
    const result = deepFind(child, value, path.push(key));
    if (result) {
      return result;
    }
  }

  // no path is found
  return undefined;
}
</code>```

Title: Deep find in Immutable.js

Body:
I want to be able to find the keyPath for a deeply nested value in Immutable.js. How could I fill out this function deepFind to get what I want?

const map = Immutable.fromJS({
    a: {
        a1: 1,
        b1: 2
    },
    b: {
        b1: 3
        b2: 4,
        b3: 5
    }
});

function deepFind(map, value) {
    /* ??? */
}

deepFind(map, 4); // returns ['b', 'b2']

Body:
It doesn't look like there's any built-in way to do this, so I decided to go with a depth-first search. I used .toKeyedSeq() to search through all the collection types with the same code.

NOTE: This function will hang forever if your collections contain themselves.

import Immutable from 'immutable';

function deepFind(root, value, path = Immutable.List()) {
  if (root === value) {
    return path;
  }

  if (!Immutable.isImmutable(root)) {
    // this is a leaf node, and it's not the value we want.
    return undefined;
  }

  for (const [key, child] of root.toKeyedSeq()) {
    const result = deepFind(child, value, path.push(key));
    if (result) {
      return result;
    }
  }

  // no path is found
  return undefined;
}


问:
How can you write/delete/read a file in a different user account with the same ip address with python?
Recently, I learnt how to write/delete/read a file in Python (I am a beginner). However, something has got me thinking: is it possible to write/delete/read a file  in a different user account from the same network (i.e same ip address)? If so, how? Don't worry, I'll just try it at home. ;)</p>

答: This is running into more of an OS question. The answer is if you have permission to do so then yes you can but if you do not have permissions over the file then you cannot.</p>


问:
Picking random element by user defined weights

Possible Duplicate:

  Generating random results by weight in PHP?

I have a web application where users can add 1-20 strings of text and assign a weight to them of how often it should show up. The system would then choose a random string based on the defined weights. What is the best way to go about this? Do the range values for the weight for each string matter? Could I just have the user assign a number (0-100) for each string? How would you go about choosing a random string? (Each choice doesn't worry about what was chosen before, every string has the same odds (based on weight) of being chosen at the start of each call).

答:
Here is a simple implementation:

```<code>function Probability($data, $number = 1)
{
    $result = array();

    if (is_array($data) === true)
    {
        $data = array_map('abs', $data);
        $number = min(max(1, abs($number)), count($data));

        while ($number-- > 0)
        {
            $chance = 0;
            $probability = mt_rand(1, array_sum($data));

            foreach ($data as $key => $value)
            {
                $chance += $value;

                if ($chance >= $probability)
                {
                    $result[] = $key; unset($data[$key]); break;
                }
            }
        }
    }

    return $result;
}
</code>```

With this function you can specify how many unique weighted random elements you want (IDEOne).

Body:
Here is a simple implementation:

function Probability($data, $number = 1)
{
    $result = array();

    if (is_array($data) === true)
    {
        $data = array_map('abs', $data);
        $number = min(max(1, abs($number)), count($data));

        while ($number-- > 0)
        {
            $chance = 0;
            $probability = mt_rand(1, array_sum($data));

            foreach ($data as $key => $value)
            {
                $chance += $value;

                if ($chance >= $probability)
                {
                    $result[] = $key; unset($data[$key]); break;
                }
            }
        }
    }

    return $result;
}

With this function you can specify how many unique weighted random elements you want (IDEOne).


问:
How do I add default (Default to browser country) country code before the mobile number in MVC ASP.NET?
I have got a Textbox accepting mobile number. How do I add default (Default to browser country) country code before the mobile number?

I am using MVC ASP.NET

答:
You can use the service, http://ipinfo.io, to detect the country by user's IP (The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission). It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner.

```<code>$.get("https://ipinfo.io", function(response) {
   console.log(response.city, response.country);
}, "jsonp");
</code>```

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/

Body:
You can use the service, http://ipinfo.io, to detect the country by user's IP (The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission). It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner.

$.get("https://ipinfo.io", function(response) {
   console.log(response.city, response.country);
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/


问:
How to style path in leaflet?
I have line geometry that I've styled using the dashArray option. I'm trying to add a black outline to distinguish the gaps on lighter basemaps.

I tried adding a black path underneath with a heavier weight to create the outline but it seems that the gaps are transparent.

Applying the following style to the respective layers creates a white line with a black outline:

```<code>path = {
    color: '#ffffff',
    weight: 3,
    opacity: 1
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}
</code>```

When I apply dashArray the bottom layer shows through:

```<code>path = {
    color: '#000000',
    weight: 3,
    opacity: 1,
    dashArray: '5,10'
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}
</code>```

Is there a simple way to achieve this?

Leaflet path style options here.

EDIT: Top path is dashArray by itself. Second is when I overlay the dashArray on the wider black line (outline). Third is what I'm trying to achieve.

答:
The solution I came up with combines the two examples using three layers placing the dashArray path on top of the black-outlined layer.

```<code>//base layer black & wider to create outline
outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

//white line layer that will show through the transparent gaps
pathBackground = {
    color: '#ffffff',
    weight: 3,
    opacity: 1
}

//dashed path is placed on top of the black-outlined white line
path = {
    color: '#000000',
    weight: 3,
    opacity: 1,
    dashArray: '5,10'
}
</code>```

Title: How to style path in leaflet?

Body:
I have line geometry that I've styled using the dashArray option. I'm trying to add a black outline to distinguish the gaps on lighter basemaps.

I tried adding a black path underneath with a heavier weight to create the outline but it seems that the gaps are transparent.

Applying the following style to the respective layers creates a white line with a black outline:

path = {
    color: '#ffffff',
    weight: 3,
    opacity: 1
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

When I apply dashArray the bottom layer shows through:

path = {
    color: '#000000',
    weight: 3,
    opacity: 1,
    dashArray: '5,10'
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

Is there a simple way to achieve this?

Leaflet path style options here.

EDIT: Top path is dashArray by itself. Second is when I overlay the dashArray on the wider black line (outline). Third is what I'm trying to achieve.

Body:
The solution I came up with combines the two examples using three layers placing the dashArray path on top of the black-outlined layer.

//base layer black & wider to create outline
outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

//white line layer that will show through the transparent gaps
pathBackground = {
    color: '#ffffff',
    weight: 3,
    opacity: 1
}

//dashed path is placed on top of the black-outlined white line
path = {
    color: '#000000',
    weight: 3,
    opacity: 1,
    dashArray: '5,10'
}


问:
How to test extension implementations
There are several extension points available in the JUnit 5 API.

For example:

AfterEachCallback

AfterAllCallback

AfterTestExecutionCallback

BeforeAllCallback

BeforeEachCallback

BeforeTestExecutionCallback

ExecutionCondition

ParameterResolver

TestExecutionExceptionHandler

TestInstancePostProcessor

TestTemplateInvocationContextProvider

Nearly all of these extensions take some form of ExtensionContext which provides access to the test class, test method, test instance, ability to publish report entries, store values, and other capabilities. A lot of these operate directly on class instances

Most implementations will probably use some combination of reflection using ReflectionSupport and annotation discovery using AnnotationSupport, which are all static methods, which makes them difficult to mock.

Now, say I have written an implementation of the ExecutionCondition, or an extension that implements both the BeforeEachCallback and AfterEachCallback - how do I effectively test them?

I guess I could mock ExtensionContext, but that doesn't seem like a good way to effectively exercise the different code paths.

Internally to JUnit, there is the ExecutionEventRecorder and it is used along with the JupiterTestEngine implementation for execution (which is @API(status=INTERNAL)) to select and execute the tests, and then perform assertions on the resulting events.

I could make use of the same pattern because of the public visibility on the JupiterTestEngine.

Here are a few concrete examples to demonstrate:

An ExecutionCondition that enables tests based on system properties. This can possibly be tested with some reflection and using TestInfo in a @BeforeEach or @AfterEach style, but it seems more complicated to deal with and possible issues when parallel test execution comes. This example shows an example of "how do I provide a real-life ExtensionContext and assert on the result".

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(SystemPropertyCondition.class)
public @interface SystemProperty {
  String key();
  String value();
}

public class SystemPropertyCondition implements ExecutionCondition {
  @Override
  public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) {
    return context.getTestMethod()
        .flatMap(element -> AnnotationSupport.findAnnotation(element, SystemProperty.class))
        .map(systemProperty -> {
          if (systemProperty.value().equals(System.getProperty(systemProperty.key()))) {
            return ConditionEvaluationResult.enabled("Property is available");
          } else {
            return ConditionEvaluationResult.disabled("Property not equal");
          }
        })
        .orElseGet(() -> ConditionEvaluationResult.enabled("No annotations"));
  }
}
```</li>
<li><p>An <code>ExecutionCondition</code> that only runs on the provided day of the week. How would a test clock be injected? How would you test if the condition was the expected result? I guess some state/implementations can be placed into a <code>ExtensionContext.Store</code> which would allow for some sort of state being passed between extensions (like with a <code>BeforeEachCallback</code> as well, which might be the right path, but that is going to depend on the ordering of extension execution. I don't believe <code>BeforeEachCallback</code> is called before an <code>ExecutionCondition</code>, so that path might not be the right one. This example shows both the "how do I inject dependencies" and also shows the same issue as the previous example of providing the <code>ExtensionContext</code> and asserting on the result.</p>

<pre class="lang-java prettyprint-override"><code>@ExtendWith(RunOnDayCondition.class)
public @interface RunOnDay {
  DayOfWeek[] value();
}

final class RunOnDayCondition implements ExecutionCondition {

  private static final ConditionEvaluationResult DEFAULT = disabled(
      RunOnDay.class + " is not present"
  );

  @Override
  public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) {
    return context.getElement()
        .flatMap(annotatedElement -> findAnnotation(annotatedElement, RunOnDay.class))
        .map(RunOnDay::value)
        .map(RunOnDayCondition::evaluateIfRunningOnDay)
        .orElse(DEFAULT);
  }

  private static ConditionEvaluationResult evaluateIfRunningOnDay(final DayOfWeek[] days) {
    // TODO: How would you inject a test clock?
    final DayOfWeek currentDay = LocalDate.now().getDayOfWeek();
    final boolean runningInday = Stream.of(days).anyMatch(currentDay::equals);

    if (runningInday) {
      return enabled("Current day is " + currentDay + ", in the specified days of " + Arrays.toString(days));
    } else {
      return disabled("Current day is " + currentDay + ", not in the specified days of " + Arrays.toString(days));
    }
  }
}
</code>```

An extension that sets up a temporary directory, provides it as a parameter, and then cleans it up after the test. This would use ParameterResolver, BeforeEachCallback, AfterEachCallback, and the ExtensionContext.Store. This example shows that an extension implementation may use multiple extensions points and can make use of the store to keep track of state.

Would a custom test engine for extension tests be the right approach?

So, how do I test various extension implementations without relying on internal APIs and without "duplicating" effort into mocks?

答:
I know that is not a complete answer (but I am on mobile now and your question is very complex)... Try however if
this project could help you.

If you limit a little your question I could try to help you better

Title: How to test extension implementations

Body:
There are several extension points available in the JUnit 5 API.

For example:

AfterEachCallback

AfterAllCallback

AfterTestExecutionCallback

BeforeAllCallback

BeforeEachCallback

BeforeTestExecutionCallback

ExecutionCondition

ParameterResolver

TestExecutionExceptionHandler

TestInstancePostProcessor

TestTemplateInvocationContextProvider

Nearly all of these extensions take some form of ExtensionContext which provides access to the test class, test method, test instance, ability to publish report entries, store values, and other capabilities. A lot of these operate directly on class instances

Most implementations will probably use some combination of reflection using ReflectionSupport and annotation discovery using AnnotationSupport, which are all static methods, which makes them difficult to mock.

Now, say I have written an implementation of the ExecutionCondition, or an extension that implements both the BeforeEachCallback and AfterEachCallback - how do I effectively test them?

I guess I could mock ExtensionContext, but that doesn't seem like a good way to effectively exercise the different code paths.

Internally to JUnit, there is the ExecutionEventRecorder and it is used along with the JupiterTestEngine implementation for execution (which is @API(status=INTERNAL)) to select and execute the tests, and then perform assertions on the resulting events.

I could make use of the same pattern because of the public visibility on the JupiterTestEngine.

Here are a few concrete examples to demonstrate:

An ExecutionCondition that enables tests based on system properties. This can possibly be tested with some reflection and using TestInfo in a @BeforeEach or @AfterEach style, but it seems more complicated to deal with and possible issues when parallel test execution comes. This example shows an example of "how do I provide a real-life ExtensionContext and assert on the result".

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(SystemPropertyCondition.class)
public @interface SystemProperty {
  String key();
  String value();
}

public class SystemPropertyCondition implements ExecutionCondition {
  @Override
  public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) {
    return context.getTestMethod()
        .flatMap(element -> AnnotationSupport.findAnnotation(element, SystemProperty.class))
        .map(systemProperty -> {
          if (systemProperty.value().equals(System.getProperty(systemProperty.key()))) {
            return ConditionEvaluationResult.enabled("Property is available");
          } else {
            return ConditionEvaluationResult.disabled("Property not equal");
          }
        })
        .orElseGet(() -> ConditionEvaluationResult.enabled("No annotations"));
  }
}

An ExecutionCondition that only runs on the provided day of the week. How would a test clock be injected? How would you test if the condition was the expected result? I guess some state/implementations can be placed into a ExtensionContext.Store which would allow for some sort of state being passed between extensions (like with a BeforeEachCallback as well, which might be the right path, but that is going to depend on the ordering of extension execution. I don't believe BeforeEachCallback is called before an ExecutionCondition, so that path might not be the right one. This example shows both the "how do I inject dependencies" and also shows the same issue as the previous example of providing the ExtensionContext and asserting on the result.

@ExtendWith(RunOnDayCondition.class)
public @interface RunOnDay {
  DayOfWeek[] value();
}

final class RunOnDayCondition implements ExecutionCondition {

  private static final ConditionEvaluationResult DEFAULT = disabled(
      RunOnDay.class + " is not present"
  );

  @Override
  public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) {
    return context.getElement()
        .flatMap(annotatedElement -> findAnnotation(annotatedElement, RunOnDay.class))
        .map(RunOnDay::value)
        .map(RunOnDayCondition::evaluateIfRunningOnDay)
        .orElse(DEFAULT);
  }

  private static ConditionEvaluationResult evaluateIfRunningOnDay(final DayOfWeek[] days) {
    // TODO: How would you inject a test clock?
    final DayOfWeek currentDay = LocalDate.now().getDayOfWeek();
    final boolean runningInday = Stream.of(days).anyMatch(currentDay::equals);

    if (runningInday) {
      return enabled("Current day is " + currentDay + ", in the specified days of " + Arrays.toString(days));
    } else {
      return disabled("Current day is " + currentDay + ", not in the specified days of " + Arrays.toString(days));
    }
  }
}

An extension that sets up a temporary directory, provides it as a parameter, and then cleans it up after the test. This would use ParameterResolver, BeforeEachCallback, AfterEachCallback, and the ExtensionContext.Store. This example shows that an extension implementation may use multiple extensions points and can make use of the store to keep track of state.

Would a custom test engine for extension tests be the right approach?

So, how do I test various extension implementations without relying on internal APIs and without "duplicating" effort into mocks?


问:
pyspark: join tables based on nested keys
I have two tables with the below example schemas. The keys for table A are nested in a list in table B. I would like to join table A and table B based on the table A keys to generate table C. The values from table A should be a nested structure in table C based on the list of keyAs in table B. How can I do this using pyspark? Thanks!

Table A

```<code>root
|-- item1: string (nullable = true)
|-- item2: long (nullable = true)
|-- keyA: string (nullable = true)
</code>```

Table B

```<code>root
|-- item1: string (nullable = true)
|-- item2: long (nullable = true)
|-- keyB: string (nullable = true)
|-- keyAs: array (nullable = true)
| |-- element: string (containsNull = true)
</code>```

Table C

```<code>root
|-- item1: string (nullable = true)
|-- item2: long (nullable = true)
|-- keyB: string (nullable = true)
|-- keyAs: array (nullable = true)
| |-- element: string (containsNull = true)
|-- valueAs: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- item1: string (nullable = true)
| | |-- item2: long (nullable = true)
| | |-- keyA: string (nullable = true)
</code>```

答:
For joining A and B you need to explode B.keyAs first, like this:

```<code>tableB.withColumn('keyA', explode('keyAs')).join(tableA, 'keyA')
</code>```

For creating a nested structure please see this answer

Body:
I have two tables with the below example schemas. The keys for table A are nested in a list in table B. I would like to join table A and table B based on the table A keys to generate table C. The values from table A should be a nested structure in table C based on the list of keyAs in table B. How can I do this using pyspark? Thanks!

Table A

root
|-- item1: string (nullable = true)
|-- item2: long (nullable = true)
|-- keyA: string (nullable = true)

Table B

root
|-- item1: string (nullable = true)
|-- item2: long (nullable = true)
|-- keyB: string (nullable = true)
|-- keyAs: array (nullable = true)
| |-- element: string (containsNull = true)

Table C

root
|-- item1: string (nullable = true)
|-- item2: long (nullable = true)
|-- keyB: string (nullable = true)
|-- keyAs: array (nullable = true)
| |-- element: string (containsNull = true)
|-- valueAs: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- item1: string (nullable = true)
| | |-- item2: long (nullable = true)
| | |-- keyA: string (nullable = true)

Body:
For joining A and B you need to explode B.keyAs first, like this:

tableB.withColumn('keyA', explode('keyAs')).join(tableA, 'keyA')

For creating a nested structure please see this answer


问:
Reinterpreting Pointers in Julia
I have some C++ code that has existing python bindings, and I am trying to graft it on to Julia using PyCall.  One of the functions that gets called generates a pointer to a 2D array in memory to which I would like to wrap a Julia array around so that I can add/subtract/multiply by scalars, etc.   I know the size of the array, and it's currently represented as a PyObject to which I can do x_ptr[1], x_ptr[2] and get correct values out.  But I'd like to have an array, x.

答:
Here's a simple example using numpy array interface. By default, PyCall converts numpy arrays to Julia's arrays, but we can prevent that with @pycall and the ::Any annotation to show how you'd do it manually. You need to dig into the object to find that pointer.

```<code>julia> obj = @pycall numpy.reshape(numpy.arange(20), (4,5))::Any
PyObject array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

julia> array_interface = obj.__array_interface__
Dict{Any,Any} with 6 entries:
  "shape"   => (4, 5)
  "strides" => nothing
  "typestr" => "<i8"
  "data"    => (4705395216, false)
  "descr"   => Tuple{String,String}[("", "<i8")]
  "version" => 3

julia> array_interface["data"] # This is the actual pointer!
(4705395216, false)

julia> unsafe_wrap(Matrix{Int}, Ptr{Int}(array_interface["data"][1]), reverse(array_interface["shape"]))
5×4 Array{Int64,2}:
 0  5  10  15
 1  6  11  16
 2  7  12  17
 3  8  13  18
 4  9  14  19
</code>```

Of course, I don't know how your python object stores its pointer.  You'll have to dig into your Python object to find that pointer yourself.

Title: Reinterpreting Pointers in Julia

Body:
Here's a simple example using numpy array interface. By default, PyCall converts numpy arrays to Julia's arrays, but we can prevent that with @pycall and the ::Any annotation to show how you'd do it manually. You need to dig into the object to find that pointer.

julia> obj = @pycall numpy.reshape(numpy.arange(20), (4,5))::Any
PyObject array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

julia> array_interface = obj.__array_interface__
Dict{Any,Any} with 6 entries:
  "shape"   => (4, 5)
  "strides" => nothing
  "typestr" => "<i8"
  "data"    => (4705395216, false)
  "descr"   => Tuple{String,String}[("", "<i8")]
  "version" => 3

julia> array_interface["data"] # This is the actual pointer!
(4705395216, false)

julia> unsafe_wrap(Matrix{Int}, Ptr{Int}(array_interface["data"][1]), reverse(array_interface["shape"]))
5×4 Array{Int64,2}:
 0  5  10  15
 1  6  11  16
 2  7  12  17
 3  8  13  18
 4  9  14  19

Of course, I don't know how your python object stores its pointer.  You'll have to dig into your Python object to find that pointer yourself.

ContentLicense: CC BY-SA 4.0


问:
How to randomize the location of a button in kivy python screen manager?
I'm a newbie when it comes to python and kivy, and I have been working on this problem for a while and getting nowhere, so any help is greatly appreciated.  I am working on a behavioral task for rats, in which they would need to press a white square button on a screen to get a treat.  I want the white square to appear in one of three locations each time the stimulus screen appears.  Here is the relevant code that I have so far:

main.kv:

```<code><Stimulus>:
    on_pre_enter: self.update_pos()
    FloatLayout:
        StimButton:
            id: stimbutton
            on_press: root.manager.current = 'screen1'

<StimButton>
    background_normal: ''
    color: 1,1,1,1
    size_hint: 0.2, 0.3
</code>```

and within the python main.py:

```<code>class Stimulus(Screen):
    a = ObjectProperty(None)
    def update_pos(self):
        b = randint(1,3)
        if b==1:
            a = {'x':0.1,'y':0.33}
        elif b==2:
            a = {'x':0.4,'y':0.33}
        elif b==3:
            a = {'x':0.7,'y':0.33}
        self.ids.stimbutton.pos_hint = a

class StimButton(Button):
    def on_press(self):
        deliver_pellet()
</code>```

What should happen is that a white square appears, when the rat presses it they get a treat and it switches to a dark screen.  After a delay, a white square shows up in a different one of the 3 possible locations, and they go again.  What ends up happening is that I get one white square in the lower left corner, and the next time the screen appears I have a square in one of the random 3 positions, and one in the lower left corner.  Pressing either square produces the desired outcome.  How do I get that square in the lower left to go away?

答:
Please refer to the explanations and complete example for details.

#1. Add a method into Python script

We will add a method, "display_stimulus_screen" into the Stimulus class. This method will be schedule once when the rat pressed the stimulus button.

```<code>class Stimulus(Screen):
...
    # dt means delta time
    def display_stimulus_screen(self, dt):
        self.manager.current = "stimulus"
</code>```

#2. Add id and screen names into kv File

We will give an id to the Stimulus screen so that we can reference the new method that we just added in the Python script.

```<code><ScreenManagement>:
    Stimulus:
        id: stimulus
        name: "stimulus"
    Screen1:
        name: "screen1"
</code>```

#3. Create a delay

We will import Kivy Clock and use Clock.schedule_once method to invoke the new method called "display_stimulus_screen" with a specific time interval. In this example we use 0.5 seconds. The following is added to the kv file.

```<code>#:import Clock kivy.clock.Clock
...
            on_press:
                root.manager.current = 'screen1'    # display black screen
                Clock.schedule_once(root.manager.ids.stimulus.display_stimulus_screen, 0.5)
</code>```

Example

main.py

```<code>from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.properties import ObjectProperty

from random import randint

def deliver_pellet():
    print("deliver pellet")

class ScreenManagement(ScreenManager):
    pass

class Screen1(Screen):
    pass

class Stimulus(Screen):
    a = ObjectProperty(None)

    def update_pos(self):
        b = randint(1, 3)
        if b == 1:
            a = {'x': 0.1, 'y': 0.33}
        elif b == 2:
            a = {'x': 0.4, 'y': 0.33}
        elif b == 3:
            a = {'x': 0.7, 'y': 0.33}
        self.ids.stimbutton.pos_hint = a

    # dt means delta time
    def display_stimulus_screen(self, dt):
        self.manager.current = "stimulus"   # name of Stimulus Screen

class StimButton(Button):
    def on_press(self):
        deliver_pellet()

class TestApp(App):
    def build(self):
        return ScreenManagement()

if __name__ == "__main__":
    TestApp().run()
</code>```

test.kv

```<code>#:kivy 1.10.0
#:import Clock kivy.clock.Clock

<ScreenManagement>:
    Stimulus:
        id: stimulus
        name: "stimulus"
    Screen1:
        name: "screen1"

<Screen1>:

<Stimulus>:
    on_pre_enter: self.update_pos()

    FloatLayout:
        StimButton:
            id: stimbutton
            on_press:
                root.manager.current = 'screen1'    # display black screen
                Clock.schedule_once(root.manager.ids.stimulus.display_stimulus_screen, 0.5)

<StimButton>
    background_normal: ''
    color: 1,1,1,1
    size_hint: 0.2, 0.3
</code>```

Body:
I'm a newbie when it comes to python and kivy, and I have been working on this problem for a while and getting nowhere, so any help is greatly appreciated.  I am working on a behavioral task for rats, in which they would need to press a white square button on a screen to get a treat.  I want the white square to appear in one of three locations each time the stimulus screen appears.  Here is the relevant code that I have so far:

main.kv:

<Stimulus>:
    on_pre_enter: self.update_pos()
    FloatLayout:
        StimButton:
            id: stimbutton
            on_press: root.manager.current = 'screen1'

<StimButton>
    background_normal: ''
    color: 1,1,1,1
    size_hint: 0.2, 0.3

and within the python main.py:

class Stimulus(Screen):
    a = ObjectProperty(None)
    def update_pos(self):
        b = randint(1,3)
        if b==1:
            a = {'x':0.1,'y':0.33}
        elif b==2:
            a = {'x':0.4,'y':0.33}
        elif b==3:
            a = {'x':0.7,'y':0.33}
        self.ids.stimbutton.pos_hint = a

class StimButton(Button):
    def on_press(self):
        deliver_pellet()

What should happen is that a white square appears, when the rat presses it they get a treat and it switches to a dark screen.  After a delay, a white square shows up in a different one of the 3 possible locations, and they go again.  What ends up happening is that I get one white square in the lower left corner, and the next time the screen appears I have a square in one of the random 3 positions, and one in the lower left corner.  Pressing either square produces the desired outcome.  How do I get that square in the lower left to go away?

Body:
Please refer to the explanations and complete example for details.

#1. Add a method into Python script

We will add a method, "display_stimulus_screen" into the Stimulus class. This method will be schedule once when the rat pressed the stimulus button.

class Stimulus(Screen):
...
    # dt means delta time
    def display_stimulus_screen(self, dt):
        self.manager.current = "stimulus"

#2. Add id and screen names into kv File

We will give an id to the Stimulus screen so that we can reference the new method that we just added in the Python script.

<ScreenManagement>:
    Stimulus:
        id: stimulus
        name: "stimulus"
    Screen1:
        name: "screen1"

#3. Create a delay

We will import Kivy Clock and use Clock.schedule_once method to invoke the new method called "display_stimulus_screen" with a specific time interval. In this example we use 0.5 seconds. The following is added to the kv file.

#:import Clock kivy.clock.Clock
...
            on_press:
                root.manager.current = 'screen1'    # display black screen
                Clock.schedule_once(root.manager.ids.stimulus.display_stimulus_screen, 0.5)

Example

main.py

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.properties import ObjectProperty

from random import randint

def deliver_pellet():
    print("deliver pellet")

class ScreenManagement(ScreenManager):
    pass

class Screen1(Screen):
    pass

class Stimulus(Screen):
    a = ObjectProperty(None)

    def update_pos(self):
        b = randint(1, 3)
        if b == 1:
            a = {'x': 0.1, 'y': 0.33}
        elif b == 2:
            a = {'x': 0.4, 'y': 0.33}
        elif b == 3:
            a = {'x': 0.7, 'y': 0.33}
        self.ids.stimbutton.pos_hint = a

    # dt means delta time
    def display_stimulus_screen(self, dt):
        self.manager.current = "stimulus"   # name of Stimulus Screen

class StimButton(Button):
    def on_press(self):
        deliver_pellet()

class TestApp(App):
    def build(self):
        return ScreenManagement()

if __name__ == "__main__":
    TestApp().run()

test.kv

#:kivy 1.10.0
#:import Clock kivy.clock.Clock

<ScreenManagement>:
    Stimulus:
        id: stimulus
        name: "stimulus"
    Screen1:
        name: "screen1"

<Screen1>:

<Stimulus>:
    on_pre_enter: self.update_pos()

    FloatLayout:
        StimButton:
            id: stimbutton
            on_press:
                root.manager.current = 'screen1'    # display black screen
                Clock.schedule_once(root.manager.ids.stimulus.display_stimulus_screen, 0.5)

<StimButton>
    background_normal: ''
    color: 1,1,1,1
    size_hint: 0.2, 0.3


问:
How to properly set a network timeout before showing an animation on iOS?
as the title says I have a problem with my app. Let me explain a little more in detail what I'm trying to achieve using a bulleted list:

The app loads the main menù and connect to firebase in order to see if there's some product to show

Download the product image

Animate the content in order to show the product info and image

I created functions to handle the case the connection doesn't work or the product doesn't exist. The problem is when the connection is too slow to load the image before the animation starts (about 2 seconds). In this case, the app stuck a little and the product will be shown before the animation ends.

Load code

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // The view where the product will be shown
    self.productView.alpha = 0.0

    // Checks the internet connection
    if (ConnectionService.isConnectedToNetwork()) {
        fetchDataFromDatabase(downloadCompleted: { (productToShow) in
            self.fillPromoView(usingProduct: productToShow)
        })
    } else {
        fillPromoView(nil)
    }
}
</code>```

Appear code

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 0.5, delay: 2.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
          ...
    }
}
</code>```

Here the code to download the product image:

```<code>func fetchDataFromDatabase(downloadCompleted: @escaping ((Product?) -> Void)) {
    FirebaseService.instance.getProductList { (productList) in
        if (productList.count != 0) {
            do {
                let productImage = try Data(contentsOf: productList.productImage as URL)

                // Fill the IBOutlet with the downloaded image
                self.promoProductImg.image = UIImage(data: productImage)

                downloadCompleted(productList)
            } catch {
                downloadCompleted(nil)
            }
        } else {
            downloadCompleted(nil)
        }
    }
}
</code>```

My aim is to launch the animation once I have a response from the download status or because the connection takes more than 2 seconds to download the image. Any advice?

答:
I would setup the default state of the view to show loading process (An empty view with UIActivityIndicatorView in the center is the simplest example of what I am talking about). This ensures that the user understands the app is not frozen while your fetch method is being processed.
Then I would modify downloadCompleted method by moving UIView.animate method into its end. This means that any UI update is performed only after fetching process is complete.

Your issue is that viewDidAppear might be invoked before fetching is complete due to asynchronous nature of your mechanism.

Body:
as the title says I have a problem with my app. Let me explain a little more in detail what I'm trying to achieve using a bulleted list:

The app loads the main menù and connect to firebase in order to see if there's some product to show

Download the product image

Animate the content in order to show the product info and image

I created functions to handle the case the connection doesn't work or the product doesn't exist. The problem is when the connection is too slow to load the image before the animation starts (about 2 seconds). In this case, the app stuck a little and the product will be shown before the animation ends.

Load code

override func viewDidLoad() {
    super.viewDidLoad()

    // The view where the product will be shown
    self.productView.alpha = 0.0

    // Checks the internet connection
    if (ConnectionService.isConnectedToNetwork()) {
        fetchDataFromDatabase(downloadCompleted: { (productToShow) in
            self.fillPromoView(usingProduct: productToShow)
        })
    } else {
        fillPromoView(nil)
    }
}

Appear code

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 0.5, delay: 2.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
          ...
    }
}

Here the code to download the product image:

func fetchDataFromDatabase(downloadCompleted: @escaping ((Product?) -> Void)) {
    FirebaseService.instance.getProductList { (productList) in
        if (productList.count != 0) {
            do {
                let productImage = try Data(contentsOf: productList.productImage as URL)

                // Fill the IBOutlet with the downloaded image
                self.promoProductImg.image = UIImage(data: productImage)

                downloadCompleted(productList)
            } catch {
                downloadCompleted(nil)
            }
        } else {
            downloadCompleted(nil)
        }
    }
}

My aim is to launch the animation once I have a response from the download status or because the connection takes more than 2 seconds to download the image. Any advice?


问:
Show an actionlink in a tooltip mvc razorview
I have a datatable with Edit,Delete actionlinks in each row. Instead of showing them as a column in the table, I would like to show them in a tooltip to save space. I am not sure how this can be achieved. I would like the tooltip to appear on the <code>@rowNo.ToString("000")</code> field. Thanks for the help. My code is as follows: </p>

```<code> <tbody>
            @foreach (var item in Model)
                {
                    rowNo++;
                <tr>
                    <td>
                        @rowNo.ToString("000")

                        @Html.ActionLink("Edit", "Edit", new { id = item.Id })
| @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                        </td>
    </tr>
    </tbody>
</code>```

答:
It really depends on your HTML Framework. Assuming, you might probably use Bootstrap, I'd suggest something like Dropdowns. I think, by the example, you get the point...</p>

```<code><div class="dropdown show">
  <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Actions...
  </a>

  <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
    @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "dropdown-item" })
    @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "dropdown-item" })
  </div>
</div>
</code>```

Body:
I have a datatable with Edit,Delete actionlinks in each row. Instead of showing them as a column in the table, I would like to show them in a tooltip to save space. I am not sure how this can be achieved. I would like the tooltip to appear on the @rowNo.ToString("000") field. Thanks for the help. My code is as follows:

            @foreach (var item in Model)
                {
                    rowNo++;

                        @rowNo.ToString("000")

                        @Html.ActionLink("Edit", "Edit", new { id = item.Id })
| @Html.ActionLink("Delete", "Delete", new { id = item.Id })

Body:
It really depends on your HTML Framework. Assuming, you might probably use Bootstrap, I'd suggest something like Dropdowns. I think, by the example, you get the point...

<div class="dropdown show">
  <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Actions...
  </a>

  <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
    @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "dropdown-item" })
    @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "dropdown-item" })
  </div>
</div>