问:
How to modify a string inside a struct in C?
I am trying to modify a field inside a struct. I have no trouble doing this with other types (i.e. int, float etc.) but char * is giving me problems. I think I have to do something like:

```<code>typedef struct{
    char *string_field;
} struct_name;

struct_name *struct_name1;
struct_name1 = (struct_name *) malloc(sizeof(struct_name));
strcpy(struct_name1->string_field, new_string);

printf("New string: %s\n", struct_name1->string_field);
</code>```

But this gives me a segmentation fault. What reason do you think I would get this problem for? Initially, I thought maybe the char *string_field was not big enough to copy to, but I changed the size of it manually to be of size 100 (more than enough) and I still get this problem.

答:
Allocate memory for the structure as well as for the string.
In example below there is a room for 63 characters in the string.
Remember to free the allocated memory.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
    char *string_field;
} struct_name;

int main()
{
   struct_name *struct_name1;
    struct_name1 =  malloc(sizeof(struct_name));
    struct_name1->string_field = malloc(64*sizeof(char));

    strcpy(struct_name1->string_field, "new_string");

    printf("New string: %s\n", struct_name1->string_field);

    free(struct_name1->string_field);
    free(struct_name1);

    return 0;
}
</code>```

OUTPUT:

```<code>New string: new_string
</code>```

Body:
I am trying to modify a field inside a struct. I have no trouble doing this with other types (i.e. int, float etc.) but char * is giving me problems. I think I have to do something like:

typedef struct{
    char *string_field;
} struct_name;

struct_name *struct_name1;
struct_name1 = (struct_name *) malloc(sizeof(struct_name));
strcpy(struct_name1->string_field, new_string);

printf("New string: %s\n", struct_name1->string_field);

But this gives me a segmentation fault. What reason do you think I would get this problem for? Initially, I thought maybe the char *string_field was not big enough to copy to, but I changed the size of it manually to be of size 100 (more than enough) and I still get this problem.

Body:
Allocate memory for the structure as well as for the string.
In example below there is a room for 63 characters in the string.
Remember to free the allocated memory.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
    char *string_field;
} struct_name;

int main()
{
   struct_name *struct_name1;
    struct_name1 =  malloc(sizeof(struct_name));
    struct_name1->string_field = malloc(64*sizeof(char));

    strcpy(struct_name1->string_field, "new_string");

    printf("New string: %s\n", struct_name1->string_field);

    free(struct_name1->string_field);
    free(struct_name1);

    return 0;
}

OUTPUT:

New string: new_string


来源: stackexchange

问:
PHP - can not connect to remote mysql database
I have a problem connecting to my mysql database on another server from my VPS, connecting to localhost mysql works fine. This is my PHP script:

```<code><?php
$servername = "mysql.example.com";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=database", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
</code>```

I am getting this error: SQLSTATE[HY000] [1045] Access denied for user 'username'@'fh24-219.cybersales.cz' (using password: YES)

The problem is propably that host changed from mysql.example.com to fh24-219.cybersales.cz(it points to my VPS ip). I have no idea why. I have already changed httpd_can_network_connect_db and httpd_can_network_connect to 1. I would appreciate some help. I can connect to mysql.example.com with phpmyadmin. Thanks.

答:
Possible, that your $username do not have permissions to connect to database from server, where the PHP script is executed.

Try to create a user with permission to connect from remote server. Execute on MySQL server:

```<code>CREATE USER 'testuser'@'fh24-219.cybersales.cz' IDENTIFIED BY 'mypass';
</code>```

Change 'fh24-219.cybersales.cz' to PHP server IP. If you will write '%' as server IP it will be accessible from anywhere (it is not recommended).

Updated:

If you do not know what permissions user have, execute SHOW GRANTS; on for e.g. PhpMyAdmin to see if remote IP is mentioned.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem connecting to my mysql database on another server from my VPS, connecting to localhost mysql works fine. This is my PHP script:

<?php
$servername = "mysql.example.com";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=database", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

I am getting this error: SQLSTATE[HY000] [1045] Access denied for user 'username'@'fh24-219.cybersales.cz' (using password: YES)

The problem is propably that host changed from mysql.example.com to fh24-219.cybersales.cz(it points to my VPS ip). I have no idea why. I have already changed httpd_can_network_connect_db and httpd_can_network_connect to 1. I would appreciate some help. I can connect to mysql.example.com with phpmyadmin. Thanks.

Body:
Possible, that your $username do not have permissions to connect to database from server, where the PHP script is executed.

Try to create a user with permission to connect from remote server. Execute on MySQL server:

CREATE USER 'testuser'@'fh24-219.cybersales.cz' IDENTIFIED BY 'mypass';

Change 'fh24-219.cybersales.cz' to PHP server IP. If you will write '%' as server IP it will be accessible from anywhere (it is not recommended).

Updated:

If you do not know what permissions user have, execute SHOW GRANTS; on for e.g. PhpMyAdmin to see if remote IP is mentioned.


问:
Pycharm with Django throws ImportError: cannot import name 'unittest'
I am working through the Django tutorial, and am trying to get the test cases to run with PyCharm. I have encountered a problem however. When I run the command: app test

I am faced with this exception: test framework quit unexpectedly:

```<code>F:\programming\Python\python.exe "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py" test a F:\programming\Projects\pycharm\untitled
Testing started at 4:54 PM ...
Traceback (most recent call last):
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 157, in <module>
    utility.execute()
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 110, in execute
    from django_test_runner import is_nosetest
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_runner.py", line 42, in <module>
    from django.utils import unittest
ImportError: cannot import name 'unittest'

Process finished with exit code 1
</code>```

Apparently, the django_test_manage.py file does not work. How can I fix this?
this happens even when the test.py class is empty. So it must be a problem with PyCharm then(?)
I am using PyCharm Pro 2017.2.4, Django 2.0 and Python 3.6
My run/debug configurations are just the basic, preset Django Settings that PyCharm does.

答:
I think it's a bug in django_test_runner.py of Pycharm.

In my pycharm, the code is :

```<code>  if VERSION[1] >= 7:
    import unittest
  else:
    from django.utils import unittest
</code>```

But you (and i) use Django 2.0, so pycharm import  'from django.utils import unittest' ...

I have modified my test_runner like that :

```<code>  if VERSION[0] > 1 or VERSION[1] >= 7:
    import unittest
  else:
    from django.utils import unittest
</code>```

You need modify the same file in other places with the same tricks.

It's work !

ContentLicense: CC BY-SA 4.0

Body:
I am working through the Django tutorial, and am trying to get the test cases to run with PyCharm. I have encountered a problem however. When I run the command: app test

I am faced with this exception: test framework quit unexpectedly:

F:\programming\Python\python.exe "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py" test a F:\programming\Projects\pycharm\untitled
Testing started at 4:54 PM ...
Traceback (most recent call last):
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 157, in <module>
    utility.execute()
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 110, in execute
    from django_test_runner import is_nosetest
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_runner.py", line 42, in <module>
    from django.utils import unittest
ImportError: cannot import name 'unittest'

Process finished with exit code 1

Apparently, the django_test_manage.py file does not work. How can I fix this?
this happens even when the test.py class is empty. So it must be a problem with PyCharm then(?)
I am using PyCharm Pro 2017.2.4, Django 2.0 and Python 3.6
My run/debug configurations are just the basic, preset Django Settings that PyCharm does.

Body:
I think it's a bug in django_test_runner.py of Pycharm.

In my pycharm, the code is :

  if VERSION[1] >= 7:
    import unittest
  else:
    from django.utils import unittest

But you (and i) use Django 2.0, so pycharm import  'from django.utils import unittest' ...

I have modified my test_runner like that :

  if VERSION[0] > 1 or VERSION[1] >= 7:
    import unittest
  else:
    from django.utils import unittest

You need modify the same file in other places with the same tricks.

It's work !


问:
Normalize CSV data before inserting into SQLite database with Pandas or plain SQL
Here is a diagram of what I want to accomplish:

The actual CSV files can have tens of thousands or hundreds of thousands of rows per their equivalent of a Name/Phone combination, which wastes an enormous amount of memory and disk space. I know how to normalize this data once it is actually in the database using SQL, but I wish to avoid copying all those duplicates in the first place and instead insert a foreign key relation. The disk space consumed by repeated values in these columns is considerable.

Currently I am using Python and Pandas to automate the process of creating a SQLite database and inserting the data into it. I have also tried PostgreSQL for this, though found it slower than pandas+sqlite for some reason.

How do I split this data into multiple tables before inserting into the database?

EDIT Because of the size of the files, I am processing them in chunks, like this:

```<code>import glob
import pandas as pd
import sqlite3

def read_nlines(file: str, n: int = 10) -> pd.DataFrame:
    return pd.read_csv(file, nrows=n, comment='#', skip_blank_lines=True,
                       sep='\t', encoding='utf-8')

conn = sqlite3.connect("data.db")
cur = conn.cursor()

files = glob.glob("data/*.txt")

for file in files:
    data = read_nlines(file)
###--->
###---> This is where I want to transform the data, before writing to sql <---###
###--->
    data.to_sql('table',con=conn,if_exists='replace')

conn.close()
</code>```

Body:
Here is a diagram of what I want to accomplish:

The actual CSV files can have tens of thousands or hundreds of thousands of rows per their equivalent of a Name/Phone combination, which wastes an enormous amount of memory and disk space. I know how to normalize this data once it is actually in the database using SQL, but I wish to avoid copying all those duplicates in the first place and instead insert a foreign key relation. The disk space consumed by repeated values in these columns is considerable.

Currently I am using Python and Pandas to automate the process of creating a SQLite database and inserting the data into it. I have also tried PostgreSQL for this, though found it slower than pandas+sqlite for some reason.

How do I split this data into multiple tables before inserting into the database?

EDIT Because of the size of the files, I am processing them in chunks, like this:

import glob
import pandas as pd
import sqlite3

def read_nlines(file: str, n: int = 10) -> pd.DataFrame:
    return pd.read_csv(file, nrows=n, comment='#', skip_blank_lines=True,
                       sep='\t', encoding='utf-8')

conn = sqlite3.connect("data.db")
cur = conn.cursor()

files = glob.glob("data/*.txt")

for file in files:
    data = read_nlines(file)
###--->
###---> This is where I want to transform the data, before writing to sql <---###
###--->
    data.to_sql('table',con=conn,if_exists='replace')

conn.close()

Body:
You can use pandas

df=pd.DataFrame({'Name':['Joe','Bob','Bob','Bob','Steve','Steve','Steve'],'Phone':['111','222','222','222','333','333','333'],'S1':[1,2,3,4,5,6,7],'S2':[1,2,3,4,5,6,7],'S3':[1,2,3,4,5,6,7]})
df['ID']=pd.factorize(df['Name'])[0]+1
sql1=df[['ID','S1','S2','S3']]
sql2=df[['ID','Name','Phone']].drop_duplicates()
sql1
Out[729]:
   ID  S1  S2  S3
0   1   1   1   1
1   2   2   2   2
2   2   3   3   3
3   2   4   4   4
4   3   5   5   5
5   3   6   6   6
6   3   7   7   7
sql2
Out[730]:
   ID   Name Phone
0   1    Joe   111
1   2    Bob   222
4   3  Steve   333

EDIT:

ncount=1
for file in files:
    data = read_nlines(file)

    data['ID'] = pd.factorize(data['Name'])[0] + ncount
    ncount+=data['Name'].nunique()
    sql1 = df[['ID', 'S1', 'S2', 'S3']]
    sql2 = df[['ID', 'Name', 'Phone']].drop_duplicates()


问:
Removing \r from lines read from file
I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

```<code>    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOutput.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }
</code>```

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

```<code>cleanLine.Replace("\r",""); //assigns a value to nothing
</code>```

I should have assigned cleanLine to cleanLine.Replace();

```<code>cleanLine = cleanLine.Replace("\r","");
</code>```

答:
In Windows, the line indicator is actually \r\n, so your best bet may be to do an initial replace of "\r\n" with some other character that isn't found elsewhere in the file (like maybe "|"), and then split on the replaced character.  Otherwise, if you just replace "\r", you may end up replacing a "\r" that isn't actually at the end of a line (although this is pretty doubtful).

How are you reading the file in the first place?  The .Net TextReader class has a ReadLine() method, the use of which would let you avoid this particular problem entirely.

ContentLicense: CC BY-SA 2.5

Title: Removing \r from lines read from file

Body:
I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOutput.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

cleanLine.Replace("\r",""); //assigns a value to nothing

I should have assigned cleanLine to cleanLine.Replace();

cleanLine = cleanLine.Replace("\r","");


问:
SQL How to SELECT all rows with repeated id's but not the first of each one?
I have a database with repeated IDs, and I want to change the names of this repeated IDs.

So, I have a database of Vehicles and in columns I have the License number (id), the type of vehicle, the colour and also the make.

All the ids are repeated in the database, and I want to SELECT all of them except the first row of each different ID (something like a "DISTINCT id" but inverse...).

EDIT 2:

I have created this table

```<code>DROP TABLE IF EXISTS Proces1 CASCADE;
CREATE TABLE Proces1 AS
(
    SELECT id_importat AS id_aux, driver_city AS city_aux, driver_state AS state_aux, gender AS g_aux, race AS r_aux
    FROM ImportaViolations
    WHERE id_importat IN (
        SELECT id_importat
        FROM ImportaViolations
        GROUP BY id_importat
        HAVING (COUNT(*) > 1))
    GROUP BY id_importat, driver_city, driver_state, gender, race
);
</code>```

And in this table I have repeated id's but with different information in the columns.

Something like:

```<code>id_aux   city_aux      state_aux     g_aux     r_aux
1        London        England        M        WHITE
1        London        England        F        BLACK
2        Madrid        Spain          M        BLACK
2        London        England        F        WHITE
2        London        England        M        WHITE
...
</code>```

So now, I want to SELECT all the rows with repeated id_aux except for the first one of each different id_aux. So I want to have this final result (in this example):

```<code>id_aux   city_aux      state_aux      g_aux    r_aux
1        London        England        F        BLACK
2        London        England        F        WHITE
2        London        England        M        WHITE
...
</code>```

答:
Please pay close attention to the order of rows in the following demonstration. & please note I added a few extra rows as well. Initially we start with "random" rows as and when created in ImportaViolations for this example  "first row" for each id_importat

```<code>INSERT INTO ImportaViolations
    (id_importat, driver_city, driver_state, gender, race)
VALUES
    (1, 'London', 'England', 'M', 'WHITE'),
    (2, 'Madrid', 'Spain', 'M', 'BLACK'),
</code>```

BUT if we run this query (with no "order by"):

```<code>SELECT id_importat AS id_aux, driver_city AS city_aux
     , driver_state AS state_aux, gender AS g_aux, race AS r_aux
     , rn
FROM (
      select id_importat, driver_city, driver_state, gender, race
           , row_number() over(partition by id_importat) as rn
      from ImportaViolations
     ) d
WHERE rn = 1
</code>```

This is the result:

```<code>| id_aux | city_aux | state_aux | g_aux | r_aux | rn |
|--------|----------|-----------|-------|-------|----|
|      1 |   London |   England |     M | WHITE |  1 |
|      2 |   London |   England |     F | WHITE |  1 |
</code>```

That result is affected by the necessary partition by (without this there would be a total of one row in the table with a row number of 1).

So: The moral of this tale is that you MUST carefully consider the ORDER to determine what should be "The FIRST ROW" of each id_importat.

SQL Fiddle Demo

```<code>CREATE TABLE ImportaViolations
    (id_importat int, driver_city varchar(6), driver_state varchar(7), gender varchar(1), race varchar(5))
;

INSERT INTO ImportaViolations
    (id_importat, driver_city, driver_state, gender, race)
VALUES
    (1, 'London', 'England', 'M', 'WHITE'),
    (2, 'Madrid', 'Spain', 'M', 'BLACK'),
    (1, 'London', 'England', 'F', 'BLACK'),
    (2, 'London', 'England', 'M', 'WHITE'),
    (1, 'London', 'England', 'F', 'BLACK'),
    (2, 'Madrid', 'Spain', 'M', 'BLACK'),
    (2, 'London', 'England', 'F', 'WHITE'),
    (1, 'London', 'England', 'M', 'WHITE'),
    (2, 'London', 'England', 'F', 'WHITE')
;
</code>```

Main Query:

```<code>DROP TABLE IF EXISTS Proces1 CASCADE;
CREATE TABLE Proces1 AS
(
    SELECT id_importat AS id_aux, driver_city AS city_aux
         , driver_state AS state_aux, gender AS g_aux, race AS r_aux
         , rn
    FROM (
          select id_importat, driver_city, driver_state, gender, race
               , row_number() over(partition by id_importat order by 1) as rn
          from ImportaViolations
         ) d
    WHERE rn > 1
);
</code>```

Query 1:

```<code>select * from Proces1
</code>```

Results:

```<code>| id_aux | city_aux | state_aux | g_aux | r_aux | rn |
|--------|----------|-----------|-------|-------|----|
|      1 |   London |   England |     F | BLACK |  2 |
|      1 |   London |   England |     F | BLACK |  3 |
|      1 |   London |   England |     M | WHITE |  4 |
|      2 |   Madrid |     Spain |     M | BLACK |  2 |
|      2 |   Madrid |     Spain |     M | BLACK |  3 |
|      2 |   London |   England |     F | WHITE |  4 |
|      2 |   London |   England |     M | WHITE |  5 |
</code>```

Query 2:

```<code>select * from ImportaViolations
</code>```

Results:

```<code>| id_importat | driver_city | driver_state | gender |  race |
|-------------|-------------|--------------|--------|-------|
|           1 |      London |      England |      M | WHITE |
|           2 |      Madrid |        Spain |      M | BLACK |
|           1 |      London |      England |      F | BLACK |
|           2 |      London |      England |      M | WHITE |
|           1 |      London |      England |      F | BLACK |
|           2 |      Madrid |        Spain |      M | BLACK |
|           2 |      London |      England |      F | WHITE |
|           1 |      London |      England |      M | WHITE |
|           2 |      London |      England |      F | WHITE |
</code>```

Body:
I have a database with repeated IDs, and I want to change the names of this repeated IDs.

So, I have a database of Vehicles and in columns I have the License number (id), the type of vehicle, the colour and also the make.

All the ids are repeated in the database, and I want to SELECT all of them except the first row of each different ID (something like a "DISTINCT id" but inverse...).

EDIT 2:

I have created this table

DROP TABLE IF EXISTS Proces1 CASCADE;
CREATE TABLE Proces1 AS
(
    SELECT id_importat AS id_aux, driver_city AS city_aux, driver_state AS state_aux, gender AS g_aux, race AS r_aux
    FROM ImportaViolations
    WHERE id_importat IN (
        SELECT id_importat
        FROM ImportaViolations
        GROUP BY id_importat
        HAVING (COUNT(*) > 1))
    GROUP BY id_importat, driver_city, driver_state, gender, race
);

And in this table I have repeated id's but with different information in the columns.

Something like:

id_aux   city_aux      state_aux     g_aux     r_aux
1        London        England        M        WHITE
1        London        England        F        BLACK
2        Madrid        Spain          M        BLACK
2        London        England        F        WHITE
2        London        England        M        WHITE
...

So now, I want to SELECT all the rows with repeated id_aux except for the first one of each different id_aux. So I want to have this final result (in this example):

id_aux   city_aux      state_aux      g_aux    r_aux
1        London        England        F        BLACK
2        London        England        F        WHITE
2        London        England        M        WHITE
...

Body:
Please pay close attention to the order of rows in the following demonstration. & please note I added a few extra rows as well. Initially we start with "random" rows as and when created in ImportaViolations for this example  "first row" for each id_importat

INSERT INTO ImportaViolations
    (id_importat, driver_city, driver_state, gender, race)
VALUES
    (1, 'London', 'England', 'M', 'WHITE'),
    (2, 'Madrid', 'Spain', 'M', 'BLACK'),

BUT if we run this query (with no "order by"):

SELECT id_importat AS id_aux, driver_city AS city_aux
     , driver_state AS state_aux, gender AS g_aux, race AS r_aux
     , rn
FROM (
      select id_importat, driver_city, driver_state, gender, race
           , row_number() over(partition by id_importat) as rn
      from ImportaViolations
     ) d
WHERE rn = 1

This is the result:

| id_aux | city_aux | state_aux | g_aux | r_aux | rn |
|--------|----------|-----------|-------|-------|----|
|      1 |   London |   England |     M | WHITE |  1 |
|      2 |   London |   England |     F | WHITE |  1 |

That result is affected by the necessary partition by (without this there would be a total of one row in the table with a row number of 1).

So: The moral of this tale is that you MUST carefully consider the ORDER to determine what should be "The FIRST ROW" of each id_importat.

SQL Fiddle Demo

CREATE TABLE ImportaViolations
    (id_importat int, driver_city varchar(6), driver_state varchar(7), gender varchar(1), race varchar(5))
;

INSERT INTO ImportaViolations
    (id_importat, driver_city, driver_state, gender, race)
VALUES
    (1, 'London', 'England', 'M', 'WHITE'),
    (2, 'Madrid', 'Spain', 'M', 'BLACK'),
    (1, 'London', 'England', 'F', 'BLACK'),
    (2, 'London', 'England', 'M', 'WHITE'),
    (1, 'London', 'England', 'F', 'BLACK'),
    (2, 'Madrid', 'Spain', 'M', 'BLACK'),
    (2, 'London', 'England', 'F', 'WHITE'),
    (1, 'London', 'England', 'M', 'WHITE'),
    (2, 'London', 'England', 'F', 'WHITE')
;

Main Query:

DROP TABLE IF EXISTS Proces1 CASCADE;
CREATE TABLE Proces1 AS
(
    SELECT id_importat AS id_aux, driver_city AS city_aux
         , driver_state AS state_aux, gender AS g_aux, race AS r_aux
         , rn
    FROM (
          select id_importat, driver_city, driver_state, gender, race
               , row_number() over(partition by id_importat order by 1) as rn
          from ImportaViolations
         ) d
    WHERE rn > 1
);

Query 1:

select * from Proces1

Results:

| id_aux | city_aux | state_aux | g_aux | r_aux | rn |
|--------|----------|-----------|-------|-------|----|
|      1 |   London |   England |     F | BLACK |  2 |
|      1 |   London |   England |     F | BLACK |  3 |
|      1 |   London |   England |     M | WHITE |  4 |
|      2 |   Madrid |     Spain |     M | BLACK |  2 |
|      2 |   Madrid |     Spain |     M | BLACK |  3 |
|      2 |   London |   England |     F | WHITE |  4 |
|      2 |   London |   England |     M | WHITE |  5 |

Query 2:

select * from ImportaViolations

Results:

| id_importat | driver_city | driver_state | gender |  race |
|-------------|-------------|--------------|--------|-------|
|           1 |      London |      England |      M | WHITE |
|           2 |      Madrid |        Spain |      M | BLACK |
|           1 |      London |      England |      F | BLACK |
|           2 |      London |      England |      M | WHITE |
|           1 |      London |      England |      F | BLACK |
|           2 |      Madrid |        Spain |      M | BLACK |
|           2 |      London |      England |      F | WHITE |
|           1 |      London |      England |      M | WHITE |
|           2 |      London |      England |      F | WHITE |


问:
How to unregister device backbutton on moving to model or when moving to another page from sidemenu
I have override the registerbackbuttonaction inside my home page and unregistering my backbutton action ionViewDidLeave it works fine when i push to another page from my home page.

Issues:

I have written this.nav.push("pagename") inside my app.component.ts file For side menu items. because of this i am not able to go back onclick of device back button after over-ridding the device back button.

When i remove the over-ridding back button function from my entire app i am getting the output what i am expecting.

This also happens when on opening model page also my lifecycle event is not triggering.

Here is my code

ts file

```<code>initializeBackButtonCustomHandler(){

    let self = this
    this.platform.ready().then(() => {

    self.unregisterBackButtonAction = self.platform.registerBackButtonAction(() => {
      if (this.menuCtrl.getOpen() != null) {
        this.menuCtrl.close();
        return
      }else if(this.modal && this.modal.index === 0) {
        console.log("invoking modal value")
        /* closes modal */
        // this.modal.dismiss();
        this.viewCtrl.dismiss();
        return

      }
      this.toast = this.toastCtrl.create({
        message: "Press back again to exit the app",
        position: 'bottom',
        duration: 1500
      });
        this.toast.present();
        this.clickCount = this.clickCount + 1;
        this.toast.onDidDismiss(() => {
          this.clickCount = 0;
        })

      if(this.clickCount == 2){
        this.clickCount = 0;
        this.toast.dismiss();
          this.platform.exitApp();
      }
    }, 10)
  });
  }

  ionViewDidEnter(){
    this.initializeBackButtonCustomHandler();

}

  ionViewDidLeave() {
    this.unregisterBackButtonAction && this.unregisterBackButtonAction();

}
</code>```

The above code works fine when i do push it is unregistering the back button but for model and sidemenu part it is not working.

答:
The app.component is a special component. In effect it is your entire application, therefore it does not have ionic life-cycle events available to it. Only ionic pages have those events.

Also try to lower the priority of your back button listener from 10 to 0. Here is an example of one my team has implemented in app.component, we also recently added a are you sure modal popup before closing the app.

```<code>/**
 * Method will listen for native backButton on Android
 * Back:
 * If not at nav root will perform nav.pop() same as ionic menu back button.
 * Login:
 * Because of the behavior of backButton on mobile we need to force
 * the user back to the Azure logon page if they are not logged in .
 * Close App:
 * If at a root page and android will ask user if want to close app. Then react to yes/no.
 */
public setupMobileBackButtonListener(): void {
    if (PlatformUtils.isMobile()) {
        this.platform.registerBackButtonAction(() => {
            let user = this.memoryStoreProvider.loginMemoryData().data;
            if (cmp.isUndefinedOrNull(user)) {
                this.platform.exitApp();
            }

            if (cmp.isDefinedAndNotNull(this.nav) && this.nav.length() === 1) {
                this.modalProvider.openYesNoActionModal(CLOSE_APPLICATION_QUESTION_MESSAGE).then(result => {
                    if (result === YES_NO_MODAL_YES_SELECTED) {
                        this.platform.exitApp(); // no back pages in queue exit app
                    }
                });
            } else {
                this.nav.pop(); // backPage
            }
        }, 0);
    }
}
</code>```

Notice the 0 priority and we never kill the listener. The downside of this is extra logic to make it work like the ionic back menu button.

Body:
I have override the registerbackbuttonaction inside my home page and unregistering my backbutton action ionViewDidLeave it works fine when i push to another page from my home page.

Issues:

I have written this.nav.push("pagename") inside my app.component.ts file For side menu items. because of this i am not able to go back onclick of device back button after over-ridding the device back button.

When i remove the over-ridding back button function from my entire app i am getting the output what i am expecting.

This also happens when on opening model page also my lifecycle event is not triggering.

Here is my code

ts file

initializeBackButtonCustomHandler(){

    let self = this
    this.platform.ready().then(() => {

    self.unregisterBackButtonAction = self.platform.registerBackButtonAction(() => {
      if (this.menuCtrl.getOpen() != null) {
        this.menuCtrl.close();
        return
      }else if(this.modal && this.modal.index === 0) {
        console.log("invoking modal value")
        /* closes modal */
        // this.modal.dismiss();
        this.viewCtrl.dismiss();
        return

      }
      this.toast = this.toastCtrl.create({
        message: "Press back again to exit the app",
        position: 'bottom',
        duration: 1500
      });
        this.toast.present();
        this.clickCount = this.clickCount + 1;
        this.toast.onDidDismiss(() => {
          this.clickCount = 0;
        })

      if(this.clickCount == 2){
        this.clickCount = 0;
        this.toast.dismiss();
          this.platform.exitApp();
      }
    }, 10)
  });
  }

  ionViewDidEnter(){
    this.initializeBackButtonCustomHandler();

}

  ionViewDidLeave() {
    this.unregisterBackButtonAction && this.unregisterBackButtonAction();

}

The above code works fine when i do push it is unregistering the back button but for model and sidemenu part it is not working.

Body:
The app.component is a special component. In effect it is your entire application, therefore it does not have ionic life-cycle events available to it. Only ionic pages have those events.

Also try to lower the priority of your back button listener from 10 to 0. Here is an example of one my team has implemented in app.component, we also recently added a are you sure modal popup before closing the app.

/**
 * Method will listen for native backButton on Android
 * Back:
 * If not at nav root will perform nav.pop() same as ionic menu back button.
 * Login:
 * Because of the behavior of backButton on mobile we need to force
 * the user back to the Azure logon page if they are not logged in .
 * Close App:
 * If at a root page and android will ask user if want to close app. Then react to yes/no.
 */
public setupMobileBackButtonListener(): void {
    if (PlatformUtils.isMobile()) {
        this.platform.registerBackButtonAction(() => {
            let user = this.memoryStoreProvider.loginMemoryData().data;
            if (cmp.isUndefinedOrNull(user)) {
                this.platform.exitApp();
            }

            if (cmp.isDefinedAndNotNull(this.nav) && this.nav.length() === 1) {
                this.modalProvider.openYesNoActionModal(CLOSE_APPLICATION_QUESTION_MESSAGE).then(result => {
                    if (result === YES_NO_MODAL_YES_SELECTED) {
                        this.platform.exitApp(); // no back pages in queue exit app
                    }
                });
            } else {
                this.nav.pop(); // backPage
            }
        }, 0);
    }
}

Notice the 0 priority and we never kill the listener. The downside of this is extra logic to make it work like the ionic back menu button.


问:
CMake fails to find packages after removing conda
I removed conda by following option A in the documentation, i.e. I simply removed the
~/anaconda3 directory and got rid of the relevant line in my ~.bashrc. However, when I call cmake in a different project of mine, cmake still tries to link to libraries installed with anaconda:

```<code>$ cmake ..
CMake Error at /usr/share/cmake-3.9/Modules/FindBoost.cmake:1247 (file):
  file STRINGS file "/home/USERNAME/anaconda3/include/boost/version.hpp"
  cannot be read.
Call Stack (most recent call first):
  dbklib/CMakeLists.txt:5 (find_package)

-- Boost version: 0.0.0
-- DBKLIB:
CMake Error at pydbk/pybind11/tools/FindPythonLibsNew.cmake:95 (message):
  Python config failure:

Call Stack (most recent call first):
  pydbk/pybind11/tools/pybind11Tools.cmake:16 (find_package)
  pydbk/pybind11/CMakeLists.txt:33 (include)
</code>```

How do I get rid of anaconda completely? Can I still somehow run the anaconda-clean tool without having conda?

答:
After modifying installed packages set (especially after removing the package), when rebuild CMake project it is needed to clean CMake cache of that project, so CMake will recheck results of previous searching of packages.

CMake cache may be cleared by removing CMakeCache.txt file from build directory, or by completely cleaning the build directory.

Body:
I removed conda by following option A in the documentation, i.e. I simply removed the
~/anaconda3 directory and got rid of the relevant line in my ~.bashrc. However, when I call cmake in a different project of mine, cmake still tries to link to libraries installed with anaconda:

$ cmake ..
CMake Error at /usr/share/cmake-3.9/Modules/FindBoost.cmake:1247 (file):
  file STRINGS file "/home/USERNAME/anaconda3/include/boost/version.hpp"
  cannot be read.
Call Stack (most recent call first):
  dbklib/CMakeLists.txt:5 (find_package)

-- Boost version: 0.0.0
-- DBKLIB:
CMake Error at pydbk/pybind11/tools/FindPythonLibsNew.cmake:95 (message):
  Python config failure:

Call Stack (most recent call first):
  pydbk/pybind11/tools/pybind11Tools.cmake:16 (find_package)
  pydbk/pybind11/CMakeLists.txt:33 (include)

How do I get rid of anaconda completely? Can I still somehow run the anaconda-clean tool without having conda?


问:
Unix, find, ls, grep and sort
With this Unix command, I try to search text in a directory

```<code>find . -type f -iname *index*jsp -print | xargs ls -t | xargs grep body
</code>```

./apache-tomcat-6.0.18/a/index.jsp:

./apache-tomcat-6.0.18/b/index.jsp:

But this result is not perfect, I want to get the file creation date and line number of matched string, like

./apache-tomcat-6.0.18/a/index.jsp: 2011-1-2 Line 3

./apache-tomcat-6.0.18/b/index.jsp: 2011-1-1 Line 4

How can I achieve this?

答:
What you might want to do to get the format you want is something like (in bash/Linux, not tested):</p>

```<code>find . -type f -iname \*index\*jsp -print |
while read f; do
  if grep -q body "$f"; then
    modified_time=`stat -f %c "$f"`
    match_line=`awk '/body/ {print NR; exit}' "$f"`
    echo "$f $modified_time Line $match_line"
  fi
done
</code>```

Title: Unix, find, ls, grep and sort

Body:
With this Unix command, I try to search text in a directory

find . -type f -iname *index*jsp -print | xargs ls -t | xargs grep body

./apache-tomcat-6.0.18/a/index.jsp:

./apache-tomcat-6.0.18/b/index.jsp:

But this result is not perfect, I want to get the file creation date and line number of matched string, like

./apache-tomcat-6.0.18/a/index.jsp: 2011-1-2 Line 3

./apache-tomcat-6.0.18/b/index.jsp: 2011-1-1 Line 4

How can I achieve this?

Body:
What you might want to do to get the format you want is something like (in bash/Linux, not tested):

find . -type f -iname \*index\*jsp -print |
while read f; do
  if grep -q body "$f"; then
    modified_time=`stat -f %c "$f"`
    match_line=`awk '/body/ {print NR; exit}' "$f"`
    echo "$f $modified_time Line $match_line"
  fi
done


问:
Machine learning - normalizing features with no theoretical maximum value
What approach is the best one to normalize / standardize features that have no theoretical maximum value ?

for example a trend like a stock value that has always been between 0-1000$ doesn't mean it couldn't go further up, so what is the correct approach?

i thought about training a model on a higher maximum (ex. 2000 ),but it doesn't feel right, because no data would be available for the 1000-2000 range, and i think this would introduce bias

答:
TL;DR: use z-scores, maybe take log, maybe take inverse logit, maybe don't normalize at all.

If you wish to normalize safely, use a monotonic mapping, e.g.:

To map (0, inf) into (-inf, inf), you can use y = log(x)

To map (-inf, inf) into (0, 1), you can use y = 1 / (1 + exp(-x)) (inverse logit)

To map (0, inf) into (0, 1), you can use y = x / (1 + x) (inverse logit after log)

If you don't care about bounds, use a linear mapping: y=(x - m) / s, where m is the mean of your feature, and s is its standard deviation. This is called standard scaling, or sometimes z-scoring.

The question you should have asked yourself: why normalize at all?. What are you going to do with your data? Use it as an input feature? Or use it as a target to predict?

For an input feature, leaving it not-normalized is OK, unless you do regularization on model coefficients (like Ridge or Lasso), which works best if all the coefficients are in the same scale (that is, after standard scaling).

For a target feature, leaving it non-normalized is sometimes also OK.

Additive models (like linear regression or gradient boosting) sometimes work better with symmetric distributions. Distributions of stock values (and money values in general) are often skewed to the right, so taking log makes them more convenient.

Finally, if you predict your feature with a neural net with sigmoid activation function, it is inherently bounded. In this case, you might wish the target to be bounded as well. To achieve this, you may use x / (1 + x) as a target: if x is always positive, this value will always be between 0 and 1, just like output of the neural net.


问:
Call PHP function from Twig template
I have a function in my controller that returns array of entities so in my twig template I do this to iterate over elements:

```<code>{% for groupName, entity in items %}
    <ul>
        <ul>
            {% for element in entity %}
                <li>{{ element.getLabel }}</li>
                <li><input type="text" name="detail[{{ element.getId }}]" id="pd_{{ element.getId }}" /><input type="text" name="price[{{ element.getId }}]" id="pd_price_{{ element.getId }}" /><input type="text" name="stock[{{ element.getId }}]" id="pd_stock_{{ element.getId }}" /></li>
            {% endfor %}
        </ul>
    </ul>
{% endfor %}
</code>```

In my controller I have also this PHP function:

```<code>private function DetailCombination($arr, $level, &$result, $curr = array()) {
    for ($i = 0; $i < count($arr); $i++) {
        $new = array_merge($curr, array($arr[$i]));
        if ($level == 1) {
            sort($new);
            if (!in_array($new, $result)) {
                $result[] = $new;
            }
        } else {
            combinations($arr, $level - 1, $result, $new);
        }
    }
}
</code>```

I can call it in this way:

```<code>for ($i = 0; $i < count($arr); $i++) {
    $this->DetailCombination($arr, $i + 1, $result);
}

// TEST
foreach ($result as $arr) {
    echo join(" ", $arr) . '<br>';
}
</code>```

It's possible access to the PHP function from Twig template in order to get all the possible combinations of elements in entity? How?

** UPDATE **

This is the function that returns entities processed after by Twig Template:

```<code>private function getVariations($category_id) {
    $items = array();

    $em = $this->getDoctrine()->getManager();
    $entityCategory = $em->getRepository('CategoryBundle:Category')->find($category_id);

    foreach ($entityCategory->getProductDetails() as $entity) {
        if ($entity->getToProduct() == 1) {
            foreach ($entity->getDetailGroup() as $group) {
                if (!array_key_exists($group->getName(), $items)) {
                    $items [$group->getName()] = array();
                }

                $items [$group->getName()] [] = $entity;
            }
        }
    }

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

答:
I know this is an old thread. But with symfony 3.3 I did this:

```<code>{{ render(controller(
    'AppBundle\\Controller\\yourController::yourAction'
)) }}
</code>```

Symfony docs

Title: Call PHP function from Twig template

Body:
I have a function in my controller that returns array of entities so in my twig template I do this to iterate over elements:

{% for groupName, entity in items %}

            {% for element in entity %}

{{ element.getLabel }}

<input type="text" name="detail[{{ element.getId }}]" id="pd_{{ element.getId }}" /><input type="text" name="price[{{ element.getId }}]" id="pd_price_{{ element.getId }}" /><input type="text" name="stock[{{ element.getId }}]" id="pd_stock_{{ element.getId }}" />

            {% endfor %}

{% endfor %}

In my controller I have also this PHP function:

private function DetailCombination($arr, $level, &$result, $curr = array()) {
    for ($i = 0; $i < count($arr); $i++) {
        $new = array_merge($curr, array($arr[$i]));
        if ($level == 1) {
            sort($new);
            if (!in_array($new, $result)) {
                $result[] = $new;
            }
        } else {
            combinations($arr, $level - 1, $result, $new);
        }
    }
}

I can call it in this way:

for ($i = 0; $i < count($arr); $i++) {
    $this->DetailCombination($arr, $i + 1, $result);
}

// TEST
foreach ($result as $arr) {
    echo join(" ", $arr) . '
';
}

It's possible access to the PHP function from Twig template in order to get all the possible combinations of elements in entity? How?

** UPDATE **

This is the function that returns entities processed after by Twig Template:

private function getVariations($category_id) {
    $items = array();

    $em = $this->getDoctrine()->getManager();
    $entityCategory = $em->getRepository('CategoryBundle:Category')->find($category_id);

    foreach ($entityCategory->getProductDetails() as $entity) {
        if ($entity->getToProduct() == 1) {
            foreach ($entity->getDetailGroup() as $group) {
                if (!array_key_exists($group->getName(), $items)) {
                    $items [$group->getName()] = array();
                }

                $items [$group->getName()] [] = $entity;
            }
        }
    }

    return $items;
}

Body:
I know this is an old thread. But with symfony 3.3 I did this:

{{ render(controller(
    'AppBundle\\Controller\\yourController::yourAction'
)) }}

Symfony docs


问:
How can I get a reference to the TFS WorkItem in a WorkItemChangedEvent?
Seems like this would be super simple, but I'm struggling to find what I need.

I'm implementing a TFS 2013 event handler and simply want to get a reference to the Work Item that raised the change event. It seems easy enough to get the title, but I can't find a property or method in the event signature objects that gives me either a reference to the WorkItem object or the information I'd need to go query it (e.g. the ID).

```<code>public EventNotificationStatus ProcessEvent(
         TeamFoundationRequestContext requestContext,
         NotificationType notificationType,
         object notificationEventArgs,
         out int statusCode,
         out string statusMessage,
         out ExceptionPropertyCollection properties)
    {
        var ev = notificationEventArgs as WorkItemChangedEvent;
        string WorkItemTitle = ev.WorkItemTitle; /* easy enough */

        /*********** need help with this bit *********/
        int ChangedWorkItemID = ???
              OR
        WorkItem ChangedWorkItem= ???
    }
</code>```

Note: this code has been stripped down to bare bones to make it easier to read and focus on the problem at hand.

答:
You can get the ID by using the following code:

```<code>// Get the ID of the work item that was just changed by the user.
int workItemId = ev.CoreFields.IntegerFields[0].NewValue;
</code>```

Without having to connect to the project or the workitem store. It's a little bit simpler than the accepted answer.

Body:
Seems like this would be super simple, but I'm struggling to find what I need.

I'm implementing a TFS 2013 event handler and simply want to get a reference to the Work Item that raised the change event. It seems easy enough to get the title, but I can't find a property or method in the event signature objects that gives me either a reference to the WorkItem object or the information I'd need to go query it (e.g. the ID).

public EventNotificationStatus ProcessEvent(
         TeamFoundationRequestContext requestContext,
         NotificationType notificationType,
         object notificationEventArgs,
         out int statusCode,
         out string statusMessage,
         out ExceptionPropertyCollection properties)
    {
        var ev = notificationEventArgs as WorkItemChangedEvent;
        string WorkItemTitle = ev.WorkItemTitle; /* easy enough */

        /*********** need help with this bit *********/
        int ChangedWorkItemID = ???
              OR
        WorkItem ChangedWorkItem= ???
    }

Note: this code has been stripped down to bare bones to make it easier to read and focus on the problem at hand.

Body:
You can get the ID by using the following code:

// Get the ID of the work item that was just changed by the user.
int workItemId = ev.CoreFields.IntegerFields[0].NewValue;

Without having to connect to the project or the workitem store. It's a little bit simpler than the accepted answer.


问:
Convert returned JSON Object Properties to (lower first) camelCase
I have JSON returned from an API like so:

```<code>Contacts: [{ GivenName: "Matt", FamilyName: "Berry" }]
</code>```

To keep this consistent with my code style (camelCase - lower case first letter) I want to transform the array to produce the following:

```<code> contacts: [{ givenName: "Matt", familyName: "Berry" }]
</code>```

What's the easiest/best way to do this? Create a new Contact object and iterate over all the contacts in the returned array?

```<code>var jsonContacts = json["Contacts"],
    contacts= [];

_.each(jsonContacts , function(item){
    var contact = new Contact( item.GivenName, item.FamilyName );
    contacts.push(contact);
});
</code>```

or can I map the original array or transform it somehow?

答:
Took the challenge with lodash and some es6+ features
Here is my implementation with the reduce function.</p>

```<code>function deeplyToCamelCase(obj) {
  return _.reduce(obj, (camelCaseObj, value, key) => {
    const convertedDeepValue = _.isPlainObject(value) || _.isArray(value)
      ? deeplyToCamelCase(value)
      : value;
    return { ...camelCaseObj, [_.camelCase(key)] : convertedDeepValue };
  }, {});
};
</code>```

Body:
I have JSON returned from an API like so:

Contacts: [{ GivenName: "Matt", FamilyName: "Berry" }]

To keep this consistent with my code style (camelCase - lower case first letter) I want to transform the array to produce the following:

 contacts: [{ givenName: "Matt", familyName: "Berry" }]

What's the easiest/best way to do this? Create a new Contact object and iterate over all the contacts in the returned array?

var jsonContacts = json["Contacts"],
    contacts= [];

_.each(jsonContacts , function(item){
    var contact = new Contact( item.GivenName, item.FamilyName );
    contacts.push(contact);
});

or can I map the original array or transform it somehow?

Body:
Took the challenge with lodash and some es6+ features
Here is my implementation with the reduce function.

function deeplyToCamelCase(obj) {
  return _.reduce(obj, (camelCaseObj, value, key) => {
    const convertedDeepValue = _.isPlainObject(value) || _.isArray(value)
      ? deeplyToCamelCase(value)
      : value;
    return { ...camelCaseObj, [_.camelCase(key)] : convertedDeepValue };
  }, {});
};


问:
WordPress links not clickable on mobile
My added hyperlinks are not clickable on mobile, noting that it works fine on desktop and also other built in links works fine too.
My website is built on wordpress framework and I am using Femto theme.
Please help me.</p>

答:
I added this piece of code in 'footer.php' before  directly and it worked like magic:</p>

    jQuery(document).ready(function($) {
      $("#buynwa").on("touchstart", function(event) {
          window.location.href = $(event.target).attr('href');
        });
     });

Title: WordPress links not clickable on mobile

Body:
I added this piece of code in 'footer.php' before  directly and it worked like magic:

    jQuery(document).ready(function($) {
      $("#buynwa").on("touchstart", function(event) {
          window.location.href = $(event.target).attr('href');
        });
     });


答:
I think you're misunderstanding how strings work in C#, and how text files generally work on Windows.

On Windows a new line is delimited by Carriage Return (\r), and Line Feed (\n)?  So, this is "normal".

Secondly, in C# strings are immutable.

if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
does not assign the 'cleaned' value.

You would need to use cleanLine = cleanLine.Replace("\r","");

Thirdly, from a style perspective in C# - you should place code blocks on another line, and surround them with brackets.   It's valid syntax not to, but it reduces readability.

As a last thing - you could simply open the text file and call ReadLine rather than needing to do string replacement as you're doing now.

Title: Removing \r from lines read from file


问:
Bubble sorting doesn't work to sort dynamic array of objects in C++
I have class City with following private data: name of city(type char), width(double),length(double) and height(double) of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.mA is my object of cities.I should use bubble sort to sort the cities by their length.I have copy constructor, operator = and I have to convert double max(this is variable, used in bubble sort to store current max value) to type City and in this purpose I used contructor with one parameter: City(double max).The problem is that the sort doesn't work. I think that the problem is in my definition of constructor with one parameter(to convert type double to type city). </p>

```<code>#include "stdafx.h"
#include<iostream>
#include<math.h>
#include <algorithm>
using namespace std;

class City{
private: char *name;
         double width;
         double length;
         double height;
public:

    void Output();
    City();
    ~City();
    City(double max){
        name = "";
        width = 0;
        length = max;
        height = 0;
    }
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }
    City(const City& that)
    {
        name = new char[strlen(that.name) + 1];
        for (int i = 0; i <= strlen(that.name); i++)
            name[i] = that.name[i];
        //strcpy(name, that.name);
        width = that.width;
        length = that.length;
        height = that.height;
    }

    City& operator=(const City that)
    {
        name = that.name;
        width = that.width;
        length = that.length;
        height = that.height;
        return*this;
    }
};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <= strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}

void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width << " deg" << endl;;
    cout << " Length is: " << length << " deg" << endl;
    cout << " Height is: " << height << " m" << endl;
    return;
}
City::~City()
{
    cout << " " << endl;
    cout << "Destructor of City!" << endl;
    delete[] name;

}

int main()
{

    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;

    double max = mA[0].GetLength();
    for (int j = 1; j<n; j++)
    {
        if (mA[j - 1].GetLength()>mA[j].GetLength())
        {
            max = mA[j - 1].GetLength();

            mA[j - 1] = mA[j];
            mA[j] = max;
        }
    }
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}
</code>```

答:
```<code>City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <= strlen(ime); i++)
        name[i] = ime[i];
    ...
}
</code>```

First you have to fix the constructor. Although it is not necessarily wrong, you should not ask for input in the constructor. Add a separate function for Input() instead

```<code>City& operator=(const City that)
{
    name = that.name;
    ...
    return*this;
}
</code>```

This assignment operator is wrong. name is a pointer, you don't want to assign the pointers (not in this scenario). You should be using the same method as before to copy the name instead:

```<code>name = new char[strlen(ime) + 1];
strcpy(name, ime);
</code>```

bubble sort should be done like the method in below. Also, you have added #included <string>. You should be using std::string instead!

```<code>#include <iostream>
#include <string>

using namespace std;

class City
{
private:
    char *name;
    double width;
    double length;
    double height;
public:
    City()
    {
        name = nullptr;
        width = 0;
        length = 0;
        height = 0;
    }

    City(const City& that)
    {
        name = new char[strlen(that.name) + 1];
        strcpy(name, that.name);
        width = that.width;
        length = that.length;
        height = that.height;
    }

    City& operator=(const City that)
    {
        name = new char[strlen(that.name) + 1];
        strcpy(name, that.name);
        width = that.width;
        length = that.length;
        height = that.height;
        return*this;
    }

    ~City()
    {
        delete[] name;
    }

    void Input()
    {
        char buffer[100];
        cout << "Name= ";
        cin >> buffer;
        name = new char[strlen(buffer) + 1];
        strcpy(name, buffer);
        cout << "Width= ";
        cin >> width;
        cout << "Length= ";
        cin >> length;
        cout << "Height= ";
        cin >> height;
    }

    void Output()
    {
        cout << "Name is: " << name << ", " << length << endl;
        cout << " Width is: " << width << " deg" << endl;
        cout << " Length is: " << length << " deg" << endl;
        cout << " Height is: " << height << " m" << endl << endl;
    }

    double GetLength() { return length; }
    double GetWidth() { return width; }
    double GetHeight() { return height; }
    char GetName() { return *name; }
};

int main()
{
    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    City *mA = new City[n];

    //read input
    for(int j = 0; j < n; j++)
        mA[j].Input();

    //bubble sort:
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
            if(mA[i].GetLength() > mA[j].GetLength())
            {
                //swap values:
                City temp = mA[i];
                mA[i] = mA[j];
                mA[j] = temp;
            }
        }
    }

    for(int j = 0; j < n; j++)
        mA[j].Output();

    delete[]mA;

    system("pause");
    return 0;
}
</code>```

Body:
I have class City with following private data: name of city(type char), width(double),length(double) and height(double) of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.mA is my object of cities.I should use bubble sort to sort the cities by their length.I have copy constructor, operator = and I have to convert double max(this is variable, used in bubble sort to store current max value) to type City and in this purpose I used contructor with one parameter: City(double max).The problem is that the sort doesn't work. I think that the problem is in my definition of constructor with one parameter(to convert type double to type city).

#include "stdafx.h"
#include<iostream>
#include<math.h>
#include <algorithm>
using namespace std;

class City{
private: char *name;
         double width;
         double length;
         double height;
public:

    void Output();
    City();
    ~City();
    City(double max){
        name = "";
        width = 0;
        length = max;
        height = 0;
    }
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }
    City(const City& that)
    {
        name = new char[strlen(that.name) + 1];
        for (int i = 0; i <= strlen(that.name); i++)
            name[i] = that.name[i];
        //strcpy(name, that.name);
        width = that.width;
        length = that.length;
        height = that.height;
    }

    City& operator=(const City that)
    {
        name = that.name;
        width = that.width;
        length = that.length;
        height = that.height;
        return*this;
    }
};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <= strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}

void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width << " deg" << endl;;
    cout << " Length is: " << length << " deg" << endl;
    cout << " Height is: " << height << " m" << endl;
    return;
}
City::~City()
{
    cout << " " << endl;
    cout << "Destructor of City!" << endl;
    delete[] name;

}

int main()
{

    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;

    double max = mA[0].GetLength();
    for (int j = 1; j<n; j++)
    {
        if (mA[j - 1].GetLength()>mA[j].GetLength())
        {
            max = mA[j - 1].GetLength();

            mA[j - 1] = mA[j];
            mA[j] = max;
        }
    }
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}

Body:
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <= strlen(ime); i++)
        name[i] = ime[i];
    ...
}

First you have to fix the constructor. Although it is not necessarily wrong, you should not ask for input in the constructor. Add a separate function for Input() instead

City& operator=(const City that)
{
    name = that.name;
    ...
    return*this;
}

This assignment operator is wrong. name is a pointer, you don't want to assign the pointers (not in this scenario). You should be using the same method as before to copy the name instead:

name = new char[strlen(ime) + 1];
strcpy(name, ime);

bubble sort should be done like the method in below. Also, you have added #included <string>. You should be using std::string instead!

#include <iostream>
#include <string>

using namespace std;

class City
{
private:
    char *name;
    double width;
    double length;
    double height;
public:
    City()
    {
        name = nullptr;
        width = 0;
        length = 0;
        height = 0;
    }

    City(const City& that)
    {
        name = new char[strlen(that.name) + 1];
        strcpy(name, that.name);
        width = that.width;
        length = that.length;
        height = that.height;
    }

    City& operator=(const City that)
    {
        name = new char[strlen(that.name) + 1];
        strcpy(name, that.name);
        width = that.width;
        length = that.length;
        height = that.height;
        return*this;
    }

    ~City()
    {
        delete[] name;
    }

    void Input()
    {
        char buffer[100];
        cout << "Name= ";
        cin >> buffer;
        name = new char[strlen(buffer) + 1];
        strcpy(name, buffer);
        cout << "Width= ";
        cin >> width;
        cout << "Length= ";
        cin >> length;
        cout << "Height= ";
        cin >> height;
    }

    void Output()
    {
        cout << "Name is: " << name << ", " << length << endl;
        cout << " Width is: " << width << " deg" << endl;
        cout << " Length is: " << length << " deg" << endl;
        cout << " Height is: " << height << " m" << endl << endl;
    }

    double GetLength() { return length; }
    double GetWidth() { return width; }
    double GetHeight() { return height; }
    char GetName() { return *name; }
};

int main()
{
    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    City *mA = new City[n];

    //read input
    for(int j = 0; j < n; j++)
        mA[j].Input();

    //bubble sort:
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
            if(mA[i].GetLength() > mA[j].GetLength())
            {
                //swap values:
                City temp = mA[i];
                mA[i] = mA[j];
                mA[j] = temp;
            }
        }
    }

    for(int j = 0; j < n; j++)
        mA[j].Output();

    delete[]mA;

    system("pause");
    return 0;
}


问:
how does the concept of id's work in firebase?
How does the concept of id's work in Firebase? If I insert an array of json objects into a table then Firebase assigns 0-based Id's by default. For example, if I add the following array as a value for Products:

```<code>[
{
"Id": 123,
"Name": "my-product-1",
"Price": 9.99
},
{
"Id": 124,
"Name": "my-product-2",
"Price": 24.99
}
]
</code>```

Then, I would retrieve "my-product-1" from the array above as:

```<code>firebase.database().ref('Products/0')
</code>```

So it looks like the concept of a record id in Firebase is based on insert order as opposed to a discrete Id record property.  Is this correct?  Is there a way to configure the rest calls to be 1-based instead of 0-based?  I can see how some people might be uncomfortable accessing a record by an Id of 0 in a rest call.

答:
You are inserting an array, then you are accessing by array's index instead of the id you are passing.

If you want to access by id, you need to insert the id as the key of the object.

```<code>{
  "123": {
    "Id": 123,
    "Name": "my-product-1",
    "Price": 9.99
  },
  "124": {
    "Id": 124,
    "Name": "my-product-2",
    "Price": 24.99
  }
}
</code>```

The id from within is optional.

Body:
How does the concept of id's work in Firebase? If I insert an array of json objects into a table then Firebase assigns 0-based Id's by default. For example, if I add the following array as a value for Products:

[
{
"Id": 123,
"Name": "my-product-1",
"Price": 9.99
},
{
"Id": 124,
"Name": "my-product-2",
"Price": 24.99
}
]

Then, I would retrieve "my-product-1" from the array above as:

firebase.database().ref('Products/0')

So it looks like the concept of a record id in Firebase is based on insert order as opposed to a discrete Id record property.  Is this correct?  Is there a way to configure the rest calls to be 1-based instead of 0-based?  I can see how some people might be uncomfortable accessing a record by an Id of 0 in a rest call.

Body:
You are inserting an array, then you are accessing by array's index instead of the id you are passing.

If you want to access by id, you need to insert the id as the key of the object.

{
  "123": {
    "Id": 123,
    "Name": "my-product-1",
    "Price": 9.99
  },
  "124": {
    "Id": 124,
    "Name": "my-product-2",
    "Price": 24.99
  }
}

The id from within is optional.


问:
Linked List not properly initialising
So I have a assignment hich involves creating your own implementation of a HashMap. My code - below works by first calling a constructor which sets the size of the Array. It then calculates the Hash value of a word to be added to the list. It goes to that position in the Array and checks whether there is a value there already. If there isn't, it creates a new Node there and adds the data, with the pointer pointing to null. If there is a Cell already there, it creates a new Cell but the pointer points to the Cell that was previously there, thus creating a Linked List.

My count method, works by first finding the hash value of the requested word. It then searches the linked list present at the point and returns a value.

```<code>public class WordStoreImp implements WordStore{

public class Node<T>{
   public T data;
   public Node<T> next;
   public Node(){
   }

   public Node(T data, Node<T> next)
   {
      this.data = data;
      this.next = next;
   }
}

static Node[] array;

public WordStoreImp(int n){
    array = new Node[n];
}

public void add(String word){
    int position = hashFunction(word);
    if(position<0){
        position =  position *- 1;
    }
    if(array[position] == null){
        array[position] = new Node(word, null);
    }else{
        Node newHead = new Node(word, array[position]);
        array[position] = newHead;
    }
}

public int count(String word){
        int number = 0;
        int position = hashFunction(word);
        if(position<0){
            position = position *- 1;
        }
        for(; array[position] != null; array[position] = array[position].next){
            if(array[position].data == word){
                number++;
            }
        }
        //System.out.println(number);
        return number;
    }

public int hashFunction(String a){
    int sum = 1;
        for(int i = 0; i<a.length(); i++){
            char b = a.charAt(i);
            int value = (int) b;
            sum *= value;
     }
     sum = sum % array.length;
     if(sum<0){
         sum = sum*-1;
     }
     return sum;
 }

public static void main(String[] args) {
    WordStoreImp a = new WordStoreImp(100);
    a.addthings("abc", 100);
    a.count("abc");
    a.count("abc");
}
}
</code>```

My issue is that my count method is not working and I can't figure out why - the first time it returns how many times a item is present fine, but it then dosent work - and returns 0. I cant figure out why - can someone point me in the right direction?

答:
You are changing the head of your linked list when you call your count method.  You are doing this in your for loop line:

```<code>for(; array[position] != null; array[position] = array[position].next){
</code>```

When this loop is done, you've effectively moved all your linked list items off your bucket by repeatedly updating array[position] until it's null.

Instead, use a local variable initialized to array[position], and update it instead of array[position], something like this:

```<code>for(Node<T> curr = array[position]; curr != null; curr = curr.next){
    if(curr.data == word){
        number++;
    }
}
</code>```

You may also want to consider using the .equals method; the == operator will determine if they are the same object, and two equals objects may not necessarily be the same object.

Title: Linked List not properly initialising

Body:
So I have a assignment hich involves creating your own implementation of a HashMap. My code - below works by first calling a constructor which sets the size of the Array. It then calculates the Hash value of a word to be added to the list. It goes to that position in the Array and checks whether there is a value there already. If there isn't, it creates a new Node there and adds the data, with the pointer pointing to null. If there is a Cell already there, it creates a new Cell but the pointer points to the Cell that was previously there, thus creating a Linked List.

My count method, works by first finding the hash value of the requested word. It then searches the linked list present at the point and returns a value.

public class WordStoreImp implements WordStore{

public class Node<T>{
   public T data;
   public Node<T> next;
   public Node(){
   }

   public Node(T data, Node<T> next)
   {
      this.data = data;
      this.next = next;
   }
}

static Node[] array;

public WordStoreImp(int n){
    array = new Node[n];
}

public void add(String word){
    int position = hashFunction(word);
    if(position<0){
        position =  position *- 1;
    }
    if(array[position] == null){
        array[position] = new Node(word, null);
    }else{
        Node newHead = new Node(word, array[position]);
        array[position] = newHead;
    }
}

public int count(String word){
        int number = 0;
        int position = hashFunction(word);
        if(position<0){
            position = position *- 1;
        }
        for(; array[position] != null; array[position] = array[position].next){
            if(array[position].data == word){
                number++;
            }
        }
        //System.out.println(number);
        return number;
    }

public int hashFunction(String a){
    int sum = 1;
        for(int i = 0; i<a.length(); i++){
            char b = a.charAt(i);
            int value = (int) b;
            sum *= value;
     }
     sum = sum % array.length;
     if(sum<0){
         sum = sum*-1;
     }
     return sum;
 }

public static void main(String[] args) {
    WordStoreImp a = new WordStoreImp(100);
    a.addthings("abc", 100);
    a.count("abc");
    a.count("abc");
}
}

My issue is that my count method is not working and I can't figure out why - the first time it returns how many times a item is present fine, but it then dosent work - and returns 0. I cant figure out why - can someone point me in the right direction?

Body:
You are changing the head of your linked list when you call your count method.  You are doing this in your for loop line:

for(; array[position] != null; array[position] = array[position].next){

When this loop is done, you've effectively moved all your linked list items off your bucket by repeatedly updating array[position] until it's null.

Instead, use a local variable initialized to array[position], and update it instead of array[position], something like this:

for(Node<T> curr = array[position]; curr != null; curr = curr.next){
    if(curr.data == word){
        number++;
    }
}

You may also want to consider using the .equals method; the == operator will determine if they are the same object, and two equals objects may not necessarily be the same object.


问:
How to select one plot from coplot(), or how to plot a specific subset
I am trying to use coplot like this:

coplot(lat ~ long | depth, data = quakes)

Which produce this"

However, this will give a plot for each level of conditioning variable. I would like to get a whole scatter plot without showing the levels of variables. For example similar to this:

How can I customize this? any help please?

答:
It appears like what you really want is to plot a subset. How you subset data varies a bit depending on what form it is in (vector, matrix, dataframe, list; numeric, logical, character). This here will work with a numeric dataframe like data(quake).

First of all you'll need to understand the function of []. If you search the help for Extract you'll find info on it and its siblings. [] is used to extract elements from vectors, matrices, dataframes and arrays of any dimension, based on indices of each dimension, with each dimension separated by a comma.

Say you have a vector vec <- c(1, 3, 2, 6, 4). A vector only have one dimension so you don't have to worry about which dimension you are addressing. vec[3] will return 2, the value at place, or index, 3 in the vector, the third element from the left. vec[5] will return the fifth element: 4, while vec[c(2, 1, 4)] will return the second, first and fourth element, in that order.

When dealing with matrices and dataframes we are dealing with two dimensions, commonly referred to as rows and columns. When using [] the dimensions will always be separated like this: [rows, columns]. Lets create a matrix.

```<code>mat <- matrix(c(9, 8, 7
                6, 5, 4
                3, 2, 1), nrow=3, byrow=TRUE)
mat
#      [,1] [,2] [,3]
# [1,]    9    8    7
# [2,]    6    5    4
# [3,]    3    2    1
</code>```

Along the top and bottom there are []'s with numbers in them referring to the index of each dimension. You'll also notice that along the side the number is in front of a comma, signifying row, while along the top the number stand after the comma, signifying column.

So what happens if I call mat[3, ] or mat[, 2]? Well I get every element in that respective row or column.
What about if we want to extract the 4 in the above matrix? Well its row is nr 2, and its column is nr 3, so could it simply be mat[2, 3]? Why yes, it is!

We're nearly there now, only other thing to show is that we can reference rows and columns by name, not just by index. The above matrix doesn't have any dimension names, so we'll have to add them.

```<code>rownames(mat) <- c("r1", "r2", "r3")
colnames(mat) <- c("c1", "c2", "c3")
mat
#    c1 c2 c3
# r1  9  8  7
# r2  6  5  4
# r3  3  2  1
</code>```

Now mat[,"c2"] will return the column called c2, and mat["r1"] the row called r1.

Onto quakes.

Say we want to plot all earthquakes with a focus deeper than 400 km.

One straight forward way of extracting that subset could be

```<code>quakes.sub <- quakes[quakes[,"depth"] > 400, c("long", "lat")]
</code>```

The only new thing here is >, which in this instance asks: "are the values in quakes[,"depth"] larger than 400?". For every yes a TRUE is returned, and for every no a FALSE. Only columns returning TRUE will be included in the subset.

To plot the subset you only have to

```<code>plot(quakes.sub)
</code>```

This is only the start of course. You can use with() to avoid having to type quakes several times, using which() will deal with NA's more gracefully, and conditions (<, >, ==) can be stacked using logical operators (not: !, and: &, or: |), allowing for more advanced subsetting rules.

```<code>rows <- with(quakes, which(depth < 400 &
                           depth > 100 &
                             mag > 4.3 &
                        stations > 20))
quakes.sub <- quakes[rows, c("long", "lat")]

plot(quakes.sub)
</code>```

Body:
It appears like what you really want is to plot a subset. How you subset data varies a bit depending on what form it is in (vector, matrix, dataframe, list; numeric, logical, character). This here will work with a numeric dataframe like data(quake).

First of all you'll need to understand the function of []. If you search the help for Extract you'll find info on it and its siblings. [] is used to extract elements from vectors, matrices, dataframes and arrays of any dimension, based on indices of each dimension, with each dimension separated by a comma.

Say you have a vector vec <- c(1, 3, 2, 6, 4). A vector only have one dimension so you don't have to worry about which dimension you are addressing. vec[3] will return 2, the value at place, or index, 3 in the vector, the third element from the left. vec[5] will return the fifth element: 4, while vec[c(2, 1, 4)] will return the second, first and fourth element, in that order.

When dealing with matrices and dataframes we are dealing with two dimensions, commonly referred to as rows and columns. When using [] the dimensions will always be separated like this: [rows, columns]. Lets create a matrix.

mat <- matrix(c(9, 8, 7
                6, 5, 4
                3, 2, 1), nrow=3, byrow=TRUE)
mat
#      [,1] [,2] [,3]
# [1,]    9    8    7
# [2,]    6    5    4
# [3,]    3    2    1

Along the top and bottom there are []'s with numbers in them referring to the index of each dimension. You'll also notice that along the side the number is in front of a comma, signifying row, while along the top the number stand after the comma, signifying column.

So what happens if I call mat[3, ] or mat[, 2]? Well I get every element in that respective row or column.
What about if we want to extract the 4 in the above matrix? Well its row is nr 2, and its column is nr 3, so could it simply be mat[2, 3]? Why yes, it is!

We're nearly there now, only other thing to show is that we can reference rows and columns by name, not just by index. The above matrix doesn't have any dimension names, so we'll have to add them.

rownames(mat) <- c("r1", "r2", "r3")
colnames(mat) <- c("c1", "c2", "c3")
mat
#    c1 c2 c3
# r1  9  8  7
# r2  6  5  4
# r3  3  2  1

Now mat[,"c2"] will return the column called c2, and mat["r1"] the row called r1.

Onto quakes.

Say we want to plot all earthquakes with a focus deeper than 400 km.

One straight forward way of extracting that subset could be

quakes.sub <- quakes[quakes[,"depth"] > 400, c("long", "lat")]

The only new thing here is >, which in this instance asks: "are the values in quakes[,"depth"] larger than 400?". For every yes a TRUE is returned, and for every no a FALSE. Only columns returning TRUE will be included in the subset.

To plot the subset you only have to

plot(quakes.sub)

This is only the start of course. You can use with() to avoid having to type quakes several times, using which() will deal with NA's more gracefully, and conditions (<, >, ==) can be stacked using logical operators (not: !, and: &, or: |), allowing for more advanced subsetting rules.

rows <- with(quakes, which(depth < 400 &
                           depth > 100 &
                             mag > 4.3 &
                        stations > 20))
quakes.sub <- quakes[rows, c("long", "lat")]

plot(quakes.sub)


问:
List index out of range (searched for answer, none work)
When i run this code

```<code>f = open("test.txt", "r")
xp_levelup_save=f.readlines(3)
xp_levelup_save=[int(i.replace("\n", "")) for i in xp_levelup_save][2]
f.close()
print (xp_levelup_save)
</code>```

but a error comes up "List index out of range" If the readlines is 2 and the [2] is [1] it works fine. Not sure why this is happening. Can anyone help me and find a fix. I've tried looking at mulitple other discussions but none
seem to work with this code.
My text document looks like this

```<code>1
2
3
4
5
6
</code>```

答:
f.readlines() doesn't need an argument to retrieve the lines of a document. If you provide this optional argument like f.readlines(n), Python reads it as "expect n bytes and finish the line". Depending on your text file, this could be one, two or even more lines.

To read the text file, just use

```<code>xp_levelup_save = f.readlines()
#resume with your code
</code>```

where each line is stored as a string list element in your variable xp_levelup_save.

Or simply

```<code>xp_levelup_save = [int(i.replace("\n", "")) for i in f.readlines()][2]
</code>```

Body:
When i run this code

f = open("test.txt", "r")
xp_levelup_save=f.readlines(3)
xp_levelup_save=[int(i.replace("\n", "")) for i in xp_levelup_save][2]
f.close()
print (xp_levelup_save)

but a error comes up "List index out of range" If the readlines is 2 and the [2] is [1] it works fine. Not sure why this is happening. Can anyone help me and find a fix. I've tried looking at mulitple other discussions but none
seem to work with this code.
My text document looks like this

1
2
3
4
5
6

Body:
f.readlines() doesn't need an argument to retrieve the lines of a document. If you provide this optional argument like f.readlines(n), Python reads it as "expect n bytes and finish the line". Depending on your text file, this could be one, two or even more lines.

To read the text file, just use

xp_levelup_save = f.readlines()
#resume with your code

where each line is stored as a string list element in your variable xp_levelup_save.

Or simply

xp_levelup_save = [int(i.replace("\n", "")) for i in f.readlines()][2]


问:
Can the owner of a repo see clones?
I know that the owner of a repo is able to see a fork request when one is performed. But what about a clone? Can the owner of the repo see when someone clones it?</p>

答: Open Github, find your repo, click on it. Then click on Insights and finally click on Traffic. Github shows a graph Traffic including git clones. Salutes!</p>

Title: Can the owner of a repo see clones?


问:
How do I use getch from curses without clearing the screen?
I'm learning to program in C and want to be able to type characters into the terminal while my code is running without pressing return. My program works, however when I call initscr(), the screen is cleared - even after calling filter(). The documentation for filter suggests it should disable clearing - however this is not the case for me.

```<code>#include <stdio.h>
#include <curses.h>
#include <term.h>

int main(void) {

    int ch;

    filter();
    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    while((ch = getch()) != EOF);

    endwin();

    return 0;
}
</code>```

Why does the above code still clearr the screen, and what could be done to fix it?

I'm using Debian Lenny (stable) and gnome-terminal if that helps.

答:
Extending the answer by mike.dld, this works for me on MacOS X 10.6.6 (GCC 4.5.2) with the system curses library - without clearing the screen.  I added the ability to record the characters typed (logged to a file "x"), and the ability to type CONTROL-D and stop the program rather than forcing the user to interrupt.

```<code>#include <stdio.h>
#include <curses.h>
#include <term.h>

#define CONTROL(x)  ((x) & 0x1F)

int main(void)
{
    FILE *fp = fopen("x", "w");
    if (fp == 0)
        return(-1);
    SCREEN *s = newterm(NULL, stdin, stdout);
    if (s == 0)
        return(-1);
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    int ch;
    while ((ch = getch()) != EOF && ch != CONTROL('d'))
        fprintf(fp, "%d\n", ch);

    endwin();

    return 0;
}
</code>```

Body:
I'm learning to program in C and want to be able to type characters into the terminal while my code is running without pressing return. My program works, however when I call initscr(), the screen is cleared - even after calling filter(). The documentation for filter suggests it should disable clearing - however this is not the case for me.

#include <stdio.h>
#include <curses.h>
#include <term.h>

int main(void) {

    int ch;

    filter();
    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    while((ch = getch()) != EOF);

    endwin();

    return 0;
}

Why does the above code still clearr the screen, and what could be done to fix it?

I'm using Debian Lenny (stable) and gnome-terminal if that helps.

Body:
Extending the answer by mike.dld, this works for me on MacOS X 10.6.6 (GCC 4.5.2) with the system curses library - without clearing the screen.  I added the ability to record the characters typed (logged to a file "x"), and the ability to type CONTROL-D and stop the program rather than forcing the user to interrupt.

#include <stdio.h>
#include <curses.h>
#include <term.h>

#define CONTROL(x)  ((x) & 0x1F)

int main(void)
{
    FILE *fp = fopen("x", "w");
    if (fp == 0)
        return(-1);
    SCREEN *s = newterm(NULL, stdin, stdout);
    if (s == 0)
        return(-1);
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    int ch;
    while ((ch = getch()) != EOF && ch != CONTROL('d'))
        fprintf(fp, "%d\n", ch);

    endwin();

    return 0;
}


问:
mvc razor dropdownlistfor display default from javascript
In my MVC view, I have a country list which is populated with all the countries.  This works ok and the user selects different countries & they are displayed ok.  I want the ability in Javascript to change that field back to "Select Country", how do I do this?

This is in my view

```<code><div class="form-group">
    @Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { @id = "ddlcountry" })
</div>
</code>```

This is my javascript

```<code>$("#ddlcountry").val(44);    //this works to set the country code to 44
$("#ddlcountry").val("Select Country");    //this does not work to display "Select Country" like the default when you first load the page
</code>```

How can I have the default of "Select Country" show again?

答:
Your DropDownListFor() method is generating the 'label option' with a null value

```<code><option value="">Select Country</option>
</code>```

to select that option with jQuery use

```<code>$("#ddlcountry").val('');
</code>```

Body:
In my MVC view, I have a country list which is populated with all the countries.  This works ok and the user selects different countries & they are displayed ok.  I want the ability in Javascript to change that field back to "Select Country", how do I do this?

This is in my view

    @Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { @id = "ddlcountry" })

This is my javascript

$("#ddlcountry").val(44);    //this works to set the country code to 44
$("#ddlcountry").val("Select Country");    //this does not work to display "Select Country" like the default when you first load the page

How can I have the default of "Select Country" show again?

Body:
Your DropDownListFor() method is generating the 'label option' with a null value

<option value="">Select Country</option>

to select that option with jQuery use

$("#ddlcountry").val('');


问:
Edit HTML in Divi Theme
This is my first post here, so apologies if anything is formatted incorrectly. Please do let me know how I can improve my questions.

I am building a website for a client using the Divi theme in Wordpress. I would like to create a custom overlay (showing the title of the video) to display on hover. I need it to appear in front of the video and it's displayed image (also an overlay) and behind the play button. Currently, the custom overlay sits on top of the play button on hover, which is obviously a problem since that button needs to be clickable.

I attempted to use the z-index property (being sure all the divs were positioned), but to no avail. I currently suspect that the reason the z-index isn't working is because my custom overlay overlay-one class is being applied to a parent div, and so isn't being included in the proper stacking context.

In order to move the class, I need to edit the HTML which I am not sure how to do in Divi. Usually, I'd directly edit via FTP but my client is one of those slightly paranoid people who doesn't want anyone to have FTP access...even the developer of his site. So, if there is a workaround that doesn't involve me fighting with my client over FTP, I'd appreciate knowing about it.

Link to homepage, I'm working with the first video "Welcome to Moab": http://finleyholidayproductions.com/home-finley-holiday-productions/

HTML showing overlay-one in the top-most div, I assume I need to move it to the div containing et_pb_video_overlay instead.

Here is the code:

.et_pb_video_box {
  position: relative;
  z-index: -1;
}

.et_pb_video_overlay {
  position: absolute;
  z-index: 1;
}

.et_pb_video_play {
  position: absolute;
  z-index: 100;
}

.overlay-one {
  position: absolute;
}

.overlay-one:after {
  position: absolute;
  z-index: 5;
  content: '';
  background: url('http://finleyholidayproductions.com/wp-content/uploads/2017/12/Video-Overlay-Template-Recovered.png');
  background-size: cover;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  transition: .5s ease all;
}

.overlay-one:hover:after {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="et_pb_module et_pb_video overlay-one et_animated et_pb_video_0">
  <div class="et_pb_video_box">
    <iframe src="https://player.vimeo.com/video/230963151" width="1080" height="608" frameborder="0" title="Secrets of the Moab Desert" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
  </div>
  <div class="et_pb_video_overlay" style="background-image: url(http://finleyholidayproductions.com/wp-content/uploads/2017/12/Thumbnails-1-Secrets-of-the-Moab-Desert.jpg);">
    <div class="et_pb_video_overlay_hover">

    </div>
  </div></code>```

So in summary:

I am correct in my solution

How would I edit the HTML in Divi to enact this solution.

Thanks.

答:
If you insist on not getting access to the html:

I would suggest adding an :after pseudo-element on class="et_pb_video_overlay_hover".
I would put the title in content: like so:

```<code>et_pb_video_overlay_hover::after {
    content: "Title";
    ///other css properties to style your title etc.
}
</code>```

Title: Edit HTML in Divi Theme

Body:
This is my first post here, so apologies if anything is formatted incorrectly. Please do let me know how I can improve my questions.

I am building a website for a client using the Divi theme in Wordpress. I would like to create a custom overlay (showing the title of the video) to display on hover. I need it to appear in front of the video and it's displayed image (also an overlay) and behind the play button. Currently, the custom overlay sits on top of the play button on hover, which is obviously a problem since that button needs to be clickable.

I attempted to use the z-index property (being sure all the divs were positioned), but to no avail. I currently suspect that the reason the z-index isn't working is because my custom overlay overlay-one class is being applied to a parent div, and so isn't being included in the proper stacking context.

In order to move the class, I need to edit the HTML which I am not sure how to do in Divi. Usually, I'd directly edit via FTP but my client is one of those slightly paranoid people who doesn't want anyone to have FTP access...even the developer of his site. So, if there is a workaround that doesn't involve me fighting with my client over FTP, I'd appreciate knowing about it.

Link to homepage, I'm working with the first video "Welcome to Moab": http://finleyholidayproductions.com/home-finley-holiday-productions/

HTML showing overlay-one in the top-most div, I assume I need to move it to the div containing et_pb_video_overlay instead.

Here is the code:

.et_pb_video_box {
  position: relative;
  z-index: -1;
}

.et_pb_video_overlay {
  position: absolute;
  z-index: 1;
}

.et_pb_video_play {
  position: absolute;
  z-index: 100;
}

.overlay-one {
  position: absolute;
}

.overlay-one:after {
  position: absolute;
  z-index: 5;
  content: '';
  background: url('http://finleyholidayproductions.com/wp-content/uploads/2017/12/Video-Overlay-Template-Recovered.png');
  background-size: cover;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  transition: .5s ease all;
}

.overlay-one:hover:after {
  opacity: 1;
}

So in summary:

I am correct in my solution

How would I edit the HTML in Divi to enact this solution.

Thanks.

Body:
If you insist on not getting access to the html:

I would suggest adding an :after pseudo-element on class="et_pb_video_overlay_hover".
I would put the title in content: like so:

et_pb_video_overlay_hover::after {
    content: "Title";
    ///other css properties to style your title etc.
}


问:
I'm not sure what I am doing wrong in this try catch block
```<code>int memberChoice;
    boolean accountLoop = true;
    while (accountLoop) {
        try {
            System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
            memberChoice = input.nextInt();
            if (memberChoice == 1 || memberChoice == 2) {
                accountLoop = false;
            }
            if (memberChoice < 1 || memberChoice > 2) {
                System.out.println("Please choose either 1 or 2");
            }
            System.out.println();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input");
        }
    }
</code>```

Whenever I type a string it should say invalid input go back to the beginning of the loop and direct me to input a number again. Instead it gives me an infinite loop. I feel like its something really small but I've been at this for 5 hours and can't figure it out. Any suggestions?

答: For me, your code workes just fine. You might have a problem with your ide. Anyway change the line if (memberChoice < 1 || memberChoice > 2) to if (memberChoice < 1 && memberChoice > 2)

Body:
int memberChoice;
    boolean accountLoop = true;
    while (accountLoop) {
        try {
            System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
            memberChoice = input.nextInt();
            if (memberChoice == 1 || memberChoice == 2) {
                accountLoop = false;
            }
            if (memberChoice < 1 || memberChoice > 2) {
                System.out.println("Please choose either 1 or 2");
            }
            System.out.println();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input");
        }
    }

Whenever I type a string it should say invalid input go back to the beginning of the loop and direct me to input a number again. Instead it gives me an infinite loop. I feel like its something really small but I've been at this for 5 hours and can't figure it out. Any suggestions?


问:
PYQT4 - How do I compile and import a qrc file into my program?
I'm having trouble importing a resource file. I'm using pyqt4 with monkey studio and I am trying to import a png image. When I run the program I get an import error like

ImportError: No module named icon_rc

I know that I have to compile it using pyrcc4 but I don't understand how to do this can anybody help please. It would be very helpful to have an answer that fully explains how to compile the resource file so I can import it.

答:
its because when you also used pyuic5 to convert your UI to py, the resource file name from the UI sticks.

then use

```<code>Pyrcc5 input_file.qrc -o icons.py
</code>```

remove from main_script.py

```<code>import icon_rc
</code>```

and use

```<code>import icons
</code>```

the when calling the actual icons from the icons module, you have to look at your qrc file prefix.

```<code>< RCC >
    < qresource
    prefix = "ico5" >
    < file > plugin.png < / file >
    < / qresource >
< / RCC >
</code>```

if prefix is ico5
then you load icons with

```<code> QtGui.QIcon(":/ico5/plugin.png")
</code>```

and if prefix is , lets say,

```<code><RCC>
    <qresource prefix="icons">
</code>```

then its:

```<code>  QtGui.QIcon(":/icons/plugin.png")
</code>```

Body:
its because when you also used pyuic5 to convert your UI to py, the resource file name from the UI sticks.

then use

Pyrcc5 input_file.qrc -o icons.py

remove from main_script.py

import icon_rc

and use

import icons

the when calling the actual icons from the icons module, you have to look at your qrc file prefix.

< RCC >
    < qresource
    prefix = "ico5" >
    < file > plugin.png < / file >
    < / qresource >
< / RCC >

if prefix is ico5
then you load icons with

 QtGui.QIcon(":/ico5/plugin.png")

and if prefix is , lets say,

<RCC>
    <qresource prefix="icons">

then its:

  QtGui.QIcon(":/icons/plugin.png")


问:
HTML5 - audio stream
when I run my application audio stream in browser, no problem but when I run it in BB web/widget it is not appear in my BB simulator?</p>

答: Not sure what BB means, but it probably does not have HTML5 support, yet. You might want to consider using jPlayer, it will automatically detect the presence of HTML5, if HTML5 doesn't exist, it will present the audio using flash. </p>

Title: HTML5 - audio stream