问:
Core Data Duplicating TableView Cells Upon App Launch
When I relaunch my app, my cells in my table view are duplicated.  Otherwise they are fine when being added and deleted, etc.

Here is my code:

```<code>@implementation RoutineTableViewController

@synthesize routineTableView;
@synthesize eventsArray;
@synthesize entered;
@synthesize managedObjectContext;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

- (void)viewDidUnload
{
    self.eventsArray = nil;
    [super viewDidUnload];
}

-(void)toggleEdit
{
    [self.routineTableView setEditing: !self.routineTableView.editing animated:YES];

    if (self.routineTableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

- (void)dealloc
{
    [managedObjectContext release];
    [eventsArray release];
    [entered release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -
#pragma mark Add an event

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    /*
    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
     */
     }

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

        if(eventsArray && entered)
        {
            Routine *tempRoutine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
            tempRoutine.name = entered;
            [eventsArray addObject:tempRoutine];
            [routineTableView reloadData];
            [self addEvent];
            NSLog(@"tempRoutine.name is: %@",tempRoutine.name);
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [eventsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    Routine *tempRoutine = (Routine *)[eventsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = tempRoutine.name;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {

     if (editingStyle == UITableViewCellEditingStyleDelete) {

         // Delete the managed object at the given index path.
         NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
         [managedObjectContext deleteObject:eventToDelete];

         // Update the array and table view.
         [eventsArray removeObjectAtIndex:indexPath.row];
         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

         // Commit the change.
         NSError *error = nil;
         if (![managedObjectContext save:&error]) {
             // Handle the error.
         }
     }
</code>```

答:
I think, we are adding it twice....

```<code>Routine *tempRoutine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
            tempRoutine.name = entered;
        ---->    [eventsArray addObject:tempRoutine];
            [routineTableView reloadData];
         ---->   [self addEvent]; //comment this line in alertViewDelegate
</code>```

or you can use following code changes..... it may have syntax error

```<code>- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

        if(eventsArray && entered)
        {
           [self addEvent];

        }
    }
}

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray addObject:routine];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[eventsArray count] inSection:0];

    [self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

     }
</code>```

Thanks,

Body:
When I relaunch my app, my cells in my table view are duplicated.  Otherwise they are fine when being added and deleted, etc.

Here is my code:

@implementation RoutineTableViewController

@synthesize routineTableView;
@synthesize eventsArray;
@synthesize entered;
@synthesize managedObjectContext;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

- (void)viewDidUnload
{
    self.eventsArray = nil;
    [super viewDidUnload];
}

-(void)toggleEdit
{
    [self.routineTableView setEditing: !self.routineTableView.editing animated:YES];

    if (self.routineTableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

- (void)dealloc
{
    [managedObjectContext release];
    [eventsArray release];
    [entered release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -
#pragma mark Add an event

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    /*
    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
     */
     }

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

        if(eventsArray && entered)
        {
            Routine *tempRoutine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
            tempRoutine.name = entered;
            [eventsArray addObject:tempRoutine];
            [routineTableView reloadData];
            [self addEvent];
            NSLog(@"tempRoutine.name is: %@",tempRoutine.name);
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [eventsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    Routine *tempRoutine = (Routine *)[eventsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = tempRoutine.name;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {

     if (editingStyle == UITableViewCellEditingStyleDelete) {

         // Delete the managed object at the given index path.
         NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
         [managedObjectContext deleteObject:eventToDelete];

         // Update the array and table view.
         [eventsArray removeObjectAtIndex:indexPath.row];
         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

         // Commit the change.
         NSError *error = nil;
         if (![managedObjectContext save:&error]) {
             // Handle the error.
         }
     }

Body:
I think, we are adding it twice....

Routine *tempRoutine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
            tempRoutine.name = entered;
        ---->    [eventsArray addObject:tempRoutine];
            [routineTableView reloadData];
         ---->   [self addEvent]; //comment this line in alertViewDelegate

or you can use following code changes..... it may have syntax error

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

        if(eventsArray && entered)
        {
           [self addEvent];

        }
    }
}

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray addObject:routine];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[eventsArray count] inSection:0];

    [self.routineTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

     }

Thanks,


来源: stackexchange

问:
ImportError: No module named Mail python sendgrid
User.views.py
this is the folder of Mail/views.py im having error when i started the local development server

```<code>from Mail.views import sendgrid_mail

content['url'] = input_values["host"] + "/EmailVerification/" +
user.email + '/' + md5_key
message = render_to_string('accountverification.html', content)
# sendMail.delay("[GavaGives] Account created successfully", message,
content['email'])
sendgrid_mail('info', user.email, '[GavaGives] Account created
successfully', message, 'user_offline_donation')

return response("create", "success", [])
</code>```

Mail.views.py

```<code>def sendgrid_mail(from_email, to_email, subject, content, template):
sg = sendgrid.SendGridClient(config('SENDGRID_API_KEY'))
mail = sendgrid.Mail()

mail.add_to(to_email)
mail.set_from(mail_from(from_email))
mail.set_subject(subject)
mail.set_html(content)

mail.add_filter('templates', 'enable', '1')
mail.add_filter('templates', 'template_id', get_templates(template))

sg.send(mail)
</code>```

Settings.py
this is the folder of the main project/settings.py im having error when i started the local development server

```<code>INSTALLED_APPS = [
'django.contrib.sessions',
'corsheaders',  # CORS installation
'django_cron',  # celery
'django_crontab',  # Cron jobs
'celery',
'djcelery',
'Users',
'Campaign',
'Donor',
'Media',
'Admin',
'Common',
'CommonModules',
'Event',
'Cards',
'Mail'
]
</code>```

this my project Folder Structure base on django. any help would be much appreciated. thanks

```<code>```
[projectname]/
├── [admin]/
├── campaign/
├── card/
├── common/
├── commonmodules/
├── donor/
├── event/
├── gavagives/
│       ├── __init__.py
│       ├── cel.py
│       ├── cronjobs.py
│       ├── custom_commands.py
│       ├── settings.py
│       ├── urls.py
│       ├── views.py
│       ├── wsgi.py
├── logs/
├── Mail/
│       ├── mail.py
│       ├── views.py
├── node_modules/
├── manage.py
├── README.rst
├── requirements.txt
├── .env
├── Users/
│       ├── __init__.py
│       ├── admin.py
│       ├── apps.py
│       ├── cronjobs.py
│       ├── models.py
│       ├── urls.py
│       ├── validations.py
│       ├── views.py
├── venv/
│       ├── include
│       ├── Lib
│       ├── Scripts
│       ├── tcl
├── License.txt
├── .gitignore
```
</code>```

答:
you need to import mail python send grid by using  pip.

you enter this line in juper note book or command.

```<code>pip install mail python sendgrid
</code>```

or

```<code> pip3 install mail python sendgrid
</code>```

ContentLicense: CC BY-SA 4.0

Body:
User.views.py
this is the folder of Mail/views.py im having error when i started the local development server

from Mail.views import sendgrid_mail

content['url'] = input_values["host"] + "/EmailVerification/" +
user.email + '/' + md5_key
message = render_to_string('accountverification.html', content)
# sendMail.delay("[GavaGives] Account created successfully", message,
content['email'])
sendgrid_mail('info', user.email, '[GavaGives] Account created
successfully', message, 'user_offline_donation')

return response("create", "success", [])

Mail.views.py

def sendgrid_mail(from_email, to_email, subject, content, template):
sg = sendgrid.SendGridClient(config('SENDGRID_API_KEY'))
mail = sendgrid.Mail()

mail.add_to(to_email)
mail.set_from(mail_from(from_email))
mail.set_subject(subject)
mail.set_html(content)

mail.add_filter('templates', 'enable', '1')
mail.add_filter('templates', 'template_id', get_templates(template))

sg.send(mail)

Settings.py
this is the folder of the main project/settings.py im having error when i started the local development server

INSTALLED_APPS = [
'django.contrib.sessions',
'corsheaders',  # CORS installation
'django_cron',  # celery
'django_crontab',  # Cron jobs
'celery',
'djcelery',
'Users',
'Campaign',
'Donor',
'Media',
'Admin',
'Common',
'CommonModules',
'Event',
'Cards',
'Mail'
]

this my project Folder Structure base on django. any help would be much appreciated. thanks

[projectname]/
├── [admin]/
├── campaign/
├── card/
├── common/
├── commonmodules/
├── donor/
├── event/
├── gavagives/
│       ├── __init__.py
│       ├── cel.py
│       ├── cronjobs.py
│       ├── custom_commands.py
│       ├── settings.py
│       ├── urls.py
│       ├── views.py
│       ├── wsgi.py
├── logs/
├── Mail/
│       ├── mail.py
│       ├── views.py
├── node_modules/
├── manage.py
├── README.rst
├── requirements.txt
├── .env
├── Users/
│       ├── __init__.py
│       ├── admin.py
│       ├── apps.py
│       ├── cronjobs.py
│       ├── models.py
│       ├── urls.py
│       ├── validations.py
│       ├── views.py
├── venv/
│       ├── include
│       ├── Lib
│       ├── Scripts
│       ├── tcl
├── License.txt
├── .gitignore

Body:
you need to import mail python send grid by using  pip.

you enter this line in juper note book or command.

pip install mail python sendgrid

or

 pip3 install mail python sendgrid


问:
Property displayed as undefined in React Component - Retrieve props.match and additional property in component
I have an index.js from which i am calling a Component like this

```<code>const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);
</code>```

But in MyComponent.js, this.props.prop1 is displayed as undefined. Any idea why ?
I need to able to get this.props.match.params and prop1

答:
@jonrsharpe 's comment is very important:

Route only passes the route props, history, match and location, to the
  components it mounts.

So, if you want to pass props to your component in the Route, it should be like this:

```<code><Switch>
   <Route path="/pathname" render={() => (<MyComponent prop1={prop1}/>)} />
</Switch>
</code>```

Body:
I have an index.js from which i am calling a Component like this

const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);

But in MyComponent.js, this.props.prop1 is displayed as undefined. Any idea why ?
I need to able to get this.props.match.params and prop1

Body:
@jonrsharpe 's comment is very important:

Route only passes the route props, history, match and location, to the
  components it mounts.

So, if you want to pass props to your component in the Route, it should be like this:

<Switch>
   <Route path="/pathname" render={() => (<MyComponent prop1={prop1}/>)} />
</Switch>


问:
Laravel Docker Container not connecting to local mysql
I have an issue connecting to mysql running in the local machine in my DockerFile i have mentioned

```<code>FROM php:7
RUN apt-get update -y && apt-get install -y openssl zip unzip git
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN docker-php-ext-install pdo mbstring pdo_mysql
WORKDIR /home
COPY . /home
RUN composer install --ignore-platform-reqs

CMD php artisan serve --host=0.0.0.0 --port=8081
EXPOSE 8081
</code>```

and this in my .env configuration

```<code>DB_HOST=localhost
DB_DATABASE=databasename
DB_USERNAME=root
DB_PASSWORD=testpassword
</code>```

I have very less clue about where it is failing. Do i need to install mysql for Docker container also?

答:
you are trying to connect to mysql in localhost, which is (surprisingly) the reference to the local host. since its a relative address, inside the container it is being resolved as the container own address, and no mysql is awaiting you there...
so to solve it - just give it your real host ip instead of localhost or 127.0.0.1.

step 1 - fix .env file:

```<code>DB_HOST=<your_host_ip> #run `ifconfig` and look for your ip on `docker0` network
DB_DATABASE=databasename
DB_USERNAME=laravel_server #not root, since we are going to allow this user remote access.
DB_PASSWORD=testpassword
</code>```

step 2 - create dedicated user:

open your mysql: mysql -u root -p, give your root password, and run the following:

```<code>CREATE USER 'laravel_server'@'%' IDENTIFIED BY 'testpassword';
GRANT ALL PRIVILEGES ON databasename.* TO 'laravel_server'@'%';
FLUSH PRIVILEGES;
</code>```

we created the user and gave it the permissions.

step 3 - open mysql to remote access:

we have to make it listening on all interfaces and not just localhost and therefore we run:

sudo sed 's/.*bind-address.*/bind-address=0.0.0.0/' /etc/mysql/mysql.conf.d/mysqld.cnf

(you will be prompted for password. this command is just replacing the line in mysql configuration file)

step 4 - updating:

in the project directory: php artisan config:cache

service mysql restart

then docker build and run a new container again. it should work for you.

Body:
I have an issue connecting to mysql running in the local machine in my DockerFile i have mentioned

FROM php:7
RUN apt-get update -y && apt-get install -y openssl zip unzip git
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN docker-php-ext-install pdo mbstring pdo_mysql
WORKDIR /home
COPY . /home
RUN composer install --ignore-platform-reqs

CMD php artisan serve --host=0.0.0.0 --port=8081
EXPOSE 8081

and this in my .env configuration

DB_HOST=localhost
DB_DATABASE=databasename
DB_USERNAME=root
DB_PASSWORD=testpassword

I have very less clue about where it is failing. Do i need to install mysql for Docker container also?

Body:
you are trying to connect to mysql in localhost, which is (surprisingly) the reference to the local host. since its a relative address, inside the container it is being resolved as the container own address, and no mysql is awaiting you there...
so to solve it - just give it your real host ip instead of localhost or 127.0.0.1.

step 1 - fix .env file:

DB_HOST=<your_host_ip> #run `ifconfig` and look for your ip on `docker0` network
DB_DATABASE=databasename
DB_USERNAME=laravel_server #not root, since we are going to allow this user remote access.
DB_PASSWORD=testpassword

step 2 - create dedicated user:

open your mysql: mysql -u root -p, give your root password, and run the following:

CREATE USER 'laravel_server'@'%' IDENTIFIED BY 'testpassword';
GRANT ALL PRIVILEGES ON databasename.* TO 'laravel_server'@'%';
FLUSH PRIVILEGES;

we created the user and gave it the permissions.

step 3 - open mysql to remote access:

we have to make it listening on all interfaces and not just localhost and therefore we run:

sudo sed 's/.*bind-address.*/bind-address=0.0.0.0/' /etc/mysql/mysql.conf.d/mysqld.cnf

(you will be prompted for password. this command is just replacing the line in mysql configuration file)

step 4 - updating:

in the project directory: php artisan config:cache

service mysql restart

then docker build and run a new container again. it should work for you.


问:
Uncaught TypeError: Cannot set property 'value' of null after the page loads
I know this has been asked so many times, but i couldn't find the answer for my scenerio. Below is my code. I'm getting this error in the last line inside findPattern function. But i have that ID created inside createMyArea as textArea += 'id="P'+app_page_id+'_VALUE'+key+'". But why this is not finding the ID? Please let me know what i'm doing wrong here. I'm loading this after the page loads

```<code>var app_page_id         = 40;
var app_pattern_page_id     = 32;
var app_id;
var checksum;
var lang;

$(document).ready(function() {
    app_id = $("#pFlowId").val();
    checksum = $("#pInstance").val();

    createMyFlow();

    function createMyFlow(){
        var result = new htmldb_Get(null, $v('pFlowId'), 'APPLICATION_PROCESS='+getAllLanguagesProc,  $v('pFlowStepId'));
        lang = jQuery.parseJSON(result.get()).lang;
        createMyArea();
        result = loadDataFromMyOra();
        if(result !== null)
            findPattern(result);
    }

    function createMyArea(){
        var textArea;
        for ( var key in lang){
            textArea = '<tr><td  align="right"><label for="P'+app_page_id+'_VALUE_'+key+'">';
            textArea += '<span class="optional">Name '+languages[key][0]+': </span></label></td>';
            textArea += '<td  align="left" valign="middle">';
            textArea += '<input type="hidden" name="p_arg_names" />';
            textArea += '<fieldset id="P'+app_page_id+'_VALUE_fieldset_'+key+'" class="textarea" tabindex="-1">';
            textArea += '<input name="p_t04" type="text" maxlength="50" size="32" value=""';
            textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
            textArea += '</td></tr>';
        $('.formlayout').append(textArea);
        }
    }

    function findPattern(patterns)
    {
        var item = "";
        for ( var key in patterns){
            item = patterns[key]+"";
            item = item.replace(/,/g,",");
            item = item.replace(/“/g,'"')
            document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;   //error here
        }
    }
});
</code>```

答:
The error indicates document.getElementById("P"+app_page_id+"_VALUE"+key) is null. Work backwards and think of all the reasons it might be null:

What does "P"+app_page_id+"_VALUE"+key evaluate to? Does an element with this id exist in the DOM? (You can manually inspect the DOM tree with browser dev tools, or try running getElementById() in the dev console.)

An element with that id probably doesn't exist. You point out you are trying to create it, but is there any reason that createMyArea() might not be working?

If lang is an empty object, this loop will execute 0 times: for (var key in lang) ...

The for loop iterates on keys of the lang object, but inside the loop you access via languages[key]. That is a little weird.

Their are many more things to check, but this should give you an idea of things to look for. Work backwards and test all your assumptions!

Body:
I know this has been asked so many times, but i couldn't find the answer for my scenerio. Below is my code. I'm getting this error in the last line inside findPattern function. But i have that ID created inside createMyArea as textArea += 'id="P'+app_page_id+'_VALUE'+key+'". But why this is not finding the ID? Please let me know what i'm doing wrong here. I'm loading this after the page loads

var app_page_id         = 40;
var app_pattern_page_id     = 32;
var app_id;
var checksum;
var lang;

$(document).ready(function() {
    app_id = $("#pFlowId").val();
    checksum = $("#pInstance").val();

    createMyFlow();

    function createMyFlow(){
        var result = new htmldb_Get(null, $v('pFlowId'), 'APPLICATION_PROCESS='+getAllLanguagesProc,  $v('pFlowStepId'));
        lang = jQuery.parseJSON(result.get()).lang;
        createMyArea();
        result = loadDataFromMyOra();
        if(result !== null)
            findPattern(result);
    }

    function createMyArea(){
        var textArea;
        for ( var key in lang){
            textArea = '
';
            textArea += 'Name '+languages[key][0]+': 	';
            textArea += '';
            textArea += '<input type="hidden" name="p_arg_names" />';
            textArea += '<fieldset id="P'+app_page_id+'_VALUE_fieldset_'+key+'" class="textarea" tabindex="-1">';
            textArea += '<input name="p_t04" type="text" maxlength="50" size="32" value=""';
            textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
            textArea += '
';
        $('.formlayout').append(textArea);
        }
    }

    function findPattern(patterns)
    {
        var item = "";
        for ( var key in patterns){
            item = patterns[key]+"";
            item = item.replace(/,/g,",");
            item = item.replace(/“/g,'"')
            document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;   //error here
        }
    }
});


问:
Getting the values of parameters for ParameterizedTests in TestExecutionListener
In my test framework, I have to manually generate the TestSuite.xml.  In Junit4, the "Description" object passed by the listener contains the value of the parameters passed in a parameterized test, so the XML looks like this.

```<code><testcase
  11     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
  12     name="testTransformAndGenerate[77: RegexGenTest: [0-9]{1,28}]"
  13     time="9.1E-4"/>
  14   <testcase
  15     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
  16     name="testTransformAndGenerate[123: RegexGenTest: [A-Za-z0-9 -]{1,64}]"
  17     time="0.0020299999999999997"/>
  18   <testcase
  19     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
  20     name="testTransformAndGenerate[112: RegexGenTest: [A-Za-z0-9 -]{1,31}]"
  21     time="0.00171"/>
  22   <testcase
  23     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
  24     name="testTransformAndGenerate[318: RegexGenTest: \d{37}]"
  25     time="7.3E-4"/>
</code>```

In JUnit5, I use the TestExecutionListener callback and I get the method name like this:

```<code>    @Override
    public void executionFinished(final TestIdentifier testIdentifier, final TestExecutionResult testExecutionResult) {
        super.executionFinished(testIdentifier, testExecutionResult);
        logWithThrowable("Execution Finished: %s - %s - %s", testExecutionResult.getThrowable().orElse(null),
                testIdentifier.getDisplayName(), testIdentifier.getUniqueId(), testExecutionResult);
        final Optional<TestSource> source = testIdentifier.getSource();
        if (source.isPresent()) {
            final TestSource testSource = source.get();
            if (testSource instanceof ClassSource) {
               ...
            }
            else if (testSource instanceof MethodSource) {
                final MethodSource methodSource = (MethodSource) testSource;
                LOG.info("MethodSource: executionFinished for class: " + methodSource.getClassName() + " and method: "
                        + methodSource.getMethodName());
                final OmsTestMethod testMethod = getOmsTestMethod(methodSource);
                if (testMethod == null) {
                    return;
                }
                testMethod.setResult(testExecutionResult);
            }
        }
    }
</code>```

This method name does not contain the parameters passed in, so the XML looks like this:

```<code><testcase
 12     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
 13     name="testTransformAndGenerate"
 14     time="0.00366"/>
</code>```

I treat the method names as unique, so there is only one entry.

TeamCity goes by the number of testcases in the XML file, so the reporting is wrong.  SummaryGeneratingListener has the number of tests information, but I can't get TeamCity to use that.

Any idea of how to do this?

I have tried the various APIs in MethodSource.

```<code>    @Override
    public void executionFinished(final TestIdentifier testIdentifier, final TestExecutionResult testExecutionResult) {
        super.executionFinished(testIdentifier, testExecutionResult);
        logWithThrowable("Execution Finished: %s - %s - %s", testExecutionResult.getThrowable().orElse(null),
                testIdentifier.getDisplayName(), testIdentifier.getUniqueId(), testExecutionResult);
        final Optional<TestSource> source = testIdentifier.getSource();
        if (source.isPresent()) {
            final TestSource testSource = source.get();
            if (testSource instanceof ClassSource) {
               ...
            }
            else if (testSource instanceof MethodSource) {
                final MethodSource methodSource = (MethodSource) testSource;
                LOG.info("MethodSource: executionFinished for class: " + methodSource.getClassName() + " and method: "
                        + methodSource.getMethodName());
                final OmsTestMethod testMethod = getOmsTestMethod(methodSource);
                if (testMethod == null) {
                    return;
                }
                testMethod.setResult(testExecutionResult);
            }
        }
    }
</code>```

I expect to see the method name contain the parameterized values as well so I can differentiate between various tests.

答:
If you have not customized the display name, the display name for a @ParameterizedTest should contain the arguments.

If that is not sufficient for you, feel free to raise an issue here: https://github.com/junit-team/junit5/issues/new/choose

Body:
In my test framework, I have to manually generate the TestSuite.xml.  In Junit4, the "Description" object passed by the listener contains the value of the parameters passed in a parameterized test, so the XML looks like this.

<testcase
  11     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
  12     name="testTransformAndGenerate[77: RegexGenTest: [0-9]{1,28}]"
  13     time="9.1E-4"/>
  14   <testcase
  15     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
  16     name="testTransformAndGenerate[123: RegexGenTest: [A-Za-z0-9 -]{1,64}]"
  17     time="0.0020299999999999997"/>
  18   <testcase
  19     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
  20     name="testTransformAndGenerate[112: RegexGenTest: [A-Za-z0-9 -]{1,31}]"
  21     time="0.00171"/>
  22   <testcase
  23     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
  24     name="testTransformAndGenerate[318: RegexGenTest: \d{37}]"
  25     time="7.3E-4"/>

In JUnit5, I use the TestExecutionListener callback and I get the method name like this:

    @Override
    public void executionFinished(final TestIdentifier testIdentifier, final TestExecutionResult testExecutionResult) {
        super.executionFinished(testIdentifier, testExecutionResult);
        logWithThrowable("Execution Finished: %s - %s - %s", testExecutionResult.getThrowable().orElse(null),
                testIdentifier.getDisplayName(), testIdentifier.getUniqueId(), testExecutionResult);
        final Optional<TestSource> source = testIdentifier.getSource();
        if (source.isPresent()) {
            final TestSource testSource = source.get();
            if (testSource instanceof ClassSource) {
               ...
            }
            else if (testSource instanceof MethodSource) {
                final MethodSource methodSource = (MethodSource) testSource;
                LOG.info("MethodSource: executionFinished for class: " + methodSource.getClassName() + " and method: "
                        + methodSource.getMethodName());
                final OmsTestMethod testMethod = getOmsTestMethod(methodSource);
                if (testMethod == null) {
                    return;
                }
                testMethod.setResult(testExecutionResult);
            }
        }
    }

This method name does not contain the parameters passed in, so the XML looks like this:

<testcase
 12     classname="com.workday.scramble.datagen.generator.regex.generator.RegexGenTest"
 13     name="testTransformAndGenerate"
 14     time="0.00366"/>

I treat the method names as unique, so there is only one entry.

TeamCity goes by the number of testcases in the XML file, so the reporting is wrong.  SummaryGeneratingListener has the number of tests information, but I can't get TeamCity to use that.

Any idea of how to do this?

I have tried the various APIs in MethodSource.

    @Override
    public void executionFinished(final TestIdentifier testIdentifier, final TestExecutionResult testExecutionResult) {
        super.executionFinished(testIdentifier, testExecutionResult);
        logWithThrowable("Execution Finished: %s - %s - %s", testExecutionResult.getThrowable().orElse(null),
                testIdentifier.getDisplayName(), testIdentifier.getUniqueId(), testExecutionResult);
        final Optional<TestSource> source = testIdentifier.getSource();
        if (source.isPresent()) {
            final TestSource testSource = source.get();
            if (testSource instanceof ClassSource) {
               ...
            }
            else if (testSource instanceof MethodSource) {
                final MethodSource methodSource = (MethodSource) testSource;
                LOG.info("MethodSource: executionFinished for class: " + methodSource.getClassName() + " and method: "
                        + methodSource.getMethodName());
                final OmsTestMethod testMethod = getOmsTestMethod(methodSource);
                if (testMethod == null) {
                    return;
                }
                testMethod.setResult(testExecutionResult);
            }
        }
    }

I expect to see the method name contain the parameterized values as well so I can differentiate between various tests.


问:
complex hierarchal SQL query help needed please!
Calling all mySQL gurus!

I am in need of a complex query for mySQL but I can't get my head around it. There are 2 tables in question:

locations

(columns: location_id, parent, location)

Data is split in a hierarchal fashion into Country, Region, County and Town thus:

1, 0, England (country)

2, 1, South West (region)

3, 1, South East (region)

4, 2, Dorset (county)

5, 4, Bournemouth (town)

6, 4, Poole (town)

7, 4, Wimborne (town)

etc up to 400+ rows of location data

profiles

(columns: profile_id, title, location_id)

Each row has one location ID which is ALWAYS a town (ie the last child of). Eg:

1, 'This profile has location set as Bournemouth', 5

2, 'This profile has location set as Poole', 6

etc

What I need to achieve is to return all IDs from the Locations table where itself or it's children have entries associated with it. So in the example above I would need the following location IDs returned: 1, 2, 4, 5, 6

Reasons:

1 - YES, England is parent of South West, Dorset and Bournemouth which has an entry

2 - YES, South West is parent of Dorset and Bournemouth which has an entry

3 - NO, South East has no entries under it or any of it's children

4 - YES, Dorset is parent of Bournemouth which has an entry

5 - YES, Bournemouth has an entry

6 - YES, Poole has an entry

7 - NO, Wimborne has no entries

So, is this actually possible? I attempted to do it in PHP with nested SQL queries but the script timed out so there must be a way to do this just in a SQL query?

Thanking you in advance! :)

===========

UPDATE

After reading through and playing with all these solutions I realised that I was going about the problem completely the wrong way. Instead of going through all the locations and returning those that have entries it makes more sense and is far more efficient to get all the entries and return the corresponding locations and then go up the hierarchy to get each location parent until the root is hit.

Thank you very much for your help, it at least made me realise that what I was attempting was unnecessary.

答:
Not sure if I fully understand your requirements but the following stored procedure example might be a good starting point for you:

Example calls (note the included column)

```<code>mysql> call location_hier(1);
+-------------+---------------------+--------------------+---------------------+-------+----------+
| location_id | location            | parent_location_id | parent_location     | depth | included |
+-------------+---------------------+--------------------+---------------------+-------+----------+
|           1 | England (country)   |               NULL | NULL                |     0 |        1 |
|           2 | South West (region) |                  1 | England (country)   |     1 |        1 |
|           3 | South East (region) |                  1 | England (country)   |     1 |        0 |
|           4 | Dorset (county)     |                  2 | South West (region) |     2 |        1 |
|           5 | Bournemouth (town)  |                  4 | Dorset (county)     |     3 |        1 |
|           6 | Poole (town)        |                  4 | Dorset (county)     |     3 |        1 |
|           7 | Wimborne (town)     |                  4 | Dorset (county)     |     3 |        0 |
+-------------+---------------------+--------------------+---------------------+-------+----------+
7 rows in set (0.00 sec)
</code>```

You'd call the stored procedure from php as follows:

```<code>$startLocationID = 1;
$result = $conn->query(sprintf("call location_hier(%d)", $startLocationID));
</code>```

Full script:

http://pastie.org/1785995

```<code>drop table if exists profiles;
create table profiles
(
profile_id smallint unsigned not null auto_increment primary key,
location_id smallint unsigned null,
key (location_id)
)
engine = innodb;

insert into profiles (location_id) values (5),(6);

drop table if exists locations;
create table locations
(
location_id smallint unsigned not null auto_increment primary key,
location varchar(255) not null,
parent_location_id smallint unsigned null,
key (parent_location_id)
)
engine = innodb;

insert into locations (location, parent_location_id) values
('England (country)',null),
    ('South West (region)',1),
    ('South East (region)',1),
        ('Dorset (county)',2),
            ('Bournemouth (town)',4),
            ('Poole (town)',4),
            ('Wimborne (town)',4);

drop procedure if exists location_hier;
delimiter #

create procedure location_hier
(
in p_location_id smallint unsigned
)
begin

declare v_done tinyint unsigned default 0;
declare v_depth smallint unsigned default 0;

create temporary table hier(
 parent_location_id smallint unsigned,
 location_id smallint unsigned,
 depth smallint unsigned default 0,
 included tinyint unsigned default 0,
 primary key (location_id),
 key (parent_location_id)
)engine = memory;

insert into hier select parent_location_id, location_id, v_depth, 0 from locations where location_id = p_location_id;
create temporary table tmp engine=memory select * from hier;

/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */

while not v_done do

    if exists( select 1 from locations c
        inner join tmp on c.parent_location_id = tmp.location_id and tmp.depth = v_depth) then

        insert into hier select c.parent_location_id, c.location_id, v_depth + 1, 0 from locations c
            inner join tmp on c.parent_location_id = tmp.location_id and tmp.depth = v_depth;

    update hier inner join tmp on hier.location_id = tmp.parent_location_id
    set hier.included = 1;

        set v_depth = v_depth + 1;

        truncate table tmp;
        insert into tmp select * from hier where depth = v_depth;

    else
        set v_done = 1;
    end if;

end while;

update hier inner join tmp on hier.location_id = tmp.parent_location_id
set hier.included = 1;

-- include any locations that have profiles ???

update hier inner join profiles on hier.location_id = profiles.location_id
set hier.included = 1;

-- output the results

select
 c.location_id,
 c.location as location,
 p.location_id as parent_location_id,
 p.location as parent_location,
 hier.depth,
 hier.included
from
 hier
inner join locations c on hier.location_id = c.location_id
left outer join locations p on hier.parent_location_id = p.location_id
-- where included = 1 -- filter in your php or here up to you !
order by
 hier.depth;

-- clean up

drop temporary table if exists hier;
drop temporary table if exists tmp;

end #

delimiter ;

call location_hier(1);
</code>```

Hope this helps :)

ContentLicense: CC BY-SA 3.0

Body:
Not sure if I fully understand your requirements but the following stored procedure example might be a good starting point for you:

Example calls (note the included column)

mysql> call location_hier(1);
+-------------+---------------------+--------------------+---------------------+-------+----------+
| location_id | location            | parent_location_id | parent_location     | depth | included |
+-------------+---------------------+--------------------+---------------------+-------+----------+
|           1 | England (country)   |               NULL | NULL                |     0 |        1 |
|           2 | South West (region) |                  1 | England (country)   |     1 |        1 |
|           3 | South East (region) |                  1 | England (country)   |     1 |        0 |
|           4 | Dorset (county)     |                  2 | South West (region) |     2 |        1 |
|           5 | Bournemouth (town)  |                  4 | Dorset (county)     |     3 |        1 |
|           6 | Poole (town)        |                  4 | Dorset (county)     |     3 |        1 |
|           7 | Wimborne (town)     |                  4 | Dorset (county)     |     3 |        0 |
+-------------+---------------------+--------------------+---------------------+-------+----------+
7 rows in set (0.00 sec)

You'd call the stored procedure from php as follows:

$startLocationID = 1;
$result = $conn->query(sprintf("call location_hier(%d)", $startLocationID));

Full script:

http://pastie.org/1785995

drop table if exists profiles;
create table profiles
(
profile_id smallint unsigned not null auto_increment primary key,
location_id smallint unsigned null,
key (location_id)
)
engine = innodb;

insert into profiles (location_id) values (5),(6);

drop table if exists locations;
create table locations
(
location_id smallint unsigned not null auto_increment primary key,
location varchar(255) not null,
parent_location_id smallint unsigned null,
key (parent_location_id)
)
engine = innodb;

insert into locations (location, parent_location_id) values
('England (country)',null),
    ('South West (region)',1),
    ('South East (region)',1),
        ('Dorset (county)',2),
            ('Bournemouth (town)',4),
            ('Poole (town)',4),
            ('Wimborne (town)',4);

drop procedure if exists location_hier;
delimiter #

create procedure location_hier
(
in p_location_id smallint unsigned
)
begin

declare v_done tinyint unsigned default 0;
declare v_depth smallint unsigned default 0;

create temporary table hier(
 parent_location_id smallint unsigned,
 location_id smallint unsigned,
 depth smallint unsigned default 0,
 included tinyint unsigned default 0,
 primary key (location_id),
 key (parent_location_id)
)engine = memory;

insert into hier select parent_location_id, location_id, v_depth, 0 from locations where location_id = p_location_id;
create temporary table tmp engine=memory select * from hier;

/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */

while not v_done do

    if exists( select 1 from locations c
        inner join tmp on c.parent_location_id = tmp.location_id and tmp.depth = v_depth) then

        insert into hier select c.parent_location_id, c.location_id, v_depth + 1, 0 from locations c
            inner join tmp on c.parent_location_id = tmp.location_id and tmp.depth = v_depth;

    update hier inner join tmp on hier.location_id = tmp.parent_location_id
    set hier.included = 1;

        set v_depth = v_depth + 1;

        truncate table tmp;
        insert into tmp select * from hier where depth = v_depth;

    else
        set v_done = 1;
    end if;

end while;

update hier inner join tmp on hier.location_id = tmp.parent_location_id
set hier.included = 1;

-- include any locations that have profiles ???

update hier inner join profiles on hier.location_id = profiles.location_id
set hier.included = 1;

-- output the results

select
 c.location_id,
 c.location as location,
 p.location_id as parent_location_id,
 p.location as parent_location,
 hier.depth,
 hier.included
from
 hier
inner join locations c on hier.location_id = c.location_id
left outer join locations p on hier.parent_location_id = p.location_id
-- where included = 1 -- filter in your php or here up to you !
order by
 hier.depth;

-- clean up

drop temporary table if exists hier;
drop temporary table if exists tmp;

end #

delimiter ;

call location_hier(1);

Hope this helps :)


问:
How can I return symbols based on the sum of lists?
So I am new to Scheme and have encountered a problem. What I am trying to do is the following. It's a rather simple problem nevertheless I am receiving several errors:

I try to sum up the elements of lists (which only consists of numbers). If the total amount is even, the procedure should return <'divisible_by_2>.
If the total amount is odd, it should return <'not_divisible_by_2>.

The initial sstep was to build a procedure that sums up the lists. This one works. The second step was to build an if function which takes the sum of lists and returns <'divisible_by_2> if the sum is even and <'not_divisible_by_2> if it is odd.

What I wrote so far:

```<code>(define (divisible_or_not list-sum lst)

(if (odd? list-sum lst)
  (lambda (list-sum lst)
                        (cond
                          ((null? lst)
                           0)
                          ((pair? (car lst))
                           (+(list-sum (car lst)) (list-sum (cdr lst)))
                          (else
                           (+ (car lst) (list-sum (cdr lst)))
                          )
                          )
                        )
    ('divisible_by_2)
    ('not_divisible_by_2)
  )
)
</code>```

)

Version 2.0 (lst=tree; tree-count=sum-lst):

```<code>(define (divisible-or-not tree)
  (define (tree-count tree)
    (cond
      ((null? tree)
        0)
      ((pair? (car tree))
        (+(tree-count (car tree)) (tree-count (cdr tree)))
      (else
        (+ (car tree) (tree-count (cdr tree))))))
  (if (odd? tree-count tree)
    ('divisible-by-2)
    ('not-divisible-by-2))))
</code>```

答:
Your code, properly indented, looks like so:

```<code>(define (divisible_or_not list-sum lst)
  (if (odd? list-sum lst)
      (lambda (list-sum lst)
        (cond
         ((null? lst)
          0)
         ((pair? (car lst))
          (+(list-sum (car lst)) (list-sum (cdr lst)))
          (else
           (+ (car lst) (list-sum (cdr lst))))))
        ('divisible_by_2)
        ('not_divisible_by_2))))
</code>```

The structure of your program looks like this:

```<code>(if ...
  (lambda (...) ...))
</code>```

In other words, if your test succeeds, you return an anonymous function, and if the test fails, you return nothing (in Scheme, the value is undefined in that case).

Inside your lambda, the code is a list of three expressions, a cond, the form ('divisible_by_2) and the form ('not_divisible_by_2).

First of all, do not use underscores for separating words in Lisp/Scheme, use dashes, like so: divisible-by-2.

Secondly, only the last expression's value is returned from the lambda, so the intermediate cond, since it has no side-effect, is basically doing work for nothing. The second form, ('divisible_by_2), looks like a function call but is going to give you an error. If you want to return a symbol, just quote it, without parentheses: 'divisible-by-2.

Since you already have an intermediate function, you can associate it to a name:

```<code>(define tree-count (sum tree)
  (cond ...))
</code>```

I named it tree-count because you also recurse into the car of your lists.

Once you have this function, you only need to apply it:

```<code>(if (even? (tree-count tree))
    'divisible-by-2
    'not-divisible-by-2)
</code>```

Body:
So I am new to Scheme and have encountered a problem. What I am trying to do is the following. It's a rather simple problem nevertheless I am receiving several errors:

I try to sum up the elements of lists (which only consists of numbers). If the total amount is even, the procedure should return <'divisible_by_2>.
If the total amount is odd, it should return <'not_divisible_by_2>.

The initial sstep was to build a procedure that sums up the lists. This one works. The second step was to build an if function which takes the sum of lists and returns <'divisible_by_2> if the sum is even and <'not_divisible_by_2> if it is odd.

What I wrote so far:

(define (divisible_or_not list-sum lst)

(if (odd? list-sum lst)
  (lambda (list-sum lst)
                        (cond
                          ((null? lst)
                           0)
                          ((pair? (car lst))
                           (+(list-sum (car lst)) (list-sum (cdr lst)))
                          (else
                           (+ (car lst) (list-sum (cdr lst)))
                          )
                          )
                        )
    ('divisible_by_2)
    ('not_divisible_by_2)
  )
)

)

Version 2.0 (lst=tree; tree-count=sum-lst):

(define (divisible-or-not tree)
  (define (tree-count tree)
    (cond
      ((null? tree)
        0)
      ((pair? (car tree))
        (+(tree-count (car tree)) (tree-count (cdr tree)))
      (else
        (+ (car tree) (tree-count (cdr tree))))))
  (if (odd? tree-count tree)
    ('divisible-by-2)
    ('not-divisible-by-2))))

Body:
Your code, properly indented, looks like so:

(define (divisible_or_not list-sum lst)
  (if (odd? list-sum lst)
      (lambda (list-sum lst)
        (cond
         ((null? lst)
          0)
         ((pair? (car lst))
          (+(list-sum (car lst)) (list-sum (cdr lst)))
          (else
           (+ (car lst) (list-sum (cdr lst))))))
        ('divisible_by_2)
        ('not_divisible_by_2))))

The structure of your program looks like this:

(if ...
  (lambda (...) ...))

In other words, if your test succeeds, you return an anonymous function, and if the test fails, you return nothing (in Scheme, the value is undefined in that case).

Inside your lambda, the code is a list of three expressions, a cond, the form ('divisible_by_2) and the form ('not_divisible_by_2).

First of all, do not use underscores for separating words in Lisp/Scheme, use dashes, like so: divisible-by-2.

Secondly, only the last expression's value is returned from the lambda, so the intermediate cond, since it has no side-effect, is basically doing work for nothing. The second form, ('divisible_by_2), looks like a function call but is going to give you an error. If you want to return a symbol, just quote it, without parentheses: 'divisible-by-2.

Since you already have an intermediate function, you can associate it to a name:

(define tree-count (sum tree)
  (cond ...))

I named it tree-count because you also recurse into the car of your lists.

Once you have this function, you only need to apply it:

(if (even? (tree-count tree))
    'divisible-by-2
    'not-divisible-by-2)


问:
PyCharm 2019.01 and Anaconda 3 Don't Work Together
I recently upgraded to the latest version of PyCharm (2019.01) and my Anaconda 3 install no longer starts up in the Python Console. I get the following error:

```<code>Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\pydevconsole.py", line 5, in <module>
    from _pydev_comm.rpc import make_rpc_client, start_rpc_server, start_rpc_server_and_make_client
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_comm\rpc.py", line 4, in <module>
    from _pydev_comm.server import TSingleThreadedServer
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_comm\server.py", line 4, in <module>
    from _shaded_thriftpy.server import TServer
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\server.py", line 9, in <module>
    from _shaded_thriftpy.transport import (
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\transport\__init__.py", line 57, in <module>
    from .sslsocket import TSSLSocket, TSSLServerSocket  # noqa
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\transport\sslsocket.py", line 7, in <module>
    import ssl
  File "C:\Users\bnielson\AppData\Local\Continuum\anaconda3\lib\ssl.py", line 98, in <module>
    import _ssl             # if we can't import it, let the error propagate
ImportError: DLL load failed: The specified module could not be found.
</code>```

I have Googled this and there are a number of sites that talk about similar errors but none of their fixes have worked for me so far.

Strangely, I can go to the Terminal tab and start up Anaconda 3's Python Manually and this works just fine.

I have tried uninstalling and reinstalling Anaconda 3 and PyCharm. I have tried not importing previous settings so that I'm getting a fresh start. None of this has worked.

Anaconda 2.7 works just fine.

I tried this link already:

Python 3.7 anaconda environment - import _ssl DLL load fail error

I'm not even clear why I'd be getting this error in the first place, so it's hard to troubleshoot.

Note: I am intentionally trying to start up Anaconda 3 as originally installed and not a Conda or Virtual Environment (as this loses all the installed items that come as default.)

I am on Windows.

答: Try PyCharm 2019.1.3 RC build. The problem should be fixed there I believe (PY-35141).</p>

Body:
I recently upgraded to the latest version of PyCharm (2019.01) and my Anaconda 3 install no longer starts up in the Python Console. I get the following error:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\pydevconsole.py", line 5, in <module>
    from _pydev_comm.rpc import make_rpc_client, start_rpc_server, start_rpc_server_and_make_client
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_comm\rpc.py", line 4, in <module>
    from _pydev_comm.server import TSingleThreadedServer
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_comm\server.py", line 4, in <module>
    from _shaded_thriftpy.server import TServer
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\server.py", line 9, in <module>
    from _shaded_thriftpy.transport import (
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\transport\__init__.py", line 57, in <module>
    from .sslsocket import TSSLSocket, TSSLServerSocket  # noqa
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\third_party\thriftpy\_shaded_thriftpy\transport\sslsocket.py", line 7, in <module>
    import ssl
  File "C:\Users\bnielson\AppData\Local\Continuum\anaconda3\lib\ssl.py", line 98, in <module>
    import _ssl             # if we can't import it, let the error propagate
ImportError: DLL load failed: The specified module could not be found.

I have Googled this and there are a number of sites that talk about similar errors but none of their fixes have worked for me so far.

Strangely, I can go to the Terminal tab and start up Anaconda 3's Python Manually and this works just fine.

I have tried uninstalling and reinstalling Anaconda 3 and PyCharm. I have tried not importing previous settings so that I'm getting a fresh start. None of this has worked.

Anaconda 2.7 works just fine.

I tried this link already:

Python 3.7 anaconda environment - import _ssl DLL load fail error

I'm not even clear why I'd be getting this error in the first place, so it's hard to troubleshoot.

Note: I am intentionally trying to start up Anaconda 3 as originally installed and not a Conda or Virtual Environment (as this loses all the installed items that come as default.)

I am on Windows.


问:
Login \ Registration redirection
I created login\registration form for user. My problem is that when I login I get an error:

Page not found (404) Request Method:  GET Request
  URL:  http://127.0.0.1:8000/accounts/profile/

If login is successful it should redirect me to "home.html". If I login I came to an error above and if I hit "Back" button in browser I am redirected on my "Home.html" and I am successfully logged in.
My other problem is that when I loggout I am redirected to DJANGO default logout page instead of mine "logged_out.html".

Views.py

```<code>@login_required
def home(request):
    return render(request, 'home.html')

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'signup.html', {'form': form})
</code>```

Urls.py

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.home, name='home'),
    url(r'^login/$', auth_views.LoginView.as_view(), {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', auth_views.LogoutView.as_view(), {'next_page': 'login'}, name='logout'),
    url(r'^signup/$', views.signup, name='signup'),
]
</code>```

login.html

```<code>{% extends 'base.html' %}

{% block content %}
  <h2>Log in to My Site</h2>
  {% if form.errors %}
    <p style="color: red">Your username and password didn't match. Please try again.</p>
  {% endif %}
  <form method="post">
    {% csrf_token %}
    <input type="hidden" name="next" value="{{ next }}" />
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}<br>
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
        {% if field.help_text %}
          <p><small style="color: grey">{{ field.help_text }}</small></p>
        {% endif %}
      </p>
    {% endfor %}
    <button type="submit">Log in</button>
    <a href="{% url 'signup' %}">New to My Site? Sign up</a>
  </form>
{% endblock %}
</code>```

logged_out.html

```<code>{% extends 'base.html' %}

{% block content %}
  <h2>Why are You leaving :(</h2>
{% endblock %}
</code>```

base.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>{% block title %}Simple is Better Than Complex{% endblock %}</title>
  </head>
  <body>
    <header>
      <h1>My Site</h1>
      {% if user.is_authenticated %}
        <a href="{% url 'logout' %}">logout</a>
      {% else %}
        <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a>
      {% endif %}
      <hr>
    </header>
    <main>
      {% block content %}
      {% endblock %}
    </main>
  </body>
</html>
</code>```

home.html

```<code>{% extends 'base.html' %}

{% block content %}
  <h2>Welcome, {{ user.username }}!</h2>
  {% if request.user.is_staff %}
    <a href="{% url 'admin:index' %}">link to admin panel</a>
    <!--<a href="{% url 'signup' %}">Admin</a>-->
  {% endif %}
{% endblock %}
</code>```

答:
```<code>LOGIN_REDIRECT_URL = '/'
</code>```

you need to put this in your settings.py file as you are using django's inbuilt login system, Django always looks for a url 'profile'

Title: Login \ Registration redirection

Body:
I created login\registration form for user. My problem is that when I login I get an error:

Page not found (404) Request Method:  GET Request
  URL:  http://127.0.0.1:8000/accounts/profile/

If login is successful it should redirect me to "home.html". If I login I came to an error above and if I hit "Back" button in browser I am redirected on my "Home.html" and I am successfully logged in.
My other problem is that when I loggout I am redirected to DJANGO default logout page instead of mine "logged_out.html".

Views.py

@login_required
def home(request):
    return render(request, 'home.html')

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'signup.html', {'form': form})

Urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.home, name='home'),
    url(r'^login/$', auth_views.LoginView.as_view(), {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', auth_views.LogoutView.as_view(), {'next_page': 'login'}, name='logout'),
    url(r'^signup/$', views.signup, name='signup'),
]

login.html

{% extends 'base.html' %}

{% block content %}

Log in to My Site

  {% if form.errors %}

Your username and password didn't match. Please try again.

  {% endif %}
  <form method="post">
    {% csrf_token %}
    <input type="hidden" name="next" value="{{ next }}" />
    {% for field in form %}

        {{ field.label_tag }}

        {{ field }}

        {% for error in field.errors %}

{{ error }}

        {% endfor %}
        {% if field.help_text %}

{{ field.help_text }}

        {% endif %}

    {% endfor %}
    <button type="submit">Log in</button>
    New to My Site? Sign up
  </form>
{% endblock %}

logged_out.html

{% extends 'base.html' %}

{% block content %}

Why are You leaving :(

{% endblock %}

base.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>{% block title %}Simple is Better Than Complex{% endblock %}</title>

My Site

      {% if user.is_authenticated %}
        logout
      {% else %}
        login / signup
      {% endif %}

      {% block content %}
      {% endblock %}

home.html

{% extends 'base.html' %}

{% block content %}

Welcome, {{ user.username }}!

  {% if request.user.is_staff %}
    link to admin panel

  {% endif %}
{% endblock %}

Body:
LOGIN_REDIRECT_URL = '/'

you need to put this in your settings.py file as you are using django's inbuilt login system, Django always looks for a url 'profile'


问:
Is there any way to automatically Delete/Remove Push notification after 2 hours in iOS?
I tried many ways to do that from the app and from the server but didn't get success.</p>

答:
Managing Delivered Notifications

When local and remote notifications are not handled directly by your app or the user, they are displayed in Notification Center so that they can be viewed later. Use the getDeliveredNotificationsWithCompletionHandler: method of the shared UNUserNotificationCenter object to get a list of notifications still being displayed in Notification Center. If you find any notifications that are now outdated and should not be displayed to the user, you can remove them using the removeDeliveredNotificationsWithIdentifiers: method.

https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html#//apple_ref/doc/uid/TP40008194-CH4-SW1

Send a silent push notification in which you have to get all the notifications of your app from notification canter and remove them according to your need.


问:
woocommerce hook add to cart button and save custom fields
I first followed the guideline to override the single product page by creating a woocommerce folder in my theme root, then created a single.product.php, and inside this file, I added the following:

```<code><div class="product-content flex">
    <figure class="thumbnail">
        <?php the_post_thumbnail(); ?>
    </figure>
    <main id="product-content">
        <h1><?php the_title(); ?></h1>
        <p>R <?php echo get_post_meta( get_the_ID(), '_regular_price', true); ?></p>
        <div class="description">
            <?php the_content();  ?>
        </div>
        <div class="flex size">
            <span>Product size</span>
            <select name="product_size" id="product_size">
                <option value="small">Small</option>
                <option value="medium">Medium</option>
                <option value="large">Large</option>
            </select>
        </div>
        <div class="flex quantity">
            <span>Quantity</span>
            <input type="number" name="quanitity" id="product_quantity">
        </div>
    </main>
</div>
</code>```

First: how can I now hook up the add to cart button?
Lastly, after hooking the add to cart, how can I save the size and quantity?

答:
You can use the below code for add to cart button</p>

```<code><a href="<?php
          $add_to_cart = do_shortcode('[add_to_cart_url id="'.get_the_ID().'"]');
          echo $add_to_cart;
?>" class="more">Buy now</a>
</code>```

Body:
I first followed the guideline to override the single product page by creating a woocommerce folder in my theme root, then created a single.product.php, and inside this file, I added the following:

        <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

R <?php echo get_post_meta( get_the_ID(), '_regular_price', true); ?>

            <?php the_content();  ?>

            Product size
            <select name="product_size" id="product_size">
                <option value="small">Small</option>
                <option value="medium">Medium</option>
                <option value="large">Large</option>
            </select>

            Quantity
            <input type="number" name="quanitity" id="product_quantity">

First: how can I now hook up the add to cart button?
Lastly, after hooking the add to cart, how can I save the size and quantity?

Body:
You can use the below code for add to cart button

<a href="<?php
          $add_to_cart = do_shortcode('[add_to_cart_url id="'.get_the_ID().'"]');
          echo $add_to_cart;
?>" class="more">Buy now</a>


问:
Flutter compiler error when installing location 2.3.5 package
I installed the: flutter package - location 2.3.5
https://pub.dev/packages/location

And when I try to run the application I get a compilation error:

```<code>* What went wrong:
Execution failed for task ':location:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
</code>```

And here is the full error

```<code>Launching lib\main.dart on Android SDK built for x86 in debug mode...

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:15: error: cannot find symbol
import androidx.annotation.MainThread;

                          ^
  symbol:   class MainThread
  location: package androidx.annotation

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:16: error: cannot find symbol
import androidx.annotation.NonNull;
                          ^
  symbol:   class NonNull

  location: package androidx.annotation
C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:17: error: cannot find symbol
import androidx.annotation.Nullable;

                          ^
  symbol:   class Nullable
  location: package androidx.annotation

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:18: error: package androidx.core.app does not exist
import androidx.core.app.ActivityCompat;
                        ^

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:19: error: package androidx.core.content does not exist
import androidx.core.content.ContextCompat;
                            ^

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:357: error: cannot find symbol
        this.locationPermissionState = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
                                       ^
  symbol:   variable ActivityCompat

  location: class LocationPlugin

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:362: error: cannot find symbol
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},

        ^
  symbol:   variable ActivityCompat
  location: class LocationPlugin

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:367: error: cannot find symbol
        return ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION);
               ^
  symbol:   variable ActivityCompat
  location: class LocationPlugin

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:405: error: cannot find symbol
                public void onFailure(@NonNull Exception e) {
                                       ^
  symbol: class NonNull
C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:438: error: cannot find symbol

                    public void onFailure(@NonNull Exception e) {
                                           ^
  symbol: class NonNull
10 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':location:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s

*******************************************************************************************

The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
See for more information on the problem and how to fix it.
*******************************************************************************************

Gradle task assembleDebug failed with exit code 1

Exited (sigterm)

</code>```

I did all the steps of the installation.

I created a new project just with this location package

I run: flutter clear

I updated flutter to the latest version

I updated android studio to the latest version

I updated android SDK

Nothing helped

Here is my android/build.gradle file:

```<code>buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.50'
        classpath 'com.google.gms:google-services:4.2.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```

Here is my android/gradle.properties file:

```<code>org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
</code>```

Here is my android/app/src/build.gradle file:

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.flutter_course"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
    configurations.all {
        resolutionStrategy.force 'com.android.support:support-compat:27.1.1'
        resolutionStrategy.force 'com.android.support:appcompat-v7:27.1.1'
        resolutionStrategy.force 'com.android.support:support-v4:27.1.1'
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation "com.android.support:support-v4:27.1.1"
}

</code>```

Here is my root/pubspec.yaml file:

```<code>name: flutter_course
description: A new Flutter project.

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.0
  scoped_model: ^1.0.1
  http: ^0.12.0+2
  shared_preferences: ^0.5.2+1
  rxdart: ^0.22.0
  map_view: ^0.0.14
  location: ^2.3.5

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/food.jpg
    - assets/background.jpg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.io/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.io/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  fonts:
    - family: Oswald
      fonts:
        - asset: assets/Oswald-Bold.ttf
          weight: 700
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.io/custom-fonts/#from-packages

</code>```

What can be the problem?

And how can I fix it?

答:
replying to first issue reported "cannot find symbol
import androidx.annotation.NonNull;" not just it any other issue related to non null symbol not found. It could be a issue related to java version that is installed in your machine. It might occur when you are using latest java version such 11 or you are are using very old dependency.

I am replying issue general to adding new dependency and compile related issue in flutter not to location. Hope it helps.

Body:
I installed the: flutter package - location 2.3.5
https://pub.dev/packages/location

And when I try to run the application I get a compilation error:

* What went wrong:
Execution failed for task ':location:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

And here is the full error

Launching lib\main.dart on Android SDK built for x86 in debug mode...

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:15: error: cannot find symbol
import androidx.annotation.MainThread;

                          ^
  symbol:   class MainThread
  location: package androidx.annotation

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:16: error: cannot find symbol
import androidx.annotation.NonNull;
                          ^
  symbol:   class NonNull

  location: package androidx.annotation
C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:17: error: cannot find symbol
import androidx.annotation.Nullable;

                          ^
  symbol:   class Nullable
  location: package androidx.annotation

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:18: error: package androidx.core.app does not exist
import androidx.core.app.ActivityCompat;
                        ^

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:19: error: package androidx.core.content does not exist
import androidx.core.content.ContextCompat;
                            ^

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:357: error: cannot find symbol
        this.locationPermissionState = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
                                       ^
  symbol:   variable ActivityCompat

  location: class LocationPlugin

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:362: error: cannot find symbol
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},

        ^
  symbol:   variable ActivityCompat
  location: class LocationPlugin

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:367: error: cannot find symbol
        return ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION);
               ^
  symbol:   variable ActivityCompat
  location: class LocationPlugin

C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:405: error: cannot find symbol
                public void onFailure(@NonNull Exception e) {
                                       ^
  symbol: class NonNull
C:\flutter\.pub-cache\hosted\pub.dartlang.org\location-2.3.5\android\src\main\java\com\lyokone\location\LocationPlugin.java:438: error: cannot find symbol

                    public void onFailure(@NonNull Exception e) {
                                           ^
  symbol: class NonNull
10 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':location:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s

*******************************************************************************************

The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
See for more information on the problem and how to fix it.
*******************************************************************************************

Gradle task assembleDebug failed with exit code 1

Exited (sigterm)

I did all the steps of the installation.

I created a new project just with this location package

I run: flutter clear

I updated flutter to the latest version

I updated android studio to the latest version

I updated android SDK

Nothing helped

Here is my android/build.gradle file:

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.50'
        classpath 'com.google.gms:google-services:4.2.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Here is my android/gradle.properties file:

org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true

Here is my android/app/src/build.gradle file:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.flutter_course"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
    configurations.all {
        resolutionStrategy.force 'com.android.support:support-compat:27.1.1'
        resolutionStrategy.force 'com.android.support:appcompat-v7:27.1.1'
        resolutionStrategy.force 'com.android.support:support-v4:27.1.1'
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation "com.android.support:support-v4:27.1.1"
}

Here is my root/pubspec.yaml file:

name: flutter_course
description: A new Flutter project.

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.0
  scoped_model: ^1.0.1
  http: ^0.12.0+2
  shared_preferences: ^0.5.2+1
  rxdart: ^0.22.0
  map_view: ^0.0.14
  location: ^2.3.5

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/food.jpg
    - assets/background.jpg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.io/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.io/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  fonts:
    - family: Oswald
      fonts:
        - asset: assets/Oswald-Bold.ttf
          weight: 700
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.io/custom-fonts/#from-packages

What can be the problem?

And how can I fix it?


问:
Disable (GitGutter) message about commit on Sublime Text
Sublime Text is showing a message about git commit.
It appears in the middle of source code but is not part of it and totally confuses myself. Its like an annotation and message reads like:

```<code>Commit author (a day ago) - Commit message
</code>```

Please, how to remove that?

I'm pretty sure it comes from GitGutter package (https://jisaacks.github.io/GitGutter/settings/) because it stops appearing when I disable the package for view. But could not find any reference about this feature.

答:
Set "show_line_annotation": "auto" to "show_line_annotation": false.

There is section Line Annotation in document where you can edit template shown or disable it.

Body:
Sublime Text is showing a message about git commit.
It appears in the middle of source code but is not part of it and totally confuses myself. Its like an annotation and message reads like:

Commit author (a day ago) - Commit message

Please, how to remove that?

I'm pretty sure it comes from GitGutter package (https://jisaacks.github.io/GitGutter/settings/) because it stops appearing when I disable the package for view. But could not find any reference about this feature.


问:
Append values from dataframe column to list
I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

```<code>empty_list = [value_1,value_2,value_3...]
</code>```

I have tried the following:

```<code>df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())
</code>```

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

答:
This example should be enough:

```<code>myList = df['iso'].tolist()
print(myList)
</code>```

Output:

['x', 'y', 'z', 'w']

Body:
I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

empty_list = [value_1,value_2,value_3...]

I have tried the following:

df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

Body:
This example should be enough:

myList = df['iso'].tolist()
print(myList)

Output:

['x', 'y', 'z', 'w']


问:
Why doesn't gcloud app deploy include my custom made module?
In my Node application script I require a custom made module which has its own dependencies. In local development this all works fine and everything works as expected. However, when I want to deploy my application as a whole through gcloud app deploy the following error occurs:

```

Updating service [myapp]...failed.
ERROR: (gcloud.app.deploy) Error Response: [9]
Application startup error:

> myapp@1.0.0 start /app
> node server.js

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module 'mycustommodule'

```

Does this have anything to do with that maybe gcloud tries to download all node modules for itself from the NPM server and therefore obviously can't find my local module? I can't figure out how to include my own node modules (that also have their own dependencies).

I thank you for thinking along with me in advance.
Help is much appreciated.

答:
When you run the gcloud app deploy command, the SDK automatically creates a .gcloudignore file that pretty much works like .gitignore and filters out some files or directories that won't be deployed.

.gcloudignore by defaults include the node_modules/ directory so your installed dependencies aren't uploaded alongside your code. You can remove this entry from the .gcloudignore and try to deploy again.

Body:
In my Node application script I require a custom made module which has its own dependencies. In local development this all works fine and everything works as expected. However, when I want to deploy my application as a whole through gcloud app deploy the following error occurs:

Updating service [myapp]...failed.
ERROR: (gcloud.app.deploy) Error Response: [9]
Application startup error:

> myapp@1.0.0 start /app
> node server.js

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module 'mycustommodule'

Does this have anything to do with that maybe gcloud tries to download all node modules for itself from the NPM server and therefore obviously can't find my local module? I can't figure out how to include my own node modules (that also have their own dependencies).

I thank you for thinking along with me in advance.
Help is much appreciated.