问:
React hooks: setState() with string that contains html?
I'm trying to setState from a json file value that contains html. So something like:</p>
```<code>...
const quote = [quote, setQuote] = useState('');

const quotes = [
    { quote: "Some text." },
    { quote: 'Some text with <span class="red">HTML</span>.' },
  ];
  const handleClick = () => {
    setQuote(quotes[1].quote);
  };
...
return (
  <div>{quote}</div> // right now it's printing the html as text.
);
</code>```

答:
Use dangeriouslySetInnerHTML to parse and render an HTML string. You may also want to cleanse/sanitize any values with DOMPurify.

Example:

```<code>import DOMPurify from "dompurify";

...

const quote = [quote, setQuote] = useState('');

const quotes = [
  { quote: "Some text." },
  { quote: 'Some text with <span class="red">HTML</span>.' },
];
const handleClick = () => {
  setQuote(quotes[1].quote);
};

...

return (
  <div dangerouslySetInnerHTML ={{ __html: DOMPurify.sanitize(quote) }} />
);
</code>```

Body:
I'm trying to setState from a json file value that contains html. So something like:

...
const quote = [quote, setQuote] = useState('');

const quotes = [
    { quote: "Some text." },
    { quote: 'Some text with HTML.' },
  ];
  const handleClick = () => {
    setQuote(quotes[1].quote);
  };
...
return (

{quote}
 // right now it's printing the html as text.
);

Body:
Use dangeriouslySetInnerHTML to parse and render an HTML string. You may also want to cleanse/sanitize any values with DOMPurify.

Example:

import DOMPurify from "dompurify";

...

const quote = [quote, setQuote] = useState('');

const quotes = [
  { quote: "Some text." },
  { quote: 'Some text with <span class="red">HTML</span>.' },
];
const handleClick = () => {
  setQuote(quotes[1].quote);
};

...

return (
  <div dangerouslySetInnerHTML ={{ __html: DOMPurify.sanitize(quote) }} />
);


来源: stackexchange

问:
Difference between cursor.fetchall() and pandas Dataframe
I know there are a few ways to retrieve data from RDB table.
One with pandas as read_sql, the other with cursore.fetchall().
What are the main differences between both ways in terms of:

memory usage - is df less reccomended?

performance - selecting data from a table (e.g. large set of data)

performace - inserting data with a loop for cursor vs df.to_sql.

Thanks!

答:
That's an interesting question.
For a ~10GB SQLite database, I get the following results for your second question.
pandas.sql_query seems comparable to speed with the cursor.fetchall.

The rest I leave as an exercise. :D

import sqlite3
import time
import pandas as pd

def db_operation(db_name):
    connection = sqlite3.connect(db_name)
    c = connection.cursor()
    yield c
    connection.commit()
    connection.close()

start = time.perf_counter()
for i in range(0, 10):
    with db_operation('components.db') as c:
            c.execute('''SELECT * FROM hashes WHERE (weight > 50 AND weight < 100)''')
            fetchall = c.fetchall()

time.perf_counter() - start
2.967 # fractional seconds

start = time.perf_counter()
for i in range(0, 10):
    connection = sqlite3.connect('components.db')
    sql_query = pd.read_sql_query('''SELECT * FROM hashes WHERE (weight > 50 AND weight < 100)''', con = connection)
    connection.commit()
    connection.close()

time.perf_counter() - start
2.983 # fractional seconds
```

The difference is that cursor.fetchall() is a bit more spartan (=plain).
pandas.read_sql_query returns a <class 'pandas.core.frame.DataFrame'> and so you can use all the methods of pandas.DataFrame, like pandas.DataFrame.to_latex, pandas.DataFrame.to_csv pandas.DataFrame.to_excel, etc. (documentation link)

One can accomplish the same exact goals with cursor.fetchall, but needs to press some or a lot extra keys.

ContentLicense: CC BY-SA 4.0

Body:
That's an interesting question.
For a ~10GB SQLite database, I get the following results for your second question.
pandas.sql_query seems comparable to speed with the cursor.fetchall.

The rest I leave as an exercise. :D

import sqlite3
import time
import pandas as pd

def db_operation(db_name):
    connection = sqlite3.connect(db_name)
    c = connection.cursor()
    yield c
    connection.commit()
    connection.close()

start = time.perf_counter()
for i in range(0, 10):
    with db_operation('components.db') as c:
            c.execute('''SELECT * FROM hashes WHERE (weight > 50 AND weight < 100)''')
            fetchall = c.fetchall()

time.perf_counter() - start
2.967 # fractional seconds

start = time.perf_counter()
for i in range(0, 10):
    connection = sqlite3.connect('components.db')
    sql_query = pd.read_sql_query('''SELECT * FROM hashes WHERE (weight > 50 AND weight < 100)''', con = connection)
    connection.commit()
    connection.close()

time.perf_counter() - start
2.983 # fractional seconds

The difference is that cursor.fetchall() is a bit more spartan (=plain).
pandas.read_sql_query returns a <class 'pandas.core.frame.DataFrame'> and so you can use all the methods of pandas.DataFrame, like pandas.DataFrame.to_latex, pandas.DataFrame.to_csv pandas.DataFrame.to_excel, etc. (documentation link)

One can accomplish the same exact goals with cursor.fetchall, but needs to press some or a lot extra keys.


问:
pyspark create all possible combinations of column values of a dataframe
I want to get all the possible combinations of size 2 of a column in pyspark dataframe.
My pyspark dataframe looks like

```<code>| id |
|  1 |
|  2 |
|  3 |
|  4 |

For above input, I want to get output as

| id1 |  id2 |
|  1  |   2  |
|  1  |   3  |
|  1  |   4  |
|  2  |   3  |
and so on..
</code>```

One way would be to collect the values and get them into python iterable (list, pandas df) and use itertools.combinations to generate all combinations.

```<code>values = df.select(F.collect_list('id')).first()[0]
combns = list(itertools.combinations(values, 2))
</code>```

However, I want to avoid collecting the dataframe column to the driver since the rows can be extremely large. Is there a better way to achieve this using spark APIs?

答:
You can use the crossJoin method, and then cull the lines with id1 > id2.

```<code>df = df.toDF('id1').crossJoin(df.toDF('id2')).filter('id1 < id2')
</code>```

Body:
I want to get all the possible combinations of size 2 of a column in pyspark dataframe.
My pyspark dataframe looks like

| id |
|  1 |
|  2 |
|  3 |
|  4 |

For above input, I want to get output as

| id1 |  id2 |
|  1  |   2  |
|  1  |   3  |
|  1  |   4  |
|  2  |   3  |
and so on..

One way would be to collect the values and get them into python iterable (list, pandas df) and use itertools.combinations to generate all combinations.

values = df.select(F.collect_list('id')).first()[0]
combns = list(itertools.combinations(values, 2))

However, I want to avoid collecting the dataframe column to the driver since the rows can be extremely large. Is there a better way to achieve this using spark APIs?

Body:
You can use the crossJoin method, and then cull the lines with id1 > id2.

df = df.toDF('id1').crossJoin(df.toDF('id2')).filter('id1 < id2')


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
there is a tradeoff: if you read a big chunk of the file, you save the disc seek time, but you may have read information you will not need, since the change was encountered on the first lines.

You should probably run some experiments [benchmarks], with varying chunk size, to find out what is the optimal chunk to read, in the average case.

ContentLicense: CC BY-SA 3.0

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!


问:
when I use the return keyword in my code, I get only the first value of a list return instead of all
I wrote a function which when I use the return keyword, I only get the first item of the list returned instead of all items. The code works properly without the return keyword.

code snippet

```<code>function generateNames(){
  for (let i = 0; i < 5; i++) {
    const playersName = fetch('https://www.balldontlie.io/api/v1/players?per_page=5')
      .then(response => response.json())
      .then(json => console.log(json['data'][i]['first_name']))
    // return playersName
  }
}
generateNames()
</code>```

The result i get is;

```<code>Ike
Ron
Jabari
MarShon
Lorenzo
</code>```

but when I uncomment the, return playersName line of code, I only get the first value returned.

The result i get is;

```<code>Ike
</code>```

After refactoring the code:

async function generateNames() {
  var playerList = [];
  const playersName = await fetch('https://www.balldontlie.io/api/v1/players?per_page=5')
    .then(response => response.json())
    .then(json => {
      for (let i = 0; i < 5; i++)
        playerList.push(json['data'][i]['first_name'])
    })
  // return playersName
  return playerList;
}
(async () => console.log(await generateNames()))()```

答:
I think this is what you want:

async function fetchPlayerNames( count = 1 ) {
    let playersResponse = await fetch(`https://www.balldontlie.io/api/v1/players?per_page=${count}`)
    let players = await playersResponse.json()
    let desiredPlayers = players.data.slice(0, count)
    return desiredPlayers.map( player => player.first_name )
}

(async function main() {
    let names = await fetchPlayerNames(5)
    console.log(names)
})()
```

Some notes:

async/await is easier to work with than chaining .then handlers, so if your function can be marked async (and some cannot), you should have a strong preference to avoid any .then or .catch inside that function. Your refactor makes the function async, but continues to use .then.

Your refactor won't work anyway, because return playerList will execute before either of the .then functions executes. As a result, I'd expect your refactor to return an empty array immediately every time.

Even though your refactor immediately returns an empty dataset, it still makes the API call five times. That is silly. The URL suggests that the API response can include multiple players, and so your plan should be: (1) make a single request that contains all the rows you want, and then (2) extract the items from that list that you want. If you are careless about making extra network calls, the people who own the API may ultimately block your application because it wastes resources.

Avoid hard-coding things like the 5. That is what is known as a "magic number". Instead, your function should be provided with the desired number. Calling code will get the correct number from a settings file or user input or something else. My version takes it as an argument, but hard-codes it at the call site because there's not really a better place in such a small code sample.

I am going to criticize your naming. Naming matters. Your function does not "generate" names -- it does not create or invent names randomly, but that is what the English word "generate" implies. Your function downloads names from the internet (the correct verb for which is "fetch"). If you name your functions badly, your app will become a mess.

Body:
I wrote a function which when I use the return keyword, I only get the first item of the list returned instead of all items. The code works properly without the return keyword.

code snippet

function generateNames(){
  for (let i = 0; i < 5; i++) {
    const playersName = fetch('https://www.balldontlie.io/api/v1/players?per_page=5')
      .then(response => response.json())
      .then(json => console.log(json['data'][i]['first_name']))
    // return playersName
  }
}
generateNames()

The result i get is;

Ike
Ron
Jabari
MarShon
Lorenzo

but when I uncomment the, return playersName line of code, I only get the first value returned.

The result i get is;

Ike

After refactoring the code:

async function generateNames() {
  var playerList = [];
  const playersName = await fetch('https://www.balldontlie.io/api/v1/players?per_page=5')
    .then(response => response.json())
    .then(json => {
      for (let i = 0; i < 5; i++)
        playerList.push(json['data'][i]['first_name'])
    })
  // return playersName
  return playerList;
}
(async () => console.log(await generateNames()))()

Body:
I think this is what you want:

async function fetchPlayerNames( count = 1 ) {
    let playersResponse = await fetch(`https://www.balldontlie.io/api/v1/players?per_page=${count}`)
    let players = await playersResponse.json()
    let desiredPlayers = players.data.slice(0, count)
    return desiredPlayers.map( player => player.first_name )
}

(async function main() {
    let names = await fetchPlayerNames(5)
    console.log(names)
})()

Some notes:

async/await is easier to work with than chaining .then handlers, so if your function can be marked async (and some cannot), you should have a strong preference to avoid any .then or .catch inside that function. Your refactor makes the function async, but continues to use .then.

Your refactor won't work anyway, because return playerList will execute before either of the .then functions executes. As a result, I'd expect your refactor to return an empty array immediately every time.

Even though your refactor immediately returns an empty dataset, it still makes the API call five times. That is silly. The URL suggests that the API response can include multiple players, and so your plan should be: (1) make a single request that contains all the rows you want, and then (2) extract the items from that list that you want. If you are careless about making extra network calls, the people who own the API may ultimately block your application because it wastes resources.

Avoid hard-coding things like the 5. That is what is known as a "magic number". Instead, your function should be provided with the desired number. Calling code will get the correct number from a settings file or user input or something else. My version takes it as an argument, but hard-codes it at the call site because there's not really a better place in such a small code sample.

I am going to criticize your naming. Naming matters. Your function does not "generate" names -- it does not create or invent names randomly, but that is what the English word "generate" implies. Your function downloads names from the internet (the correct verb for which is "fetch"). If you name your functions badly, your app will become a mess.


问:
REGULAR EXPRESSIONS
I have a simple data frame:

test = { "City": ['A'], "Features":[ "Street20 - Statue of
liberty\n-Avenue40 - Manhattan\n-street40 - Opera320"]}

I am using regular expressions to pull out certain information to be shown as follows:

Land_marks

Statue of Liberty

Manhattan

Opera320

I am trying with regular expressions, but it only returns the first value "Statue of Liberty". Could you help me out?

Thank you in advance

答:
You can use below regular expression #

```<code>(?<=\"Features\":\[\ ").*?(?=\])

</code>```

Demo : https://regex101.com/r/HUVQoj/1

Why you are using regular expression to get data from JSON? You can convert JSON to object and fetch desire result.

Title: REGULAR EXPRESSIONS

Body:
You can use below regular expression #

(?<=\"Features\":\[\ ").*?(?=\])

Demo : https://regex101.com/r/HUVQoj/1

Why you are using regular expression to get data from JSON? You can convert JSON to object and fetch desire result.


问:
Cypress - get value that is inside a component (into a variable)
I'm a new developer and I am trying to build a certain test using cypress. the client has a dynamic grid, and I'd like to see which row in the grid contains the data I want. I cannot change the HTML file.

At the moment I am trying to iterate over all rows using each() cypress command. So I have two questions:

is this a correct approach?

assuming it is correct, how do I get the value out of the component? for example, how do I get the value of "aaaaaaaa" out of here (and into a variable):
html structure

thanks!

答:
I have a test doing the same thing and the way I've approached it was:

```<code>cy.contains('aaaa').invoke("text").as('variableName')
</code>```

This can now be used like this:

```<code>cy.get(this.variableName).should('be.visible')

cy.contains('aaaa').parent().next().children() //Used to iterate through rows.
</code>```

Body:
I have a test doing the same thing and the way I've approached it was:

cy.contains('aaaa').invoke("text").as('variableName')

This can now be used like this:

cy.get(this.variableName).should('be.visible')

cy.contains('aaaa').parent().next().children() //Used to iterate through rows.


问:
How to save my progress from a public repo to my private repo?
I have been working on a series of exercises from a popular GitHub repository.
But unfortunately I have committed my answers to the main branch of their repository. I should have cloned their repository first and then committed my changes to the cloned repository. Both of these are on GitHub.

Do I have a way to do this?: I don't want to loose my progress and redo the exercises, but more importantly I want to preserve the timestamps associated with my commits. I want to commit the answers to my clone (which is to be created) and then push the already committed commits to it.

All of guides/solutions to similar problems started with the clone first and then

Here is what I have done:

$ git clone repo_of_exercises.git

< Solved many exercises and I have a commit message for each exercise >
$ git add <solution to an exercise>
$ git commit -m "<Appropriate commit message>"
< Note that I have not pushed these changes, it's all on my computer >
```

What are the next steps that I should take to copy all of commits to a clone that I will create soon?

答:
Here is how I solved my problem:

I just had to add my repository as a remote.

```<code>git remote add main link_to_my_repo.git
< I could have removed the origin, which points to the original public repository
 - read the documentation linked below >

git push main
< to push all the commits to my private repository >
</code>```

With these commands I will preserve the timestamp of my commits.

With my first attempt I had rebased the local repository to correct some commit messages and because of this all the commit messages were updated with a new timestamp.

I could have removed the original remote of the public repository but I chose not to thinking that it if I kept it then it may be recognised as a fork of the public repository.

But I was wrong and it does not recognise it as a fork.

git remote documentation

a tutorial that I followed

Body:
I have been working on a series of exercises from a popular GitHub repository.
But unfortunately I have committed my answers to the main branch of their repository. I should have cloned their repository first and then committed my changes to the cloned repository. Both of these are on GitHub.

Do I have a way to do this?: I don't want to loose my progress and redo the exercises, but more importantly I want to preserve the timestamps associated with my commits. I want to commit the answers to my clone (which is to be created) and then push the already committed commits to it.

All of guides/solutions to similar problems started with the clone first and then

Here is what I have done:

$ git clone repo_of_exercises.git

< Solved many exercises and I have a commit message for each exercise >
$ git add <solution to an exercise>
$ git commit -m "<Appropriate commit message>"
< Note that I have not pushed these changes, it's all on my computer >

What are the next steps that I should take to copy all of commits to a clone that I will create soon?

Body:
Here is how I solved my problem:

I just had to add my repository as a remote.

git remote add main link_to_my_repo.git
< I could have removed the origin, which points to the original public repository
 - read the documentation linked below >

git push main
< to push all the commits to my private repository >

With these commands I will preserve the timestamp of my commits.

With my first attempt I had rebased the local repository to correct some commit messages and because of this all the commit messages were updated with a new timestamp.

I could have removed the original remote of the public repository but I chose not to thinking that it if I kept it then it may be recognised as a fork of the public repository.

But I was wrong and it does not recognise it as a fork.

git remote documentation

a tutorial that I followed


问:
C++ friend operator definition inside class body serves as function declaration?
I'm a newbie reading the C++ Primer book. It says:

A friend declaration only specifies access. It is not a general declaration of the function. If we want users of the class to be able to call a friend function, then we must also declare the function separately from the friend declaration. To make a friend visible to users of the class, we usually declare each friend (outside the class) in the same header as the class itself.

But I just found that this is not the case for friend operator functions defined inside the class body. In the following code, f could not be found but operator+ is found:

```<code>struct X
{
    friend void f()
    {
        // friend functions can be defined in the class
        // this does NOT serve as a declaration, even though this is already a definition
        // to use this function, another declaration is REQUIRED
    }

    friend X operator+(const X & x1, const X & x2)
    {
        // this stuff serves as declaration somehow
        return {x1.v + x2.v};
    }

    void foo()
    {
        f();                    // ERROR: no declaration for f
        X tmp = X {1} + X {2};  // CORRECT
    }

    int v;
};
</code>```

Could someone tell me what makes this difference?
I am using g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, as a reference.
I have searched many questions involving friend declaration and definition on StackOverflow but did not find an answer on this. Sorry if this question is duplicated.

答:
The difference is the operator+ takes X as parameter, then ADL could find the name; f takes nothing, ADL can't help any.

(emphasis mine)

Names introduced by friend declarations within a non-local class X become members of the innermost enclosing namespace of X, but they do not become visible to ordinary name lookup (neither unqualified nor qualified) unless a matching declaration is provided at namespace scope, either before or after the class definition. Such name may be found through ADL which considers both namespaces and classes.

Body:
I'm a newbie reading the C++ Primer book. It says:

A friend declaration only specifies access. It is not a general declaration of the function. If we want users of the class to be able to call a friend function, then we must also declare the function separately from the friend declaration. To make a friend visible to users of the class, we usually declare each friend (outside the class) in the same header as the class itself.

But I just found that this is not the case for friend operator functions defined inside the class body. In the following code, f could not be found but operator+ is found:

struct X
{
    friend void f()
    {
        // friend functions can be defined in the class
        // this does NOT serve as a declaration, even though this is already a definition
        // to use this function, another declaration is REQUIRED
    }

    friend X operator+(const X & x1, const X & x2)
    {
        // this stuff serves as declaration somehow
        return {x1.v + x2.v};
    }

    void foo()
    {
        f();                    // ERROR: no declaration for f
        X tmp = X {1} + X {2};  // CORRECT
    }

    int v;
};

Could someone tell me what makes this difference?
I am using g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, as a reference.
I have searched many questions involving friend declaration and definition on StackOverflow but did not find an answer on this. Sorry if this question is duplicated.


问:
How to split csv file keeping its header in each smaller files in Python?
I have splited up a csv files into many smaller ones using code from here(Scroll down to see the full code): https://dzone.com/articles/splitting-csv-files-in-python

files have been successfully split up with its structure preserved,but the headers have disappeared. I suspect something off with the parameters within the pd.read()function.

Please help me have a look at this:

inputfile:

```<code>    Text Header    tag
0    textbody1    Y
1    textbody2    N
2    textbody2    Y
</code>```

outcome(Structure is still there but my headers are gone in my splitup csv files):

```<code>0    textbody1    Y
1    textbody2    N
2    textbody2    Y
</code>```

Please see below the full script:

```<code>    import pandas as pd

    #csv file name to be read in
    in_csv = 'iii_baiterEmailTagged.csv'

    #get the number of lines of the csv file to be read
    number_lines = sum(1 for row in (open(in_csv)))

    #size of rows of data to write to the csv,

    #you can change the row size according to your need
    rowsize = 10000

    #start looping through data writing it to a new file for each set
    for i in range(1,number_lines,rowsize):

        df = pd.read_csv(in_csv,

              header=None,

              nrows = rowsize,#number of rows to read at each loop

              skiprows = i)#skip rows that have been read

        #csv to write data to a new file with indexed name. input_1.csv etc.
        out_csv = 'Enronset' + str(i) + '.csv'

        df.to_csv(out_csv,

              index=False,

              header=False,
              mode='a',#append data to csv file
              chunksize=rowsize)#size of data to append for each loop
</code>```

Thanks

答:
This code works for me.</p>
```<code>

    import re
    import pandas as pd
    import random

    ## Provide file name with path for example: "C:\Users\xxxxx\flights.csv"
    split_source_file = input("File Name with absolute Path? : ")

    ## find number of lines using Pandas
    pd_dataframe = pd.read_csv(split_source_file, header=0, encoding = 'latin_1')
    number_of_rows = len(pd_dataframe.index) + 1
    the_header = pd_dataframe.columns.tolist()

    print(number_of_rows)

    ## Incase of equal split, provide the same number for min and max
    min_rows = int(input("Minimum Number of rows per file? : "))
    max_rows = int(input("Maximum Number of rows per file? : "))

    file_increment = 1
    skip_rows = 1

    ## first file random numbers
    number_of_rows_perfile = random.randint(min_rows, max_rows)

    while True:
        if number_of_rows_perfile<=0:
            break
        ## Read CSV file with number of rows and skip respective number of lines
        df = pd.read_csv(split_source_file, header=None, nrows = number_of_rows_perfile,skiprows = skip_rows,encoding = 'latin_1', lineterminator='\n' )

        # Thanks for Gist https://gist.github.com/smram/d6ded3c9028272360eb65bcab564a18a
        # got to handle both escaped and literal
        df.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=True, inplace=True)

        ## Target file name
        split_target_file = split_source_file[:-4] + "_" + str(file_increment) + ".csv"

        ## write to csv
        df.to_csv(split_target_file, index=False, header=the_header, mode='a', chunksize=number_of_rows_perfile)

        file_increment += 1

        skip_rows += number_of_rows_perfile

        ## Last file handler
        if skip_rows >= number_of_rows:
            number_of_rows_perfile = number_of_rows - skip_rows
        else:
            number_of_rows_perfile = random.randint(min_rows, max_rows)

</code>
```

Body:
I have splited up a csv files into many smaller ones using code from here(Scroll down to see the full code): https://dzone.com/articles/splitting-csv-files-in-python

files have been successfully split up with its structure preserved,but the headers have disappeared. I suspect something off with the parameters within the pd.read()function.

Please help me have a look at this:

inputfile:

    Text Header    tag
0    textbody1    Y
1    textbody2    N
2    textbody2    Y

outcome(Structure is still there but my headers are gone in my splitup csv files):

0    textbody1    Y
1    textbody2    N
2    textbody2    Y

Please see below the full script:

    import pandas as pd

    #csv file name to be read in
    in_csv = 'iii_baiterEmailTagged.csv'

    #get the number of lines of the csv file to be read
    number_lines = sum(1 for row in (open(in_csv)))

    #size of rows of data to write to the csv,

    #you can change the row size according to your need
    rowsize = 10000

    #start looping through data writing it to a new file for each set
    for i in range(1,number_lines,rowsize):

        df = pd.read_csv(in_csv,

              header=None,

              nrows = rowsize,#number of rows to read at each loop

              skiprows = i)#skip rows that have been read

        #csv to write data to a new file with indexed name. input_1.csv etc.
        out_csv = 'Enronset' + str(i) + '.csv'

        df.to_csv(out_csv,

              index=False,

              header=False,
              mode='a',#append data to csv file
              chunksize=rowsize)#size of data to append for each loop

Thanks

Body:
This code works for me.

    import re
    import pandas as pd
    import random

    ## Provide file name with path for example: "C:\Users\xxxxx\flights.csv"
    split_source_file = input("File Name with absolute Path? : ")

    ## find number of lines using Pandas
    pd_dataframe = pd.read_csv(split_source_file, header=0, encoding = 'latin_1')
    number_of_rows = len(pd_dataframe.index) + 1
    the_header = pd_dataframe.columns.tolist()

    print(number_of_rows)

    ## Incase of equal split, provide the same number for min and max
    min_rows = int(input("Minimum Number of rows per file? : "))
    max_rows = int(input("Maximum Number of rows per file? : "))

    file_increment = 1
    skip_rows = 1

    ## first file random numbers
    number_of_rows_perfile = random.randint(min_rows, max_rows)

    while True:
        if number_of_rows_perfile<=0:
            break
        ## Read CSV file with number of rows and skip respective number of lines
        df = pd.read_csv(split_source_file, header=None, nrows = number_of_rows_perfile,skiprows = skip_rows,encoding = 'latin_1', lineterminator='\n' )

        # Thanks for Gist https://gist.github.com/smram/d6ded3c9028272360eb65bcab564a18a
        # got to handle both escaped and literal
        df.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=True, inplace=True)

        ## Target file name
        split_target_file = split_source_file[:-4] + "_" + str(file_increment) + ".csv"

        ## write to csv
        df.to_csv(split_target_file, index=False, header=the_header, mode='a', chunksize=number_of_rows_perfile)

        file_increment += 1

        skip_rows += number_of_rows_perfile

        ## Last file handler
        if skip_rows >= number_of_rows:
            number_of_rows_perfile = number_of_rows - skip_rows
        else:
            number_of_rows_perfile = random.randint(min_rows, max_rows)


问:
Using a LIKE statement in an IN using a parameter - Report Builder
I'm trying to figure out how to build a report where I have a char(255) field and I'm giving the initial dataset a statement like such:

```<code>WHERE an.NoteText like '%COM[1-49CFJO]%' COLLATE SQL_Latin1_General_CP1_CS_AS
</code>```

I use the COLLATE to ensure it only picks up these values in capital letters so it doesn't pick up 'comfort' or words with como in them unless they are all caps.

This works in terms of giving me the dataset I want but I then want to filter on the report based on a multi-select parameter @Code.

I can get it to show me values of NoteText when the value is ONLY 'COMF' or 'COM1' by using NoteText IN @Code, but then it won't show anything were the NoteText value is something like "COMF
Customer blah blah blah".  So I need it to pull all records with all the text within the same NoteText instance like it does without the filter added.

I try to use a filter with the expression NoteText IN %@code% or ('%' + @Code + '%') or ('%' & @Code & '%') and in each of these cases it doesn't work even if I only select one value to display at a time.  I'm using SSRS Report Builder.  Any help would be appreciated.

答:
For the exact code you showed above, you can consolidate it using SQL Server's enhanced LIKE operator, which supports some primitive regex behavior:

WHERE an.NoteText like '%COM[1-49CFJO]%' COLLATE SQL_Latin1_General_CP1_CS_AS
```

Body:
I'm trying to figure out how to build a report where I have a char(255) field and I'm giving the initial dataset a statement like such:

WHERE an.NoteText like '%COM[1-49CFJO]%' COLLATE SQL_Latin1_General_CP1_CS_AS

I use the COLLATE to ensure it only picks up these values in capital letters so it doesn't pick up 'comfort' or words with como in them unless they are all caps.

This works in terms of giving me the dataset I want but I then want to filter on the report based on a multi-select parameter @Code.

I can get it to show me values of NoteText when the value is ONLY 'COMF' or 'COM1' by using NoteText IN @Code, but then it won't show anything were the NoteText value is something like "COMF
Customer blah blah blah".  So I need it to pull all records with all the text within the same NoteText instance like it does without the filter added.

I try to use a filter with the expression NoteText IN %@code% or ('%' + @Code + '%') or ('%' & @Code & '%') and in each of these cases it doesn't work even if I only select one value to display at a time.  I'm using SSRS Report Builder.  Any help would be appreciated.


问:
laravel BelongsTo relationship with different databases not working
I've seen in several places to "stay away" from this, but alas - this is how my DB is built:

```<code>class Album extends Eloquent {

   // default connection

   public function genre() {
       return $this->belongsTo('genre');
   }
</code>```

and the Genre table:

```<code>class Genre extends Eloquent {
    protected $connection = 'Resources';

}
</code>```

My database.php:

```<code>'Resources' => array(
                    'driver'    => 'mysql',
                    'host'      => 'localhost',
                    'database'  => 'resources',
                    'username'  => 'user',
                    'password'  => 'password',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',
            ),

 'mysql' => array(
                    'driver'    => 'mysql',
                    'host'      => 'localhost',
                    'database'  => 'my_data',
                    'username'  => 'user',
                    'password'  => 'password',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',
            ),
</code>```

and when I try to run

```<code>Album::whereHas('genre', function ($q) {
   $q->where('genre', 'German HopScotch');
});
</code>```

it doesn't select properly (doesn't add the database name to the table "genres"):

```<code>Next exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'my_data.genres' doesn't exist
</code>```

Its important to note that this works perfectly:

```<code>Album::first()->genre;
</code>```

Update

The best I've found so far is to use the builder's "from" method to specifically name the correct connection.
I've discovered that the builder inside the query can receive "from"

```<code>Album::whereHas('genre', function ($q) {
   $q->from('resources.genres')->where('genre', 'German HopScotch');
});
</code>```

This is a decent solution but it requires me to dig in the database php and find a good way to get the proper table and database name from the relation 'genre'.

I will appreciate if anyone else can build on this solution and make it more general.

答:
Just in case someone reaches here.

When you are fetching data using a relationship from different database connections, make sure that your related table has the $connection property defined even if it's the default connection.

Account Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Account extends Model {

    protected $connection = 'different_connection';

    public function verifiedBy()
    {
        return $this->belongsTo(User::class, 'verified_by');
    }
}
```
<p><code>User</code> Model:</p>
<pre class="lang-php prettyprint-override"><code><?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {
    // this one uses the default - `database.default` connection
    public function approved()
    {
        return $this->hasMany(Account::class, 'verified_by');
    }
}
</code>```

As soon as I do Account:find($id)->verifiedBy, it will throw error. Look at the database name and you'll find. But if you do, User::find($id)->approved, it will work fine, because the Account model has the connection defined. And not the vice-versa.

So, just to be safe, if you deal with multiple database connections, put the $connection property in the models.

Laravel's implementation

Body:
I've seen in several places to "stay away" from this, but alas - this is how my DB is built:

class Album extends Eloquent {

   // default connection

   public function genre() {
       return $this->belongsTo('genre');
   }

and the Genre table:

class Genre extends Eloquent {
    protected $connection = 'Resources';

}

My database.php:

'Resources' => array(
                    'driver'    => 'mysql',
                    'host'      => 'localhost',
                    'database'  => 'resources',
                    'username'  => 'user',
                    'password'  => 'password',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',
            ),

 'mysql' => array(
                    'driver'    => 'mysql',
                    'host'      => 'localhost',
                    'database'  => 'my_data',
                    'username'  => 'user',
                    'password'  => 'password',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',
            ),

and when I try to run

Album::whereHas('genre', function ($q) {
   $q->where('genre', 'German HopScotch');
});

it doesn't select properly (doesn't add the database name to the table "genres"):

Next exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'my_data.genres' doesn't exist

Its important to note that this works perfectly:

Album::first()->genre;

Update

The best I've found so far is to use the builder's "from" method to specifically name the correct connection.
I've discovered that the builder inside the query can receive "from"

Album::whereHas('genre', function ($q) {
   $q->from('resources.genres')->where('genre', 'German HopScotch');
});

This is a decent solution but it requires me to dig in the database php and find a good way to get the proper table and database name from the relation 'genre'.

I will appreciate if anyone else can build on this solution and make it more general.

Body:
Just in case someone reaches here.

When you are fetching data using a relationship from different database connections, make sure that your related table has the $connection property defined even if it's the default connection.

Account Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Account extends Model {

    protected $connection = 'different_connection';

    public function verifiedBy()
    {
        return $this->belongsTo(User::class, 'verified_by');
    }
}

User Model:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {
    // this one uses the default - `database.default` connection
    public function approved()
    {
        return $this->hasMany(Account::class, 'verified_by');
    }
}

As soon as I do Account:find($id)->verifiedBy, it will throw error. Look at the database name and you'll find. But if you do, User::find($id)->approved, it will work fine, because the Account model has the connection defined. And not the vice-versa.

So, just to be safe, if you deal with multiple database connections, put the $connection property in the models.

Laravel's implementation


问:
java.lang.RuntimeException: Unable to instantiate activity in Flutter
Flutter newly created app gives error when using fire base.

How should i fix this problem as it is asking flutter app main activity cannot be cast to android app activity.

```<code>04-05 21:16:07.570 27391-27391/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.firestoreflutterchat, PID: 27391
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firestoreflutterchat/com.example.firestoreflutterchat.MainActivity}: java.lang.ClassCastException: com.example.firestoreflutterchat.MainActivity cannot be cast to android.app.Activity
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2124)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
        at android.app.ActivityThread.access$800(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5097)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: com.example.firestoreflutterchat.MainActivity cannot be cast to android.app.Activity
        at android.app.Instrumentation.newActivity(Instrumentation.java:1084)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2115)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
        at android.app.ActivityThread.access$800(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5097)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
</code>```

This is main dart file , no changes are made here.

```<code>import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {

      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

This is android src Main activity kotlin :

```<code>package com.example.firestoreflutterchat

import android.content.Context
//import androidx.multidex.MultiDex
import io.flutter.app.FlutterApplication
import io.flutter.embedding.android.FlutterActivity

class MainActivity : FlutterApplication() {

    }
</code>```

I only opened a new flutter project and  followed the fire base steps to add dependencies and google-services.json file to project.

It later was giving firebase in it error so i added multidex.

In the main dart file of flutter application and android module Main activity no changes were made.

Is it some thing i did wrong , i am new to flutter so i am not understanding.

答:
Update the folders containing your MainActivity.kt with the package name in the MainActivity.kt
enter image description here</p>

Body:
Flutter newly created app gives error when using fire base.

How should i fix this problem as it is asking flutter app main activity cannot be cast to android app activity.

04-05 21:16:07.570 27391-27391/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.firestoreflutterchat, PID: 27391
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firestoreflutterchat/com.example.firestoreflutterchat.MainActivity}: java.lang.ClassCastException: com.example.firestoreflutterchat.MainActivity cannot be cast to android.app.Activity
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2124)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
        at android.app.ActivityThread.access$800(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5097)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: com.example.firestoreflutterchat.MainActivity cannot be cast to android.app.Activity
        at android.app.Instrumentation.newActivity(Instrumentation.java:1084)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2115)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
        at android.app.ActivityThread.access$800(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5097)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)

This is main dart file , no changes are made here.

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {

      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

This is android src Main activity kotlin :

package com.example.firestoreflutterchat

import android.content.Context
//import androidx.multidex.MultiDex
import io.flutter.app.FlutterApplication
import io.flutter.embedding.android.FlutterActivity

class MainActivity : FlutterApplication() {

    }

I only opened a new flutter project and  followed the fire base steps to add dependencies and google-services.json file to project.

It later was giving firebase in it error so i added multidex.

In the main dart file of flutter application and android module Main activity no changes were made.

Is it some thing i did wrong , i am new to flutter so i am not understanding.


问:
how to pass in objects from Angular to backend in a GET request?
I am trying to pass in objects from Angular to backend using GET request, but I am getting null values for all the properties if I am using a custom objects in the back end, what are the correct ways to pass in objects in a GET call?

So here's my code in the UI :

```<code> public getRules(lockedFolder: Folder, pageSize: number, requiredCount: boolean, search: AdvancedSearch, filters: AdvancedSearch): Observable<PaginateResults<Rules>> {
        const searchOption = {
            projectId: lockedFolder.projectId,
            pageSize: pageSize,
            requiredCount: requiredCount,
            search: search,
            filters: filters
        };
        return this._http.get<PaginateResults<Rules>>(this._rulesResourceUrl, {params: this.setQueryString(searchOption)});
    }
</code>```

and the setQueryString method is:

```<code>setQueryString(params: object) {
        let httpParams = new HttpParams();
        if (params) {
            for (const key of Object.keys(params)) {
                httpParams = httpParams.set(key, params[key]);
            }
        }
        return httpParams;
      }
</code>```

and the API method I have :

```<code>public ResponseEntity<PaginateResults<Rule>> getRules(@RequestParam("projectId") Integer projectId,
  @RequestParam("pageSize") Integer pageSize,
@RequestParam("requiredCount") Boolean requiredCount,
 RuleAdvancedSearch search, RuleAdvancedSearch filter) {

</code>```

I am able to get the primitive types values, which is projectId, pageSize and requiredCount in the backend.

However, I also want to get the search ( RuleAdvancedSearch Object), BUT the properties are always null for some reason.

The RuleAdvancedSearch have the following fields:

ruleType

ruleName

modelRestriction

optionRestriction

For example, if I pass in the following to the GET request :

```<code>{
    "projectId": 123456,
    "pageSize": 100,
    "requiredCount": true,
    "search": {
        "ruleName": "%00ABC"
    }
}
</code>```

I am able to get the projectId, pageSize, requiredCount, but for the search,
 it has null values for all properties, which is not I expect. I expect the ruleName should have "%00ABC", but what I got is :

```<code> - ruleType = null
 - ruleName = null
 - modelRestriction = null
 - optionRestriction = null
</code>```

What is the correct way to pass in custom objects to GET request?
Thank you!

答:
there is no way you can pass object to get method, you have to pass via query string.

before passing through the query string check that query string has null value, if has null value exclude it and if not include it in the query string.

Body:
I am trying to pass in objects from Angular to backend using GET request, but I am getting null values for all the properties if I am using a custom objects in the back end, what are the correct ways to pass in objects in a GET call?

So here's my code in the UI :

 public getRules(lockedFolder: Folder, pageSize: number, requiredCount: boolean, search: AdvancedSearch, filters: AdvancedSearch): Observable<PaginateResults<Rules>> {
        const searchOption = {
            projectId: lockedFolder.projectId,
            pageSize: pageSize,
            requiredCount: requiredCount,
            search: search,
            filters: filters
        };
        return this._http.get<PaginateResults<Rules>>(this._rulesResourceUrl, {params: this.setQueryString(searchOption)});
    }

and the setQueryString method is:

setQueryString(params: object) {
        let httpParams = new HttpParams();
        if (params) {
            for (const key of Object.keys(params)) {
                httpParams = httpParams.set(key, params[key]);
            }
        }
        return httpParams;
      }

and the API method I have :

public ResponseEntity<PaginateResults<Rule>> getRules(@RequestParam("projectId") Integer projectId,
  @RequestParam("pageSize") Integer pageSize,
@RequestParam("requiredCount") Boolean requiredCount,
 RuleAdvancedSearch search, RuleAdvancedSearch filter) {

I am able to get the primitive types values, which is projectId, pageSize and requiredCount in the backend.

However, I also want to get the search ( RuleAdvancedSearch Object), BUT the properties are always null for some reason.

The RuleAdvancedSearch have the following fields:

ruleType

ruleName

modelRestriction

optionRestriction

For example, if I pass in the following to the GET request :

{
    "projectId": 123456,
    "pageSize": 100,
    "requiredCount": true,
    "search": {
        "ruleName": "%00ABC"
    }
}

I am able to get the projectId, pageSize, requiredCount, but for the search,
 it has null values for all properties, which is not I expect. I expect the ruleName should have "%00ABC", but what I got is :

 - ruleType = null
 - ruleName = null
 - modelRestriction = null
 - optionRestriction = null

What is the correct way to pass in custom objects to GET request?
Thank you!


问:
Why my table is getting collapsed when I am moving div elements?
I am trying to make a table in which we can interchange colored boxes via drag and drop with animation. It is working fine sometimes but in some cases the table is getting collapsed .Steps to replicate the problem.

Move 100 - 400

Move 100 -500

Move 100 - 200

Move 100 - 300

You can find my code in this attached link :

https://jsfiddle.net/manikathuria2001/oveq91Lu/6/

HTML

var columns = document.querySelectorAll('.card');
var draggingClass = 'dragging';
var dragSource;

Array.prototype.forEach.call(columns, function (col) {
  col.addEventListener('dragstart', handleDragStart, false);
  col.addEventListener('dragenter', handleDragEnter, false)
  col.addEventListener('dragover', handleDragOver, false);
  col.addEventListener('dragleave', handleDragLeave, false);
  col.addEventListener('drop', handleDrop, false);
  col.addEventListener('dragend', handleDragEnd, false);
});

function handleDragStart (evt) {
  dragSource = this;
  evt.target.classList.add(draggingClass);
  evt.dataTransfer.effectAllowed = 'move';

}

function handleDragOver (evt) {
  evt.dataTransfer.dropEffect = 'move';
  evt.preventDefault();
}

function handleDragEnter (evt) {
  this.classList.add('over');
}

function handleDragLeave (evt) {
  this.classList.remove('over');
}

function handleDrop (evt) {
  evt.stopPropagation();

  if (dragSource !== this) {
   $(this).swap($(dragSource),300);
  }
  evt.preventDefault();
}

function handleDragEnd (evt) {
  Array.prototype.forEach.call(columns, function (col) {
    ['over', 'dragging'].forEach(function (className) {
      col.classList.remove(className);
    });
  });
}

(function( $ ){
    $.fn.swap = function(other,speed) {

        //get the position
        var position1 = $(this).offset();
        var position2 = other.offset();

        //position this where it is
        $(this).css({
            top: position1.top + 'px',
            left: position1.left + 'px',
            position: 'absolute'
        });

        //position the other element where it is
        other.css({
            top: position2.top + 'px',
            left: position2.left + 'px',
            position: 'absolute'
        });

        $(this).animate({
            'top': position2.top + 'px',
            'left': position2.left + 'px',
            position: 'absolute'
        }, speed, function() {
                // Animation complete.
        });

        other.animate({
            'top': position1.top + 'px',
            'left': position1.left + 'px',
            position: 'absolute'
        }, speed, function() {
            // Animation complete.
        });

    };
})( jQuery );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  text-align: center;
}

#table1 {
  width: 100%;
  height: 50%;
}

#table1,
.block {
  border: 1px solid black;
  border-collapse: collapse;
}

.block {
  padding: 30px !important;
  margin: 100px !important;
  /* min-width: 200px !important;
    min-height: 400px !important; */
}

.card {
  width: 100px;
  height: 60px;
  border-radius: 25px;
  /* display: inline-block; */
  /* margin-right: 1.2%; */
  box-sizing: border-box;
  font-size: larger;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  text-align: center;
  z-index: 100;
}

.card.dragging {
  opacity: 0.5;
}

.card.over {
  border: 3px dashed #000;
}

.box1 {
  background-color: #E74C3C;
}

.box2 {
  background-color: #8E44AD;
}

.box3 {
  background-color: #5DADE2;
}

.box4 {
  background-color: #1ABC9C;
}

.box5 {
  background-color: #F1C40F;
}

.box6 {
  background-color: #F39C12;
}

.box7 {
  background-color: #34495E;
}

.box8 {
  background-color: #FF00FF;
}

.box9 {
  background-color: #008080;
}

[draggable] {
  user-select: none;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="./styles.css">
  <title>Document</title>

100

200

300

400

500

600

700

800

900

```

答:
The height of .block is dependent on the .card inside it. But when the card is moved it gets position: absolute;, so it's out of the flow, and the block collapses. You don't notice this until all the cards on the same row are moved, then the row collapses.

Give .block a fixed height in CSS and the problem goes away.

There's a similar problem with the column widths if you drag all the cards in the same column, so you also have to give .block a fixed width.

var columns = document.querySelectorAll('.card');
var draggingClass = 'dragging';
var dragSource;

Array.prototype.forEach.call(columns, function (col) {
  col.addEventListener('dragstart', handleDragStart, false);
  col.addEventListener('dragenter', handleDragEnter, false)
  col.addEventListener('dragover', handleDragOver, false);
  col.addEventListener('dragleave', handleDragLeave, false);
  col.addEventListener('drop', handleDrop, false);
  col.addEventListener('dragend', handleDragEnd, false);
});

function handleDragStart (evt) {
  dragSource = this;
  evt.target.classList.add(draggingClass);
  evt.dataTransfer.effectAllowed = 'move';

}

function handleDragOver (evt) {
  evt.dataTransfer.dropEffect = 'move';
  evt.preventDefault();
}

function handleDragEnter (evt) {
  this.classList.add('over');
}

function handleDragLeave (evt) {
  this.classList.remove('over');
}

function handleDrop (evt) {
  evt.stopPropagation();

  if (dragSource !== this) {
   $(this).swap($(dragSource),300);
  }
  evt.preventDefault();
}

function handleDragEnd (evt) {
  Array.prototype.forEach.call(columns, function (col) {
    ['over', 'dragging'].forEach(function (className) {
      col.classList.remove(className);
    });
  });
}

(function( $ ){
    $.fn.swap = function(other,speed) {

        //get the position
        var position1 = $(this).offset();
        var position2 = other.offset();

        //position this where it is
        $(this).css({
            top: position1.top + 'px',
            left: position1.left + 'px',
            position: 'absolute'
        });

        //position the other element where it is
        other.css({
            top: position2.top + 'px',
            left: position2.left + 'px',
            position: 'absolute'
        });

        $(this).animate({
            'top': position2.top + 'px',
            'left': position2.left + 'px',
            position: 'absolute'
        }, speed, function() {
                // Animation complete.
        });

        other.animate({
            'top': position1.top + 'px',
            'left': position1.left + 'px',
            position: 'absolute'
        }, speed, function() {
            // Animation complete.
        });

    };
})( jQuery );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  text-align: center;
}

#table1 {
  width: 100%;
  height: 50%;
}

#table1,
.block {
  border: 1px solid black;
  border-collapse: collapse;
}

.block {
  padding: 30px !important;
  margin: 100px !important;
  /* min-width: 200px !important;
    min-height: 400px !important; */
  height: 60px; /* prevent collapse when card is moved */
  width: 340px;
}

.card {
  width: 100px;
  height: 60px;
  border-radius: 25px;
  /* display: inline-block; */
  /* margin-right: 1.2%; */
  box-sizing: border-box;
  font-size: larger;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  text-align: center;
  z-index: 100;
}

.card.dragging {
  opacity: 0.5;
}

.card.over {
  border: 3px dashed #000;
}

.box1 {
  background-color: #E74C3C;
}

.box2 {
  background-color: #8E44AD;
}

.box3 {
  background-color: #5DADE2;
}

.box4 {
  background-color: #1ABC9C;
}

.box5 {
  background-color: #F1C40F;
}

.box6 {
  background-color: #F39C12;
}

.box7 {
  background-color: #34495E;
}

.box8 {
  background-color: #FF00FF;
}

.box9 {
  background-color: #008080;
}

[draggable] {
  user-select: none;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="./styles.css">
  <title>Document</title>

100

200

300

400

500

600

700

800

900

```

Body:
I am trying to make a table in which we can interchange colored boxes via drag and drop with animation. It is working fine sometimes but in some cases the table is getting collapsed .Steps to replicate the problem.

Move 100 - 400

Move 100 -500

Move 100 - 200

Move 100 - 300

You can find my code in this attached link :

https://jsfiddle.net/manikathuria2001/oveq91Lu/6/

HTML

var columns = document.querySelectorAll('.card');
var draggingClass = 'dragging';
var dragSource;

Array.prototype.forEach.call(columns, function (col) {
  col.addEventListener('dragstart', handleDragStart, false);
  col.addEventListener('dragenter', handleDragEnter, false)
  col.addEventListener('dragover', handleDragOver, false);
  col.addEventListener('dragleave', handleDragLeave, false);
  col.addEventListener('drop', handleDrop, false);
  col.addEventListener('dragend', handleDragEnd, false);
});

function handleDragStart (evt) {
  dragSource = this;
  evt.target.classList.add(draggingClass);
  evt.dataTransfer.effectAllowed = 'move';

}

function handleDragOver (evt) {
  evt.dataTransfer.dropEffect = 'move';
  evt.preventDefault();
}

function handleDragEnter (evt) {
  this.classList.add('over');
}

function handleDragLeave (evt) {
  this.classList.remove('over');
}

function handleDrop (evt) {
  evt.stopPropagation();

  if (dragSource !== this) {
   $(this).swap($(dragSource),300);
  }
  evt.preventDefault();
}

function handleDragEnd (evt) {
  Array.prototype.forEach.call(columns, function (col) {
    ['over', 'dragging'].forEach(function (className) {
      col.classList.remove(className);
    });
  });
}

(function( $ ){
    $.fn.swap = function(other,speed) {

        //get the position
        var position1 = $(this).offset();
        var position2 = other.offset();

        //position this where it is
        $(this).css({
            top: position1.top + 'px',
            left: position1.left + 'px',
            position: 'absolute'
        });

        //position the other element where it is
        other.css({
            top: position2.top + 'px',
            left: position2.left + 'px',
            position: 'absolute'
        });

        $(this).animate({
            'top': position2.top + 'px',
            'left': position2.left + 'px',
            position: 'absolute'
        }, speed, function() {
                // Animation complete.
        });

        other.animate({
            'top': position1.top + 'px',
            'left': position1.left + 'px',
            position: 'absolute'
        }, speed, function() {
            // Animation complete.
        });

    };
})( jQuery );

.container {
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  text-align: center;
}

#table1 {
  width: 100%;
  height: 50%;
}

#table1,
.block {
  border: 1px solid black;
  border-collapse: collapse;
}

.block {
  padding: 30px !important;
  margin: 100px !important;
  /* min-width: 200px !important;
    min-height: 400px !important; */
}

.card {
  width: 100px;
  height: 60px;
  border-radius: 25px;
  /* display: inline-block; */
  /* margin-right: 1.2%; */
  box-sizing: border-box;
  font-size: larger;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  text-align: center;
  z-index: 100;
}

.card.dragging {
  opacity: 0.5;
}

.card.over {
  border: 3px dashed #000;
}

.box1 {
  background-color: #E74C3C;
}

.box2 {
  background-color: #8E44AD;
}

.box3 {
  background-color: #5DADE2;
}

.box4 {
  background-color: #1ABC9C;
}

.box5 {
  background-color: #F1C40F;
}

.box6 {
  background-color: #F39C12;
}

.box7 {
  background-color: #34495E;
}

.box8 {
  background-color: #FF00FF;
}

.box9 {
  background-color: #008080;
}

[draggable] {
  user-select: none;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="./styles.css">
  <title>Document</title>

100

200

300

400

500

600

700

800

900

Body:
The height of .block is dependent on the .card inside it. But when the card is moved it gets position: absolute;, so it's out of the flow, and the block collapses. You don't notice this until all the cards on the same row are moved, then the row collapses.

Give .block a fixed height in CSS and the problem goes away.

There's a similar problem with the column widths if you drag all the cards in the same column, so you also have to give .block a fixed width.

var columns = document.querySelectorAll('.card');
var draggingClass = 'dragging';
var dragSource;

Array.prototype.forEach.call(columns, function (col) {
  col.addEventListener('dragstart', handleDragStart, false);
  col.addEventListener('dragenter', handleDragEnter, false)
  col.addEventListener('dragover', handleDragOver, false);
  col.addEventListener('dragleave', handleDragLeave, false);
  col.addEventListener('drop', handleDrop, false);
  col.addEventListener('dragend', handleDragEnd, false);
});

function handleDragStart (evt) {
  dragSource = this;
  evt.target.classList.add(draggingClass);
  evt.dataTransfer.effectAllowed = 'move';

}

function handleDragOver (evt) {
  evt.dataTransfer.dropEffect = 'move';
  evt.preventDefault();
}

function handleDragEnter (evt) {
  this.classList.add('over');
}

function handleDragLeave (evt) {
  this.classList.remove('over');
}

function handleDrop (evt) {
  evt.stopPropagation();

  if (dragSource !== this) {
   $(this).swap($(dragSource),300);
  }
  evt.preventDefault();
}

function handleDragEnd (evt) {
  Array.prototype.forEach.call(columns, function (col) {
    ['over', 'dragging'].forEach(function (className) {
      col.classList.remove(className);
    });
  });
}

(function( $ ){
    $.fn.swap = function(other,speed) {

        //get the position
        var position1 = $(this).offset();
        var position2 = other.offset();

        //position this where it is
        $(this).css({
            top: position1.top + 'px',
            left: position1.left + 'px',
            position: 'absolute'
        });

        //position the other element where it is
        other.css({
            top: position2.top + 'px',
            left: position2.left + 'px',
            position: 'absolute'
        });

        $(this).animate({
            'top': position2.top + 'px',
            'left': position2.left + 'px',
            position: 'absolute'
        }, speed, function() {
                // Animation complete.
        });

        other.animate({
            'top': position1.top + 'px',
            'left': position1.left + 'px',
            position: 'absolute'
        }, speed, function() {
            // Animation complete.
        });

    };
})( jQuery );

.container {
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  text-align: center;
}

#table1 {
  width: 100%;
  height: 50%;
}

#table1,
.block {
  border: 1px solid black;
  border-collapse: collapse;
}

.block {
  padding: 30px !important;
  margin: 100px !important;
  /* min-width: 200px !important;
    min-height: 400px !important; */
  height: 60px; /* prevent collapse when card is moved */
  width: 340px;
}

.card {
  width: 100px;
  height: 60px;
  border-radius: 25px;
  /* display: inline-block; */
  /* margin-right: 1.2%; */
  box-sizing: border-box;
  font-size: larger;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  text-align: center;
  z-index: 100;
}

.card.dragging {
  opacity: 0.5;
}

.card.over {
  border: 3px dashed #000;
}

.box1 {
  background-color: #E74C3C;
}

.box2 {
  background-color: #8E44AD;
}

.box3 {
  background-color: #5DADE2;
}

.box4 {
  background-color: #1ABC9C;
}

.box5 {
  background-color: #F1C40F;
}

.box6 {
  background-color: #F39C12;
}

.box7 {
  background-color: #34495E;
}

.box8 {
  background-color: #FF00FF;
}

.box9 {
  background-color: #008080;
}

[draggable] {
  user-select: none;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
  <link rel="stylesheet" href="./styles.css">
  <title>Document</title>
</head>

<body>
  <div class="container">
    <table id="table1" cellspacing="0" cellpadding="0">
      <tr class="columns">
        <td class="block">
          <div class="card box1" draggable="true">100</div>
        </td>
        <td class="block">
          <div class="card box2" draggable="true">200</div>
        </td>
        <td class="block">
          <div class="card box3" draggable="true">300</div>
        </td>
      </tr>
      <tr class="columns">
        <td class="block">
          <div class="card box4" draggable="true">400</div>
        </td>
        <td class="block">
          <div class="card box5" draggable="true">500</div>
        </td>
        <td class="block">
          <div class="card box6" draggable="true">600</div>
        </td>
      </tr>
      <tr class="columns">
        <td class="block">
          <div class="card box7" draggable="true">700</div>
        </td>
        <td class="block">
          <div class="card box8" draggable="true">800</div>
        </td>
        <td class="block">
          <div class="card box9" draggable="true">900</div>
        </td>
      </tr>
    </table>
  </div>

  <script src="./index.js"></script>
</body>

</html>


问:
Issue with Dolby API Integrated with GCP
I'm currently trying to use Dolby's enhance API and I'm running into an issue when trying to write the output file. Here's the code I'm using to get the blob for the input and output blobs:

```<code>file = await storage_client.get_capture_file(capture.filename)
input_file = file.generate_signed_url(
    version="v4",
    expiration=datetime.timedelta(minutes=15),
    method="GET",
)
blob = storage_client.capture_bucket.blob(
    "{}_{}".format(preset, capture.filename)
    if preset
    else "{}_{}_{}_{}_{}".format(
        speech_isolation,
        range_control,
        noise_reduction,
        peak_limit,
        capture.filename,
    )
)
output_file = blob.generate_signed_url(
    version="v4",
    expiration=datetime.timedelta(minutes=15),
    method="PUT",
    content_type="application/octet-stream",
)
</code>```

The input file works fine since if I write to Dolby's temporary storage, there's no problem. Here's my payload and API call

```<code>payload = {
    "content": {"type": "mobile_phone"},
    ...

    "input": input_file,
    "output": output_file,
}
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "x-api-key": os.environ.get("DOLBY_API_KEY"),
}
enhance_response = requests.request(
    "POST", "https://api.dolby.com/media/enhance", json=payload, headers=headers
)
</code>```

The specific error I'm receiving is the following:

```<code>{'path': '/media/enhance', 'status': 'InternalError', 'progress': 43, 'api_version': 'v1.1.2', 'error': {'type': '/problems/internal-error', 'title': 'An internal service error has occurred'}}
</code>```

I believe the issue has something to do with uploading the new file to GCP. I don't really know what the exact issue is though. Any guidance would be appreciated.

答:
Remove the

```<code>content_type="application/octet-stream",
</code>```

and it will work. I received this answer from Dolby tech support after several days of troubleshooting and it is currently working for me.

Body:
I'm currently trying to use Dolby's enhance API and I'm running into an issue when trying to write the output file. Here's the code I'm using to get the blob for the input and output blobs:

file = await storage_client.get_capture_file(capture.filename)
input_file = file.generate_signed_url(
    version="v4",
    expiration=datetime.timedelta(minutes=15),
    method="GET",
)
blob = storage_client.capture_bucket.blob(
    "{}_{}".format(preset, capture.filename)
    if preset
    else "{}_{}_{}_{}_{}".format(
        speech_isolation,
        range_control,
        noise_reduction,
        peak_limit,
        capture.filename,
    )
)
output_file = blob.generate_signed_url(
    version="v4",
    expiration=datetime.timedelta(minutes=15),
    method="PUT",
    content_type="application/octet-stream",
)

The input file works fine since if I write to Dolby's temporary storage, there's no problem. Here's my payload and API call

payload = {
    "content": {"type": "mobile_phone"},
    ...

    "input": input_file,
    "output": output_file,
}
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "x-api-key": os.environ.get("DOLBY_API_KEY"),
}
enhance_response = requests.request(
    "POST", "https://api.dolby.com/media/enhance", json=payload, headers=headers
)

The specific error I'm receiving is the following:

{'path': '/media/enhance', 'status': 'InternalError', 'progress': 43, 'api_version': 'v1.1.2', 'error': {'type': '/problems/internal-error', 'title': 'An internal service error has occurred'}}

I believe the issue has something to do with uploading the new file to GCP. I don't really know what the exact issue is though. Any guidance would be appreciated.

Body:
Remove the

content_type="application/octet-stream",

and it will work. I received this answer from Dolby tech support after several days of troubleshooting and it is currently working for me.


问:
Align a div container at the bottom of an image
I can't align a div container at the bottom of an image.
What I've tried is editing the attribute position of the image and set it's value to "relative".

Explaining this is a little bit difficult, but I got html and css code snippets with a little preview:
codepen.io/Proudyy/pen/PoOjYpK
(it's not 84 lines long, so not too much in my opinion)

This is how it should look like:
https://imgur.com/a/LShx2cM

答:
set position: absolute for .skin-item-footer  and position: relative on it's parent div. Check below code

.skin-item-splashart {
    width: 100%;
    border-radius: 12px;
    position: relative;
}
.skin-item-footer-left-container {
    grid-column: 1;
    display: grid;
    grid-template-rows: repeat(2, auto);
    align-self: start;
    height: 100%;
}
.skin-item-footer-right-container {
    grid-column: 2;
    display: grid;
    align-items: center;
    justify-content: end;
    align-self: end;
    height: 100%;
}
.skin-item-default-name {
    font-size: 24px;
    font-weight: bold;
    margin-left: 3vh;
}
.skin-item-name {
    font-size: 18px;
    color: gainsboro;
    margin: 0;
    margin-left: 3vh;
    grid-row: 1;
}
.skin-item-cost {
    display: grid;
    grid-row: 2;
    grid-template-columns: repeat(2, auto);
    grid-template-rows: 1fr;
}
.skin-item-cost-value {
    color: gainsboro;
    grid-column: 1;
    margin: 0;
}
.skin-item-cost-icon {
    grid-column: 2;
    margin: 0;
}
.skin-item-save-icon {
    cursor: pointer;
    margin-right: 2vh;
}

.skin-item {
    background-color: rgb(0, 40, 75);
    margin: 15px;
    border-radius: 12px;
    height: auto;
    width: 50%;
    position: relative;
}
img{
    max-width: 100%;
}
.skin-item-footer {
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 0 0 12px 12px;
    position: absolute;
    bottom: 0;
    height: auto;
    width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="skin-item">
    <img class="skin-item-splashart" src="https://cdn.communitydragon.org/latest/champion/1/splash-art/skin/1"/>
    <div class="skin-item-footer">
        <div class="skin-item-footer-left-container">
          <p class="skin-item-name">SkinName</p>
          <div class="skin-item-cost">
              <img class="skin-item-cost-icon" src="https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/icon-rp-24.png"/>
              <p class="skin-item-cost-value">Spaceholder</p>
          </div>
        </div>
        <div class="skin-item-footer-right-container">
            <img class="skin-item-save-icon" src="https://img.icons8.com/color/32/000000/save--v1.png"/>
        </div>
    </div>
</div></code>```

Body:
set position: absolute for .skin-item-footer  and position: relative on it's parent div. Check below code

.skin-item-splashart {
    width: 100%;
    border-radius: 12px;
    position: relative;
}
.skin-item-footer-left-container {
    grid-column: 1;
    display: grid;
    grid-template-rows: repeat(2, auto);
    align-self: start;
    height: 100%;
}
.skin-item-footer-right-container {
    grid-column: 2;
    display: grid;
    align-items: center;
    justify-content: end;
    align-self: end;
    height: 100%;
}
.skin-item-default-name {
    font-size: 24px;
    font-weight: bold;
    margin-left: 3vh;
}
.skin-item-name {
    font-size: 18px;
    color: gainsboro;
    margin: 0;
    margin-left: 3vh;
    grid-row: 1;
}
.skin-item-cost {
    display: grid;
    grid-row: 2;
    grid-template-columns: repeat(2, auto);
    grid-template-rows: 1fr;
}
.skin-item-cost-value {
    color: gainsboro;
    grid-column: 1;
    margin: 0;
}
.skin-item-cost-icon {
    grid-column: 2;
    margin: 0;
}
.skin-item-save-icon {
    cursor: pointer;
    margin-right: 2vh;
}

.skin-item {
    background-color: rgb(0, 40, 75);
    margin: 15px;
    border-radius: 12px;
    height: auto;
    width: 50%;
    position: relative;
}
img{
    max-width: 100%;
}
.skin-item-footer {
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 0 0 12px 12px;
    position: absolute;
    bottom: 0;
    height: auto;
    width: 100%;
}

<div class="skin-item">
    <img class="skin-item-splashart" src="https://cdn.communitydragon.org/latest/champion/1/splash-art/skin/1"/>
    <div class="skin-item-footer">
        <div class="skin-item-footer-left-container">
          <p class="skin-item-name">SkinName</p>
          <div class="skin-item-cost">
              <img class="skin-item-cost-icon" src="https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/icon-rp-24.png"/>
              <p class="skin-item-cost-value">Spaceholder</p>
          </div>
        </div>
        <div class="skin-item-footer-right-container">
            <img class="skin-item-save-icon" src="https://img.icons8.com/color/32/000000/save--v1.png"/>
        </div>
    </div>
</div>


问:
Ignoring Android unit tests depending on SDK level
Is there an annotation or some other convenient way to ignore junit tests for specific Android SDK versions? Is there something similar to the Lint annotation TargetApi(x)? Or do I manually have to check whether to run the test using the Build.VERSION?</p>

答:
I think @mark.w's answer is the path of least resistance:

You might wanna take a look at SdkSuppress annotation. It has two methods -- maxSdkVersion and minSdkVersion which you could use depending on your need.

for example:

```<code>@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.KITKAT)
public void testMethodThatRunsConditionally() {
    System.out.print("Test me!");
}
</code>```

Body:
I think @mark.w's answer is the path of least resistance:

You might wanna take a look at SdkSuppress annotation. It has two methods -- maxSdkVersion and minSdkVersion which you could use depending on your need.

for example:

@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.KITKAT)
public void testMethodThatRunsConditionally() {
    System.out.print("Test me!");
}


问:
What does the keyword ref mean in C#?
Below is my code please explain what is ref cboListType.</p>

```<code>Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}
</code>```

答: The C# ref keyword causes a method to refer to the same variable that was passed into the method.  Any changes made to that variable are reflected in that variable when control is passed back.</p>

Title: What does the keyword ref mean in C#?

Body:
Below is my code please explain what is ref cboListType.

Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}


问:
Moodle - move QR code from profile to login page
I'm trying to move the QR code block to the main login page, i don't want to use the QR code to login, just the download app QR code generated on the profile page, i seems that the only way is via code insert but i'm not very sure how to do it because i can't find either the code or the function related to the img generation, i looked at the profile.php page on my moodle and it seems that it is created by the function:

```<code>  echo $OUTPUT->custom_block_region('content');
</code>```

but this function looks like is related to all the profile fields instead of just the QR code block, i'm trying to find some code or function related to it but no success until so i'm asking if someone knows if it is possible to put the "download app QR code" block on the login and how to do it.

答:
Mobile QR code section renderer from the component tool_mobile.

you can find the QR code image generation method on the function tool_mobile_myprofile_navigation in "YourMoodle\admin\tool\mobile\lib.PHP"

You can generate the QR code to access the mobile app using the below code.

```<code>$mobilesettings = get_config('tool_mobile');
$qrcodeimg = tool_mobile\api::generate_login_qrcode($mobilesettings);
$qrcodeforappstr = get_string('qrcodeformobileappaccess', 'tool_mobile');

echo html_writer::div(html_writer::img($qrcodeimg, $qrcodeforappstr));
</code>```

If you want to add this QR code to the login page. You can do it by rendering the login page using the theme (recommended). Or you can do it by modifying the core.

Render by theme.

In your boost theme core_renderer.php file. Please add the below function in the core_renderer class to render the login page.
you can find the core_renderer file in "Moodle\theme\boost\classes\output\core_renderer.php"

```<code>public function render_login(\core_auth\output\login $form) {
    global $CFG, $SITE;

    $context = $form->export_for_template($this);

    // Override because rendering is not supported in template yet.
    if ($CFG->rememberusername == 0) {
        $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
    } else {
        $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
    }
    $context->errorformatted = $this->error_text($context->error);
    $url = $this->get_logo_url();
    if ($url) {
        $url = $url->out(false);
    }
    $context->logourl = $url;
    $context->sitename = format_string($SITE->fullname, true,
            ['context' => \context_course::instance(SITEID), "escape" => false]);
    // QR Code to access the site URL in mobile app.
    $mobilesettings = get_config('tool_mobile');
    $qrcodeimg = \tool_mobile\api::generate_login_qrcode($mobilesettings);
    $qrcodeforappstr = get_string('qrcodeformobileappaccess', 'tool_mobile');

    $context->qrcodeimage = \html_writer::div(\html_writer::img($qrcodeimg, $qrcodeforappstr));

    return $this->render_from_template('core/loginform', $context);
}
</code>```

Then create the folder "core" in your boost theme templates folder.

Then copy the loginform.mustache file from Moodle\lib\templates\loginform.mustache to the folder "core" which is created in your boost theme templates folder.

And add the code {{{qrcodeimage}}} in the copied loginform.mustache file.

Body:
I'm trying to move the QR code block to the main login page, i don't want to use the QR code to login, just the download app QR code generated on the profile page, i seems that the only way is via code insert but i'm not very sure how to do it because i can't find either the code or the function related to the img generation, i looked at the profile.php page on my moodle and it seems that it is created by the function:

  echo $OUTPUT->custom_block_region('content');

but this function looks like is related to all the profile fields instead of just the QR code block, i'm trying to find some code or function related to it but no success until so i'm asking if someone knows if it is possible to put the "download app QR code" block on the login and how to do it.

Body:
Mobile QR code section renderer from the component tool_mobile.

you can find the QR code image generation method on the function tool_mobile_myprofile_navigation in "YourMoodle\admin\tool\mobile\lib.PHP"

You can generate the QR code to access the mobile app using the below code.

$mobilesettings = get_config('tool_mobile');
$qrcodeimg = tool_mobile\api::generate_login_qrcode($mobilesettings);
$qrcodeforappstr = get_string('qrcodeformobileappaccess', 'tool_mobile');

echo html_writer::div(html_writer::img($qrcodeimg, $qrcodeforappstr));

If you want to add this QR code to the login page. You can do it by rendering the login page using the theme (recommended). Or you can do it by modifying the core.

Render by theme.

In your boost theme core_renderer.php file. Please add the below function in the core_renderer class to render the login page.
you can find the core_renderer file in "Moodle\theme\boost\classes\output\core_renderer.php"

public function render_login(\core_auth\output\login $form) {
    global $CFG, $SITE;

    $context = $form->export_for_template($this);

    // Override because rendering is not supported in template yet.
    if ($CFG->rememberusername == 0) {
        $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
    } else {
        $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
    }
    $context->errorformatted = $this->error_text($context->error);
    $url = $this->get_logo_url();
    if ($url) {
        $url = $url->out(false);
    }
    $context->logourl = $url;
    $context->sitename = format_string($SITE->fullname, true,
            ['context' => \context_course::instance(SITEID), "escape" => false]);
    // QR Code to access the site URL in mobile app.
    $mobilesettings = get_config('tool_mobile');
    $qrcodeimg = \tool_mobile\api::generate_login_qrcode($mobilesettings);
    $qrcodeforappstr = get_string('qrcodeformobileappaccess', 'tool_mobile');

    $context->qrcodeimage = \html_writer::div(\html_writer::img($qrcodeimg, $qrcodeforappstr));

    return $this->render_from_template('core/loginform', $context);
}

Then create the folder "core" in your boost theme templates folder.

Then copy the loginform.mustache file from Moodle\lib\templates\loginform.mustache to the folder "core" which is created in your boost theme templates folder.

And add the code {{{qrcodeimage}}} in the copied loginform.mustache file.