问:
Turning NUMLOCK on at the end of a macro run
What code does: I have a code that moves the mouse around the screen, takes printscreens and pastes it to excel.

Problem: For some reason, my code always (with absolutely no exceptions) turns the NUMLOCK key off after every run.

What I tried so far: I searched around and found the SendKeys (NUMLOCK), which in theory works (although it seems to be very problematic for users).

What I want to do: I want to turn the NUMLOCK on after each macro run,

Obs1: I have no idea what is causing the macro to turn it off in the first place. Fixing whatever is causing this would be ideal, but since I have no idea what the problem is, I first want to get my code functional. I am going to work on that as soon as find a way to turn the NUMLOCK key on.

Question: Can I do this using the SendKeys? Am I using it properly? Is there a better way?

Obs2: Since it is a much bigger code, as soon as this is solved, I am going to post another question with the entire code, and go over on what is causing the problem.

Code I am trying to sue to turn numlock on:

```<code>Application.Sendkeys (NUMLOCK)
</code>```

Also tried:

```<code>Application.Sendkeys ("NUMLOCK")
</code>```

and

```<code>Application.Sendkeys {NUMLOCK}
</code>```

答:
I found this solution so far the best and does not interfere with NUMLOCK.
Put below code in a module and call it from anywhere in your project. The script object overwrites the SendKeys in VBA.

```<code>Public Sub Sendkeys(text as variant, Optional wait As Boolean = False)
   Dim WshShell As Object
   Set WshShell = CreateObject("wscript.shell")
   WshShell.Sendkeys cstr(text), wait
   Set WshShell = Nothing
End Sub
</code>```

I found it in below thread:

SendKeys() permission denied error in Visual Basic

Body:
What code does: I have a code that moves the mouse around the screen, takes printscreens and pastes it to excel.

Problem: For some reason, my code always (with absolutely no exceptions) turns the NUMLOCK key off after every run.

What I tried so far: I searched around and found the SendKeys (NUMLOCK), which in theory works (although it seems to be very problematic for users).

What I want to do: I want to turn the NUMLOCK on after each macro run,

Obs1: I have no idea what is causing the macro to turn it off in the first place. Fixing whatever is causing this would be ideal, but since I have no idea what the problem is, I first want to get my code functional. I am going to work on that as soon as find a way to turn the NUMLOCK key on.

Question: Can I do this using the SendKeys? Am I using it properly? Is there a better way?

Obs2: Since it is a much bigger code, as soon as this is solved, I am going to post another question with the entire code, and go over on what is causing the problem.

Code I am trying to sue to turn numlock on:

Application.Sendkeys (NUMLOCK)

Also tried:

Application.Sendkeys ("NUMLOCK")

and

Application.Sendkeys {NUMLOCK}

Body:
I found this solution so far the best and does not interfere with NUMLOCK.
Put below code in a module and call it from anywhere in your project. The script object overwrites the SendKeys in VBA.

Public Sub Sendkeys(text as variant, Optional wait As Boolean = False)
   Dim WshShell As Object
   Set WshShell = CreateObject("wscript.shell")
   WshShell.Sendkeys cstr(text), wait
   Set WshShell = Nothing
End Sub

I found it in below thread:

SendKeys() permission denied error in Visual Basic


来源: stackexchange

问:
How do i write a function in JavaScript that compares two trees defined by TreeNodes a and b?
I'm trying to write a JavaScript function that compares two binary trees defined by TreeNodes a and b and returns true if they are equal in structure and in value and false otherwise.

for example example of comparing both values and structure of two binary trees

Given the following class:

```<code>class TreeNode {
  constructor(data, left=null, right=null) {
    this.data = data;
    this.left = left;
    this.right = right;
  }
}
</code>```

Here is the code i tried writing so far comapring TreeNode a and b.

```<code>const binaryTreeCompare = (a, b) => {
  if(a==null && b==null){
    return true;
  }else if(a!=null && b!=null){
    return(
      a.data == b.data && binaryTreeCompare(a.left, b.left) && binaryTreeCompare(a.right, b.right)
    );
  }
    else return false;
}
</code>```

I expected an ouput of either true or false but this is what i get:

```<code>ReferenceError: compare is not defined
    at Context.it (test.js:116:16)
</code>```

答:
Solution to my own question after serious research is shown in the snippet below.

function compare(a, b){
  if (!a && !b) {
      return true;
   } else if (!a || !b) {
      return false;
   } else {
      return a.val === b.val && compare(a.left, b.left) && compare(a.right, b.right);
   }
}```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a JavaScript function that compares two binary trees defined by TreeNodes a and b and returns true if they are equal in structure and in value and false otherwise.

for example example of comparing both values and structure of two binary trees

Given the following class:

class TreeNode {
  constructor(data, left=null, right=null) {
    this.data = data;
    this.left = left;
    this.right = right;
  }
}

Here is the code i tried writing so far comapring TreeNode a and b.

const binaryTreeCompare = (a, b) => {
  if(a==null && b==null){
    return true;
  }else if(a!=null && b!=null){
    return(
      a.data == b.data && binaryTreeCompare(a.left, b.left) && binaryTreeCompare(a.right, b.right)
    );
  }
    else return false;
}

I expected an ouput of either true or false but this is what i get:

ReferenceError: compare is not defined
    at Context.it (test.js:116:16)


问:
Have fixed parameters in Java constructor - possible?
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

```<code>public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}
</code>```

and then call something along the lines of:

```<code>switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}
</code>```

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

答:
If I understand you correctly, you want the constraint that the value of the first argument to each constructor must match the constructor being called.

Simple:

```<code>public MenuNode(int type, param1, param2, param3) {
    if (type != 1) throw new IllegalArgumentException ("type must be 1")
    doStuffHere();
}
public MenuNode(int type, paramX, paramY) {
    if (type != 2) throw new IllegalArgumentException ("type must be 2")
    doStuffHere();
}
</code>```

If you have two or more types that have the same list of parameters associated with them, the validation would look more like this;

```<code>    if (type != 1 && type != 3) throw new IllegalArgumentException ("type must be 1 or 3");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}

and then call something along the lines of:

switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

Body:
If I understand you correctly, you want the constraint that the value of the first argument to each constructor must match the constructor being called.

Simple:

public MenuNode(int type, param1, param2, param3) {
    if (type != 1) throw new IllegalArgumentException ("type must be 1")
    doStuffHere();
}
public MenuNode(int type, paramX, paramY) {
    if (type != 2) throw new IllegalArgumentException ("type must be 2")
    doStuffHere();
}

If you have two or more types that have the same list of parameters associated with them, the validation would look more like this;

    if (type != 1 && type != 3) throw new IllegalArgumentException ("type must be 1 or 3");


问:
ScrollView contentView size not changing accordingly
I have a ScrollView in which I change its contentSize (the height to be specific). When I do this, the ContentView's size that is attached to the ScrollView doesn't change accordingly.

The ContentView's height and width is equal to the ScrollView, and the priority is 250 (height).

See my constraints:

for test purposes I changes the height of the contentSize to this:

```<code> scrollView.contentSize.height += self.postedImageView.getImageHeight(forImage: selectedImage)
</code>```

Thanks in advance

答:
You can't set contentSize.height directly. Please see this very similar question.

Basically you want

```<code>scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + self.postedImageView.getImageHeight(forImage: selectedImage))
</code>```

EDIT: from your comment

Why don't you just:

```<code>scrollView.ContentView.frame = CGRect(x: scrollView.ContentView.frame.origin.x, y: scrollView.ContentView.frame.origin.y, width: scrollView.ContentView.frame.width, height: scrollView.ContentView.frame.height + self.postedImageView.getImageHeight(forImage: selectedImage))
</code>```

At the same time as you adjust the content size?

Or this:

```<code>scrollView.ContentView.frame = CGRect(x: scrollView.ContentView.frame.origin.x, y: scrollView.ContentView.frame.origin.y, width: scrollView.ContentView.frame.width, height: scrollView.contentSize.height)
</code>```

Body:
I have a ScrollView in which I change its contentSize (the height to be specific). When I do this, the ContentView's size that is attached to the ScrollView doesn't change accordingly.

The ContentView's height and width is equal to the ScrollView, and the priority is 250 (height).

See my constraints:

for test purposes I changes the height of the contentSize to this:

 scrollView.contentSize.height += self.postedImageView.getImageHeight(forImage: selectedImage)

Thanks in advance

Body:
You can't set contentSize.height directly. Please see this very similar question.

Basically you want

scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + self.postedImageView.getImageHeight(forImage: selectedImage))

EDIT: from your comment

Why don't you just:

scrollView.ContentView.frame = CGRect(x: scrollView.ContentView.frame.origin.x, y: scrollView.ContentView.frame.origin.y, width: scrollView.ContentView.frame.width, height: scrollView.ContentView.frame.height + self.postedImageView.getImageHeight(forImage: selectedImage))

At the same time as you adjust the content size?

Or this:

scrollView.ContentView.frame = CGRect(x: scrollView.ContentView.frame.origin.x, y: scrollView.ContentView.frame.origin.y, width: scrollView.ContentView.frame.width, height: scrollView.contentSize.height)


问:
ERROR: Could not determine java version from 'JavaVersion.VERSION_1_8'
Could anyone help me please ?

"ERROR: Could not determine java version from 'JavaVersion.VERSION_1_8'."

答:
Use this:</p>

```<code>targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
</code>```

Body:
Use this:

targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8


问:
Date filter for DataGridView
I need to make a date filter for DataGridView which gets data by this code

```<code>    DataSet dataSet = new DataSet();
    OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
    OleDbDataAdapter dataAdapter1 = new OleDbDataAdapter();

    string query = "select * from Договор";
    string query1 = "select * from Поставщики";

    conn = new OleDbConnection(conn_string);

    dataAdapter.SelectCommand = new OleDbCommand(query, conn);
    dataAdapter1.SelectCommand = new OleDbCommand(query1, conn);

    dataAdapter.TableMappings.Add("Table", "Договор");
    dataAdapter1.TableMappings.Add("Table", "Поставщики");

    dataAdapter.Fill(dataSet);
    dataAdapter1.Fill(dataSet);

    BindingSource dogSource = new BindingSource();
    dogSource.DataSource = dataSet;
    dogSource.DataMember = "Договор";
    dataGridView1.DataSource = dogSource;

    BindingSource postSource = new BindingSource();
    postSource.DataSource = dataSet;
    postSource.DataMember = "Поставщики";

    DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
    comboColumn.HeaderText = "Поставщики";
    comboColumn.DataSource = postSource;

    comboColumn.DataPropertyName = "Код поставщика";

    comboColumn.DisplayMember = "Название";

    comboColumn.ValueMember = "Код поставщика";
</code>```

I used to filter data with this code, but now it did't work, I guess because of DataSource.

```<code>    DataView dv = new DataView(dt);
    dv.RowFilter = string.Format(" CONVERT([Дата заключения], 'System.DateTime') >= '{0:dd.MM.yyyy}' AND CONVERT([Дата заключения], 'System.DateTime') <= '{0:dd.MM.yyyy}'",
    dateTimePicker1.Value.ToShortDateString());;
    dataGridView1.DataSource=dv;
</code>```

I'll appriciate any help, thanks.

答:
Not sure if it's right, but it's worked out for me.</p>

```<code>DataTable all = dataSet.Tables[0];
DataView dv = new DataView(all);
dv.RowFilter = string.Format(" [Дата заключения] >= '{0:dd.MM.yyyy}' AND [Дата заключения] <= '{0:dd.MM.yyyy}'", dateTimePicker1.Value.ToShortDateString());
dataGridView1.DataSource=dv;
</code>```

Title: Date filter for DataGridView

Body:
I need to make a date filter for DataGridView which gets data by this code

    DataSet dataSet = new DataSet();
    OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
    OleDbDataAdapter dataAdapter1 = new OleDbDataAdapter();

    string query = "select * from Договор";
    string query1 = "select * from Поставщики";

    conn = new OleDbConnection(conn_string);

    dataAdapter.SelectCommand = new OleDbCommand(query, conn);
    dataAdapter1.SelectCommand = new OleDbCommand(query1, conn);

    dataAdapter.TableMappings.Add("Table", "Договор");
    dataAdapter1.TableMappings.Add("Table", "Поставщики");

    dataAdapter.Fill(dataSet);
    dataAdapter1.Fill(dataSet);

    BindingSource dogSource = new BindingSource();
    dogSource.DataSource = dataSet;
    dogSource.DataMember = "Договор";
    dataGridView1.DataSource = dogSource;

    BindingSource postSource = new BindingSource();
    postSource.DataSource = dataSet;
    postSource.DataMember = "Поставщики";

    DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
    comboColumn.HeaderText = "Поставщики";
    comboColumn.DataSource = postSource;

    comboColumn.DataPropertyName = "Код поставщика";

    comboColumn.DisplayMember = "Название";

    comboColumn.ValueMember = "Код поставщика";

I used to filter data with this code, but now it did't work, I guess because of DataSource.

    DataView dv = new DataView(dt);
    dv.RowFilter = string.Format(" CONVERT([Дата заключения], 'System.DateTime') >= '{0:dd.MM.yyyy}' AND CONVERT([Дата заключения], 'System.DateTime') <= '{0:dd.MM.yyyy}'",
    dateTimePicker1.Value.ToShortDateString());;
    dataGridView1.DataSource=dv;

I'll appriciate any help, thanks.

Body:
Not sure if it's right, but it's worked out for me.

DataTable all = dataSet.Tables[0];
DataView dv = new DataView(all);
dv.RowFilter = string.Format(" [Дата заключения] >= '{0:dd.MM.yyyy}' AND [Дата заключения] <= '{0:dd.MM.yyyy}'", dateTimePicker1.Value.ToShortDateString());
dataGridView1.DataSource=dv;


问:
What is the best way to format strings in Python?
I am currently reading books and taking online courses on Python. There are numerous ways we can format strings in python, but I was wondering what is the best way.

For example if we have this two ways of formating strings, which one would be better to use? Does it even make a difference?

```<code>    print("I am %d years old." % (age))
</code>```

or

```<code>    print("I am {} years old".format(age))
</code>```

or maybe even

```<code>    print("I am " + str(age) + " years old")
</code>```

Well anyway, it's more a theoretical question. I am new to coding, but I know some functions or methods are more memory consuming than others, so I am trying to figure out if maybe one of these is a better practice.

答:
Python 3.6+ offers a new string format.</p>

```<code>name = "jack"
my_string = f"hello my name is {name}"
</code>```

Body:
I am currently reading books and taking online courses on Python. There are numerous ways we can format strings in python, but I was wondering what is the best way.

For example if we have this two ways of formating strings, which one would be better to use? Does it even make a difference?

    print("I am %d years old." % (age))

or

    print("I am {} years old".format(age))

or maybe even

    print("I am " + str(age) + " years old")

Well anyway, it's more a theoretical question. I am new to coding, but I know some functions or methods are more memory consuming than others, so I am trying to figure out if maybe one of these is a better practice.

Body:
Python 3.6+ offers a new string format.

name = "jack"
my_string = f"hello my name is {name}"


问:
Set the title of an UIPopOver View Programmatically
How do you set the title of an UIPopOver View programmatically?

I found some sample code but wasn't able to set the title.

```<code>myView *theView = [[myView alloc] initWithNibName:@"myView"
                                       bundle:nil];
UIPopoverController* aPopover = [[UIPopoverController alloc] initWithContentViewController:theView];
[aPopover setDelegate:self];
[aPopover setPopoverContentSize:CGSizeMake(320, 320) animated:YES];

[theView setPopover:aPopover];
[theView release];

[self.popoverController presentPopoverFromRect:CGRectMake(510,370,0,0) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
</code>```

答:
yes, exactly. the whole thing could look like this:</p>

```<code>InfoView *infoView = [[InfoView alloc] init];
UINavigationController *container = [[[UINavigationController alloc] initWithRootViewController:infoView] autorelease];
UIPopoverController *pop = [[UIPopoverController alloc] initWithContentViewController:container];

infoView.title = @"My Title";

[pop setDelegate:self];
[pop setPopoverContentSize:CGSizeMake(320, 400)];
[pop presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
[infoView release];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How do you set the title of an UIPopOver View programmatically?

I found some sample code but wasn't able to set the title.

myView *theView = [[myView alloc] initWithNibName:@"myView"
                                       bundle:nil];
UIPopoverController* aPopover = [[UIPopoverController alloc] initWithContentViewController:theView];
[aPopover setDelegate:self];
[aPopover setPopoverContentSize:CGSizeMake(320, 320) animated:YES];

[theView setPopover:aPopover];
[theView release];

[self.popoverController presentPopoverFromRect:CGRectMake(510,370,0,0) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];

Body:
yes, exactly. the whole thing could look like this:

InfoView *infoView = [[InfoView alloc] init];
UINavigationController *container = [[[UINavigationController alloc] initWithRootViewController:infoView] autorelease];
UIPopoverController *pop = [[UIPopoverController alloc] initWithContentViewController:container];

infoView.title = @"My Title";

[pop setDelegate:self];
[pop setPopoverContentSize:CGSizeMake(320, 400)];
[pop presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
[infoView release];


问:
phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)
I am unable to connect to my MySQL in xampp I have this error:

MySQL said: Documentation

#1045 - Access denied for user 'root'@'localhost' (using password: NO)
mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: NO)
phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.

CONFIG.INC.PHP file

```<code><?php
/*
* This is needed for cookie based authentication to encrypt password in
* cookie
*/
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

/*
* Servers configuration
*/
$i = 0;

/*
* First server
*/
$i++;

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';

/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';

/*
 * End of servers configuration
 */

?>
</code>```

答:
You may have set different passwords for user 'root' or have been changed your password. I had the same error as:

mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES)

and I found that my root password for PHPMyAdmin is not the same on both 'mysql' and 'phpmyadmin' databases, so I updated my password for 'phpmyadmin' database same as 'mysql' database as follow:

```<code>sudo gedit /etc/phpmyadmin/config-db.php
</code>```

and update the fields

```<code>$dbuser='root';

$dbpass='myNewPassword'; <-- update your new password here
</code>```

Body:
I am unable to connect to my MySQL in xampp I have this error:

MySQL said: Documentation

#1045 - Access denied for user 'root'@'localhost' (using password: NO)
mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: NO)
phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.

CONFIG.INC.PHP file

<?php
/*
* This is needed for cookie based authentication to encrypt password in
* cookie
*/
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

/*
* Servers configuration
*/
$i = 0;

/*
* First server
*/
$i++;

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';

/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';

/*
 * End of servers configuration
 */

?>

Body:
You may have set different passwords for user 'root' or have been changed your password. I had the same error as:

mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES)

and I found that my root password for PHPMyAdmin is not the same on both 'mysql' and 'phpmyadmin' databases, so I updated my password for 'phpmyadmin' database same as 'mysql' database as follow:

sudo gedit /etc/phpmyadmin/config-db.php

and update the fields

$dbuser='root';

$dbpass='myNewPassword'; <-- update your new password here


问:
How to cut long labels in Matplotlib
I would like to cut long labels, so that only the first 4 letters are displayed, without changing the values in the original data frame.

Example:

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

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text',d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');
```

Current output:

Desirable output:

答:
I will provide a slightly general solution: Iterate through your y-tick labels and then create a list of new labels, which stores only up to 4 characters if any label has more than 4 characters. Finally, assign this new list of labels as the y-ticks

```<code># Plot
f, axes = plt.subplots()
ax = sns.countplot(y='var', data=d, orient='h');

new_labels = []

for i in ax.yaxis.get_ticklabels():
    label = i.get_text()
    if len(label) > 4:
        new_labels.append(label[0:4])
    else:
        new_labels.append(label)

ax.yaxis.set_ticklabels(new_labels)
</code>```

Or you can create the new labels in a single line using list comprehension as

```<code>new_labels = [i.get_text()[0:4] if len(i.get_text()) > 4 else i.get_text()
              for i in ax.yaxis.get_ticklabels()]
</code>```

Title: How to cut long labels in Matplotlib

Body:
I would like to cut long labels, so that only the first 4 letters are displayed, without changing the values in the original data frame.

Example:

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

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text',d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');

Current output:

Desirable output:

Body:
I will provide a slightly general solution: Iterate through your y-tick labels and then create a list of new labels, which stores only up to 4 characters if any label has more than 4 characters. Finally, assign this new list of labels as the y-ticks

# Plot
f, axes = plt.subplots()
ax = sns.countplot(y='var', data=d, orient='h');

new_labels = []

for i in ax.yaxis.get_ticklabels():
    label = i.get_text()
    if len(label) > 4:
        new_labels.append(label[0:4])
    else:
        new_labels.append(label)

ax.yaxis.set_ticklabels(new_labels)

Or you can create the new labels in a single line using list comprehension as

new_labels = [i.get_text()[0:4] if len(i.get_text()) > 4 else i.get_text()
              for i in ax.yaxis.get_ticklabels()]


问:
Joomla: Hide categories in Google search results
We use Joomla 3.4.4 for our Company website.  We have mod_rewrite and SEF-Urls.

In our company website, we use categories only to organize articles internally, not for public access.

Nevertheless, Google has somehow found out the categories and displays them in the search results. People clicking on these category search results land on a page with several articles, which is not intended.

How can I prevent Google from indexing the category pages?

答:
This was a major problem with our websites. Google searches would show several unwanted categories and include a number prefix (10-videos). Clicking the Google search would show a dozen various articles that were all marked noindex, nofollow. As the category itself was marked noindex, nofollow and the global default was noindex, nofollow, it was a complete mystery why this was happening.

After a several years of frustration, I finally solved it. There are two parts. A long-term permanent solution and a short-term temporary solution which will remove them from Google searches within 24 hours.

The long-term permanent solution is to disallow the categories in robots.txt. When the site is re-crawled, they should go away. Add the offending categories at the end of robots.txt. This will also take care of their sub-categories. These are case sensitive in Google so make sure to use only lower case. (Disallow: /10-videos)

The short-term 90 day solution is to manually remove the URLs in Google Search Console. This can currently only be done in the old version of GSC. It is not yet available in the new version.

In the new Search Console click Index : Coverage. Make sure the Valid tab is highlighted. At the bottom, click on “Indexed, not submitted in sitemap” to see the offending links.

In the old version go to Google Index : Remove URLs. Click Temporarily Hide. Enter just the category (10-videos) as it will automatically add the website link. This will also take care of their sub-categories. By the next day the bad URLs will be gone (for 90 days). These are case sensitive so make sure to use only lower case.


问:
ELMAH doesn't log exceptions raised from ASP.NET MVC Ajax.BeginForm
I added ELMAH to my ASP.NET MVC project and all was well. I noticed that exceptions that arise from Ajax.BeginForm (simple ajax form post) do not get logged.

When I make those same exceptions happen by calling the Controller Action directly OR doing a JQUERY $.post() ELMAH catches these exceptions.

Controller .cs

```<code>[HttpPost]
[Roles(AcctRoles.ThisRole)]
public ActionResult CreateTicket(TicketCreateViewModel ticketvm)
{
    throw new Exception("HEY THIS IS AN AJAX ERROR. TEST.");
    return null;
}
</code>```

View (ELMAH DOES NOT LOG)

```<code>@using (Ajax.BeginForm("CreateTicket", "Tickets", null, new AjaxOptions
{
    HttpMethod = "POST"
}))
{

    <div class="form-horizontal">
    Form here
    </div>
}
</code>```

JQUERY (ELMAH DOES LOG)

```<code> <button onclick="$.post('@Url.Action("CreateTicket", "Tickets")', '');">TEST EXCEPTION BUTTON</button>
</code>```

When I use Fiddler or the Chrome Inspector network tab to view the response i see the normal Yellow Screen of death. When I look at the event viewer I see the standard ASP.NET warning entry.

答: I didn't realize there was a rich text editor on the page sending html. This is an apparent bug with ELMAH as seen here: Elmah not logging exceptions for http post requests in MVC app - if the request contains XML</p>

Body:
I added ELMAH to my ASP.NET MVC project and all was well. I noticed that exceptions that arise from Ajax.BeginForm (simple ajax form post) do not get logged.

When I make those same exceptions happen by calling the Controller Action directly OR doing a JQUERY $.post() ELMAH catches these exceptions.

Controller .cs

[HttpPost]
[Roles(AcctRoles.ThisRole)]
public ActionResult CreateTicket(TicketCreateViewModel ticketvm)
{
    throw new Exception("HEY THIS IS AN AJAX ERROR. TEST.");
    return null;
}

View (ELMAH DOES NOT LOG)

@using (Ajax.BeginForm("CreateTicket", "Tickets", null, new AjaxOptions
{
    HttpMethod = "POST"
}))
{

    Form here

}

JQUERY (ELMAH DOES LOG)

 <button onclick="$.post('@Url.Action("CreateTicket", "Tickets")', '');">TEST EXCEPTION BUTTON</button>

When I use Fiddler or the Chrome Inspector network tab to view the response i see the normal Yellow Screen of death. When I look at the event viewer I see the standard ASP.NET warning entry.


问:
How do I hide all tabs without anything in cell F6?
I have a macro to merge multiple excel workbooks and then print everything instead of having to open each workbook individually.

However, in each of these workbooks are blank template tabs called PR1,2,3,4,5 etc.
Is there a way to loop through each tab in the merged workbook and hide all tabs that don't have anything in a specific cell (in this case F6)?

In a perfect world if an employee uses the template tabs, they are supposed to rename the tab itself. But they don't always do this so I don't want to hide based on tab name.

Any help would be appreciated!

答:
The below is NOT the correct code but the guidelines on how to proceed.   </p>

```<code>Option Explicit

Sub test()

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets

        With ws
            'If sheet name is Sheet1 then delete
            If .Name = "Sheet1" Then
                .Delete
            End If

        End With

    Next ws

 End Sub
</code>```

Body:
The below is NOT the correct code but the guidelines on how to proceed.

Option Explicit

Sub test()

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets

        With ws
            'If sheet name is Sheet1 then delete
            If .Name = "Sheet1" Then
                .Delete
            End If

        End With

    Next ws

 End Sub


答:
format function now is stated as the most correct and recommended way to use formatted strings because it is much more powerful than old strings.

% is stated as outdated format.

Here you can see examples of old- and new-formatting strings.

P.S. In Python 3.6 were announced new f-strings.

Title: What is the best way to format strings in Python?


问:
Swift - Tab Bar Controller not showing when pushed
I have a series of views that are accessed via the Tab Bar Controller - they all behave and the Tab Bar is visible when each icon is pressed.

However when one of these views pushes to another the Tab Bar does not show.

I have tried forcing the Tab Bar with both:

```<code>self.hidesBottomBarWhenPushed = false
self.tabBarController?.tabBar.isHidden = false
</code>```

Any ideas on how to resolve this?

答:
According to your hierarchy (but I could be wrong, it's not 100% clear what you said), it's a normal behaviour because the new view controller V2 entirely replace the current view which is the UITabBarController, not the V1. Your hierarchy is maybe something like this

```<code>UINavigationController
          |
          |
          UITabBarController ----> VC2
                 |
                 |
                VC1
</code>```

The vc1 is embedded in the tab bar controller. So when you push the VC2 is shown and the whole UITabBarController is hidden.

You should do something like this

```<code>UITabBarController
       |
       |
       UINavigationController
               |
               |
               VC1 ------> VC2
</code>```

Body:
I have a series of views that are accessed via the Tab Bar Controller - they all behave and the Tab Bar is visible when each icon is pressed.

However when one of these views pushes to another the Tab Bar does not show.

I have tried forcing the Tab Bar with both:

self.hidesBottomBarWhenPushed = false
self.tabBarController?.tabBar.isHidden = false

Any ideas on how to resolve this?

Body:
According to your hierarchy (but I could be wrong, it's not 100% clear what you said), it's a normal behaviour because the new view controller V2 entirely replace the current view which is the UITabBarController, not the V1. Your hierarchy is maybe something like this

UINavigationController
          |
          |
          UITabBarController ----> VC2
                 |
                 |
                VC1

The vc1 is embedded in the tab bar controller. So when you push the VC2 is shown and the whole UITabBarController is hidden.

You should do something like this

UITabBarController
       |
       |
       UINavigationController
               |
               |
               VC1 ------> VC2


问:
How to pull out TRUE/FALSE stratum result from R cox regression?
I have the cox model:

```<code>res <- coxph(Surv(time,status)~drugName*strata(preventative),data=df)
</code>```

time - integer 0 to N
status - integer 0 or 1
drugName - categorical variable e.g., "drugA", "drugB" etc.
preventative - boolean TRUE/FALSE

From:

```<code>summary(res)
</code>```

I see results for:

```<code>drugA
drugB
drugC
drugA:strata(preventative)=TRUE
drugB:strata(preventative)=TRUE
drugC:strata(preventative)=TRUE
</code>```

However, I can't seem to get out the results for the strata where preventative=FALSE.

I've been assured by a clinical epidemiologist that this is possible, however, I use R and she uses SAS.

Besides rerunning the calculation and changing the preventative term TRUE/FALSE around, how can I do this in R?

EDIT #1 As per Julius Vainora's reply.

I've now tried:

```<code>res <- coxph(Surv(time,status)~drugName*strata(preventative),data=df)
</code>```

and

```<code>res <- coxph(Surv(time,status)~drugName:strata(preventative),data=df)
</code>```

The respective results are:

and (the new suggestion)

If the new suggestion will help just clear the values of the categorical variable preventative, any idea why the drugNamecitaloprame in the first model has a value but NA in the second model?

答:
Your current results already include what you want: drugA corresponds to FALSE and drugA + drugA:strata(preventative)=TRUE corresponds to true. As to get the same results in a more clean way, you may run instead

```<code>coxph(Surv(time, status) ~ drugName:strata(preventative), data = df)
</code>```

Body:
I have the cox model:

res <- coxph(Surv(time,status)~drugName*strata(preventative),data=df)

time - integer 0 to N
status - integer 0 or 1
drugName - categorical variable e.g., "drugA", "drugB" etc.
preventative - boolean TRUE/FALSE

From:

summary(res)

I see results for:

drugA
drugB
drugC
drugA:strata(preventative)=TRUE
drugB:strata(preventative)=TRUE
drugC:strata(preventative)=TRUE

However, I can't seem to get out the results for the strata where preventative=FALSE.

I've been assured by a clinical epidemiologist that this is possible, however, I use R and she uses SAS.

Besides rerunning the calculation and changing the preventative term TRUE/FALSE around, how can I do this in R?

EDIT #1 As per Julius Vainora's reply.

I've now tried:

res <- coxph(Surv(time,status)~drugName*strata(preventative),data=df)

and

res <- coxph(Surv(time,status)~drugName:strata(preventative),data=df)

The respective results are:

and (the new suggestion)

If the new suggestion will help just clear the values of the categorical variable preventative, any idea why the drugNamecitaloprame in the first model has a value but NA in the second model?

Body:
Your current results already include what you want: drugA corresponds to FALSE and drugA + drugA:strata(preventative)=TRUE corresponds to true. As to get the same results in a more clean way, you may run instead

coxph(Surv(time, status) ~ drugName:strata(preventative), data = df)


答:
All ways are fine if it fits your style and there aren't any rules in your workplace.

However in my opinion the smoothest way would be f-Strings.

Do them like this:

```<code>print(f"Some text and a {value}")
</code>```

Body:
All ways are fine if it fits your style and there aren't any rules in your workplace.

However in my opinion the smoothest way would be f-Strings.

Do them like this:

print(f"Some text and a {value}")


问:
bind drop down to grid view
i have a one drop down list containing the list of items. each item is further connecting to different table.
there is gridview that show the selected table by selecetd item in drop down list.
how is it possible?
that to show the selected table f</p>

答:
```<code>gridView.DataSource = tableCollection[dropDownList.SelectedValue];
</code>```

Title: bind drop down to grid view


问:
Bootstrap Vue Animate Dropdowns
I am using bootstrap vue and am trying to animate/transition the drop downs. This is proving to be fairly difficult as they do not use v-if or v-show so the transition will not work. Alternatively because the way the components work if you use v-if the drop down trigger will be hidden. I can't find anything online to bootstrap vue specifically on this but I feel this shouldn't be as tough as it has turned out to be. thanks for any help you can give</p>

```<code><div id="app">
  <b-navbar type="dark" fixed>
    <b-navbar-nav class="ml-auto">

      <b-nav-item-dropdown text="Tools">
          <b-dropdown-item to="/navItem1">Item 1</b-dropdown-item>
          <b-dropdown-item to="/export"> Item 2</b-dropdown-item>
       </b-nav-item-dropdown>

        // This won't work as it hides the main dropdown trigger right form the start
        <b-nav-item-dropdown text="Tools" v-if="toggleDropdown">
           <b-dropdown-item to="/navItem1">Item 1</b-dropdown-item>
           <b-dropdown-item to="/export"> Item 2</b-dropdown-item>
        </b-nav-item-dropdown>
    </b-navbar-nav>
  </b-navbar>
</div>

<script>
export default {
  name: 'nav',
  data () {
    return { toggleDropdown: false }
  },
  mounted: function () {
    // I can listen for events here but I still can't trigger the transition
    this.$root.$on('bv::dropdown::show', bvEvent => {
      this.toggleDropdown = true
    })

    this.$root.$on('bv::dropdown::hide', bvEvent => {
      this.toggleDropdown = false
    })
  }
}
</script>

<style lang="scss">
   .navbar {
      .dropdown-menu {
          transform-origin: top;
          transition: transform 10s ease-in-out;;
       }
   }

  .dd-slide-enter,
  .dd-slide-leave-to { transform: scaleY(0); }

</style>
</code>```

答:
It's pretty hard to achieve a clean slide-up/down animation because BootstrapVue uses display:none/block to hide/show the dropdown menu. What you can do it's manipulate the max-height of the element as explained here.

I added an 'animated' class to the parent element, for example your b-navbar to select which dropdown has to be animated. Then i removed display: none from the default status of the dropdown and hidden it setting its max-height and padding to 0 and its border to none. When you click the button the dropdown gets the class 'show'so you can give it a max-height different than 0, as explained in the answer i've linked to you, you have to set it higher than the actual height of the dropdown menu otherwise it gets cropped out.

```<code>.animated {
    .dropdown-menu {
        overflow: hidden;
        display: block!important;
        max-height: 0!important;
        &:not(.show) {
            padding: 0;
            border: none;
        }
        &.show {
            transition: max-height 300ms ease-in-out;
            max-height: 500px!important; //this must have to be higher than the max height of the dropdown list
        }
    }
}
</code>```

Title: Bootstrap Vue Animate Dropdowns

Body:
I am using bootstrap vue and am trying to animate/transition the drop downs. This is proving to be fairly difficult as they do not use v-if or v-show so the transition will not work. Alternatively because the way the components work if you use v-if the drop down trigger will be hidden. I can't find anything online to bootstrap vue specifically on this but I feel this shouldn't be as tough as it has turned out to be. thanks for any help you can give

          Item 1
           Item 2

        // This won't work as it hides the main dropdown trigger right form the start

           Item 1
            Item 2

Body:
It's pretty hard to achieve a clean slide-up/down animation because BootstrapVue uses display:none/block to hide/show the dropdown menu. What you can do it's manipulate the max-height of the element as explained here.

I added an 'animated' class to the parent element, for example your b-navbar to select which dropdown has to be animated. Then i removed display: none from the default status of the dropdown and hidden it setting its max-height and padding to 0 and its border to none. When you click the button the dropdown gets the class 'show'so you can give it a max-height different than 0, as explained in the answer i've linked to you, you have to set it higher than the actual height of the dropdown menu otherwise it gets cropped out.

.animated {
    .dropdown-menu {
        overflow: hidden;
        display: block!important;
        max-height: 0!important;
        &:not(.show) {
            padding: 0;
            border: none;
        }
        &.show {
            transition: max-height 300ms ease-in-out;
            max-height: 500px!important; //this must have to be higher than the max height of the dropdown list
        }
    }
}


问:
How to register services in ASP.NET Boilerplate using IocManager?
For ASP.NET Core, I know how to register services using ConfigureServices method in Startup class.

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(x => {
    var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
    var factory = x.GetRequiredService<IUrlHelperFactory>();
    return factory.GetUrlHelper(actionContext);
});
```

How can I register same services using IocManager in my ASP.NET Boilerplate (ASP.NET Core) project so that I can use them in my application services?

答:
AddSingleton

IocManager.Register<IActionContextAccessor, ActionContextAccessor>();
```

<h1>AddScoped + Factory</h1>

<pre class="lang-cs prettyprint-override"><code>IocManager.IocContainer.Register(
    Component
        .For<IUrlHelper>()
        .UsingFactoryMethod(kernel =>
        {
            var actionContext = kernel.Resolve<IActionContextAccessor>().ActionContext;
            var factory = kernel.Resolve<IUrlHelperFactory>();
            return factory.GetUrlHelper(actionContext);
        })
        .LifestyleCustom<MsScopedLifestyleManager>() // ASP.NET Core
     // .LifestylePerWebRequest()                    // ASP.NET MVC 5
);
</code>```

References

ASP.NET Boilerplate documentation: Dependency Injection — Custom/Direct Registration

IoC PerWebRequest and Factory pattern: aspnetboilerplate/aspnetboilerplate#3921

IScopedDependency: aspnetboilerplate/aspnetboilerplate#3945

Body:
For ASP.NET Core, I know how to register services using ConfigureServices method in Startup class.

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(x => {
    var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
    var factory = x.GetRequiredService<IUrlHelperFactory>();
    return factory.GetUrlHelper(actionContext);
});

How can I register same services using IocManager in my ASP.NET Boilerplate (ASP.NET Core) project so that I can use them in my application services?

Body:
AddSingleton

IocManager.Register<IActionContextAccessor, ActionContextAccessor>();

AddScoped + Factory

IocManager.IocContainer.Register(
    Component
        .For<IUrlHelper>()
        .UsingFactoryMethod(kernel =>
        {
            var actionContext = kernel.Resolve<IActionContextAccessor>().ActionContext;
            var factory = kernel.Resolve<IUrlHelperFactory>();
            return factory.GetUrlHelper(actionContext);
        })
        .LifestyleCustom<MsScopedLifestyleManager>() // ASP.NET Core
     // .LifestylePerWebRequest()                    // ASP.NET MVC 5
);

References

ASP.NET Boilerplate documentation: Dependency Injection — Custom/Direct Registration

IoC PerWebRequest and Factory pattern: aspnetboilerplate/aspnetboilerplate#3921

IScopedDependency: aspnetboilerplate/aspnetboilerplate#3945


问:
Is it possible to read and write to a header file?
So I'm trying to overwrite a macro I have on a header file but I can't seem to open it by using std::ifstream. Is it even possible to read/write to an existing header file or are there default permissions that don't allow programs to modify header file contents?

```<code>std::ifstream versionH;
char temp[100];
versionH.open("..\temp.h");
if (!versionH.is_open()) {
    std::cout << "Didn't open" << std::endl;
    return 1;
}
while (!versionH.eof()) {
    versionH >> temp;
    std::cout << temp << std::endl;
}
</code>```

I would hope that I'd be able to read in the header file and display it's contents but 'versionH.is_open()' is returning false. Is there something I'm missing here?

答:
Is it possible to read and write to a header file?

Headers are files. It is possible to read and write files (assuming the file exists, and the process has sufficient permissions etc.). Therefore we can infer that header files can be read and written to.

Note that modifying a header file that has been used to compile a program has no effect on the compiled program. It can only affect programs compiled using the modified file.

Furthermore, files in the context where the program is compiled are irrelevant to the program. Only the files in the file system where the program is executed can be read.

Is there something I'm missing here?

Probably the file doesn't exist. The filename is most suspicious. Does it really contain a tab character (\t), or did you intend to write a (windows) dir separator? The backslash is the escape character, so in order to write it in a string literal, you must escape it (with another backslash: \\).

Body:
So I'm trying to overwrite a macro I have on a header file but I can't seem to open it by using std::ifstream. Is it even possible to read/write to an existing header file or are there default permissions that don't allow programs to modify header file contents?

std::ifstream versionH;
char temp[100];
versionH.open("..\temp.h");
if (!versionH.is_open()) {
    std::cout << "Didn't open" << std::endl;
    return 1;
}
while (!versionH.eof()) {
    versionH >> temp;
    std::cout << temp << std::endl;
}

I would hope that I'd be able to read in the header file and display it's contents but 'versionH.is_open()' is returning false. Is there something I'm missing here?


答:
All methods are dependant on which operations you wish to achieve and the efficiency of execution. Currently, the newest and most efficient way to format strings in python was introduced in python 3.6 and looks like:

f' {}'

If you wish to format strings, this is currently the best method.

Body:
I am currently reading books and taking online courses on Python. There are numerous ways we can format strings in python, but I was wondering what is the best way.

For example if we have this two ways of formating strings, which one would be better to use? Does it even make a difference?

    print("I am %d years old." % (age))

or

    print("I am {} years old".format(age))

or maybe even

    print("I am " + str(age) + " years old")

Well anyway, it's more a theoretical question. I am new to coding, but I know some functions or methods are more memory consuming than others, so I am trying to figure out if maybe one of these is a better practice.


问:
Detecting collision in Python turtle game
I am trying to make a Python game where the red turtle chases the blue turtle. When the red turtle catches the blue turtle, I want it to say 'COLLISION' on the screen but it is not working. When it collides, nothing happens and it gives me an error 'Turtle' object is not callable'. </p>

```<code>from turtle import Turtle, Screen

playGround = Screen()

playGround.screensize(250, 250)
playGround.title("Turtle Keys")

run = Turtle("turtle")
run.speed("fastest")
run.color("blue")
run.penup()
run.setposition(250, 250)

follow = Turtle("turtle")
follow.speed("fastest")
follow.color("red")
follow.penup()
follow.setposition(-250, -250)

def k1():
    run.forward(45)

def k2():
    run.left(45)

def k3():
    run.right(45)

def k4():
    run.backward(45)

def quitThis():
    playGround.bye()

def follow_runner():
    follow.setheading(follow.towards(run))
    follow.forward(8)
    playGround.ontimer(follow_runner, 10)

playGround.onkey(k1, "Up")  # the up arrow key
playGround.onkey(k2, "Left")  # the left arrow key
playGround.onkey(k3, "Right")  # you get it!
playGround.onkey(k4, "Down")

playGround.listen()

follow_runner()

def is_collided_with(self, run):
    return self.rect.colliderect(run.rect)

runner = run(10, 10, 'my_run')
follower = follow(20, 10)
if follow.is_collided_with(run):
    print 'collision!'

 playGround.mainloop()
</code>```

答:
This is the easiest way I can think of. Just use .pos() like this</p>

```<code>from turtle import *

import turtle

screen = turtle.Screen()

screen.setup(1920, 1080)

blue = turtle.Turtle()

blue.shape = ('turtle')

blue.color = ('blue')

red = turtle.Turtle()

red.shape = ('turtle')

red.color = ('red')

collision = turtle.Turtle()

collision.hideturtle()

if blue.pos() == red.pos():

    collision.goto(0,0)

    collision.showturtle()

    collision.write("COLLISION")
</code>```

Body:
I am trying to make a Python game where the red turtle chases the blue turtle. When the red turtle catches the blue turtle, I want it to say 'COLLISION' on the screen but it is not working. When it collides, nothing happens and it gives me an error 'Turtle' object is not callable'.

from turtle import Turtle, Screen

playGround = Screen()

playGround.screensize(250, 250)
playGround.title("Turtle Keys")

run = Turtle("turtle")
run.speed("fastest")
run.color("blue")
run.penup()
run.setposition(250, 250)

follow = Turtle("turtle")
follow.speed("fastest")
follow.color("red")
follow.penup()
follow.setposition(-250, -250)

def k1():
    run.forward(45)

def k2():
    run.left(45)

def k3():
    run.right(45)

def k4():
    run.backward(45)

def quitThis():
    playGround.bye()

def follow_runner():
    follow.setheading(follow.towards(run))
    follow.forward(8)
    playGround.ontimer(follow_runner, 10)

playGround.onkey(k1, "Up")  # the up arrow key
playGround.onkey(k2, "Left")  # the left arrow key
playGround.onkey(k3, "Right")  # you get it!
playGround.onkey(k4, "Down")

playGround.listen()

follow_runner()

def is_collided_with(self, run):
    return self.rect.colliderect(run.rect)

runner = run(10, 10, 'my_run')
follower = follow(20, 10)
if follow.is_collided_with(run):
    print 'collision!'

 playGround.mainloop()

Body:
This is the easiest way I can think of. Just use .pos() like this

from turtle import *

import turtle

screen = turtle.Screen()

screen.setup(1920, 1080)

blue = turtle.Turtle()

blue.shape = ('turtle')

blue.color = ('blue')

red = turtle.Turtle()

red.shape = ('turtle')

red.color = ('red')

collision = turtle.Turtle()

collision.hideturtle()

if blue.pos() == red.pos():

    collision.goto(0,0)

    collision.showturtle()

    collision.write("COLLISION")


问:
Insert python lists data into sql table instance
I keep getting a sql syntax error when I run the script to import the data into sql.

here is the data in question,

```<code>filtered_interfaces = (['interface Gi1/0/7']
filtered_tech =  ['description TECH_5750'])
cab =  u'10.210.44.5'
</code>```

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '['description TECH_5750'],['interface Gi1/0/7'],10.20.94.5)' at line 1")

Ive attempted dictation and tried to match values as it gets placed in to the database, I have also tried %s inplace of {}.

Im getting the same error as above on both of these methods.

```<code>sql = "INSERT INTO device (hostname, cab, localint) VALUES ({0},{1},{2})".format(filtered_tech,filtered_interface,cab)

mycursor.execute(sql)
</code>```

Long story short this application logs into switches at our DC's. It looks for CDP LLDP devices then spits out all that info into an array. I then filter the info looking for hostname and local interface. The goal is to import that data into sql (Its different on each switch). Then retrieve data on a html page and edit the hostname if applicable. I had the editable piece working but it wasn't scalable hints the sql additions. Apologies if this is an easy fix im not a programmer by trade, just trying to make life easier and learn python.

答:
If you are using MySQL behind your Python script, then you should be following the usage pattern in the documentation for prepared statements:</p>

```<code>params = (filtered_tech, filtered_interface, cab,)
sql = """INSERT INTO device (hostname, cab, localint)
         VALUES (%s, %s, %s)"""
cursor.execute(sql, params)

# retrieve data here
</code>```

Body:
I keep getting a sql syntax error when I run the script to import the data into sql.

here is the data in question,

filtered_interfaces = (['interface Gi1/0/7']
filtered_tech =  ['description TECH_5750'])
cab =  u'10.210.44.5'

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '['description TECH_5750'],['interface Gi1/0/7'],10.20.94.5)' at line 1")

Ive attempted dictation and tried to match values as it gets placed in to the database, I have also tried %s inplace of {}.

Im getting the same error as above on both of these methods.

sql = "INSERT INTO device (hostname, cab, localint) VALUES ({0},{1},{2})".format(filtered_tech,filtered_interface,cab)

mycursor.execute(sql)

Long story short this application logs into switches at our DC's. It looks for CDP LLDP devices then spits out all that info into an array. I then filter the info looking for hostname and local interface. The goal is to import that data into sql (Its different on each switch). Then retrieve data on a html page and edit the hostname if applicable. I had the editable piece working but it wasn't scalable hints the sql additions. Apologies if this is an easy fix im not a programmer by trade, just trying to make life easier and learn python.

Body:
If you are using MySQL behind your Python script, then you should be following the usage pattern in the documentation for prepared statements:

params = (filtered_tech, filtered_interface, cab,)
sql = """INSERT INTO device (hostname, cab, localint)
         VALUES (%s, %s, %s)"""
cursor.execute(sql, params)

# retrieve data here


问:
What is the difference between using the id tag on a label and an input?
My understanding of this is that if you use the id for an input it is linking to the "for" attribute for the corresponding label. However, I am unsure how it works in the reverse circumstance.

My understanding of the name attribute was to send that name to the server, but in the case where you are making a checkbox the value attribute is performing this task. Am I overcomplicating a simple concept here?

答:
The label has 2 main functions: identify to the HTML what the label is for, and in most common browsers clicking the label will set the focus to the input.  Below are the possible scenarios.  Keep in mind it's usually easiest to set both the id and name of the input to the same value.

Will not link label to input:

```<code><label for="myInput">My Input</label>
<input name="myInput">
</code>```

Will not send form data to server (custom-built AJAX objects that include by id are an exception):

```<code><label for="myInput">My Input</label>
<input id="myInput">
</code>```

Also will not link label to input (for needs to be id, not name):

```<code><label for="input">My Input</label>
<input name="input" id="myInput">
</code>```

Correct:

```<code><label for="myInput">My Input</label>
<input name="myInput" id="myInput">
</code>```

Also correct with non-matching name/id:

```<code><label for="myInput">My Input</label>
<input name="input" id="myInput">
</code>```

Body:
The label has 2 main functions: identify to the HTML what the label is for, and in most common browsers clicking the label will set the focus to the input.  Below are the possible scenarios.  Keep in mind it's usually easiest to set both the id and name of the input to the same value.

Will not link label to input:

<label for="myInput">My Input</label>
<input name="myInput">

Will not send form data to server (custom-built AJAX objects that include by id are an exception):

<label for="myInput">My Input</label>
<input id="myInput">

Also will not link label to input (for needs to be id, not name):

<label for="input">My Input</label>
<input name="input" id="myInput">

Correct:

<label for="myInput">My Input</label>
<input name="myInput" id="myInput">

Also correct with non-matching name/id:

<label for="myInput">My Input</label>
<input name="input" id="myInput">


问:
Problem registering a dll - Access Denied
When trying to run regasm in Win2008 Server:

```<code>regasm "C:\Program Files\FooProg\Bar.dll" /tlb:"C:\Program Files\FooProg\Bar.tlb"
</code>```

I get the following error:

RegAsm : error RA0000 : An error occurred while saving the exported
  type library: Access is denied.
  (Exception from HRESULT: 0x80070005
  (E_ACCESSDENIED))

what does this mean

答: For me, file was being used by other application</p>

Body:
When trying to run regasm in Win2008 Server:

regasm "C:\Program Files\FooProg\Bar.dll" /tlb:"C:\Program Files\FooProg\Bar.tlb"

I get the following error:

RegAsm : error RA0000 : An error occurred while saving the exported
  type library: Access is denied.
  (Exception from HRESULT: 0x80070005
  (E_ACCESSDENIED))

what does this mean


问:
spring-cloud-dataflow: Stream Deployments Fail on OSX
I am unable to deploy and execute a basic http | log stream following the
getting-started stream guide:

```<code>wget https://raw.githubusercontent.com/spring-cloud/spring-cloud-dataflow/2.1.0.RELEASE/spring-cloud-dataflow-server/docker-compose.yml;
export DATAFLOW_VERSION=2.1.0.RELEASE;
export SKIPPER_VERSION=2.0.2.RELEASE;
docker-compose up;
open http://localhost:9393/dashboard/#/streams/create;
echo "Then, create a stream via text input: `http | log`"
echo "Then, deploy the stream. The deployment fails with exit code 137."
</code>```

I get the green "Successfully deployed stream definition".
The status shows as "Deploying", but it never fully deploys.
There are no ERROR messages in the logs, in the UI, or in the network requests.

Here is the console output of docker-compose up after I deploy the stream.

```<code>skipper              | 2019-05-24 22:31:53.363  INFO 1 --- [io-7577-exec-10] o.s.s.support.LifecycleObjectSupport     : started UPGRADE UPGRADE_DEPLOY_TARGET_APPS_SUCCEED UPGRADE_DEPLOY_TARGET_APPS UPGRADE_START UPGRADE_DELETE_SOURCE_APPS UPGRADE_CHECK_TARGET_APPS UPGRADE_WAIT_TARGET_APPS UPGRADE_CANCEL UPGRADE_DEPLOY_TARGET_APPS_FAILED UPGRADE_CHECK_CHOICE UPGRADE_EXIT INSTALL INSTALL_INSTALL INSTALL_EXIT ERROR DELETE DELETE_DELETE DELETE_EXIT ROLLBACK ROLLBACK_START ROLLBACK_EXIT_INSTALL ROLLBACK_EXIT ROLLBACK_EXIT_UPGRADE ROLLBACK_CHOICE INITIAL ERROR_JUNCTION  /  / uuid=f1ca31f2-ddcf-4203-88c8-de367c104151 / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:53.504  INFO 1 --- [eTaskExecutor-1] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:53.540  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state StateMachineState [getIds()=[INSTALL], toString()=AbstractState [id=INSTALL, pseudoState=null, deferred=[], entryActions=[], exitActions=[], stateActions=[], regions=[], submachine=INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5], getClass()=class org.springframework.statemachine.state.StateMachineState]
skipper              | 2019-05-24 22:31:53.576  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INSTALL_INSTALL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1643670584, toString()=AbstractState [id=INSTALL_INSTALL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12493450, deferred=[], entryActions=[org.springframework.cloud.skipper.server.statemachine.InstallInstallAction@149debbb], exitActions=[], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.117  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:log-sink-kafka:jar:2.1.1.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.179  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/log-sink-kafka/2.1.1.RELEASE/log-sink-kafka-2.1.1.RELEASE.jar
skipper              | 2019-05-24 22:31:54.203  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.log-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114000/http-log-ingest-5.log-v1
skipper              | 2019-05-24 22:31:54.310  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:http-source-kafka:jar:2.1.0.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.312  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/http-source-kafka/2.1.0.RELEASE/http-source-kafka-2.1.0.RELEASE.jar
skipper              | 2019-05-24 22:31:54.313  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.http-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114208/http-log-ingest-5.http-v1
skipper              | 2019-05-24 22:31:54.369  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.370  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:54.371  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.372  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.SkipperStateMachineService   : setting future value org.springframework.cloud.skipper.domain.Release@279e0d49
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
mysql_1              | 2019-05-24T22:32:45.648870Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4662ms. The settings might not be optimal. (flushed=2 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:32:52,733] INFO Expiring session 0x10001d6560e0001, timeout of 6000ms exceeded (org.apache.zookeeper.server.ZooKeeperServer)
mysql_1              | 2019-05-24T22:33:08.378945Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 7338ms. The settings might not be optimal. (flushed=1 and evicted=0, during the time.)
mysql_1              | 2019-05-24T22:33:24.272169Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 5118ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:33:28,644] INFO Processed session termination for sessionid: 0x10001d6560e0001 (org.apache.zookeeper.server.PrepRequestProcessor)
kafka_1              | [2019-05-24 22:33:40,709] INFO [GroupMetadataManager brokerId=1001] Removed 0 expired offsets in 2216 milliseconds. (kafka.coordinator.group.GroupMetadataManager)
kafka_1              | [2019-05-24 22:33:49,359] WARN Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001 (org.apache.zookeeper.ClientCnxn)
kafka_1              | [2019-05-24 22:33:56,611] TRACE [Controller id=1001] Checking need to trigger auto leader balancing (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:06,529] DEBUG [Controller id=1001] Preferred replicas by broker Map(1001 -> Map(__consumer_offsets-22 -> Vector(1001), __consumer_offsets-30 -> Vector(1001), __consumer_offsets-8 -> Vector(1001), __consumer_offsets-21 -> Vector(1001), __consumer_offsets-4 -> Vector(1001), __consumer_offsets-27 -> Vector(1001), __consumer_offsets-7 -> Vector(1001), __consumer_offsets-9 -> Vector(1001), __consumer_offsets-46 -> Vector(1001), http-ingest-log-4.http-0 -> Vector(1001), __consumer_offsets-25 -> Vector(1001), __consumer_offsets-35 -> Vector(1001), __consumer_offsets-41 -> Vector(1001), __consumer_offsets-33 -> Vector(1001), __consumer_offsets-23 -> Vector(1001), __consumer_offsets-49 -> Vector(1001), __consumer_offsets-47 -> Vector(1001), __consumer_offsets-16 -> Vector(1001), __consumer_offsets-28 -> Vector(1001), __consumer_offsets-31 -> Vector(1001), __consumer_offsets-36 -> Vector(1001), __consumer_offsets-42 -> Vector(1001), __consumer_offsets-3 -> Vector(1001), __consumer_offsets-18 -> Vector(1001), __consumer_offsets-37 -> Vector(1001), http-ingest-log-3.http-0 -> Vector(1001), __consumer_offsets-15 -> Vector(1001), __consumer_offsets-24 -> Vector(1001), __consumer_offsets-38 -> Vector(1001), __consumer_offsets-17 -> Vector(1001), __consumer_offsets-48 -> Vector(1001), __confluent.support.metrics-0 -> Vector(1001), __consumer_offsets-19 -> Vector(1001), __consumer_offsets-11 -> Vector(1001), __consumer_offsets-13 -> Vector(1001), __consumer_offsets-2 -> Vector(1001), __consumer_offsets-43 -> Vector(1001), __consumer_offsets-6 -> Vector(1001), __consumer_offsets-14 -> Vector(1001), __consumer_offsets-20 -> Vector(1001), __consumer_offsets-0 -> Vector(1001), __consumer_offsets-44 -> Vector(1001), __consumer_offsets-39 -> Vector(1001), __consumer_offsets-12 -> Vector(1001), __consumer_offsets-45 -> Vector(1001), __consumer_offsets-1 -> Vector(1001), __consumer_offsets-5 -> Vector(1001), __consumer_offsets-26 -> Vector(1001), __consumer_offsets-29 -> Vector(1001), __consumer_offsets-34 -> Vector(1001), __consumer_offsets-10 -> Vector(1001), __consumer_offsets-32 -> Vector(1001), __consumer_offsets-40 -> Vector(1001))) (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,269] DEBUG [Controller id=1001] Topics not in preferred replica for broker 1001 Map() (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,993] TRACE [Controller id=1001] Leader imbalance ratio for broker 1001 is 0.0 (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:23,483] INFO Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
mysql_1              | 2019-05-24T22:35:19.628193Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4049ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
...
(several minutes later)
...
dataflow-server exited with code 137
</code>```

I get the same behavior when swapping out different parts of the stack; for example RabbitMQ for Kafka/Zookeeper, Postgres for MySQL.

My local stack:

OSX 10.14

Java openjdk 11.0.2

Docker engine 18.09.2

Docker Compose 1.23.2

Docker Machine 0.16.1

答: dataflow-server was failing silently due to memory issues. I raised the docker memory limit to 16 GB and stream deployment worked, but the "Runtime" page (http://localhost:9393/dashboard/#/runtime/apps) is still inaccessible. Separate issue tho!

Body:
I am unable to deploy and execute a basic http | log stream following the
getting-started stream guide:

wget https://raw.githubusercontent.com/spring-cloud/spring-cloud-dataflow/2.1.0.RELEASE/spring-cloud-dataflow-server/docker-compose.yml;
export DATAFLOW_VERSION=2.1.0.RELEASE;
export SKIPPER_VERSION=2.0.2.RELEASE;
docker-compose up;
open http://localhost:9393/dashboard/#/streams/create;
echo "Then, create a stream via text input: `http | log`"
echo "Then, deploy the stream. The deployment fails with exit code 137."

I get the green "Successfully deployed stream definition".
The status shows as "Deploying", but it never fully deploys.
There are no ERROR messages in the logs, in the UI, or in the network requests.

Here is the console output of docker-compose up after I deploy the stream.

skipper              | 2019-05-24 22:31:53.363  INFO 1 --- [io-7577-exec-10] o.s.s.support.LifecycleObjectSupport     : started UPGRADE UPGRADE_DEPLOY_TARGET_APPS_SUCCEED UPGRADE_DEPLOY_TARGET_APPS UPGRADE_START UPGRADE_DELETE_SOURCE_APPS UPGRADE_CHECK_TARGET_APPS UPGRADE_WAIT_TARGET_APPS UPGRADE_CANCEL UPGRADE_DEPLOY_TARGET_APPS_FAILED UPGRADE_CHECK_CHOICE UPGRADE_EXIT INSTALL INSTALL_INSTALL INSTALL_EXIT ERROR DELETE DELETE_DELETE DELETE_EXIT ROLLBACK ROLLBACK_START ROLLBACK_EXIT_INSTALL ROLLBACK_EXIT ROLLBACK_EXIT_UPGRADE ROLLBACK_CHOICE INITIAL ERROR_JUNCTION  /  / uuid=f1ca31f2-ddcf-4203-88c8-de367c104151 / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:53.504  INFO 1 --- [eTaskExecutor-1] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:53.540  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state StateMachineState [getIds()=[INSTALL], toString()=AbstractState [id=INSTALL, pseudoState=null, deferred=[], entryActions=[], exitActions=[], stateActions=[], regions=[], submachine=INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5], getClass()=class org.springframework.statemachine.state.StateMachineState]
skipper              | 2019-05-24 22:31:53.576  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INSTALL_INSTALL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1643670584, toString()=AbstractState [id=INSTALL_INSTALL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12493450, deferred=[], entryActions=[org.springframework.cloud.skipper.server.statemachine.InstallInstallAction@149debbb], exitActions=[], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.117  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:log-sink-kafka:jar:2.1.1.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.179  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/log-sink-kafka/2.1.1.RELEASE/log-sink-kafka-2.1.1.RELEASE.jar
skipper              | 2019-05-24 22:31:54.203  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.log-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114000/http-log-ingest-5.log-v1
skipper              | 2019-05-24 22:31:54.310  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:http-source-kafka:jar:2.1.0.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.312  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/http-source-kafka/2.1.0.RELEASE/http-source-kafka-2.1.0.RELEASE.jar
skipper              | 2019-05-24 22:31:54.313  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.http-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114208/http-log-ingest-5.http-v1
skipper              | 2019-05-24 22:31:54.369  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.370  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:54.371  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.372  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.SkipperStateMachineService   : setting future value org.springframework.cloud.skipper.domain.Release@279e0d49
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
mysql_1              | 2019-05-24T22:32:45.648870Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4662ms. The settings might not be optimal. (flushed=2 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:32:52,733] INFO Expiring session 0x10001d6560e0001, timeout of 6000ms exceeded (org.apache.zookeeper.server.ZooKeeperServer)
mysql_1              | 2019-05-24T22:33:08.378945Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 7338ms. The settings might not be optimal. (flushed=1 and evicted=0, during the time.)
mysql_1              | 2019-05-24T22:33:24.272169Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 5118ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:33:28,644] INFO Processed session termination for sessionid: 0x10001d6560e0001 (org.apache.zookeeper.server.PrepRequestProcessor)
kafka_1              | [2019-05-24 22:33:40,709] INFO [GroupMetadataManager brokerId=1001] Removed 0 expired offsets in 2216 milliseconds. (kafka.coordinator.group.GroupMetadataManager)
kafka_1              | [2019-05-24 22:33:49,359] WARN Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001 (org.apache.zookeeper.ClientCnxn)
kafka_1              | [2019-05-24 22:33:56,611] TRACE [Controller id=1001] Checking need to trigger auto leader balancing (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:06,529] DEBUG [Controller id=1001] Preferred replicas by broker Map(1001 -> Map(__consumer_offsets-22 -> Vector(1001), __consumer_offsets-30 -> Vector(1001), __consumer_offsets-8 -> Vector(1001), __consumer_offsets-21 -> Vector(1001), __consumer_offsets-4 -> Vector(1001), __consumer_offsets-27 -> Vector(1001), __consumer_offsets-7 -> Vector(1001), __consumer_offsets-9 -> Vector(1001), __consumer_offsets-46 -> Vector(1001), http-ingest-log-4.http-0 -> Vector(1001), __consumer_offsets-25 -> Vector(1001), __consumer_offsets-35 -> Vector(1001), __consumer_offsets-41 -> Vector(1001), __consumer_offsets-33 -> Vector(1001), __consumer_offsets-23 -> Vector(1001), __consumer_offsets-49 -> Vector(1001), __consumer_offsets-47 -> Vector(1001), __consumer_offsets-16 -> Vector(1001), __consumer_offsets-28 -> Vector(1001), __consumer_offsets-31 -> Vector(1001), __consumer_offsets-36 -> Vector(1001), __consumer_offsets-42 -> Vector(1001), __consumer_offsets-3 -> Vector(1001), __consumer_offsets-18 -> Vector(1001), __consumer_offsets-37 -> Vector(1001), http-ingest-log-3.http-0 -> Vector(1001), __consumer_offsets-15 -> Vector(1001), __consumer_offsets-24 -> Vector(1001), __consumer_offsets-38 -> Vector(1001), __consumer_offsets-17 -> Vector(1001), __consumer_offsets-48 -> Vector(1001), __confluent.support.metrics-0 -> Vector(1001), __consumer_offsets-19 -> Vector(1001), __consumer_offsets-11 -> Vector(1001), __consumer_offsets-13 -> Vector(1001), __consumer_offsets-2 -> Vector(1001), __consumer_offsets-43 -> Vector(1001), __consumer_offsets-6 -> Vector(1001), __consumer_offsets-14 -> Vector(1001), __consumer_offsets-20 -> Vector(1001), __consumer_offsets-0 -> Vector(1001), __consumer_offsets-44 -> Vector(1001), __consumer_offsets-39 -> Vector(1001), __consumer_offsets-12 -> Vector(1001), __consumer_offsets-45 -> Vector(1001), __consumer_offsets-1 -> Vector(1001), __consumer_offsets-5 -> Vector(1001), __consumer_offsets-26 -> Vector(1001), __consumer_offsets-29 -> Vector(1001), __consumer_offsets-34 -> Vector(1001), __consumer_offsets-10 -> Vector(1001), __consumer_offsets-32 -> Vector(1001), __consumer_offsets-40 -> Vector(1001))) (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,269] DEBUG [Controller id=1001] Topics not in preferred replica for broker 1001 Map() (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,993] TRACE [Controller id=1001] Leader imbalance ratio for broker 1001 is 0.0 (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:23,483] INFO Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
mysql_1              | 2019-05-24T22:35:19.628193Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4049ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
...
(several minutes later)
...
dataflow-server exited with code 137

I get the same behavior when swapping out different parts of the stack; for example RabbitMQ for Kafka/Zookeeper, Postgres for MySQL.

My local stack:

OSX 10.14

Java openjdk 11.0.2

Docker engine 18.09.2

Docker Compose 1.23.2

Docker Machine 0.16.1


问:
ASP.NET - Clicking on an image should redirect to a specific page with image url
I am basically making a website for my university project which is basically a photography&wallpapers site
I have saved images in folder(named as ImageStorage) and I am retrieving images through Image link from database
I have used datalist in my page(image-viewer.aspx) to show my all images as imagebutton. What I basically want is that when user clicks on an image it redirects to another page(image-detail.aspx)and also sends the url or id of that image so that I can use it to display that image on (image-detail.aspx) page

Here is my image_viewer.aspx code:

```<code><form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" CellPadding="15" CellSpacing="10" DataSourceID="SqlDataSource1" GridLines="Both" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" RepeatColumns="3" RepeatDirection="Horizontal" style="margin-left: 0px" >
<ItemTemplate>
<br />
<asp:ImageButton ID="Image1"  style="width:335px ;height:210px" runat="server" ImageUrl='<%# Eval("ImagePath") %>' CommandName="imgClick"/>
</ItemTemplate>
</asp:DataList>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:photo_stock_viewConnectionString %>" SelectCommand="SELECT * FROM [ImageInfo1]"></asp:SqlDataSource>
<br />
</div>
</form>
</code>```

HTML code in image_detail.aspx to show image:

```<code><img class="img-fluid mt-4" src="ImageStorage/image-detail.jpg"/>
</code>```

答:
You need code behind to handle the image click event

```<code>protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
    if (e.CommandName == "imgClick")
    {
       ImageButton btn = e.CommandSource as ImageButton;
       //Do what you need to do here
       string imgUrl = btn.ImageUrl;
       Response.Redirect(imgUrl,true);
}
</code>```

If you need set more info like imageID, you also can use CommandArgument as parameter, set in html and get it from code behind
Here is the URL how to know which image button I click in datalist

Body:
I am basically making a website for my university project which is basically a photography&wallpapers site
I have saved images in folder(named as ImageStorage) and I am retrieving images through Image link from database
I have used datalist in my page(image-viewer.aspx) to show my all images as imagebutton. What I basically want is that when user clicks on an image it redirects to another page(image-detail.aspx)and also sends the url or id of that image so that I can use it to display that image on (image-detail.aspx) page

Here is my image_viewer.aspx code:

<form id="form1" runat="server">

<asp:DataList ID="DataList1" runat="server" CellPadding="15" CellSpacing="10" DataSourceID="SqlDataSource1" GridLines="Both" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" RepeatColumns="3" RepeatDirection="Horizontal" style="margin-left: 0px" >
<ItemTemplate>

<asp:ImageButton ID="Image1"  style="width:335px ;height:210px" runat="server" ImageUrl='<%# Eval("ImagePath") %>' CommandName="imgClick"/>
</ItemTemplate>
</asp:DataList>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:photo_stock_viewConnectionString %>" SelectCommand="SELECT * FROM [ImageInfo1]"></asp:SqlDataSource>

</form>

HTML code in image_detail.aspx to show image:

Body:
You need code behind to handle the image click event

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
    if (e.CommandName == "imgClick")
    {
       ImageButton btn = e.CommandSource as ImageButton;
       //Do what you need to do here
       string imgUrl = btn.ImageUrl;
       Response.Redirect(imgUrl,true);
}

If you need set more info like imageID, you also can use CommandArgument as parameter, set in html and get it from code behind
Here is the URL how to know which image button I click in datalist


问:
Duplicate bases for class
I am working on a school project, using python and kivy. I am not very familier with classes and inheritance. I created a class in the python file that contains "pass". The class is inheriting kivy's property (ListItemButton) then I use this property in kivy file to create a "ListView" and an adapter in it. My kivy App is working fine but visiual studio code shows me the error"Duplicate bases for class 'Boom'pylint(duplicate-bases)", I don't why.

I have tried changing the class name from "ToDoListButton" to "Boom". Just trying but it didn't work.

```<code>"""this is python file"""
from kivy.uix.listview import ListItemButton

class Boom(ListItemButton):
    pass
</code>```

```<code>"""this is kivy file"""
#: import main thelist
#: import ListAdapter kivy.adapters.listadapter.ListAdapter
#: import ListItemButton kivy.uix.listview.ListItemButton

<TodoList> """this is another class for a window in the app"""
        ListView:
            id: thelist
            adapter:    ListAdapter(data=["study"], cls=main.Boom)
</code>```

The app is working as it supposed to but this error "Duplicate bases for class 'Boom'pylint(duplicate-bases)" is still showen in visual studio code.

答:
It means that ListItemButton is already defined. You can ignore that error as long your Kivy App is working fine. It could be a glitch from pylint. You will not get this if you use PyCharm.

Try removing class Boom, import statement, #: import main thelist and replace cls=main.Boom with cls=ListItemButton.

Since you are starting your project, you might want to use RecycleView instead because ListView has been deprecated since version 1.10.0 and totally removed in version 1.11.0.

Title: Duplicate bases for class

Body:
I am working on a school project, using python and kivy. I am not very familier with classes and inheritance. I created a class in the python file that contains "pass". The class is inheriting kivy's property (ListItemButton) then I use this property in kivy file to create a "ListView" and an adapter in it. My kivy App is working fine but visiual studio code shows me the error"Duplicate bases for class 'Boom'pylint(duplicate-bases)", I don't why.

I have tried changing the class name from "ToDoListButton" to "Boom". Just trying but it didn't work.

"""this is python file"""
from kivy.uix.listview import ListItemButton

class Boom(ListItemButton):
    pass

"""this is kivy file"""
#: import main thelist
#: import ListAdapter kivy.adapters.listadapter.ListAdapter
#: import ListItemButton kivy.uix.listview.ListItemButton

<TodoList> """this is another class for a window in the app"""
        ListView:
            id: thelist
            adapter:    ListAdapter(data=["study"], cls=main.Boom)

The app is working as it supposed to but this error "Duplicate bases for class 'Boom'pylint(duplicate-bases)" is still showen in visual studio code.


问:
Run coverage on tests directory via Travis-CI
I am unable to run coverage.py in the tests directory from a Python project. I have a tests directory containing an __init__.py file and some test_*.py files where I define the tests I want to run in the __main__ block of every test file.

The tests directory is located in the same folder as the .travis.yml file which looks like:

The script block works when I run a single file as coverage run tests/test_errors.py, but whenever I try to run all the files in the directory it does not work.

I have tried the following solutions:

How can pytest-cov report coverage of python code that is executed as a result of pexpect.spawn? => which did not work for me as Travis-CI debugger said there was no data to combine, and this solution is not excatly what I am looking for, as the most efficient way is not to list all the test files, just the directory I guess.

Python coverage: running more than 1 test => this solution works but the coverage just is made in the tests directory, and I want to test the coverage of the whole project in codecov. To clarify, codecov shows:

Whenever I run the coverage for a single file, codecov outputs this:

Which is what I am looking for, but when it comes to testing multiple Python files contained in the tests directory. Because as you can see, that is the codecov output when coverage run tests/test_investpy.py not for the whole `tests/' directory.

Any help or information is welcomed! An thank you in advance!

(NOTE: for further information about the project structure you can check the project in https://github.com/alvarob96/investpy as it is an Open Source Project)

答:
After some more research and testing I found out that pytest-cov documentation has an appendix on generating multiple coverage reports for a single test run: https://pytest-cov.readthedocs.io/en/latest/reporting.html

To execute every test contained in tests/ and get the code coverage results in codecov, the script line inside .travis.yml should be: pytest --cov-report term --cov=investpy tests/, via pytest you can generate a terminal coverage report for a project specifying the tests/ directory.

So the .travis.yml when running multiple tests on the same project to combine the code coverage results should be:

So the required packages to get to run the coverage tests on Travis-CI are:

pip install pytest==4.5.0

pip install codecov==2.0.15

pip install pytest-cov==2.7.1

As I already solved it feel free to ask me anything related if you have the same problem and I can help you anyway! If you found this answer useful please rate this answer!


问:
session error in codeigniter?
when I want to set session data in codeigniter 3 it says error like:

```<code>A PHP Error was encountered

Severity: Warning

Message: mkdir(): Invalid path

Filename: drivers/Session_files_driver.php

Line Number: 117

Backtrace:

File: C:\xampp\htdocs\ci-test\application\controllers\login.php
Line: 7
Function: __construct

File: C:\xampp\htdocs\ci-test\index.php
Line: 292
Function: require_once
</code>```

Here is the code that where want to set session data.

```<code>$sess_array = array(
         'id' => 1,
         'username' => 'bikramkc.kc@gmail.com'
       );
$this->session->set_userdata($sess_array);
</code>```

答:
I had a similar case I have a multihost in godaddy and first I corrected the .htacces file

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>
</code>```

Then correct the file config.php

```<code>$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = sys_get_temp_dir();
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
</code>```

Title: session error in codeigniter?

Body:
when I want to set session data in codeigniter 3 it says error like:

A PHP Error was encountered

Severity: Warning

Message: mkdir(): Invalid path

Filename: drivers/Session_files_driver.php

Line Number: 117

Backtrace:

File: C:\xampp\htdocs\ci-test\application\controllers\login.php
Line: 7
Function: __construct

File: C:\xampp\htdocs\ci-test\index.php
Line: 292
Function: require_once

Here is the code that where want to set session data.

$sess_array = array(
         'id' => 1,
         'username' => 'bikramkc.kc@gmail.com'
       );
$this->session->set_userdata($sess_array);

Body:
I had a similar case I have a multihost in godaddy and first I corrected the .htacces file

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>

Then correct the file config.php

$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = sys_get_temp_dir();
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;