问:
Parse only relevant parts of block via PyParsing
I am using PyParsing to parse files that look like the following:

```<code>abc_module (
   .test_test1                       ( test_test_real1              ),
   .abc_test                         ( abc_test_real                ),
   .obs_test_one                     ( obs_test_one_real            ),
   .obs_test_two                     ( obs_test_two_real            )
);

cfg_module (
   .test_test2                       ( test_test_real2              ),
   .xyz_test                         ( xyz_test_real                )
);

xyz_module (
   .test_test2                       ( test_test_real2              ),
   .xyz_test                         ( xyz_test_real                ),
   .obs_test_three                   ( obs_test_three_real          ),
   .ahc_test                         ( ahc_test_real                ),
   .obs_test_four                    ( obs_test_four_real           )
);
</code>```

I'm trying to pull out the module name of each codeblock in combination with optional lines that start with ".obs", so my desired ParseResult for this example file would be:

```<code>ParseResult = [["abc_module", ".obs_test_one", ".obs_test_two"], ["cfg_module"], ["xyz_module", ".obs_test_three", ".obs_test_four"]]
</code>```

So far I managed to parse the codeblocks, but the problem is that I am unable to pull out only .obs parts, I tried using PyParsings "skipTo" method, but I don't think that is the right tool for this.

My code so far:

```<code>keyword = Word(alphanums + '_' + ".")
sub_module_parser = keyword.setResultsName("module_name") + Suppress("(") + OneOrMore(
    keyword + Suppress("(" + keyword + ")" + Optional(","))).setResultsName("obs_param")
</code>```

答:
tl;dr - Best to not try to write a parser in one line, but step back and write up a plan first.

Often I'll write the BNF using some kind of semi-formal notation, but I'm going to try something a little different. The BNF doesn't have to be super-rigorous, as long as it spells out your thinking about the structure of the text.

This is a very clean structure, and no recursive nesting, so really lends itself to taking a few minutes and just writing down a plan for how the pyparsing code will look, before actually writing any code. It will also help you write a parser in logical groups - writing the whole parser in one line has no real benefit, and just makes it harder to understand and maintain later.

To start, look for some logical, repetitive groups in your text. For instance, your submodules look like:

```<code>(a name starting with a dot) "(" (an identifier) ")"
</code>```

Each module contains a list of these, separated by commas.

The module itself looks like this:

```<code>(an identifier) "(" (some submodules separated by commas) ")" ";"
</code>```

Thinking in structures like this helps avoid some unhelpful misstemps, such as including the delimiting commas as part of the list item.

So this is the BNF we'll work from:

```<code>module IS (an identifier) "(" (some submodules separated by commas) ")" ";"
submodule IS (a name starting with a dot) "(" (an identifier) ")"
</code>```

To translate to pyparsing, we'll need to start with the pieces, and eventually build back up to the overall module.

First the punctuation. It's useful at parse time, but just clutter afterwards, so we suppress them from the parsed results:

```<code>LPAR = Suppress("(")
RPAR = Suppress(")")
SEMI = Suppress(";")
</code>```

Next the identifiers. A common mistake when defining things like identifiers is just defining a Word with all the possible letters that could be found, such as Word(alphanums + '_'). This will match all the identifiers in your sample text, but would also match "___", "123", and "2_3_4", which I don't think you want to match. Word has a two-argument form to define the characters that are valid starting characters, and then then the valid body characters. Lets say your identifiers have to start with an alpha, and then any of the other characters - this will at least filter out integers or identifiers with no alphas:

```<code>identifier = Word(alphas, alphanums+"_")
</code>```

I'm going to be lazy and use this trick to define the submodule identifier as:

```<code>submodule_identifier = Word(".", alphanums+"_")
</code>```

See how this will work for the "name starting with a dot" for submodules.

We can now define a submodule expression:

```<code>submodule = submodule_identifier + LPAR + identifier + RPAR
</code>```

And module now is:

```<code>module = identifier + LPAR + delimited_list(submodule) + RPAR
</code>```

Is it possible to have an empty module? If so, then the list of submodules should be wrapped in an Optional.

```<code>module = identifier + LPAR + Optional(delimited_list(submodule)) + RPAR + SEMI
</code>```

That pretty much does it. Here is the full parser, with added Groups and names to help in working with the parsed results:

```<code>LPAR = Suppress("(")
RPAR = Suppress(")")
SEMI = Suppress(";")

identifier = Word(alphas, alphanums + "_").setName("identifier")
submodule_identifier = Word(".", alphanums + "_").setName("submodule_identifier")
submodule = Group(submodule_identifier("name") + LPAR + identifier("value") + RPAR).setName("submodule")
submodule_list = delimited_list(submodule).setName("submodule_list")
module = Group(identifier("name") + LPAR + Group(Optional(submodule_list))("submodules") + RPAR + SEMI).setName("module")
</code>```

Here is a diagram for this parser using the new railroad diagrams feature in pyparsing 3.

```<code>(an identifier) "(" (some submodules separated by commas) ")" ";"
</code>```0

And your parser will output this structure:

```<code>(an identifier) "(" (some submodules separated by commas) ")" ";"
</code>```1

Lastly, you wanted to only show those submodules that start with ".obs". This is best done using a parse action, added to the submodule list to filter out just the ones you want:

```<code>(an identifier) "(" (some submodules separated by commas) ")" ";"
</code>```2

After adding this filtering parse action, the results trim down to:

```<code>[['abc_module', [['.obs_test_one', 'obs_test_one_real'], ['.obs_test_two', 'obs_test_two_real']]], ...
[0]:
  ['abc_module', [['.obs_test_one', 'obs_test_one_real'], ['.obs_test_two', 'obs_test_two_real']]]
  - name: 'abc_module'
  - submodules: [['.obs_test_one', 'obs_test_one_real'], ['.obs_test_two', 'obs_test_two_real']]
    [0]:
      ['.obs_test_one', 'obs_test_one_real']
      - name: '.obs_test_one'
      - value: 'obs_test_one_real'
    [1]:
      ['.obs_test_two', 'obs_test_two_real']
      - name: '.obs_test_two'
      - value: 'obs_test_two_real'
[1]:
  ['cfg_module', []]
  - name: 'cfg_module'
  - submodules: []
[2]:
  ['xyz_module', [['.obs_test_three', 'obs_test_three_real'], ['.obs_test_four', 'obs_test_four_real']]]
  - name: 'xyz_module'
  - submodules: [['.obs_test_three', 'obs_test_three_real'], ['.obs_test_four', 'obs_test_four_real']]
    [0]:
      ['.obs_test_three', 'obs_test_three_real']
      - name: '.obs_test_three'
      - value: 'obs_test_three_real'
    [1]:
      ['.obs_test_four', 'obs_test_four_real']
      - name: '.obs_test_four'
      - value: 'obs_test_four_real'
</code>```

Exercise for the OP: with this parser, how would you add support for a submodule value that could also be an integer, which you could define as Word(nums)?

Body:
I am using PyParsing to parse files that look like the following:

abc_module (
   .test_test1                       ( test_test_real1              ),
   .abc_test                         ( abc_test_real                ),
   .obs_test_one                     ( obs_test_one_real            ),
   .obs_test_two                     ( obs_test_two_real            )
);

cfg_module (
   .test_test2                       ( test_test_real2              ),
   .xyz_test                         ( xyz_test_real                )
);

xyz_module (
   .test_test2                       ( test_test_real2              ),
   .xyz_test                         ( xyz_test_real                ),
   .obs_test_three                   ( obs_test_three_real          ),
   .ahc_test                         ( ahc_test_real                ),
   .obs_test_four                    ( obs_test_four_real           )
);

I'm trying to pull out the module name of each codeblock in combination with optional lines that start with ".obs", so my desired ParseResult for this example file would be:

ParseResult = [["abc_module", ".obs_test_one", ".obs_test_two"], ["cfg_module"], ["xyz_module", ".obs_test_three", ".obs_test_four"]]

So far I managed to parse the codeblocks, but the problem is that I am unable to pull out only .obs parts, I tried using PyParsings "skipTo" method, but I don't think that is the right tool for this.

My code so far:

keyword = Word(alphanums + '_' + ".")
sub_module_parser = keyword.setResultsName("module_name") + Suppress("(") + OneOrMore(
    keyword + Suppress("(" + keyword + ")" + Optional(","))).setResultsName("obs_param")

Body:
tl;dr - Best to not try to write a parser in one line, but step back and write up a plan first.

Often I'll write the BNF using some kind of semi-formal notation, but I'm going to try something a little different. The BNF doesn't have to be super-rigorous, as long as it spells out your thinking about the structure of the text.

This is a very clean structure, and no recursive nesting, so really lends itself to taking a few minutes and just writing down a plan for how the pyparsing code will look, before actually writing any code. It will also help you write a parser in logical groups - writing the whole parser in one line has no real benefit, and just makes it harder to understand and maintain later.

To start, look for some logical, repetitive groups in your text. For instance, your submodules look like:

(a name starting with a dot) "(" (an identifier) ")"

Each module contains a list of these, separated by commas.

The module itself looks like this:

(an identifier) "(" (some submodules separated by commas) ")" ";"

Thinking in structures like this helps avoid some unhelpful misstemps, such as including the delimiting commas as part of the list item.

So this is the BNF we'll work from:

module IS (an identifier) "(" (some submodules separated by commas) ")" ";"
submodule IS (a name starting with a dot) "(" (an identifier) ")"

To translate to pyparsing, we'll need to start with the pieces, and eventually build back up to the overall module.

First the punctuation. It's useful at parse time, but just clutter afterwards, so we suppress them from the parsed results:

LPAR = Suppress("(")
RPAR = Suppress(")")
SEMI = Suppress(";")

Next the identifiers. A common mistake when defining things like identifiers is just defining a Word with all the possible letters that could be found, such as Word(alphanums + '_'). This will match all the identifiers in your sample text, but would also match "___", "123", and "2_3_4", which I don't think you want to match. Word has a two-argument form to define the characters that are valid starting characters, and then then the valid body characters. Lets say your identifiers have to start with an alpha, and then any of the other characters - this will at least filter out integers or identifiers with no alphas:

identifier = Word(alphas, alphanums+"_")

I'm going to be lazy and use this trick to define the submodule identifier as:

submodule_identifier = Word(".", alphanums+"_")

See how this will work for the "name starting with a dot" for submodules.

We can now define a submodule expression:

submodule = submodule_identifier + LPAR + identifier + RPAR

And module now is:

module = identifier + LPAR + delimited_list(submodule) + RPAR

Is it possible to have an empty module? If so, then the list of submodules should be wrapped in an Optional.

module = identifier + LPAR + Optional(delimited_list(submodule)) + RPAR + SEMI

That pretty much does it. Here is the full parser, with added Groups and names to help in working with the parsed results:

LPAR = Suppress("(")
RPAR = Suppress(")")
SEMI = Suppress(";")

identifier = Word(alphas, alphanums + "_").setName("identifier")
submodule_identifier = Word(".", alphanums + "_").setName("submodule_identifier")
submodule = Group(submodule_identifier("name") + LPAR + identifier("value") + RPAR).setName("submodule")
submodule_list = delimited_list(submodule).setName("submodule_list")
module = Group(identifier("name") + LPAR + Group(Optional(submodule_list))("submodules") + RPAR + SEMI).setName("module")

Here is a diagram for this parser using the new railroad diagrams feature in pyparsing 3.

module.create_diagram("module_railroad_diag.html")

And your parser will output this structure:

print(module[...].parseString(sample).dump())

[['abc_module', [['.test_test1', 'test_test_real1'], ['.abc_test', 'abc_test_real'], ...
[0]:
  ['abc_module', [['.test_test1', 'test_test_real1'], ['.abc_test', 'abc_test_real'], ...
  - name: 'abc_module'
  - submodules: [['.test_test1', 'test_test_real1'], ['.abc_test', 'abc_test_real'], ...
    [0]:
      ['.test_test1', 'test_test_real1']
      - name: '.test_test1'
      - value: 'test_test_real1'
    [1]:
      ['.abc_test', 'abc_test_real']
      - name: '.abc_test'
      - value: 'abc_test_real'
    [2]:
      ['.obs_test_one', 'obs_test_one_real']
      - name: '.obs_test_one'
      - value: 'obs_test_one_real'
    [3]:
      ['.obs_test_two', 'obs_test_two_real']
      - name: '.obs_test_two'
      - value: 'obs_test_two_real'
[1]:
  ['cfg_module', [['.test_test2', 'test_test_real2'], ['.xyz_test', 'xyz_test_real']]]
  - name: 'cfg_module'
  - submodules: [['.test_test2', 'test_test_real2'], ['.xyz_test', 'xyz_test_real']]
    [0]:
      ['.test_test2', 'test_test_real2']
      - name: '.test_test2'
      - value: 'test_test_real2'
    [1]:
      ['.xyz_test', 'xyz_test_real']
      - name: '.xyz_test'
      - value: 'xyz_test_real'
[2]:
  ['xyz_module', [['.test_test2', 'test_test_real2'], ['.xyz_test', 'xyz_test_real'], ...
  - name: 'xyz_module'
  - submodules: [['.test_test2', 'test_test_real2'], ['.xyz_test', 'xyz_test_real'], ...
    [0]:
      ['.test_test2', 'test_test_real2']
      - name: '.test_test2'
      - value: 'test_test_real2'
    [1]:
      ['.xyz_test', 'xyz_test_real']
      - name: '.xyz_test'
      - value: 'xyz_test_real'
    [2]:
      ['.obs_test_three', 'obs_test_three_real']
      - name: '.obs_test_three'
      - value: 'obs_test_three_real'
    [3]:
      ['.ahc_test', 'ahc_test_real']
      - name: '.ahc_test'
      - value: 'ahc_test_real'
    [4]:
      ['.obs_test_four', 'obs_test_four_real']
      - name: '.obs_test_four'
      - value: 'obs_test_four_real'

Lastly, you wanted to only show those submodules that start with ".obs". This is best done using a parse action, added to the submodule list to filter out just the ones you want:

def obs_items_only(t):
    return ParseResults(item for item in t if item.name.startswith(".obs"))

submodule_list.addParseAction(obs_items_only)

After adding this filtering parse action, the results trim down to:

[['abc_module', [['.obs_test_one', 'obs_test_one_real'], ['.obs_test_two', 'obs_test_two_real']]], ...
[0]:
  ['abc_module', [['.obs_test_one', 'obs_test_one_real'], ['.obs_test_two', 'obs_test_two_real']]]
  - name: 'abc_module'
  - submodules: [['.obs_test_one', 'obs_test_one_real'], ['.obs_test_two', 'obs_test_two_real']]
    [0]:
      ['.obs_test_one', 'obs_test_one_real']
      - name: '.obs_test_one'
      - value: 'obs_test_one_real'
    [1]:
      ['.obs_test_two', 'obs_test_two_real']
      - name: '.obs_test_two'
      - value: 'obs_test_two_real'
[1]:
  ['cfg_module', []]
  - name: 'cfg_module'
  - submodules: []
[2]:
  ['xyz_module', [['.obs_test_three', 'obs_test_three_real'], ['.obs_test_four', 'obs_test_four_real']]]
  - name: 'xyz_module'
  - submodules: [['.obs_test_three', 'obs_test_three_real'], ['.obs_test_four', 'obs_test_four_real']]
    [0]:
      ['.obs_test_three', 'obs_test_three_real']
      - name: '.obs_test_three'
      - value: 'obs_test_three_real'
    [1]:
      ['.obs_test_four', 'obs_test_four_real']
      - name: '.obs_test_four'
      - value: 'obs_test_four_real'

Exercise for the OP: with this parser, how would you add support for a submodule value that could also be an integer, which you could define as Word(nums)?


来源: stackexchange

问:
Pydev debugger error - NameError: name 'psort' is not defined
I am getting an error message from Pydev in the Eclipse Console window when debugging Python code. The same error message repeats every time the debugger pauses:

```<code>ValueError: invalid literal for int() with base 10: "NameError: name 'psort' is not defined"
Traceback (most recent call last):
  File "C:\Users\Bill\.p2\pool\plugins\org.python.pydev.core_9.2.0.202110311311\pysrc\_pydevd_bundle\pydevd_process_net_command.py", line 63, in process_net_command
    cmd = on_command(py_db, cmd_id, seq, text)
  File "C:\Users\Bill\.p2\pool\plugins\org.python.pydev.core_9.2.0.202110311311\pysrc\_pydevd_bundle\pydevd_process_net_command.py", line 367, in _cmd_exec_or_evaluate_expression
    trim_if_too_big = int(trim) == 1
ValueError: invalid literal for int() with base 10: "NameError: name 'psort' is not defined"
</code>```

This is not a bug in my own code, and I don't know how to fix it. I can't tell if is my configuration or a Pydev bug, or what?  The debugger still works, but the console window gets filled up with those repeated messages.
I have been tolerating it for some months, thinking I just had to update Pydev, but I finally updated Pydev today(11/2021) and I still get the error messages.

I am using:

Windows 10 64bit

Eclipse IDE for C/C++, Version: 2020-12 (4.18.0), Build id: 20201210-1552

The Pydev version I updated to today:

Pydev version 9.2.0.20211031131

答:
I may have solved this, or at least a very similar looking problem. I think it was caused by some references in the Eclipse 'Expressions' view. I had let many expressions accumulate in the Expressions View. Some referenced deleted variables, out of scope variables, or variables whose definitions had changed - so expressions using them may have been buggy.

I stopped the errors by removing all of the expressions in the 'Expressions' view. I was then able to add expressions again without causing the error.

Sorry to say, I didn't identify the problem expression(s), so I didn't get to find out how they caused the problem.

ContentLicense: CC BY-SA 4.0

Body:
I am getting an error message from Pydev in the Eclipse Console window when debugging Python code. The same error message repeats every time the debugger pauses:

ValueError: invalid literal for int() with base 10: "NameError: name 'psort' is not defined"
Traceback (most recent call last):
  File "C:\Users\Bill\.p2\pool\plugins\org.python.pydev.core_9.2.0.202110311311\pysrc\_pydevd_bundle\pydevd_process_net_command.py", line 63, in process_net_command
    cmd = on_command(py_db, cmd_id, seq, text)
  File "C:\Users\Bill\.p2\pool\plugins\org.python.pydev.core_9.2.0.202110311311\pysrc\_pydevd_bundle\pydevd_process_net_command.py", line 367, in _cmd_exec_or_evaluate_expression
    trim_if_too_big = int(trim) == 1
ValueError: invalid literal for int() with base 10: "NameError: name 'psort' is not defined"

This is not a bug in my own code, and I don't know how to fix it. I can't tell if is my configuration or a Pydev bug, or what?  The debugger still works, but the console window gets filled up with those repeated messages.
I have been tolerating it for some months, thinking I just had to update Pydev, but I finally updated Pydev today(11/2021) and I still get the error messages.

I am using:

Windows 10 64bit

Eclipse IDE for C/C++, Version: 2020-12 (4.18.0), Build id: 20201210-1552

The Pydev version I updated to today:

Pydev version 9.2.0.20211031131


问:
How to transpose sumcum data in Pandas?
I have a dataset like this:

Year
City

1905
New York

1906
New York

1906
Boston

***
***

2021
Houston

I wanted to add sumcum, so I did the following:

```<code>df["Count"]=1

df['cumsum']=df.groupby(['City'])['Count'].cumsum()
</code>```

And it is working fine, although not sure if this was the best approach.

What I would like to do next is to transpose the data, but also fill all the gaps. Because occurrence of the cities is not consistent (e.g. Boston occurs in 1924 then again in 1928).

I would like to have this:

How can I make this with Pandas?

Thanks

答:
Given the following toy dataframe:

import pandas as pd

df = pd.DataFrame(
    {
        "Year": {0: 1905, 1: 1906, 2: 1906, 3: 1907, 4: 1908, 5: 1909},
        "City": {
            0: "New York",
            1: "New York",
            2: "Boston",
            3: "New York",
            4: "Boston",
            5: "New York",
        },
    }
)
```
<p>You can do it like this:</p>
<pre class="lang-py prettyprint-override"><code>new_df = (
    pd.DataFrame(df.value_counts())
    .rename(columns={0: "Count"})
    .sort_values(by=["Year", "Count"], ascending=True)
    .assign(cumsum=lambda x: x.groupby(["City"])["Count"].cumsum())
    .drop(columns="Count")
    .reset_index()
    .pipe(lambda df_: pd.pivot(df_, index="Year", columns="City"))
    .fillna(method="ffill")
    .fillna(0)
    .droplevel(0, axis=1)
    .reset_index()
    .rename_axis(None, axis=1)
)

print(new_df)
# Output
   Year  Boston  New York
0  1905     0.0       1.0
1  1906     1.0       2.0
2  1907     1.0       3.0
3  1908     2.0       3.0
4  1909     2.0       4.0
</code>```

Title: How to transpose sumcum data in Pandas?

Body:
I have a dataset like this:

Year
City

1905
New York

1906
New York

1906
Boston

***
***

2021
Houston

I wanted to add sumcum, so I did the following:

df["Count"]=1

df['cumsum']=df.groupby(['City'])['Count'].cumsum()

And it is working fine, although not sure if this was the best approach.

What I would like to do next is to transpose the data, but also fill all the gaps. Because occurrence of the cities is not consistent (e.g. Boston occurs in 1924 then again in 1928).

I would like to have this:

How can I make this with Pandas?

Thanks

Body:
Given the following toy dataframe:

import pandas as pd

df = pd.DataFrame(
    {
        "Year": {0: 1905, 1: 1906, 2: 1906, 3: 1907, 4: 1908, 5: 1909},
        "City": {
            0: "New York",
            1: "New York",
            2: "Boston",
            3: "New York",
            4: "Boston",
            5: "New York",
        },
    }
)

You can do it like this:

new_df = (
    pd.DataFrame(df.value_counts())
    .rename(columns={0: "Count"})
    .sort_values(by=["Year", "Count"], ascending=True)
    .assign(cumsum=lambda x: x.groupby(["City"])["Count"].cumsum())
    .drop(columns="Count")
    .reset_index()
    .pipe(lambda df_: pd.pivot(df_, index="Year", columns="City"))
    .fillna(method="ffill")
    .fillna(0)
    .droplevel(0, axis=1)
    .reset_index()
    .rename_axis(None, axis=1)
)

print(new_df)
# Output
   Year  Boston  New York
0  1905     0.0       1.0
1  1906     1.0       2.0
2  1907     1.0       3.0
3  1908     2.0       3.0
4  1909     2.0       4.0


问:
How to upload multiple image in laravel
I am trying to upload multiple images in a single row in a database table and access them in a show page.I have tried this tutorial:
laraveldaily.com/upload-multiple-files-laravel-5-4/
but there two different tables are made and a relation is established.

I want this to happen in a single table.

答:
html

```<code><input type="file" name="images[]" multiple>
</code>```

controller : store folder storage

```<code>foreach ($request->file('images') as $imagefile) {
   return $imagefile->store('images','public');
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to upload multiple image in laravel

Body:
html

<input type="file" name="images[]" multiple>

controller : store folder storage

foreach ($request->file('images') as $imagefile) {
   return $imagefile->store('images','public');
}


问:
Store calendar week and year in one (date) column in SQL
My table includes two columns: calendar week and year.
If I want to get the latest entries by calendar week and year, I currently perform:

SELECT * FROM table WHERE calyear = (SELECT MAX(calyear) FROM table) AND calweek = (SELECT MAX(calweek) FROM table WHERE calyear = (SELECT MAX(calyear) FROM table))

which is super long. I'd like to replace this with a combination of week and year e.g. 'calweek-calyear' column. Is there a date format for that or should I save this as a tiny text?
I want to be able to perform MAX() on it and performance shouldn't suffer singificantly.
Im open for better solutions, thanks.

答:
If you concatenate YYYYWW in a column TINYTEXT, or other text type  I think it will do what you want.
If you make sure that your week numbers are 2 digit ie 01 and not 1 you could use INT.
I would rather advise the use of a column DATE and a modified query.</p>


问:
Styling <input type="file">, cropped box-shadow and outline
I want my <input type="file" /> button to look like all my other buttons.

Now, it's easy with all browsers thanks to :

::file-selector-button (Firefox)

::-webkit-file-upload-button

::-ms-browse

This is what this input looks like in ShadowDOM :

```<code><input type="file">
  <button tabindex="-1">
  <label>No file selected</label>
</input>
</code>```

So, the button is within the input box so everything that's outsize this box is cropped (box-shadow and outline).

Do you have an idea to avoid this crop ?

I mean, I can add padding to the input but I have to calculate the border-radius spread, outline offset, correct padding with negative margins, etc.

I'm looking for something more flexible.

EDIT : overflow:visible on the input is not working. I don't know why

EDIT 2 : This is the default styling from resource://gre-ressource/forms.css (Firefox)

```<code>input[type=file] {
  white-space: nowrap !important;
  overflow: hidden !important;
  overflow-clip-box: padding-box;
  color: unset;

  /* Revert rules which apply on all inputs. */
  appearance: none;
  -moz-default-appearance: none;
  cursor: default;

  border: none;
  background-color: transparent;
  padding: unset;
}
</code>```

This explains why overflow:visible doesn't work. Also, playing with overflow-clip-box doesn't changes anything. It is set in forms.css however specifications say this property is not implemented in Firefox. Plus, there is a bug associated

EDIT 3 : Defining overflow: visible !important seems to override user agent styling, and it cancels overflow-clip-box: padding-box; as well but the overflowing content is still not visible.

Any workaround idea ?

:root {
  --base-color: purple;
  --file-border: 2px solid var(--base-color);
  --file-border-radius: 5px;
  --file-background: gold;
  --file-box-shadow: 2px 2px 3px 0 #888;
  --file-outline: 2px dadshed blue;
}

::file-selector-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}
::-webkit-file-upload-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}
::-ms-browse {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

[type=file]:focus::file-selector-button{
  outline: var(--file-outline);
  outline-offset: 2px;
}
[type=file]:focus::-webkit-file-upload-button {
  outline: var(--file-outline);
  outline-offset: 2px;
}
[type=file]:focus::-ms-browse {
  outline: var(--file-outline);
  outline-offset: 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Cropped box-shadow and outline (on focus) :
<p>
  <input type="file" />
</p>
With padding :
<p>
  <input type="file" style="padding: 5px"/>
</p>
With padding + correction :
<p>
  <input type="file" style="padding: 5px;margin-left:-5px;margin-top:-5px"/>
</p></code>```

答:
It's not possible in Chrome and Firefox.

That's because user agent stylesheets from the rendering engines of these browsers (Blink and Gecko) declare overflow: hidden !important; inside the selector input[type=file]. Unfortunately, they can't be overrided due to CSS cascading order.

The !important rule in UA stylesheets will bypass even a JS solution (I tried).

Body:
I want my <input type="file" /> button to look like all my other buttons.

Now, it's easy with all browsers thanks to :

::file-selector-button (Firefox)

::-webkit-file-upload-button

::-ms-browse

This is what this input looks like in ShadowDOM :

<input type="file">
  <button tabindex="-1">
  No file selected
</input>

So, the button is within the input box so everything that's outsize this box is cropped (box-shadow and outline).

Do you have an idea to avoid this crop ?

I mean, I can add padding to the input but I have to calculate the border-radius spread, outline offset, correct padding with negative margins, etc.

I'm looking for something more flexible.

EDIT : overflow:visible on the input is not working. I don't know why

EDIT 2 : This is the default styling from resource://gre-ressource/forms.css (Firefox)

input[type=file] {
  white-space: nowrap !important;
  overflow: hidden !important;
  overflow-clip-box: padding-box;
  color: unset;

  /* Revert rules which apply on all inputs. */
  appearance: none;
  -moz-default-appearance: none;
  cursor: default;

  border: none;
  background-color: transparent;
  padding: unset;
}

This explains why overflow:visible doesn't work. Also, playing with overflow-clip-box doesn't changes anything. It is set in forms.css however specifications say this property is not implemented in Firefox. Plus, there is a bug associated

EDIT 3 : Defining overflow: visible !important seems to override user agent styling, and it cancels overflow-clip-box: padding-box; as well but the overflowing content is still not visible.

Any workaround idea ?

:root {
  --base-color: purple;
  --file-border: 2px solid var(--base-color);
  --file-border-radius: 5px;
  --file-background: gold;
  --file-box-shadow: 2px 2px 3px 0 #888;
  --file-outline: 2px dadshed blue;
}

::file-selector-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}
::-webkit-file-upload-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}
::-ms-browse {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

[type=file]:focus::file-selector-button{
  outline: var(--file-outline);
  outline-offset: 2px;
}
[type=file]:focus::-webkit-file-upload-button {
  outline: var(--file-outline);
  outline-offset: 2px;
}
[type=file]:focus::-ms-browse {
  outline: var(--file-outline);
  outline-offset: 2px;
}

Cropped box-shadow and outline (on focus) :

  <input type="file" />

With padding :

  <input type="file" style="padding: 5px"/>

With padding + correction :

  <input type="file" style="padding: 5px;margin-left:-5px;margin-top:-5px"/>


问:
My data groups are not staying in order on my bar chart in R
I am making a bar chart with sd error bars on R but my Months (9, 10, 11, 12) won't stay in the correct order when placed on the graph. Does anybody know how to make it so they don't swap order?

```<code>library(tidyverse)
library(RColorBrewer)
d <- structure(list(Month = c("9", "9", "9", "10", "10", "10", "11", "11", "11", "12", "12", "12"), genus = c("Crustacean", "Mollusc", "Seaweed", "Crustacean", "Mollusc", "Seaweed","Crustacean", "Mollusc", "Seaweed","Crustacean", "Mollusc", "Seaweed"),
                    shannon = c(0,
                                1.1594324,
                                1.37245692,
                                0,
                                0.84868133,
                                1.54327422,
                                0.06432965,
                                1.1748941,
                                1.54612048,
                                0,
                                1.1045688,
                                1.7212854),
                    sd = c(0,
                           0.3288658,
                           0.7824814,
                           0,
                           0.8148536,
                           0.5015486,
                           0.1286593,
                           0.446148,
                           0.800392,
                           0,
                           0.1804363,
                           0.4421767)),
               row.names = c(NA, -12L), class = "data.frame")

d %>%
  ggplot(aes(x = genus, y = shannon, fill = Month)) +
  geom_col(width = 0.5,
           position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = shannon - sd, ymax = shannon + sd),
                width = 0.2,
                position = position_dodge(0.5)) +
  scale_fill_brewer(palette = "Blues") +
  theme_minimal()
</code>```

答:
Since month is of type character, the automatic order is alphabetical. You can change this using reorder():

```<code>d %>%
  ggplot(aes(x = genus, y = shannon, fill = reorder(Month, as.numeric(Month)))) +
  geom_col(width = 0.5,
           position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = shannon - sd, ymax = shannon + sd),
                width = 0.2,
                position = position_dodge(0.5)) +
  scale_fill_brewer(palette = "Blues", name = 'Month') +
  theme_minimal()
</code>```

Body:
I am making a bar chart with sd error bars on R but my Months (9, 10, 11, 12) won't stay in the correct order when placed on the graph. Does anybody know how to make it so they don't swap order?

library(tidyverse)
library(RColorBrewer)
d <- structure(list(Month = c("9", "9", "9", "10", "10", "10", "11", "11", "11", "12", "12", "12"), genus = c("Crustacean", "Mollusc", "Seaweed", "Crustacean", "Mollusc", "Seaweed","Crustacean", "Mollusc", "Seaweed","Crustacean", "Mollusc", "Seaweed"),
                    shannon = c(0,
                                1.1594324,
                                1.37245692,
                                0,
                                0.84868133,
                                1.54327422,
                                0.06432965,
                                1.1748941,
                                1.54612048,
                                0,
                                1.1045688,
                                1.7212854),
                    sd = c(0,
                           0.3288658,
                           0.7824814,
                           0,
                           0.8148536,
                           0.5015486,
                           0.1286593,
                           0.446148,
                           0.800392,
                           0,
                           0.1804363,
                           0.4421767)),
               row.names = c(NA, -12L), class = "data.frame")

d %>%
  ggplot(aes(x = genus, y = shannon, fill = Month)) +
  geom_col(width = 0.5,
           position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = shannon - sd, ymax = shannon + sd),
                width = 0.2,
                position = position_dodge(0.5)) +
  scale_fill_brewer(palette = "Blues") +
  theme_minimal()

Body:
Since month is of type character, the automatic order is alphabetical. You can change this using reorder():

d %>%
  ggplot(aes(x = genus, y = shannon, fill = reorder(Month, as.numeric(Month)))) +
  geom_col(width = 0.5,
           position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = shannon - sd, ymax = shannon + sd),
                width = 0.2,
                position = position_dodge(0.5)) +
  scale_fill_brewer(palette = "Blues", name = 'Month') +
  theme_minimal()


问:
getting this error: java.net.BindException: Address already in use: Cannot bind
Hello am building a flutter apk using vscode but I get the error below, any help on how to go about it. Did a research but am getting no solution. I have configured JAVA_HOME well in gradle setting in android studio yet gradle am still getting the same error</p>
```<code>FAILURE: Build failed with an exception.

* What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/6.5/userguide/gradle_daemon.html
Process command line: C:\Program Files\Android\Android Studio\jre\bin\java.exe --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.invoke=ALL-UNNAMED --add-opens java.prefs/java.util.prefs=ALL-UNNAMED -Xmx1536M -Dfile.encoding=windows-1252 -Duser.country=US -Duser.language=en -Duser.variant -cp C:\Users\cs\.gradle\wrapper\dists\gradle-6.5-all\2oz4ud9k3tuxjg84bbf55q0tn\gradle-6.5\lib\gradle-launcher-6.5.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 6.5
Please read the following process output to find out more:

    FAILURE: Build failed with an exception.

    * What went wrong:
    java.net.BindException: Address already in use: Cannot bind

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

    * Exception is:
    org.gradle.api.UncheckedIOException: java.net.BindException: Address already in use: Cannot bind
        at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:61)
        at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:41)
        at org.gradle.cache.internal.locklistener.FileLockCommunicator.<init>(FileLockCommunicator.java:51)
        at org.gradle.cache.internal.locklistener.DefaultFileLockContentionHandler.getCommunicator(DefaultFileLockContentionHandler.java:263)
        at org.gradle.cache.internal.locklistener.DefaultFileLockContentionHandler.reservePort(DefaultFileLockContentionHandler.java:255)
        at org.gradle.cache.internal.DefaultFileLockManager.lock(DefaultFileLockManager.java:108)
        at org.gradle.cache.internal.DefaultFileLockManager.lock(DefaultFileLockManager.java:95)
        at org.gradle.cache.internal.DefaultFileLockManager.lock(DefaultFileLockManager.java:90)
        at org.gradle.cache.internal.OnDemandFileAccess.updateFile(OnDemandFileAccess.java:51)
        at org.gradle.cache.internal.SimpleStateCache.update(SimpleStateCache.java:87)

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

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

    * Get more help at https://help.gradle.org
</code>```

答:
I disabled Mobile hotspot in my windows pc , then tried build it didn't worked for me.
then i just logged out from and logged in tried build again , its worked!</p>

Body:
Hello am building a flutter apk using vscode but I get the error below, any help on how to go about it. Did a research but am getting no solution. I have configured JAVA_HOME well in gradle setting in android studio yet gradle am still getting the same error

FAILURE: Build failed with an exception.

* What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/6.5/userguide/gradle_daemon.html
Process command line: C:\Program Files\Android\Android Studio\jre\bin\java.exe --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.invoke=ALL-UNNAMED --add-opens java.prefs/java.util.prefs=ALL-UNNAMED -Xmx1536M -Dfile.encoding=windows-1252 -Duser.country=US -Duser.language=en -Duser.variant -cp C:\Users\cs\.gradle\wrapper\dists\gradle-6.5-all\2oz4ud9k3tuxjg84bbf55q0tn\gradle-6.5\lib\gradle-launcher-6.5.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 6.5
Please read the following process output to find out more:

    FAILURE: Build failed with an exception.

    * What went wrong:
    java.net.BindException: Address already in use: Cannot bind

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

    * Exception is:
    org.gradle.api.UncheckedIOException: java.net.BindException: Address already in use: Cannot bind
        at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:61)
        at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:41)
        at org.gradle.cache.internal.locklistener.FileLockCommunicator.<init>(FileLockCommunicator.java:51)
        at org.gradle.cache.internal.locklistener.DefaultFileLockContentionHandler.getCommunicator(DefaultFileLockContentionHandler.java:263)
        at org.gradle.cache.internal.locklistener.DefaultFileLockContentionHandler.reservePort(DefaultFileLockContentionHandler.java:255)
        at org.gradle.cache.internal.DefaultFileLockManager.lock(DefaultFileLockManager.java:108)
        at org.gradle.cache.internal.DefaultFileLockManager.lock(DefaultFileLockManager.java:95)
        at org.gradle.cache.internal.DefaultFileLockManager.lock(DefaultFileLockManager.java:90)
        at org.gradle.cache.internal.OnDemandFileAccess.updateFile(OnDemandFileAccess.java:51)
        at org.gradle.cache.internal.SimpleStateCache.update(SimpleStateCache.java:87)

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

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

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


问:
Format credit card number
How to format and validate a credit card  number with spaces between each 4 digit while typing:

```<code>eg: 4464 6846 4354 3564
</code>```

I have tried:

```<code>$('.creditno').keyup(function() {
    cc = $(this).val().split("-").join("");

    cc = cc.match(new RegExp('.{1,4}$|.{1,4}', 'g')).join("-");

    $(this).val(cc);

});
</code>```

Please help

答:
This should work :</p>
```<code>const handleKeyup=(value)=>{
  //Remove whitespace
 let newValue = value.split(" ").join("")

 var format =newValue.split("").map((data, index) => {

  if ((index + 1) % 4 == 0) {
    data = data + " "
  }

  return data
})

format= format.join("")
console.log("format", format)}
</code>```

Title: Format credit card number

Body:
How to format and validate a credit card  number with spaces between each 4 digit while typing:

eg: 4464 6846 4354 3564

I have tried:

$('.creditno').keyup(function() {
    cc = $(this).val().split("-").join("");

    cc = cc.match(new RegExp('.{1,4}$|.{1,4}', 'g')).join("-");

    $(this).val(cc);

});

Please help

Body:
This should work :

const handleKeyup=(value)=>{
  //Remove whitespace
 let newValue = value.split(" ").join("")

 var format =newValue.split("").map((data, index) => {

  if ((index + 1) % 4 == 0) {
    data = data + " "
  }

  return data
})

format= format.join("")
console.log("format", format)}


问:
Converting nested loops into forEach();
Im trying to learn forEach() method but i cant find more advanced examples. So i thought about refactoring my Codewars code to learn from it. I dont know know to properly use forEach method in nested loops. Hope You can help me learn from this example :)

6 kyu - Replace With Alphabet Position
https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript

```<code>function alphabetPosition(text) {
    let textToArray = text.replace(/[^a-zA-Z]/gi,'').toUpperCase().split(''); //Eliminate anything thats not a letter
    const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    let pointsHolder = [];                            //empty array for score
    for (let i = 0; i < textToArray.length; i++){
        for  (let j = 0; j < alphabet.length; j++) {
            if (textToArray[i] == alphabet[j] ) {     //We check the index of given string letter in alphabet
                pointsHolder.push(j+1)                //give it a score based on place in alphabet(+1 for 0 as 1st index)
            }
        }
    }
    return pointsHolder.join(' ');                    //return scored array as a string with spaces
}
</code>```

答:
There is really no need to use a nested loop, which is computationally expensive. With that, you also don't have to manually create an A-Z array.

You can easily convert alphabets to any arbitrary number using String.charCodeAt(). a has a character code of 97, b has a character code of 98, and etc... to get a one-based index (a=1, b=2, ...) you jus t need to subtract 96 from the number.

```<code>function alphabetPosition(text) {
  const alphabets = text.toLowerCase().replace(/[^a-z]/g, '').split('');
  return alphabets.map(alphabet => alphabet.charCodeAt(0) - 96).join(' ');
}
</code>```

Alternatively you can also use a for...of loop, but that requires storing the array in yet another variable before returning it:

```<code>function alphabetPosition(text) {
  const alphabets = text.toLowerCase().replace(/[^a-z]/g, '');

  const codes = [];
  for (const alphabet of alphabets) {
    codes.push(alphabet.charCodeAt() - 96);
  }

  return codes.join(' ');
}
</code>```

Title: Converting nested loops into forEach();

Body:
Im trying to learn forEach() method but i cant find more advanced examples. So i thought about refactoring my Codewars code to learn from it. I dont know know to properly use forEach method in nested loops. Hope You can help me learn from this example :)

6 kyu - Replace With Alphabet Position
https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript

function alphabetPosition(text) {
    let textToArray = text.replace(/[^a-zA-Z]/gi,'').toUpperCase().split(''); //Eliminate anything thats not a letter
    const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    let pointsHolder = [];                            //empty array for score
    for (let i = 0; i < textToArray.length; i++){
        for  (let j = 0; j < alphabet.length; j++) {
            if (textToArray[i] == alphabet[j] ) {     //We check the index of given string letter in alphabet
                pointsHolder.push(j+1)                //give it a score based on place in alphabet(+1 for 0 as 1st index)
            }
        }
    }
    return pointsHolder.join(' ');                    //return scored array as a string with spaces
}

Body:
There is really no need to use a nested loop, which is computationally expensive. With that, you also don't have to manually create an A-Z array.

You can easily convert alphabets to any arbitrary number using String.charCodeAt(). a has a character code of 97, b has a character code of 98, and etc... to get a one-based index (a=1, b=2, ...) you jus t need to subtract 96 from the number.

function alphabetPosition(text) {
  const alphabets = text.toLowerCase().replace(/[^a-z]/g, '').split('');
  return alphabets.map(alphabet => alphabet.charCodeAt(0) - 96).join(' ');
}

Alternatively you can also use a for...of loop, but that requires storing the array in yet another variable before returning it:

function alphabetPosition(text) {
  const alphabets = text.toLowerCase().replace(/[^a-z]/g, '');

  const codes = [];
  for (const alphabet of alphabets) {
    codes.push(alphabet.charCodeAt() - 96);
  }

  return codes.join(' ');
}


答:
Your super long query can be simplified to:

```<code>SELECT *
FROM tablename
ORDER BY calyear DESC, calweek DESC
LIMIT 1;
</code>```

if you expect only 1 row as a result.

If there are more than 1 rows for the max calyear and calweek combination, you could use RANK() window function:

```<code>SELECT t.*
FROM (
  SELECT *, RANK() OVER (ORDER BY calyear DESC, calweek DESC) rnk
  FROM tablename
) t
WHERE t.rnk = 1;
</code>```

Also, I would advice against the use of a combination of year and week.

Keep your data as simple as possible.

For presentation purposes you could easily concatenate the 2 columns.

Title: Store calendar week and year in one (date) column in SQL

Body:
My table includes two columns: calendar week and year.
If I want to get the latest entries by calendar week and year, I currently perform:

SELECT * FROM table WHERE calyear = (SELECT MAX(calyear) FROM table) AND calweek = (SELECT MAX(calweek) FROM table WHERE calyear = (SELECT MAX(calyear) FROM table))

which is super long. I'd like to replace this with a combination of week and year e.g. 'calweek-calyear' column. Is there a date format for that or should I save this as a tiny text?
I want to be able to perform MAX() on it and performance shouldn't suffer singificantly.
Im open for better solutions, thanks.

Body:
Your super long query can be simplified to:

SELECT *
FROM tablename
ORDER BY calyear DESC, calweek DESC
LIMIT 1;

if you expect only 1 row as a result.

If there are more than 1 rows for the max calyear and calweek combination, you could use RANK() window function:

SELECT t.*
FROM (
  SELECT *, RANK() OVER (ORDER BY calyear DESC, calweek DESC) rnk
  FROM tablename
) t
WHERE t.rnk = 1;

Also, I would advice against the use of a combination of year and week.

Keep your data as simple as possible.

For presentation purposes you could easily concatenate the 2 columns.


问:
How to access external drive in melody music player / flatpak app
I am on Ubuntu 18.10 and have installed the music player Melody. I can install this flatpak and run the app, but when I want to link my music folder on my external USB drive to the library, no folders under /media are showing up.

How to make Melody have access permissions to external drives?

edit: See similar question on ask ubunt: https://askubuntu.com/questions/1086529/how-to-give-a-flatpak-app-access-to-a-directory

答: Just wanted to add, if you're using flatseal, which is a permission utility for flatpak, select you app, and just scroll down on the right pane until you find FIle System, and toggle All system files:


问:
Issues with reading tif file in Octave
I am trying to read a medical imaging data which is in .tif format using Octave . It so happens that only software from https://fiji.sc/ has the ability to read the medical images I have. A sample of the image that I am referring is this one. This image is readable in.tif format only in fiji. The image can also be converted to jpg image. Only after data points is visible to other image editing software. Now the issue is , I want to load it into octave and read it - at the moment it is not possible. The imshow() function in octave is not allowing me to visualize the given .tif file.

So, if anybody has experience in reading such file formats please let me know. Thanks.

答: imread() relies on image magic to do the conversion, some versions of which can only read TIFF in 8-bit mode (giving a warning message), but when and how this happens I do not know.</p>

Title: Issues with reading tif file in Octave


问:
Using pwntools to interact with executable just halts on receive
I have a c exectuable that I want to exploit.
The output of that file looks like this:

```<code>$ ./vuln_nostack
Enter some text:
enteringTEXT
You entered: enteringTEXT
</code>```

You enter some text, and the program spits it back.

I want to run this prorgam (and later exploit it) with python and pwntools.

So far, the functioning part of my pwntools program looks like this:

```<code>from concurrent.futures import process
from sys import stdout
from pwn import *
import time

pty = process.PTY

p = process("./vuln_nostack", stdin=pty, stdout=pty)

ss = p.recv()
p.clean()
asstring = ss.decode("utf-8")

print(asstring)
</code>```

This works fine, it gets the first line and then prints it.

What I want to do now is to send a message to the program and then get the final line.

I have tried something along these lines:

```<code>p.send(b"dong")

p.clean()

print(p.recv())
</code>```

I'm not sure whether or not the send actually ever sends anything, but as soon as I add the recv function, the prorgam just hangs and never finishes.

My guess is that the input to the executable is never given properly, and therefore it's still just waiting.

How do I actually get a message delivered to the exectuable so that it can move on and srever me the last line?

答:
You can also use p.sendline():

```<code>p.sendline("payload")
</code>```

This automatically adds a breakline after your bytes.

Moreover, to know whether your exploit is sending/receiving messages to/from the program,  you can use debug context by adding this assignment:

```<code>context.log_level = 'debug'
</code>```

Body:
I have a c exectuable that I want to exploit.
The output of that file looks like this:

$ ./vuln_nostack
Enter some text:
enteringTEXT
You entered: enteringTEXT

You enter some text, and the program spits it back.

I want to run this prorgam (and later exploit it) with python and pwntools.

So far, the functioning part of my pwntools program looks like this:

from concurrent.futures import process
from sys import stdout
from pwn import *
import time

pty = process.PTY

p = process("./vuln_nostack", stdin=pty, stdout=pty)

ss = p.recv()
p.clean()
asstring = ss.decode("utf-8")

print(asstring)

This works fine, it gets the first line and then prints it.

What I want to do now is to send a message to the program and then get the final line.

I have tried something along these lines:

p.send(b"dong")

p.clean()

print(p.recv())

I'm not sure whether or not the send actually ever sends anything, but as soon as I add the recv function, the prorgam just hangs and never finishes.

My guess is that the input to the executable is never given properly, and therefore it's still just waiting.

How do I actually get a message delivered to the exectuable so that it can move on and srever me the last line?

Body:
You can also use p.sendline():

p.sendline("payload")

This automatically adds a breakline after your bytes.

Moreover, to know whether your exploit is sending/receiving messages to/from the program,  you can use debug context by adding this assignment:

context.log_level = 'debug'


问:
constexpr of pointer to fixed address
I have code like this:

```<code>constexpr int *p = (int*)0x12345678;
</code>```

but the compiler (rightfully) says:

```<code>foo.cc:1:20: error: ‘reinterpret_cast’ from integer to pointer
    1 | constexpr int *p = (int*)0x12345678;
      |                    ^~~~~~~~~~~~~~~~
</code>```

Is there any equivalent code or way to mark this instance of a cast to be acceptable as constexpr?

Note: In the embedded / micro-controller world having memory mapped device registers is really common but because of this one can't use constexpr for any of the code involved with them.

PS: A solution requiring gcc or clang is fine. Doesn't need to be portable.

答:
This non-portable method appears to work using g++ 11 and GNU ld, even allowing the pointer to be used as a template argument. (clang++ does not allow it as a template argument.)

A pointer-type template argument must point at a named variable with external linkage, so I introduce a variable for the actual value, and get the linker rather than compiler to provide that variable's symbol name as a specific address.

```<code>#include <cstdio>

// Provide command-line argument -Wl,--defsym=p_var=0x12345678
extern volatile int p_var;
constexpr volatile int* p = &p_var;
constexpr volatile int* p2 = p+1;
constexpr volatile int* p3 = p2-1;

template <volatile int* P> void print_addr() {
    std::printf("%p\n", const_cast<void*>(static_cast<volatile void*>(P)));
}

// After linking, the code contains constant 0x1234567c and no add instruction.
volatile int* get_p2() { return p2; }

int main() {
    print_addr<p>();
    // print_addr<p2>();  ERROR: invalid template argument
    print_addr<p3>();
}
</code>```

Some of the pointer arithmetic is actually happening at link time, not compile time, but g++ apparently doesn't mind for the purposes of C++ language requirements.

Try this code on godbolt.

Title: constexpr of pointer to fixed address

Body:
I have code like this:

constexpr int *p = (int*)0x12345678;

but the compiler (rightfully) says:

foo.cc:1:20: error: ‘reinterpret_cast’ from integer to pointer
    1 | constexpr int *p = (int*)0x12345678;
      |                    ^~~~~~~~~~~~~~~~

Is there any equivalent code or way to mark this instance of a cast to be acceptable as constexpr?

Note: In the embedded / micro-controller world having memory mapped device registers is really common but because of this one can't use constexpr for any of the code involved with them.

PS: A solution requiring gcc or clang is fine. Doesn't need to be portable.

Body:
This non-portable method appears to work using g++ 11 and GNU ld, even allowing the pointer to be used as a template argument. (clang++ does not allow it as a template argument.)

A pointer-type template argument must point at a named variable with external linkage, so I introduce a variable for the actual value, and get the linker rather than compiler to provide that variable's symbol name as a specific address.

#include <cstdio>

// Provide command-line argument -Wl,--defsym=p_var=0x12345678
extern volatile int p_var;
constexpr volatile int* p = &p_var;
constexpr volatile int* p2 = p+1;
constexpr volatile int* p3 = p2-1;

template <volatile int* P> void print_addr() {
    std::printf("%p\n", const_cast<void*>(static_cast<volatile void*>(P)));
}

// After linking, the code contains constant 0x1234567c and no add instruction.
volatile int* get_p2() { return p2; }

int main() {
    print_addr<p>();
    // print_addr<p2>();  ERROR: invalid template argument
    print_addr<p3>();
}

Some of the pointer arithmetic is actually happening at link time, not compile time, but g++ apparently doesn't mind for the purposes of C++ language requirements.

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:%27%23include+%3Ccstdio%3E%0A%0A//+Note+the+linker+command-line+argument+-Wl,--defsym%3Dp_var%3D0x12345678%0Aextern+volatile+int+p_var%3B%0Aconstexpr+volatile+int*+p+%3D+%26p_var%3B%0Aconstexpr+volatile+int*+p2+%3D+p%2B1%3B%0Aconstexpr+volatile+int*+p3+%3D+p2-1%3B%0A%0Atemplate+%3Cvolatile+int*+P%3E+void+print_addr()+%7B%0A++++std::printf(%22%25p%5Cn%22,+const_cast%3Cvoid*%3E(static_cast%3Cvolatile+void*%3E(P)))%3B%0A%7D%0A%0A//+After+linking,+the+code+contains+constant+0x1234567c+and+no+add+instruction.%0Avolatile+int*+get_p2()+%7B+return+p2%3B+%7D%0A%0Aint+main()+%7B%0A++++print_addr%3Cp%3E()%3B%0A++++//+print_addr%3Cp2%3E()%3B++ERROR:+invalid+template+argument%0A++++print_addr%3Cp3%3E()%3B%0A%7D%0A%27),l:%275%27,n:%270%27,o:%27C%2B%2B+source+%231%27,t:%270%27)),k:52.66479663394111,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((g:!((h:compiler,i:(compiler:gsnapshot,filters:(b:%270%27,binary:%270%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%271%27,intel:%271%27,libraryCode:%270%27,trim:%271%27),flagsViewOpen:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,libs:!(),options:%27-std%3Dc%2B%2B20+-Wall+-Wextra+-Wl,--defsym%3Dp_var%3D0x12345678%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1,tree:%271%27),l:%275%27,n:%270%27,o:%27x86-64+gcc+(trunk)+(C%2B%2B,+Editor+%231,+Compiler+%231)%27,t:%270%27)),k:38.118348694162584,l:%274%27,m:50,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:executor,i:(argsPanelShown:%271%27,compilationPanelShown:%270%27,compiler:g112,compilerOutShown:%270%27,execArgs:%27%27,execStdin:%27%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,libs:!(),options:%27-std%3Dc%2B%2B20+-Wall+-Wextra+-Wl,--defsym%3Dp_var%3D0x12345678%27,source:1,stdinPanelShown:%270%27,tree:%271%27,wrap:%271%27),l:%275%27,n:%270%27,o:%27Executor+x86-64+gcc+11.2+(C%2B%2B,+Editor+%231)%27,t:%270%27)),header:(),l:%274%27,m:50,n:%270%27,o:%27%27,s:0,t:%270%27)),k:47.33520336605892,l:%273%27,n:%270%27,o:%27%27,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4" rel="nofollow noreferrer">Try this code on godbolt.


问:
What options are available for c++ memory debugging in OpenBSD?
I believe I have a double delete and some memory corruption happening somehow in my complex c++ application on OpenBSD.  I would like to track down the first location my object is deleted, and any points at which deallocated memory is accessed.

I would usually look into valgrind, but it is linux only.  Failing that, I would instrument my new and delete operators with some kind of tracking code, but I've been finding it difficult to determine the correct google search for this.

Is there any package for openbsd which will give me information on memory errors?  Is there any kind of standard way to redefine new and delete to detect overflows, invalid accesses, double frees?

答:
This helps a lot:

```<code>man malloc
</code>```

Debugging options can be enabled system-wide, environment-wide, or program-specific.

Body:
This helps a lot:

man malloc

Debugging options can be enabled system-wide, environment-wide, or program-specific.


问:
How to sign in with Firebase Auth using python
I'm trying to make an app and I can't figure out how to sign in to a user with the python library firebase_admin. I don't have any code as of this moment. Let me know if you can help me out.</p>

答:
The Firebase Admin SDK is designed to be used in a trusted environment, such as your development machine, a server you control, or Cloud Functions/Cloud Run. It gets its authorization from its context or from a credentials file that you provide to it, and which gives it full, administrative access to the project. Therefor it doesn't need, and doesn't have a way, to sign in as a specific user.

If your use-case requires that you sign a user in to Firebase from your Python code, you can consider calling the REST API to authenticate. But the use-case for this would typically be to then pass the ID token you receive back to a user (similar to the use-case in creating custom tokens).


问:
Trying to use a for loop to try and match user input to a premade array. Getting a warning for unreachable code and the program won't recognize match
I must get the user to enter a zip code and then the program searches a premade array to either confirm or deny their zip code.

It works fine when the zip codes don't match but it doesn't recognize it when it does.

Also, the line where I am getting the 'unreachable code' warning is in my loop controls:

```<code>for (int i = 0; i < zips.Length; i++)
</code>```

The rest of the code looks like this:

    string[] zips = { "I won't bother you with all the zip codes manually entered here" };
    System.Console.WriteLine("Enter your zip code > ";
    string userZip = System.Console.ReadLine();

    for (int i = 0; i < zips.Length; i++)
     {
        if (userZip == zips[i])
           System.Console.WriteLine("Delivery to " + userZip + " ok.");
        else
           System.Console.WriteLine("Sorry - no delivery to " + userZip);
        break;
    }
```

答:
The question is not very much clear and also not formatted well. I guss this would be the solution:</p>
```<code>public class Run {
    public static void main(String[] args) {
        String[] zips = {"11", "13", "30", "50"};
        Scanner scanner = new Scanner(System.in);
        String input = scanner.next();

        Stream<String> stream = Stream.of(zips);
        if(stream.anyMatch(x -> input.equals(x))){
            System.out.println("Delivery to " + input + " ok.");
        }else {
            System.out.println("Sorry - no delivery to " + input);
        }
    }
}
</code>```

Body:
I must get the user to enter a zip code and then the program searches a premade array to either confirm or deny their zip code.

It works fine when the zip codes don't match but it doesn't recognize it when it does.

Also, the line where I am getting the 'unreachable code' warning is in my loop controls:

for (int i = 0; i < zips.Length; i++)

The rest of the code looks like this:

    string[] zips = { "I won't bother you with all the zip codes manually entered here" };
    System.Console.WriteLine("Enter your zip code > ";
    string userZip = System.Console.ReadLine();

    for (int i = 0; i < zips.Length; i++)
     {
        if (userZip == zips[i])
           System.Console.WriteLine("Delivery to " + userZip + " ok.");
        else
           System.Console.WriteLine("Sorry - no delivery to " + userZip);
        break;
    }

Body:
The question is not very much clear and also not formatted well. I guss this would be the solution:

public class Run {
    public static void main(String[] args) {
        String[] zips = {"11", "13", "30", "50"};
        Scanner scanner = new Scanner(System.in);
        String input = scanner.next();

        Stream<String> stream = Stream.of(zips);
        if(stream.anyMatch(x -> input.equals(x))){
            System.out.println("Delivery to " + input + " ok.");
        }else {
            System.out.println("Sorry - no delivery to " + input);
        }
    }
}


答:
(Note: @Terry's solution is still the more efficient solution to your code challenge)

You can replace it in the following way:

function alphabetPosition(text) {
  let textToArray = text.replace(/[^a-zA-Z]/gi, '').toUpperCase().split('');
  const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
  let pointsHolder = [];
  textToArray.forEach(t2a => {
    alphabet.forEach((a, j) => {
      if (t2a == a) { pointsHolder.push(j + 1) }
    })
  })
  return pointsHolder.join(' ');
}

console.log(alphabetPosition("ABCSTU"))```

Title: Converting nested loops into forEach();


问:
issue iterating a python string list
Hello I'm getting an issue while I'm trying to remove every len of string in the list that is mod by 2

def remove_even_length(l):
    for i in l:
        if  len(i) %2==0:
            if i in l:
                l.remove(i)
    return l

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
print(remove_even_length(wordlist))
```

what is happening is when it goes inside the list it skips ,[is , question] which both are mod 2 I don't know why it doesn't check the len of these 2 strings.

答:
I figure it out I must remove every even element backwards.

def remove_even_length(l):
    for i in l[::-1]:
        if not (len(i) %2==1):
            l.remove(i)
    return l

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
print(remove_even_length(wordlist))

```

Title: issue iterating a python string list

Body:
Hello I'm getting an issue while I'm trying to remove every len of string in the list that is mod by 2

def remove_even_length(l):
    for i in l:
        if  len(i) %2==0:
            if i in l:
                l.remove(i)
    return l

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
print(remove_even_length(wordlist))

what is happening is when it goes inside the list it skips ,[is , question] which both are mod 2 I don't know why it doesn't check the len of these 2 strings.


问:
How can I spy on a function from setup in vuejs3?
I have a function in my component inside of setup():

export default defineComponent({
  setup() {
    const handleResume = async () => {
      msg.value = {}
      try {
      } catch (err) {
      }
    }
    return { handleResume }
  }
})
```
<p>Now in my test, I want to create a spy function like this:</p>
<pre class="lang-js prettyprint-override"><code>import App from '@/views/Frame'
jest.spyOn(App, 'handleResume')
</code>```

But I am getting this error:

```<code>Cannot spy the handleResume property because it is not a function; undefined given instead
</code>```

答:
This requires Vue 3.2.31 (released yesterday), which adds support for mocking Proxy methods, enabling spies on the wrapper.vm from @vue/test-utils.

You can expose methods (or other data) from setup() with the expose property from the context argument. For example, this component exposes handleResume only in tests:

<template>
  <button @click="handleResume">Click</button>
</template>
```
<p>If you have <code><script setup></code> instead, use the <code>defineExpose()</code> macro:</p>
<pre class="lang-html prettyprint-override"><code><!-- MyComponent.vue -->
<script setup>
const handleResume = async () => true

if (process.env.NODE_ENV === 'test') {

  defineExpose({ handleResume })
}
</script>
</code>```

Then spy on the exposed handleResume from the wrapper.vm:

// MyComponent.spec.js
import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

describe('MyComponent', () => {
  it('handles resume', async () => {
    const wrapper = shallowMount(MyComponent)

    const handleResume = jest.spyOn(wrapper.vm, 'handleResume')

    await wrapper.find('button').trigger('click')
    expect(handleResume).toHaveBeenCalled()
  })
})
```

demo

Body:
I have a function in my component inside of setup():

export default defineComponent({
  setup() {
    const handleResume = async () => {
      msg.value = {}
      try {
      } catch (err) {
      }
    }
    return { handleResume }
  }
})

Now in my test, I want to create a spy function like this:

import App from '@/views/Frame'
jest.spyOn(App, 'handleResume')

But I am getting this error:

Cannot spy the handleResume property because it is not a function; undefined given instead

Body:
This requires Vue 3.2.31 (released yesterday), which adds support for mocking Proxy methods, enabling spies on the wrapper.vm from @vue/test-utils.

You can expose methods (or other data) from setup() with the expose property from the context argument. For example, this component exposes handleResume only in tests:

<!-- MyComponent.vue -->
<script>
import { defineComponent } from 'vue'

export default defineComponent({

  setup(props, { expose }) {
    const handleResume = async () => true

    if (process.env.NODE_ENV === 'test') {

      expose({ handleResume })
    }

    return { handleResume }
  }
})
</script>

<template>
  <button @click="handleResume">Click</button>
</template>

If you have <script setup> instead, use the defineExpose() macro:

<!-- MyComponent.vue -->
<script setup>
const handleResume = async () => true

if (process.env.NODE_ENV === 'test') {

  defineExpose({ handleResume })
}
</script>

Then spy on the exposed handleResume from the wrapper.vm:

// MyComponent.spec.js
import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

describe('MyComponent', () => {
  it('handles resume', async () => {
    const wrapper = shallowMount(MyComponent)

    const handleResume = jest.spyOn(wrapper.vm, 'handleResume')

    await wrapper.find('button').trigger('click')
    expect(handleResume).toHaveBeenCalled()
  })
})

demo


问:
interact with a pc camera using c++
i intend to interact with a pc camera using c plus plus. Are there any libraries you can recommend or ways to go about ? The idea is to take shots with a Samsung wireless cam then get the images transferred unto a pc with cam and on the pc show images as per the face detection using the cam . any ideas where to start ?</p>

答:
Other options are:

1) openFrameworks.

Quoting from their website:

Openframeworks is a c++ library designed to assist the creative process by providing a simple and intuitive framework for experimentation.

The library is designed to work as a general purpose glue, and wraps together several commonly used libraries under a tidy interface: openGL for graphics, rtAudio for audio input and output, freeType for fonts,freeImage for image input and output, quicktime for video playing and sequence grabbing.

2) Qt

If you decide Qt, see this related question: Displaying WebCam video with Qt

OwnerDisplayName: joshua

Title: interact with a pc camera using c++


答:
It seems like this code might actually be written in C#, is this the language that you're targeting?  For instance, Java does not have a System.Console.WriteLine method available, however C# does:

https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline?view=net-6.0#system-console-writeline(system-char())

A question like this might be best suited for the Code Review StackExchange:

https://codereview.stackexchange.com/

EDIT

It looks like you may simply be missing a closing ) in your call to WriteLine.

<s>the break isn't necessary as it will leave the for loop after the first iteration, not allowing you to search the rest of the string[]</s> It looks like you should put the break in the body of the first if, which will require you to add {} to it

https://replit.com/@mynameishank/PrudentForthrightCodec#main.cs

```<code>class Program {
    static void Main(string[] args) {
      string[] zips = { "1", "2" };
      System.Console.WriteLine("Enter your zip code > ");
      string userZip = System.Console.ReadLine();

      for (int i = 0; i < zips.Length; i++) {
          if (userZip == zips[i]) {
             System.Console.WriteLine("Delivery to " + userZip + " ok.");
             break;
          }
          else
             System.Console.WriteLine("Sorry - no delivery to " + userZip);
      }
    }
}
</code>```

Title: Trying to use a for loop to try and match user input to a premade array. Getting a warning for unreachable code and the program won't recognize match

Body:
It seems like this code might actually be written in C#, is this the language that you're targeting?  For instance, Java does not have a System.Console.WriteLine method available, however C# does:

https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline?view=net-6.0#system-console-writeline(system-char())

A question like this might be best suited for the Code Review StackExchange:

https://codereview.stackexchange.com/

EDIT

It looks like you may simply be missing a closing ) in your call to WriteLine.

<s>the break isn't necessary as it will leave the for loop after the first iteration, not allowing you to search the rest of the string[]</s> It looks like you should put the break in the body of the first if, which will require you to add {} to it

https://replit.com/@mynameishank/PrudentForthrightCodec#main.cs

class Program {
    static void Main(string[] args) {
      string[] zips = { "1", "2" };
      System.Console.WriteLine("Enter your zip code > ");
      string userZip = System.Console.ReadLine();

      for (int i = 0; i < zips.Length; i++) {
          if (userZip == zips[i]) {
             System.Console.WriteLine("Delivery to " + userZip + " ok.");
             break;
          }
          else
             System.Console.WriteLine("Sorry - no delivery to " + userZip);
      }
    }
}


问:
Is there a code for saving your codes on Node.js
```<code>let dairy = [];

function records(events,experience) { dairy.push({events,experience});
};
</code>```

How do I save my functions , so I don’t have to write my codes after a shutdown?

答: Please see the getting started guide which directs you to write code in a text file with a .js file extension and then run it with node yourfilename.js and not to just type everything in the REPL.

Body:
let dairy = [];

function records(events,experience) { dairy.push({events,experience});
};

How do I save my functions , so I don’t have to write my codes after a shutdown?


问:
Replacing string "true" and "false" from union type to booleans
I've got one union type that is constructed from object keys, which may contain string, number, and boolean keys.

Example:

```<code>type Example = "true" | "semi" | "false";
</code>```

What I want to achieve is to get a new type, which replaces strings true or false with actual boolean values.

```<code>type Example = true | "semi" | false;
</code>```

Converting directly to boolean won't work since there might be cases where I don't have either true or false

This is what I've tried

```<code>type ReplaceTrue<T> = Extract<T, "true"> extends never ? T : Exclude<T, "true"> | true;
type ReplaceFalse<T> = Extract<T, "false"> extends never ? T : Exclude<T, "false"> | false;

type PickMyType<T> = ReplaceBoolean<T, "true", true> | ReplaceBoolean<T, "false", false>
</code>```

I've also tried combining ReplaceTrue and ReplaceFalse to a single type, but I think that this would lead to a more unreadable code.

However, I feel like these solutions are not elegant and I'm wondering if there is any other method of replacing them.

答:
Using a mapping type:</p>
```<code>type T1 = "true" | "semi" | "false";

type Mapping = { true: true; false: false };
type T2 = Mapping[T1 & keyof Mapping] | Exclude<T1, keyof Mapping>;
// T2 = boolean | "semi"
</code>```

Body:
I've got one union type that is constructed from object keys, which may contain string, number, and boolean keys.

Example:

type Example = "true" | "semi" | "false";

What I want to achieve is to get a new type, which replaces strings true or false with actual boolean values.

type Example = true | "semi" | false;

Converting directly to boolean won't work since there might be cases where I don't have either true or false

This is what I've tried

type ReplaceTrue<T> = Extract<T, "true"> extends never ? T : Exclude<T, "true"> | true;
type ReplaceFalse<T> = Extract<T, "false"> extends never ? T : Exclude<T, "false"> | false;

type PickMyType<T> = ReplaceBoolean<T, "true", true> | ReplaceBoolean<T, "false", false>

I've also tried combining ReplaceTrue and ReplaceFalse to a single type, but I think that this would lead to a more unreadable code.

However, I feel like these solutions are not elegant and I'm wondering if there is any other method of replacing them.

Body:
Using a mapping type:

type T1 = "true" | "semi" | "false";

type Mapping = { true: true; false: false };
type T2 = Mapping[T1 & keyof Mapping] | Exclude<T1, keyof Mapping>;
// T2 = boolean | "semi"


问:
Python | Find a specific line and save the two lines under it
sorry if the title confused you but what I'm looking for should be simple I think.

So basically I have a big text file that contains a list like this:

```<code>  From: United States, Chicago 2039 Street
  Name: Markus
  Code: 3294
</code>```

It has thousands of lines that contain different cities, names and codes. What I'm trying to do is find every line that contains the word "Chicago" and I want it to save the two lines under it (Name and code) in a different text file.

I have this python code that saves the line that contains a specific word:

```<code>with open("names.txt", encoding='ISO-8859-1') as f: #File that contains the names
with open("home.txt", "a", encoding='ISO-8859-1') as f1: #Second file to save the info on
    for line in f:
        if str("Chicago") in line: #If line contains Chicago
            f1.write(str(line)) #Save the line in the second file
</code>```

Thanks in advance!

答:
f is an iterable and as such we can call next() on it to get the "next" two values.

with open("names.txt", encoding='ISO-8859-1') as f: #File that contains the names
    with open("home.txt", "a", encoding='ISO-8859-1') as f1: #Second file to save the info on
        for line in f:
            if str("Chicago") in line: #If line contains Chicago
                f1.write(next(f))
                f1.write(next(f))
```
<p>Note that you might want to guard against running out of <code>f</code> via <code>next(f, None)</code> maybe.</p>
<p>If it was me, I would probably do:</p>
<pre class="lang-py prettyprint-override"><code>import contextlib
with contextlib.ExitStack() as stack:
    file_in = open('names.txt', "r", encoding="utf-8")
    file_out = open('home.txt', "w", encoding="utf-8", newline="")
    for from_line in file_in:
        name_line = next(file_in, None)
        code_line = next(file_in, None)
        if "Chicago" in from_line:
            file_out.write(name_line)
            file_out.write(code_line)
</code>```

Body:
sorry if the title confused you but what I'm looking for should be simple I think.

So basically I have a big text file that contains a list like this:

  From: United States, Chicago 2039 Street
  Name: Markus
  Code: 3294

It has thousands of lines that contain different cities, names and codes. What I'm trying to do is find every line that contains the word "Chicago" and I want it to save the two lines under it (Name and code) in a different text file.

I have this python code that saves the line that contains a specific word:

with open("names.txt", encoding='ISO-8859-1') as f: #File that contains the names
with open("home.txt", "a", encoding='ISO-8859-1') as f1: #Second file to save the info on
    for line in f:
        if str("Chicago") in line: #If line contains Chicago
            f1.write(str(line)) #Save the line in the second file

Thanks in advance!

Body:
f is an iterable and as such we can call next() on it to get the "next" two values.

with open("names.txt", encoding='ISO-8859-1') as f: #File that contains the names
    with open("home.txt", "a", encoding='ISO-8859-1') as f1: #Second file to save the info on
        for line in f:
            if str("Chicago") in line: #If line contains Chicago
                f1.write(next(f))
                f1.write(next(f))

Note that you might want to guard against running out of f via next(f, None) maybe.

If it was me, I would probably do:

import contextlib
with contextlib.ExitStack() as stack:
    file_in = open('names.txt', "r", encoding="utf-8")
    file_out = open('home.txt', "w", encoding="utf-8", newline="")
    for from_line in file_in:
        name_line = next(file_in, None)
        code_line = next(file_in, None)
        if "Chicago" in from_line:
            file_out.write(name_line)
            file_out.write(code_line)


问:
Change font size if the text exceeds the boundary of Textblock
I have a textblock with a dimension of Width=511, Height=159. FontSize=28. I want to change the font size if the text exceeds the dimension of the textblock so that all the text will be displayed. Is there a way of doing this? A formula maybe?</p>

答:
This solution implies the use of a ViewBox, i think that with Wpf transforming features there is no need to change the font size of the text, Almost the same result can be archieved using transformation (and a ViewBox in this case).

Instead of putting your TextBlock inside a ViewBox, modify it's template and put the control where the text appears inside a ViewBox, something like:

```<code><ControlTemplate TargetType="{x:Type TextBox}">
    <Microsoft_Windows_Themes:ListBoxChrome x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}" SnapsToDevicePixels="true">
        <Viewbox HorizontalAlignment="Left">
            <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        </Viewbox>
    </Microsoft_Windows_Themes:ListBoxChrome>

    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
</code>```

Now you get a control that sizes it's text to fit in the available spacee, thanks WPF.

Also here is some example

Body:
This solution implies the use of a ViewBox, i think that with Wpf transforming features there is no need to change the font size of the text, Almost the same result can be archieved using transformation (and a ViewBox in this case).

Instead of putting your TextBlock inside a ViewBox, modify it's template and put the control where the text appears inside a ViewBox, something like:

<ControlTemplate TargetType="{x:Type TextBox}">
    <Microsoft_Windows_Themes:ListBoxChrome x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}" SnapsToDevicePixels="true">
        <Viewbox HorizontalAlignment="Left">
            <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        </Viewbox>
    </Microsoft_Windows_Themes:ListBoxChrome>

    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

Now you get a control that sizes it's text to fit in the available spacee, thanks WPF.

Also here is some example


答:
This should do the trick:</p>
```<code>extraLines = 0
for line in f:
        if extraLines or str("Chicago") in line : # Chicago line + 2 more
            f1.write(str(line)) #Save the line in the second file
            extraLines = (extraLines+1)%3
</code>```

Title: Python | Find a specific line and save the two lines under it

Body:
This should do the trick:

extraLines = 0
for line in f:
        if extraLines or str("Chicago") in line : # Chicago line + 2 more
            f1.write(str(line)) #Save the line in the second file
            extraLines = (extraLines+1)%3


问:
Dagger-Hilt Did you forget to apply the Gradle Plugin? But I applied the plugin
Hello I'm trying to use the Dagger Hilt library In my project but when I'm trying to build it, it fails with this message

```<code>public final class MyApplication extends android. app.Application {
             ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See the error above for details.
</code>```

And then a java file called MyApplication.java opens with the below content:

```<code>package com.example.hilt;

import android.app.Application;
import dagger.hilt.android.HiltAndroidApp;
import kotlin.reflect.KClass;

@kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000\f\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\b\u0007\u0018\u00002\u00020\u0001B\u0005\u00a2\u0006\u0002\u0010\u0002\u00a8\u0006\u0003"}, d2 = {"Lcom/example/hilt/MyApplication;", "Landroid/app/Application;", "()V", "app_debug"})
@dagger.hilt.android.HiltAndroidApp
public final class MyApplication extends android.app.Application {

    public MyApplication() {
        super();
    }
}
</code>```

this is my project build.gradle file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.5.20"
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.37'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

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

</code>```

And this is my app module build.gradle file:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.hilt"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //Dagger - Hilt
    implementation "com.google.dagger:hilt-android:2.37"
    kapt "com.google.dagger:hilt-android-compiler:2.37"
}

kapt {
    correctErrorTypes true
}
</code>```

as you see I did everything correctly and it still gives me the error. I tested my code on another computer and it worked! I even removed android studio, Gradle, and SDK manager from my computer and reinstall them but it still gives me the error.
How can I fix it?

答:
Just change the version of this below classpath in your project level gradle to the latest version -</p>
```<code>classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:VERSION_TO_CHANGE"
</code>```

Body:
Hello I'm trying to use the Dagger Hilt library In my project but when I'm trying to build it, it fails with this message

public final class MyApplication extends android. app.Application {
             ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See the error above for details.

And then a java file called MyApplication.java opens with the below content:

package com.example.hilt;

import android.app.Application;
import dagger.hilt.android.HiltAndroidApp;
import kotlin.reflect.KClass;

@kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000\f\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\b\u0007\u0018\u00002\u00020\u0001B\u0005\u00a2\u0006\u0002\u0010\u0002\u00a8\u0006\u0003"}, d2 = {"Lcom/example/hilt/MyApplication;", "Landroid/app/Application;", "()V", "app_debug"})
@dagger.hilt.android.HiltAndroidApp
public final class MyApplication extends android.app.Application {

    public MyApplication() {
        super();
    }
}

this is my project build.gradle file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.5.20"
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.37'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

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

And this is my app module build.gradle file:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.hilt"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //Dagger - Hilt
    implementation "com.google.dagger:hilt-android:2.37"
    kapt "com.google.dagger:hilt-android-compiler:2.37"
}

kapt {
    correctErrorTypes true
}

as you see I did everything correctly and it still gives me the error. I tested my code on another computer and it worked! I even removed android studio, Gradle, and SDK manager from my computer and reinstall them but it still gives me the error.
How can I fix it?

Body:
Just change the version of this below classpath in your project level gradle to the latest version -

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:VERSION_TO_CHANGE"


答:
Try to use</p>
```<code>for i, line in enumerate(f):
        if line.find("Chicago") != -1: #If line contains Chicago
            f1.write(f[i + 1])
            f1.write(f[i + 2])
</code>```

Body:
Try to use

for i, line in enumerate(f):
        if line.find("Chicago") != -1: #If line contains Chicago
            f1.write(f[i + 1])
            f1.write(f[i + 2])