问:
unable to initialize snowflake data source
I am trying to access the snowflake datasource using "great_expectations" library.

The following is what I tried so far:

```<code>from ruamel import yaml

import great_expectations as ge
from great_expectations.core.batch import BatchRequest, RuntimeBatchRequest

context = ge.get_context()

datasource_config = {
    "name": "my_snowflake_datasource",
    "class_name": "Datasource",
    "execution_engine": {
        "class_name": "SqlAlchemyExecutionEngine",
        "connection_string": "snowflake://myusername:mypass@myaccount/myDB/myschema?warehouse=mywh&role=myadmin",
    },
    "data_connectors": {
        "default_runtime_data_connector_name": {
            "class_name": "RuntimeDataConnector",
            "batch_identifiers": ["default_identifier_name"],
        },
        "default_inferred_data_connector_name": {
            "class_name": "InferredAssetSqlDataConnector",
            "include_schema_name": True,
        },
    },
}

print(context.test_yaml_config(yaml.dump(datasource_config)))

</code>```

I initiated great_expectation before executing above code:

```<code>great_expectations init
</code>```

but I am getting the error below:

```<code>great_expectations.exceptions.exceptions.DatasourceInitializationError: Cannot initialize datasource my_snowflake_datasource, error: 'NoneType' object has no attribute 'create_engine'

</code>```

What am I doing wrong?

答:
Your configuration seems to be ok, corresponding to the example here.

If you look at the traceback you should notice that the error propagates starting at the file great_expectations/execution_engine/sqlalchemy_execution_engine.py in your virtual environment.

The actual line where the error occurs is:

```<code>            self.engine = sa.create_engine(connection_string, **kwargs)
</code>```

And if you search for that sa at the top of that file:

```<code>import sqlalchemy as sa

make_url = import_make_url()
except ImportError:
        sa = None
</code>```

So sqlalchemy is not installed, which you
don't get automatically in your environement if you install greate_expectiations. The thing to do is to
install snowflake-sqlalchemy, since you want to use sqlalchemy's snowflake
plugin (assumption based on your connection_string).

```<code>/your/virtualenv/bin/python -m pip install snowflake-sqlalchemy
</code>```

After that you should no longer get an error, it looks like test_yaml_config is waiting for the connection
to time out.

What worries me greatly is the documented use of a deprecated API of ruamel.yaml.
The function ruamel.yaml.dump is going to be removed in the near future, and you
should use the .dump() method of a ruamel.yaml.YAML() instance.

You should use the following code instead:

```<code>import sys
from ruamel.yaml import YAML

import great_expectations as ge
context = ge.get_context()

datasource_config = {
    "name": "my_snowflake_datasource",
    "class_name": "Datasource",
    "execution_engine": {
        "class_name": "SqlAlchemyExecutionEngine",
        "connection_string": "snowflake://myusername:mypass@myaccount/myDB/myschema?warehouse=mywh&role=myadmin",
    },
    "data_connectors": {
        "default_runtime_data_connector_name": {
            "class_name": "RuntimeDataConnector",
            "batch_identifiers": ["default_identifier_name"],
        },
        "default_inferred_data_connector_name": {
            "class_name": "InferredAssetSqlDataConnector",
            "include_schema_name": True,
        },
    },
}

yaml = YAML()

yaml.dump(datasource_config, sys.stdout, transform=context.test_yaml_config)
</code>```

I'll make a PR for great-excpectations to update their documentation/use of ruamel.yaml.

Body:
I am trying to access the snowflake datasource using "great_expectations" library.

The following is what I tried so far:

from ruamel import yaml

import great_expectations as ge
from great_expectations.core.batch import BatchRequest, RuntimeBatchRequest

context = ge.get_context()

datasource_config = {
    "name": "my_snowflake_datasource",
    "class_name": "Datasource",
    "execution_engine": {
        "class_name": "SqlAlchemyExecutionEngine",
        "connection_string": "snowflake://myusername:mypass@myaccount/myDB/myschema?warehouse=mywh&role=myadmin",
    },
    "data_connectors": {
        "default_runtime_data_connector_name": {
            "class_name": "RuntimeDataConnector",
            "batch_identifiers": ["default_identifier_name"],
        },
        "default_inferred_data_connector_name": {
            "class_name": "InferredAssetSqlDataConnector",
            "include_schema_name": True,
        },
    },
}

print(context.test_yaml_config(yaml.dump(datasource_config)))

I initiated great_expectation before executing above code:

great_expectations init

but I am getting the error below:

great_expectations.exceptions.exceptions.DatasourceInitializationError: Cannot initialize datasource my_snowflake_datasource, error: 'NoneType' object has no attribute 'create_engine'

What am I doing wrong?

Body:
Your configuration seems to be ok, corresponding to the example here.

If you look at the traceback you should notice that the error propagates starting at the file great_expectations/execution_engine/sqlalchemy_execution_engine.py in your virtual environment.

The actual line where the error occurs is:

            self.engine = sa.create_engine(connection_string, **kwargs)

And if you search for that sa at the top of that file:

import sqlalchemy as sa

make_url = import_make_url()
except ImportError:
        sa = None

So sqlalchemy is not installed, which you
don't get automatically in your environement if you install greate_expectiations. The thing to do is to
install snowflake-sqlalchemy, since you want to use sqlalchemy's snowflake
plugin (assumption based on your connection_string).

/your/virtualenv/bin/python -m pip install snowflake-sqlalchemy

After that you should no longer get an error, it looks like test_yaml_config is waiting for the connection
to time out.

What worries me greatly is the documented use of a deprecated API of ruamel.yaml.
The function ruamel.yaml.dump is going to be removed in the near future, and you
should use the .dump() method of a ruamel.yaml.YAML() instance.

You should use the following code instead:

import sys
from ruamel.yaml import YAML

import great_expectations as ge
context = ge.get_context()

datasource_config = {
    "name": "my_snowflake_datasource",
    "class_name": "Datasource",
    "execution_engine": {
        "class_name": "SqlAlchemyExecutionEngine",
        "connection_string": "snowflake://myusername:mypass@myaccount/myDB/myschema?warehouse=mywh&role=myadmin",
    },
    "data_connectors": {
        "default_runtime_data_connector_name": {
            "class_name": "RuntimeDataConnector",
            "batch_identifiers": ["default_identifier_name"],
        },
        "default_inferred_data_connector_name": {
            "class_name": "InferredAssetSqlDataConnector",
            "include_schema_name": True,
        },
    },
}

yaml = YAML()

yaml.dump(datasource_config, sys.stdout, transform=context.test_yaml_config)

I'll make a PR for great-excpectations to update their documentation/use of ruamel.yaml.


来源: stackexchange

问:
Why is \r not working and justs skips previous letters
the code:

```<code># Carriage return
print("123456\rabcd")
</code>```

and it's appearing in console just that

```<code>abcd
</code>```

instead of

```<code>abcd56
</code>```

答:
This is an issue with PyCharm. You can actually work around this via checking Edit Configurations -> Execution -> Emulate terminal in output console. This will run your code on python console instead of Pycharm's.

There is an issue about this in jetbrains too which mentions the solution I have suggested too.

ContentLicense: CC BY-SA 4.0

Body:
the code:

# Carriage return
print("123456\rabcd")

and it's appearing in console just that

abcd

instead of

abcd56


问:
Hover on anchor link and show icon
I'm trying to copy the CSS on those "documentation" pages of those projects such as bootstrap where when you hover on anchor link(s) it would show you a certain icon

a {
font-weight: bold;
font-size: 20px;
color: #000000;
text-decoration: none;
}

/* mouse hover link */
a:hover {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 15px 15px;
  background-repeat: no-repeat;
  background-position: 200px 50%;
  background-attachment: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some Random Header Text<br>
Some Random Header Text but Longer</code>```

I want the icon to show at the right end of the text for the both instances of anchor link when hover unto them how can I achieve it?

Here's an expected result:

答:
:root {
  --icon-size: 15px;
}

a {
  font-weight: bold;
  font-size: 20px;
  color: #000000;
  text-decoration: none;
  display: inline-flex;
  gap: 4px;
  align-items: center;
}

a::after {
  content: "";
  display: none;
  height: var(--icon-size);
  width: var(--icon-size);
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: var(--icon-size) var(--icon-size);
  background-repeat: no-repeat;
}

a:hover::after {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some Random Header Text<br>
Some Random Header Text but Longer</code>```

CSS Pseudo-elements and Pseudo-classes

You can use the CSS pseudo-elements to put an image/icon after the content. Since you want the icon to appear after the content, you can use pseudo-element ::after and put a background image after the text and give it a display from none to anything else, preferably inline-block to make it appear only on hover using CSS pseudo-class :hover.

Note: You don't really require to use the ::after pseudo-class here. You can just tack in an actual element like a span and apply all those styles to it, just that using ::after makes it look cleaner.

Title: Hover on anchor link and show icon

Body:
I'm trying to copy the CSS on those "documentation" pages of those projects such as bootstrap where when you hover on anchor link(s) it would show you a certain icon

a {
font-weight: bold;
font-size: 20px;
color: #000000;
text-decoration: none;
}

/* mouse hover link */
a:hover {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 15px 15px;
  background-repeat: no-repeat;
  background-position: 200px 50%;
  background-attachment: scroll;
}

Some Random Header Text

Some Random Header Text but Longer

I want the icon to show at the right end of the text for the both instances of anchor link when hover unto them how can I achieve it?

Here's an expected result:

Body:
:root {
  --icon-size: 15px;
}

a {
  font-weight: bold;
  font-size: 20px;
  color: #000000;
  text-decoration: none;
  display: inline-flex;
  gap: 4px;
  align-items: center;
}

a::after {
  content: "";
  display: none;
  height: var(--icon-size);
  width: var(--icon-size);
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: var(--icon-size) var(--icon-size);
  background-repeat: no-repeat;
}

a:hover::after {
  display: inline-block;
}

<a href="#">Some Random Header Text</a><br>
<a href="#">Some Random Header Text but Longer</a>

CSS Pseudo-elements and Pseudo-classes

You can use the CSS pseudo-elements to put an image/icon after the content. Since you want the icon to appear after the content, you can use pseudo-element ::after and put a background image after the text and give it a display from none to anything else, preferably inline-block to make it appear only on hover using CSS pseudo-class :hover.

Note: You don't really require to use the ::after pseudo-class here. You can just tack in an actual element like a span and apply all those styles to it, just that using ::after makes it look cleaner.


问:
How to check if a Java 8 Stream is empty?
How can I check if a Stream is empty and throw an exception if it's not, as a non-terminal operation?

Basically, I'm looking for something equivalent to the code below, but without materializing the stream in-between. In particular, the check should not occur before the stream is actually consumed by a terminal operation.

```<code>public Stream<Thing> getFilteredThings() {
    Stream<Thing> stream = getThings().stream()
                .filter(Thing::isFoo)
                .filter(Thing::isBar);
    return nonEmptyStream(stream, () -> {
        throw new RuntimeException("No foo bar things available")
    });
}

private static <T> Stream<T> nonEmptyStream(Stream<T> stream, Supplier<T> defaultValue) {
    List<T> list = stream.collect(Collectors.toList());
    if (list.isEmpty()) list.add(defaultValue.get());
    return list.stream();
}
</code>```

答:
The best simple solution I could find that does not consume the stream or convert to iterators is:

```<code>public Stream<Thing> getFilteredThings() {
    AtomicBoolean found = new AtomicBoolean(false);
    Stream<Thing> stream = getThings().stream()
        .filter(Thing::isFoo)
        .filter(Thing::isBar)
        .forEach(x -> {
             found.set(true);
             // do useful things
         })
    ;
    if (!found.get()) {
        throw new RuntimeException("No foo bar things available");
    }
}
</code>```

Feel free to suggest improvements..

ContentLicense: CC BY-SA 3.0

Body:
How can I check if a Stream is empty and throw an exception if it's not, as a non-terminal operation?

Basically, I'm looking for something equivalent to the code below, but without materializing the stream in-between. In particular, the check should not occur before the stream is actually consumed by a terminal operation.

public Stream<Thing> getFilteredThings() {
    Stream<Thing> stream = getThings().stream()
                .filter(Thing::isFoo)
                .filter(Thing::isBar);
    return nonEmptyStream(stream, () -> {
        throw new RuntimeException("No foo bar things available")
    });
}

private static <T> Stream<T> nonEmptyStream(Stream<T> stream, Supplier<T> defaultValue) {
    List<T> list = stream.collect(Collectors.toList());
    if (list.isEmpty()) list.add(defaultValue.get());
    return list.stream();
}

Body:
The best simple solution I could find that does not consume the stream or convert to iterators is:

public Stream<Thing> getFilteredThings() {
    AtomicBoolean found = new AtomicBoolean(false);
    Stream<Thing> stream = getThings().stream()
        .filter(Thing::isFoo)
        .filter(Thing::isBar)
        .forEach(x -> {
             found.set(true);
             // do useful things
         })
    ;
    if (!found.get()) {
        throw new RuntimeException("No foo bar things available");
    }
}

Feel free to suggest improvements..


问:
Fetch only Number from the value Oracle Apex
I need to fetch only number from the item how to perform that.

For Ex: P2510_PAYMENT_TOTAL =  208.00 Dr

I need to fetch only 208 from the above item how to get it

I am trying to create DA to show error if P2510_SUMMARY_OS_DR <=P2510_PAYMENT_TOTAL

My Dynamic action code

:P2510_PLSQL_ERROR_MESSAGE := NULL;

IF ROUND(:P2510_SUMMARY_OS_DR,2) <= :P2510_PAYMENT_TOTAL THEN

:P2510_PLSQL_ERROR_MESSAGE :=
'It looks like the values you''ve entered don''t match.'
||' The value of the Match value must match the value of Outstanding.'
||' Please try again.';

END IF;

But this DA is not working i am getting "PL/SQL: numeric or value error: character to number conversion error"

答:
If item value is 208.00 Dr, then you can't round it ("Dr" isn't numeric, it raises the error).

Try

```<code>if to_number(substr(:P2510_SUMMARY_OS_DR, 1, instr(:P2510_SUMMARY_OS_DR, ' ') - 1)) <=
   to_number(:P2510_PAYMENT_TOTAL)
then
   ...
</code>```

Body:
If item value is 208.00 Dr, then you can't round it ("Dr" isn't numeric, it raises the error).

Try

if to_number(substr(:P2510_SUMMARY_OS_DR, 1, instr(:P2510_SUMMARY_OS_DR, ' ') - 1)) <=
   to_number(:P2510_PAYMENT_TOTAL)
then
   ...


问:
React change only clicked button text [Looped]
When I click the button run a function called AddWait but it adds wait text to all buttons. I tried with useRef but things got messy.
Image;

I did something similar to this with jquery ;

for (let index = 0; index <= 10; index++) {
  $("#app").append(`Hello ${index}
  ===><button class=click-me>button ${index} </button>

`);
}

$(".click-me").on("click", function (event) {
  var $this = $(this);
  console.log($this.text());

  $this.text($this.text() + "hi");
  //(... rest of your JS code)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

You can check react app;

So how can I change only clicked button text?

答:
```<code>import { useState } from "react";
import "./styles.css";

export default function App() {
  const [waitText, setWaitText] = useState();
  const [arr,setArr] = useState([
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
  ]);
  const WaitThreeSeconds = (index) => {
    console.log("hi");
    let temp = [...arr];
    temp[index].waitText = "wait"
    setArr([...temp])
    // setWaitText("wait");
  };
  return (
    <div className="App">
      {arr.map((x, i) => (
        <div key={i}>
          <span>Hello {i} </span>
          <button onClick={()=>WaitThreeSeconds(i)}>
            button {i} {x.waitText}
          </button>
          <br />
          <br />
        </div>
      ))}
    </div>
  );
}

</code>```

You can check the sandbox code here .
I hope you find it helpful :)

Body:
When I click the button run a function called AddWait but it adds wait text to all buttons. I tried with useRef but things got messy.
Image;

I did something similar to this with jquery ;

for (let index = 0; index <= 10; index++) {
  $("#app").append(`Hello ${index}
  ===><button class=click-me>button ${index} </button>

`);
}

$(".click-me").on("click", function (event) {
  var $this = $(this);
  console.log($this.text());

  $this.text($this.text() + "hi");
  //(... rest of your JS code)
});

You can check react app;

So how can I change only clicked button text?

Body:
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [waitText, setWaitText] = useState();
  const [arr,setArr] = useState([
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
    {
      waitText:""
    },
  ]);
  const WaitThreeSeconds = (index) => {
    console.log("hi");
    let temp = [...arr];
    temp[index].waitText = "wait"
    setArr([...temp])
    // setWaitText("wait");
  };
  return (
    <div className="App">
      {arr.map((x, i) => (
        <div key={i}>
          <span>Hello {i} </span>
          <button onClick={()=>WaitThreeSeconds(i)}>
            button {i} {x.waitText}
          </button>
          <br />
          <br />
        </div>
      ))}
    </div>
  );
}

You can check the sandbox code here .
I hope you find it helpful :)


问:
Force scroll to a widget when its visibility is true in flutter
My app is displaying info about car mechanics near my users. I have a google maps widget I wrote, wrapped in a visibility widget. The map remains invisible until the user clicks on a button to show the map. This works fine, however the map appears at the end of the screen and sometimes users don't see that it appeared. I want to force the scrolling to go down to make sure the map is visible to the users once they click on the button.
I tried to do that using the VisibilityDetector package where I use the call back when the widget is visibly to force a scroll down, however this does not work.

Below is a simplified code I used(Sorry if it is still too long, but wanted to give you the full picture)

```<code>import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter/material.dart';
import 'package:car_of_your_dreams/Services/mySQL_setup.dart';
import 'package:car_of_your_dreams/widgets/Manufacturers.dart';
import 'package:car_of_your_dreams/widgets/CarModels.dart';
import 'package:car_of_your_dreams/Services/carModelsLists.dart';
import 'package:car_of_your_dreams/widgets/carGoodandBadThings.dart';
import 'package:car_of_your_dreams/widgets/googleMaps.dart';
import 'package:visibility_detector/visibility_detector.dart';

class ShowLocation extends StatelessWidget {
  @override

  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        backgroundColor: Colors.greenAccent,
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ElevatedButton(onPressed:(){

                    Navigator.pushNamed(context, '1');
                  },
                      style: ButtonStyle(backgroundColor:MaterialStateProperty.all<Color>(Colors.lightGreen) ),
                      child: Text("Back to Home")),
                ],
              ),
            ),
            Text('Choose a car to know its rating, mechanics and more!', style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.w700,
              fontSize: 33,
            ),),
            Expanded(child: CarDropDown())
          ],
        )
      )
    );

  }
}
class CarDropDown extends StatefulWidget {

  @override

  _CarDropDownState createState() => _CarDropDownState();
}
class _CarDropDownState extends State<CarDropDown> {
  final ScrollController _controller = ScrollController();
  Manufacturers? selectedManu;
  List<CarModel>?modelsforManu = [];
  bool isVisible = false;
  bool firstMapViz = false;
  bool secondMapViz = false;
  CarModel? selectedModel;
  var dropdownValue;
  var dropdownModel;
  var dropdownYear;
  String? agency;
  String? agencyWebSite;
  String? agencyPhone;
  String? agencyRating;
  String? maintenanceCost;
  String? carRating;
  String? firstMechanicName;
  String? firstMechanicPhone;
  String? firstMechanicLocation;
  String? secondMechanicName;
  String? secondMechanicPhone;
  String? secondMechanicLocation;
  num? latFirst;
  num? longFirst;
  num? latSecond;
  num? longSecond;
  late List<Manufacturers> cars;
  dynamic mechss;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    cars =[Manufacturers('Toyota', mToyota),Manufacturers('JEEP', mJEEP), Manufacturers('KIA', mKIA), Manufacturers('FIAT', mFIAT), Manufacturers('Hyundai', mHyundai), Manufacturers('Mercedes', mMercedes),Manufacturers('BMW', mBMW), Manufacturers('SEAT', mSEAT), Manufacturers('VolksWagen', mVolksWagen), Manufacturers('Peugeot', mPeugeot), Manufacturers('Nissan', mNissan), Manufacturers('Suzuki', mSuzuki),];
  }
  @override

  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: DropdownButton<Manufacturers>(
                value: dropdownValue,
                hint:Text('Manufacturer', style: TextStyle(fontWeight: FontWeight.w700)),
                icon: Icon(Icons.precision_manufacturing_outlined),
                style:TextStyle(color: Colors.black) ,
                onChanged: (Manufacturers? newValue) {
                  setState(() {
                    dropdownValue = newValue;
                    selectedManu = dropdownValue;
                    dropdownModel = null;
                    modelsforManu= selectedManu?.models;
                    isVisible = false;
                    mechss = null;
                  });
                },
                items: cars.map((Manufacturers item){
                  return DropdownMenuItem<Manufacturers>(
                    value: item,
                    child: Container(
                        color: Colors.greenAccent,
                        child: Text(item.name)),
                  );
                }
                ).toList()
            ),
          ),

          Padding(
            padding: const EdgeInsets.all(10.0),
            child: DropdownButton<CarModel>(
                value: dropdownModel,
                hint:Text('Model', style: TextStyle(fontWeight: FontWeight.w700)),
                icon: Icon(Icons.category),
                style:TextStyle(color: Colors.black) ,
                onChanged: (CarModel? newValue) {
                  setState(() {
                    dropdownModel = newValue;
                    isVisible = false;
                    mechss = null;
                  });
                },
                items: modelsforManu?.map((CarModel item){
                  return DropdownMenuItem<CarModel>(
                    value: item,
                    child: Container(
                        color: Colors.greenAccent,
                        child: Text(item.name)),
                  );
                }
                ).toList()
            ),
          ),
        ElevatedButton(onPressed: () async {
          var carFetchedData= await MySQL().extractCarDetails(selectedManu?.name);
          var carBest = await MySQL().extractBestWorst(selectedManu?.name, dropdownModel.name);
          print(carBest);
          if(carBest=="no data, something went wrong"){
            print("only updating agency details");
          } else {

 mechss = await MySQL().getMechanicsForMyCar(selectedManu?.name, dropdownModel.name, dropdownYear);

          setState(() {
            isVisible = true;
            agency = carFetchedData['Agency'];
            agencyWebSite = carFetchedData['Site'];
            agencyPhone = carFetchedData['Phone'];
            agencyRating = carFetchedData['Agency_Rating'];
            maintenanceCost = carBest== "no data, something went wrong"? 'no data yet': carBest['HundredK'];
            carRating = carBest== "no data, something went wrong"? 'not rated yet': carBest['Rating_all'];

            if(mechss!="no mechanics aslan") {
              firstMechanicName = mechss[0]['mechanic'];
              firstMechanicPhone = mechss[0]['phone'];
                          firstMechanicLocation = mechss[0]['location'];
                     latFirst = num.tryParse(mechss[0]['Latitude'])?.toDouble();
              longFirst = num.tryParse(mechss[0]['Longitude'])?.toDouble();
                   }
             if(mechss is List && mechss.asMap().containsKey(1)){
                secondMechanicName = mechss[1]['mechanic'];
                secondMechanicPhone = mechss[1]['phone'];
                       secondMechanicLocation = mechss[1]['location'];
                       latSecond = num.tryParse(mechss[1]['Latitude'])?.toDouble();
                longSecond = num.tryParse(mechss[1]['Longitude'])?.toDouble();
                   } else{
               secondMechanicName = "";
               secondMechanicPhone = "";
                      secondMechanicLocation = "";
                      latSecond = 0;
               longSecond = 0;
                    }
            if(mechss=="no mechanics aslan"){
              firstMechanicName = "";
              firstMechanicPhone = "";
              firstMechanicLocation ="";
                     secondMechanicName = "";
              secondMechanicPhone = "";
              secondMechanicLocation = "";
                     latFirst = 0;
              longFirst = 0;
              latSecond = 0;
              longSecond = 0;
            };

          });

        },
          child: Text('Tell me all about this car!', style: TextStyle(fontSize: 20),),
        ),

        Visibility(
          visible: isVisible,
          child: Container(
            height: MediaQuery.of(context).size.height/1.5,
            alignment: Alignment.topLeft,
            padding: EdgeInsets.fromLTRB(15, 10, 10, 10),
            child: Scrollbar(
              isAlwaysShown: true,
              child: ListView.builder(
    itemCount: 1,
itemBuilder: (BuildContext context, int index){
return Column(
  mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
RichText(text: TextSpan(text: 'Agency: ', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
    children:<TextSpan>[
      TextSpan(text: agency, style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) )),
    ])
),
  RichText(text: TextSpan(text: 'Agency web site: ', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
  children:<TextSpan>[
  TextSpan(text: agencyWebSite, style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) )),
    TextSpan(text: ' Phone: ', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),),
    TextSpan(text: agencyPhone, style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) )),
  ])),
  RichText(text: TextSpan(text: 'Agency Rating:', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
      children:<TextSpan>[
          TextSpan(text: '$agencyRating /5', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) ))
      ])
  ),

  RichText(text: TextSpan(text: 'Car Rating:', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
      children:<TextSpan>[
          TextSpan(text:'$carRating /5', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) ))
      ])
  ),

  RichText(text: TextSpan(text: 'Best Mechanics for the car:', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
  ),),

  Scrollbar(
    isAlwaysShown: true,
    child: SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: DataTable(
          columns: [
              DataColumn(label: Text(
                  'Name',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Workshop',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Phone',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Phone2',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Specialty',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Location',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Map',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),

          ],
          rows: [
              DataRow(cells: [
                DataCell(Text(' $firstMechanicName')),
                DataCell(Text('$firstMechanicWorkshop')),
                DataCell(Text('$firstMechanicPhone')),
                DataCell(Text('$firstMechanicPhone2')),
                DataCell(Text('$firstSpecialty')),
                DataCell(Text('$firstMechanicLocation')),
                DataCell(ElevatedButton( onPressed: () {
                  setState(() {
                    firstMapViz = true;
                    secondMapViz = false;

                  });

                  },
                    child:Text('location on map'))),
              ]),
              DataRow(cells: [
                DataCell(Text(' $secondMechanicName')),
                DataCell(Text('$secondMechanicWorkshop')),
                DataCell(Text('$secondMechanicPhone')),
                DataCell(Text('$secondMechanicPhone2')),
                DataCell(Text('$secondSpecialty')),
                DataCell(Text('$secondMechanicLocation')),
                DataCell(ElevatedButton( onPressed: () {
                  setState(() {
                    firstMapViz = false;
                    secondMapViz = true;
                  });
                },
                    child:Text('location on map'))),
              ]),
          ]
      ),
    ),
  ),
  VisibilityDetector (
    key: ObjectKey("map2"),
    onVisibilityChanged: (VisibilityInfo info) {
      _controller.jumpTo(_controller.position.maxScrollExtent);
    },
    child: Visibility(
      key: ObjectKey("map2"),
          visible: secondMapViz,
      child: Container(
        height: 300,
        child: GoogleMap(latSecond,longSecond,"${Random().nextInt(100)}",secondMechanicName! ),
      ),
    ),
  ),
  Visibility(
    visible: firstMapViz,
    child: Container(
      height: 300,
      child: GoogleMap(latFirst,longFirst,"${Random().nextInt(100)}", firstMechanicName!),
    ),
  ),
],
);

}
),
            ),
          ),
        )
      ],
    );
  }

}
</code>```

答:
First, You need set controller in ListView

```<code> ListView.builder(
    controller: _controller,
 )
</code>```

and use _controller.jumpTo(_controller.position.maxScrollExtent); after finish add items.

Body:
My app is displaying info about car mechanics near my users. I have a google maps widget I wrote, wrapped in a visibility widget. The map remains invisible until the user clicks on a button to show the map. This works fine, however the map appears at the end of the screen and sometimes users don't see that it appeared. I want to force the scrolling to go down to make sure the map is visible to the users once they click on the button.
I tried to do that using the VisibilityDetector package where I use the call back when the widget is visibly to force a scroll down, however this does not work.

Below is a simplified code I used(Sorry if it is still too long, but wanted to give you the full picture)

import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter/material.dart';
import 'package:car_of_your_dreams/Services/mySQL_setup.dart';
import 'package:car_of_your_dreams/widgets/Manufacturers.dart';
import 'package:car_of_your_dreams/widgets/CarModels.dart';
import 'package:car_of_your_dreams/Services/carModelsLists.dart';
import 'package:car_of_your_dreams/widgets/carGoodandBadThings.dart';
import 'package:car_of_your_dreams/widgets/googleMaps.dart';
import 'package:visibility_detector/visibility_detector.dart';

class ShowLocation extends StatelessWidget {
  @override

  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        backgroundColor: Colors.greenAccent,
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ElevatedButton(onPressed:(){

                    Navigator.pushNamed(context, '1');
                  },
                      style: ButtonStyle(backgroundColor:MaterialStateProperty.all<Color>(Colors.lightGreen) ),
                      child: Text("Back to Home")),
                ],
              ),
            ),
            Text('Choose a car to know its rating, mechanics and more!', style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.w700,
              fontSize: 33,
            ),),
            Expanded(child: CarDropDown())
          ],
        )
      )
    );

  }
}
class CarDropDown extends StatefulWidget {

  @override

  _CarDropDownState createState() => _CarDropDownState();
}
class _CarDropDownState extends State<CarDropDown> {
  final ScrollController _controller = ScrollController();
  Manufacturers? selectedManu;
  List<CarModel>?modelsforManu = [];
  bool isVisible = false;
  bool firstMapViz = false;
  bool secondMapViz = false;
  CarModel? selectedModel;
  var dropdownValue;
  var dropdownModel;
  var dropdownYear;
  String? agency;
  String? agencyWebSite;
  String? agencyPhone;
  String? agencyRating;
  String? maintenanceCost;
  String? carRating;
  String? firstMechanicName;
  String? firstMechanicPhone;
  String? firstMechanicLocation;
  String? secondMechanicName;
  String? secondMechanicPhone;
  String? secondMechanicLocation;
  num? latFirst;
  num? longFirst;
  num? latSecond;
  num? longSecond;
  late List<Manufacturers> cars;
  dynamic mechss;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    cars =[Manufacturers('Toyota', mToyota),Manufacturers('JEEP', mJEEP), Manufacturers('KIA', mKIA), Manufacturers('FIAT', mFIAT), Manufacturers('Hyundai', mHyundai), Manufacturers('Mercedes', mMercedes),Manufacturers('BMW', mBMW), Manufacturers('SEAT', mSEAT), Manufacturers('VolksWagen', mVolksWagen), Manufacturers('Peugeot', mPeugeot), Manufacturers('Nissan', mNissan), Manufacturers('Suzuki', mSuzuki),];
  }
  @override

  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: DropdownButton<Manufacturers>(
                value: dropdownValue,
                hint:Text('Manufacturer', style: TextStyle(fontWeight: FontWeight.w700)),
                icon: Icon(Icons.precision_manufacturing_outlined),
                style:TextStyle(color: Colors.black) ,
                onChanged: (Manufacturers? newValue) {
                  setState(() {
                    dropdownValue = newValue;
                    selectedManu = dropdownValue;
                    dropdownModel = null;
                    modelsforManu= selectedManu?.models;
                    isVisible = false;
                    mechss = null;
                  });
                },
                items: cars.map((Manufacturers item){
                  return DropdownMenuItem<Manufacturers>(
                    value: item,
                    child: Container(
                        color: Colors.greenAccent,
                        child: Text(item.name)),
                  );
                }
                ).toList()
            ),
          ),

          Padding(
            padding: const EdgeInsets.all(10.0),
            child: DropdownButton<CarModel>(
                value: dropdownModel,
                hint:Text('Model', style: TextStyle(fontWeight: FontWeight.w700)),
                icon: Icon(Icons.category),
                style:TextStyle(color: Colors.black) ,
                onChanged: (CarModel? newValue) {
                  setState(() {
                    dropdownModel = newValue;
                    isVisible = false;
                    mechss = null;
                  });
                },
                items: modelsforManu?.map((CarModel item){
                  return DropdownMenuItem<CarModel>(
                    value: item,
                    child: Container(
                        color: Colors.greenAccent,
                        child: Text(item.name)),
                  );
                }
                ).toList()
            ),
          ),
        ElevatedButton(onPressed: () async {
          var carFetchedData= await MySQL().extractCarDetails(selectedManu?.name);
          var carBest = await MySQL().extractBestWorst(selectedManu?.name, dropdownModel.name);
          print(carBest);
          if(carBest=="no data, something went wrong"){
            print("only updating agency details");
          } else {

 mechss = await MySQL().getMechanicsForMyCar(selectedManu?.name, dropdownModel.name, dropdownYear);

          setState(() {
            isVisible = true;
            agency = carFetchedData['Agency'];
            agencyWebSite = carFetchedData['Site'];
            agencyPhone = carFetchedData['Phone'];
            agencyRating = carFetchedData['Agency_Rating'];
            maintenanceCost = carBest== "no data, something went wrong"? 'no data yet': carBest['HundredK'];
            carRating = carBest== "no data, something went wrong"? 'not rated yet': carBest['Rating_all'];

            if(mechss!="no mechanics aslan") {
              firstMechanicName = mechss[0]['mechanic'];
              firstMechanicPhone = mechss[0]['phone'];
                          firstMechanicLocation = mechss[0]['location'];
                     latFirst = num.tryParse(mechss[0]['Latitude'])?.toDouble();
              longFirst = num.tryParse(mechss[0]['Longitude'])?.toDouble();
                   }
             if(mechss is List && mechss.asMap().containsKey(1)){
                secondMechanicName = mechss[1]['mechanic'];
                secondMechanicPhone = mechss[1]['phone'];
                       secondMechanicLocation = mechss[1]['location'];
                       latSecond = num.tryParse(mechss[1]['Latitude'])?.toDouble();
                longSecond = num.tryParse(mechss[1]['Longitude'])?.toDouble();
                   } else{
               secondMechanicName = "";
               secondMechanicPhone = "";
                      secondMechanicLocation = "";
                      latSecond = 0;
               longSecond = 0;
                    }
            if(mechss=="no mechanics aslan"){
              firstMechanicName = "";
              firstMechanicPhone = "";
              firstMechanicLocation ="";
                     secondMechanicName = "";
              secondMechanicPhone = "";
              secondMechanicLocation = "";
                     latFirst = 0;
              longFirst = 0;
              latSecond = 0;
              longSecond = 0;
            };

          });

        },
          child: Text('Tell me all about this car!', style: TextStyle(fontSize: 20),),
        ),

        Visibility(
          visible: isVisible,
          child: Container(
            height: MediaQuery.of(context).size.height/1.5,
            alignment: Alignment.topLeft,
            padding: EdgeInsets.fromLTRB(15, 10, 10, 10),
            child: Scrollbar(
              isAlwaysShown: true,
              child: ListView.builder(
    itemCount: 1,
itemBuilder: (BuildContext context, int index){
return Column(
  mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
RichText(text: TextSpan(text: 'Agency: ', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
    children:<TextSpan>[
      TextSpan(text: agency, style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) )),
    ])
),
  RichText(text: TextSpan(text: 'Agency web site: ', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
  children:<TextSpan>[
  TextSpan(text: agencyWebSite, style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) )),
    TextSpan(text: ' Phone: ', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),),
    TextSpan(text: agencyPhone, style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) )),
  ])),
  RichText(text: TextSpan(text: 'Agency Rating:', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
      children:<TextSpan>[
          TextSpan(text: '$agencyRating /5', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) ))
      ])
  ),

  RichText(text: TextSpan(text: 'Car Rating:', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
      children:<TextSpan>[
          TextSpan(text:'$carRating /5', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.purple, fontWeight:FontWeight.w500 ) ))
      ])
  ),

  RichText(text: TextSpan(text: 'Best Mechanics for the car:', style: GoogleFonts.lato(textStyle:TextStyle(fontSize: 30, color: Colors.white, fontWeight:FontWeight.w500 ) ),
  ),),

  Scrollbar(
    isAlwaysShown: true,
    child: SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: DataTable(
          columns: [
              DataColumn(label: Text(
                  'Name',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Workshop',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Phone',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Phone2',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Specialty',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Location',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),
              DataColumn(label: Text(
                  'Map',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
              )),

          ],
          rows: [
              DataRow(cells: [
                DataCell(Text(' $firstMechanicName')),
                DataCell(Text('$firstMechanicWorkshop')),
                DataCell(Text('$firstMechanicPhone')),
                DataCell(Text('$firstMechanicPhone2')),
                DataCell(Text('$firstSpecialty')),
                DataCell(Text('$firstMechanicLocation')),
                DataCell(ElevatedButton( onPressed: () {
                  setState(() {
                    firstMapViz = true;
                    secondMapViz = false;

                  });

                  },
                    child:Text('location on map'))),
              ]),
              DataRow(cells: [
                DataCell(Text(' $secondMechanicName')),
                DataCell(Text('$secondMechanicWorkshop')),
                DataCell(Text('$secondMechanicPhone')),
                DataCell(Text('$secondMechanicPhone2')),
                DataCell(Text('$secondSpecialty')),
                DataCell(Text('$secondMechanicLocation')),
                DataCell(ElevatedButton( onPressed: () {
                  setState(() {
                    firstMapViz = false;
                    secondMapViz = true;
                  });
                },
                    child:Text('location on map'))),
              ]),
          ]
      ),
    ),
  ),
  VisibilityDetector (
    key: ObjectKey("map2"),
    onVisibilityChanged: (VisibilityInfo info) {
      _controller.jumpTo(_controller.position.maxScrollExtent);
    },
    child: Visibility(
      key: ObjectKey("map2"),
          visible: secondMapViz,
      child: Container(
        height: 300,
        child: GoogleMap(latSecond,longSecond,"${Random().nextInt(100)}",secondMechanicName! ),
      ),
    ),
  ),
  Visibility(
    visible: firstMapViz,
    child: Container(
      height: 300,
      child: GoogleMap(latFirst,longFirst,"${Random().nextInt(100)}", firstMechanicName!),
    ),
  ),
],
);

}
),
            ),
          ),
        )
      ],
    );
  }

}

Body:
First, You need set controller in ListView

 ListView.builder(
    controller: _controller,
 )

and use _controller.jumpTo(_controller.position.maxScrollExtent); after finish add items.


问:
Unison command not found
Recently my Unison application has stopped working on my Mac terminal saying the command cannot be found. Not sure if this was the reason but I recently reinstalled brew (which is how it was installed), which may have broken it.

Here is the error output:

```<code>mac:~ Imran$ unison sites
-bash: unison: command not found
</code>```

I can see that if I locate unison unison is found in the following directories:

```<code>> /Users/Imran/unison.log /Users/Imran/unison.tar.gz
> /usr/local/Cellar/unison /usr/local/Cellar/unison/2.40.102
> /usr/local/Cellar/unison/2.40.102/COPYING
> /usr/local/Cellar/unison/2.40.102/INSTALL_RECEIPT.json
> /usr/local/Cellar/unison/2.40.102/NEWS
> /usr/local/Cellar/unison/2.40.102/README
> /usr/local/Cellar/unison/2.40.102/TODO.txt
> /usr/local/Cellar/unison/2.40.102/bin
> /usr/local/Cellar/unison/2.40.102/bin/unison
> /usr/local/Library/Formula/unison.rb
> /usr/local/Library/LinkedKegs/unison /usr/local/bin/unison
> /usr/local/opt/unison /usr/share/zsh/5.3/functions/_unison
</code>```

Can someone help me get this working again? I suspect its something to do with the link to the app being broken.

答:
I had the same issue when trying to use Unison from Windows to Mac (where it has been installed with Brew).

You can give an explicit path for the unison executable on the server by using the command-line option

-servercmd /full/path/name/of/unison

or adding

servercmd=/full/path/name/of/unison

to your profile

Source

Title: Unison command not found

Body:
Recently my Unison application has stopped working on my Mac terminal saying the command cannot be found. Not sure if this was the reason but I recently reinstalled brew (which is how it was installed), which may have broken it.

Here is the error output:

mac:~ Imran$ unison sites
-bash: unison: command not found

I can see that if I locate unison unison is found in the following directories:

> /Users/Imran/unison.log /Users/Imran/unison.tar.gz
> /usr/local/Cellar/unison /usr/local/Cellar/unison/2.40.102
> /usr/local/Cellar/unison/2.40.102/COPYING
> /usr/local/Cellar/unison/2.40.102/INSTALL_RECEIPT.json
> /usr/local/Cellar/unison/2.40.102/NEWS
> /usr/local/Cellar/unison/2.40.102/README
> /usr/local/Cellar/unison/2.40.102/TODO.txt
> /usr/local/Cellar/unison/2.40.102/bin
> /usr/local/Cellar/unison/2.40.102/bin/unison
> /usr/local/Library/Formula/unison.rb
> /usr/local/Library/LinkedKegs/unison /usr/local/bin/unison
> /usr/local/opt/unison /usr/share/zsh/5.3/functions/_unison

Can someone help me get this working again? I suspect its something to do with the link to the app being broken.


问:
How to find the *smallest* number in the list that is close to a given number in Python?
I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.

Foe e.x.

```<code>my_list=[1,10,15,20,45,56]
my_no=9
</code>```

Output should be equal to 1
Explanation: since 9 comes between 1 and 10 and I want the smaller number, i.e. 1.

Similarly if my_no=3, output is equal to 1

I am new to python, so any help will be much appreciated. Thanks!

答:
If you want to stick to basics and want to approach it using for loop and if statement then it can be achieved as follows:

my_list=[1,10,15,20,45,56]
given_number = 9

output=my_list[0]
for x in my_list:
  if(x < given_number and x > output):
    output= x

print(output)

# Output
1
```

Body:
I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.

Foe e.x.

my_list=[1,10,15,20,45,56]
my_no=9

Output should be equal to 1
Explanation: since 9 comes between 1 and 10 and I want the smaller number, i.e. 1.

Similarly if my_no=3, output is equal to 1

I am new to python, so any help will be much appreciated. Thanks!


问:
Why this import is not working
I'm using a the normalize function to get the absolute path from a String,

```<code>org.apache.commons.io.FilenameUtils.normalize(String)
</code>```

But when I use just normalize(String) I get :

The method normalize(String) is undefined for the type MyClass

I tried : import org.apache.commons.io.FilenameUtils;

I downloaded the library from Apache website, and linked it to my project but I get the same error.

I don't want to write everytime the whole line to call the function.

Is there any solution for this ?

Thanks

答:
Looks like a static method. You need to keep the import there and then call:</p>

```<code>FilenameUtils.normalize(String);
</code>```

Title: Why this import is not working

Body:
I'm using a the normalize function to get the absolute path from a String,

org.apache.commons.io.FilenameUtils.normalize(String)

But when I use just normalize(String) I get :

The method normalize(String) is undefined for the type MyClass

I tried : import org.apache.commons.io.FilenameUtils;

I downloaded the library from Apache website, and linked it to my project but I get the same error.

I don't want to write everytime the whole line to call the function.

Is there any solution for this ?

Thanks

Body:
Looks like a static method. You need to keep the import there and then call:

FilenameUtils.normalize(String);


问:
Groupby and map lodash keep existing fields
I have following data

```<code>[
  {
    "supplier_invoice_number": "DTR/12341",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 10025,
    "net_qty": 8,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
  },
  {
    "supplier_invoice_number": "DTR/119",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 12500,
    "net_qty": 9,
    "client_payment_req_id": 3,
    "clientidsupplier": 2,
    "markuptype": 1,
    "buyerclientid": 353,
    "markupvalue": 25
  }
]
</code>```

I am using lodash group by and map to get data like this

```<code>{
buyer_price: 22525
client_payment_req_id: undefined
contract_id: "789"
net_qty: 17
}
</code>```

const Data = [{
    "supplier_invoice_number": "DTR/12341",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 10025,
    "net_qty": 8,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
  },
  {
    "supplier_invoice_number": "DTR/119",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 12500,
    "net_qty": 9,
    "client_payment_req_id": 3,
    "clientidsupplier": 2,
    "markuptype": 1,
    "buyerclientid": 353,
    "markupvalue": 25
  }
]
const finalData = _(Data)
  .groupBy('contract_id')
  .map((buyer_price, id) => ({
    client_payment_req_id: buyer_price['client_payment_req_id'],
    contract_id: id,
    buyer_price: _.sumBy(buyer_price, 'buyer_price'),
    net_qty: _.sumBy(buyer_price, 'net_qty'),

  }))
  .value()

console.log(finalData)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script></code>```

But I want all the remaining fields there as well

"client_payment_req_id": 3,
"clientidsupplier": 1,
"markuptype": 2,
"buyerclientid": 353,
"markupvalue": 25

In the final data I want to have remaining fields as well ,but I am not able to include them ,Please help me out here .Thanks

So the final data would look like

```<code>{
    buyer_price: 22525
    client_payment_req_id: undefined
    contract_id: "789"
    net_qty: 17,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
    }
</code>```

P.s -Assuming All the rest fields would be same in all records

答:
You can try something like below ,your buyer_price is actually an array ,you can keep the first value like i have show below.

const Data = [{
  "supplier_invoice_number": "DTR/12341",
  "contract_id": 789,
  "net_amount": 10000,
  "buyer_price": 10025,
  "net_qty": 8,
  "client_payment_req_id": 3,
  "clientidsupplier": 1,
  "markuptype": 2,
  "buyerclientid": 353,
  "markupvalue": 25
}, {
  "supplier_invoice_number": "DTR/119",
  "contract_id": 789,
  "net_amount": 10000,
  "buyer_price": 12500,
  "net_qty": 9,
  "client_payment_req_id": 3,
  "clientidsupplier": 2,
  "markuptype": 1,
  "buyerclientid": 353,
  "markupvalue": 25
}]
const finalData = _(Data).groupBy('contract_id').map((buyer_price, id) => ({
  client_payment_req_id: buyer_price[0]['client_payment_req_id'],
  buyerclientid: buyer_price[0]['buyerclientid'],
  contract_id: id,
  buyer_price: _.sumBy(buyer_price, 'buyer_price'),
  net_qty: _.sumBy(buyer_price, 'net_qty'),
})).value()

console.log(finalData)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script></code>```

Body:
I have following data

[
  {
    "supplier_invoice_number": "DTR/12341",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 10025,
    "net_qty": 8,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
  },
  {
    "supplier_invoice_number": "DTR/119",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 12500,
    "net_qty": 9,
    "client_payment_req_id": 3,
    "clientidsupplier": 2,
    "markuptype": 1,
    "buyerclientid": 353,
    "markupvalue": 25
  }
]

I am using lodash group by and map to get data like this

{
buyer_price: 22525
client_payment_req_id: undefined
contract_id: "789"
net_qty: 17
}

const Data = [{
    "supplier_invoice_number": "DTR/12341",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 10025,
    "net_qty": 8,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
  },
  {
    "supplier_invoice_number": "DTR/119",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 12500,
    "net_qty": 9,
    "client_payment_req_id": 3,
    "clientidsupplier": 2,
    "markuptype": 1,
    "buyerclientid": 353,
    "markupvalue": 25
  }
]
const finalData = _(Data)
  .groupBy('contract_id')
  .map((buyer_price, id) => ({
    client_payment_req_id: buyer_price['client_payment_req_id'],
    contract_id: id,
    buyer_price: _.sumBy(buyer_price, 'buyer_price'),
    net_qty: _.sumBy(buyer_price, 'net_qty'),

  }))
  .value()

console.log(finalData)

But I want all the remaining fields there as well

"client_payment_req_id": 3,
"clientidsupplier": 1,
"markuptype": 2,
"buyerclientid": 353,
"markupvalue": 25

In the final data I want to have remaining fields as well ,but I am not able to include them ,Please help me out here .Thanks

So the final data would look like

{
    buyer_price: 22525
    client_payment_req_id: undefined
    contract_id: "789"
    net_qty: 17,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
    }

P.s -Assuming All the rest fields would be same in all records

Body:
You can try something like below ,your buyer_price is actually an array ,you can keep the first value like i have show below.

const Data = [{
  "supplier_invoice_number": "DTR/12341",
  "contract_id": 789,
  "net_amount": 10000,
  "buyer_price": 10025,
  "net_qty": 8,
  "client_payment_req_id": 3,
  "clientidsupplier": 1,
  "markuptype": 2,
  "buyerclientid": 353,
  "markupvalue": 25
}, {
  "supplier_invoice_number": "DTR/119",
  "contract_id": 789,
  "net_amount": 10000,
  "buyer_price": 12500,
  "net_qty": 9,
  "client_payment_req_id": 3,
  "clientidsupplier": 2,
  "markuptype": 1,
  "buyerclientid": 353,
  "markupvalue": 25
}]
const finalData = _(Data).groupBy('contract_id').map((buyer_price, id) => ({
  client_payment_req_id: buyer_price[0]['client_payment_req_id'],
  buyerclientid: buyer_price[0]['buyerclientid'],
  contract_id: id,
  buyer_price: _.sumBy(buyer_price, 'buyer_price'),
  net_qty: _.sumBy(buyer_price, 'net_qty'),
})).value()

console.log(finalData)

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>


问:
How can I set/provide a default value while django migration?
Scenario:

 I have a model, Customer

```<code>class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.CharField(max_length=100)
</code>```

and now I updated the company attribute witha ForeignKey relationship as below,

```<code>class Company(models.Model):
    name = models.CharField(max_length=100)
    location = models.CharField(max_length=100)

class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.ForeignKey(Company)
</code>```

What I need is, when the new migrations applied to the DB,corresponding Company instance must automatically generate and map to the company attribute of Customer instance.

Is that possible? How can I achieve this ?

答:
Something to note is if you are going through a cycle of renaming/ deprecating fields, using RunPython would leave you pointing to old model fields that wouldn't exist anymore after you are done with your field changes.

To avoid this, you might want to go with RunSQL instead.

```<code># Generated by Django 3.2.3 on 2022-02-09 04:55

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ("<your_app>", "<0006_migration_name>"),
    ]

    operations = [
        migrations.RunSQL(f"""
update public.<table_name> set new_field = old_field + some_magic;
"""
        ),
    ]

</code>```

Docs.

Body:
Scenario:

 I have a model, Customer

class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.CharField(max_length=100)

and now I updated the company attribute witha ForeignKey relationship as below,

class Company(models.Model):
    name = models.CharField(max_length=100)
    location = models.CharField(max_length=100)

class Customer(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    company = models.ForeignKey(Company)

What I need is, when the new migrations applied to the DB,corresponding Company instance must automatically generate and map to the company attribute of Customer instance.

Is that possible? How can I achieve this ?

Body:
Something to note is if you are going through a cycle of renaming/ deprecating fields, using RunPython would leave you pointing to old model fields that wouldn't exist anymore after you are done with your field changes.

To avoid this, you might want to go with RunSQL instead.

# Generated by Django 3.2.3 on 2022-02-09 04:55

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ("<your_app>", "<0006_migration_name>"),
    ]

    operations = [
        migrations.RunSQL(f"""
update public.<table_name> set new_field = old_field + some_magic;
"""
        ),
    ]

Docs.


问:
GCC - Truncation due to type conversion warning
Why is the compiler not throwing a value truncation due to the conversion from a uint32 to a uint8 variable type? Precisely the line result = reg_value;

```<code>void read_byte_register(uint32_t u32_address_rd_byte_reg,
        uint8_t *pu8_Data_rd_byte_reg)
{
    uint8_t result;
    uint32_t reg_value;
    uint32_t *reg_ptr;

    reg_ptr = (uint32_t *) u32_address_rd_byte_reg;

    reg_value = *(reg_ptr);

    result = reg_value;

    *(pu8_Data_rd_byte_reg) = result;
}
</code>```

The build command. You can see it is building for an ARM Cortex M3:

```<code>arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -pedantic -Wall -Wextra  -g3 -T "linker_script.ld" -Xlinker --gc-sections -Wl,-Map,"output_map.map" --specs=nano.specs -o "output.elf"
</code>```

答:
Adding the flag -Wconversion as stated in a comment to the question fixed the problem. Apparently it is disabled by default. -Wconversion enables warnings about implicit type conversions. Attaching a screenshot about the warning:

```<code>arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -pedantic -Wall -Wextra -Wconversion -g3 -T "linker_script.ld" -Xlinker --gc-sections -Wl,-Map,"output_map.map" --specs=nano.specs -o "output.elf"
</code>```

Body:
Why is the compiler not throwing a value truncation due to the conversion from a uint32 to a uint8 variable type? Precisely the line result = reg_value;

void read_byte_register(uint32_t u32_address_rd_byte_reg,
        uint8_t *pu8_Data_rd_byte_reg)
{
    uint8_t result;
    uint32_t reg_value;
    uint32_t *reg_ptr;

    reg_ptr = (uint32_t *) u32_address_rd_byte_reg;

    reg_value = *(reg_ptr);

    result = reg_value;

    *(pu8_Data_rd_byte_reg) = result;
}

The build command. You can see it is building for an ARM Cortex M3:

arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -pedantic -Wall -Wextra  -g3 -T "linker_script.ld" -Xlinker --gc-sections -Wl,-Map,"output_map.map" --specs=nano.specs -o "output.elf"

Body:
Adding the flag -Wconversion as stated in a comment to the question fixed the problem. Apparently it is disabled by default. -Wconversion enables warnings about implicit type conversions. Attaching a screenshot about the warning:

arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -pedantic -Wall -Wextra -Wconversion -g3 -T "linker_script.ld" -Xlinker --gc-sections -Wl,-Map,"output_map.map" --specs=nano.specs -o "output.elf"


问:
Possibility to make drop down menu scrollable in Odoo tree view
Is there a possibility to add a scrollbar into the dropdown list of the treeview ?

When more records are added than in the shown screenshot, some of the fade in columns cannot be seen and I have to scroll down to the end of the tree view list to select these columns.

How can I add a scrollbar into the dropdown menu, without scrolling down to the page but only in the dropdown menu(red bordered) ?

My CSS:

```<code> .dropdown-menu {
    height: 10px;
    overflow-y: auto;
}
</code>```

My XML:

```<code><odoo>

    <template id="asset_contacts_addon" name="contacts addon assets" inherit_id="web.assets_backend">
        <xpath expr="." position="inside">
            <link rel="stylesheet" type="text/css" href="/contacts_addon/static/src/css/contacts_addon.css"/>
        </xpath>
    </template>

<record id="contacts_addon_tree_view" model="ir.ui.view">
        <field name="name">view.contacts.addon.tree</field>
        <field name="model">res.partner</field>
        <field name="inherit_id" ref="base.view_partner_tree"/>
        <field name="arch" type="xml">

<p class="dropdown-menu">
    <field name="display_name" position="after">
        <field name="customer_codename" optional="hide"/>
    </field>
     <field name="customer_id_previous" position="after">
        <field name="klm_key" optional="hide"/>
    </field>
</p>

    <field name="customer_codename" position="after">
       <field name="id"/>
     </field>
     <field name="id" position="after">
       <field name="customer_id_previous"/>
     </field>

 </field>
</record>
</code>```

答:
One thing you can do is to edit the CSS to set the menu's height and overflow-y in the dropdown-menu class.

```<code>.dropdown-menu {
    height: 200px;
    overflow-y: auto;
}
</code>```

height is the vertical size of the element. You can set the height to the size you want.

overflow-y is a configuration for vertical scroll of the element. Setting it to auto will often result in what you need.

The result should look something like this.

Body:
Is there a possibility to add a scrollbar into the dropdown list of the treeview ?

When more records are added than in the shown screenshot, some of the fade in columns cannot be seen and I have to scroll down to the end of the tree view list to select these columns.

How can I add a scrollbar into the dropdown menu, without scrolling down to the page but only in the dropdown menu(red bordered) ?

My CSS:

 .dropdown-menu {
    height: 10px;
    overflow-y: auto;
}

My XML:

<odoo>

    <template id="asset_contacts_addon" name="contacts addon assets" inherit_id="web.assets_backend">
        <xpath expr="." position="inside">
            <link rel="stylesheet" type="text/css" href="/contacts_addon/static/src/css/contacts_addon.css"/>
        </xpath>
    </template>

<record id="contacts_addon_tree_view" model="ir.ui.view">
        <field name="name">view.contacts.addon.tree</field>
        <field name="model">res.partner</field>
        <field name="inherit_id" ref="base.view_partner_tree"/>
        <field name="arch" type="xml">

    <field name="display_name" position="after">
        <field name="customer_codename" optional="hide"/>
    </field>
     <field name="customer_id_previous" position="after">
        <field name="klm_key" optional="hide"/>
    </field>

    <field name="customer_codename" position="after">
       <field name="id"/>
     </field>
     <field name="id" position="after">
       <field name="customer_id_previous"/>
     </field>

 </field>
</record>

Body:
One thing you can do is to edit the CSS to set the menu's height and overflow-y in the dropdown-menu class.

.dropdown-menu {
    height: 200px;
    overflow-y: auto;
}

height is the vertical size of the element. You can set the height to the size you want.

overflow-y is a configuration for vertical scroll of the element. Setting it to auto will often result in what you need.

The result should look something like this.


问:
How to unstage large number of files without deleting the content
I accidentally added a lot of temporary files using git add -A

I managed to unstage the files using the following commands and managed to remove the dirty index.

```<code>git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached
</code>```

The above commands are listed in the git help rm. But sadly, my files were also deleted on execution, even though I had given cache option. How can I clear the index without losing the content?

Also it would be helpful if someone can explain the way this pipe operation works.

答:
If you have a pristine repo (or HEAD isn't set)[1] you could simply

```<code>rm .git/index
</code>```

Of course, this will require you to re-add the files that you did want to be added.

[1] Note (as explained in the comments) this would usually only happen when the repo is brand-new ("pristine") or if no commits have been made. More technically, whenever there is no checkout or work-tree.

Just making it more clear :)

Body:
I accidentally added a lot of temporary files using git add -A

I managed to unstage the files using the following commands and managed to remove the dirty index.

git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached

The above commands are listed in the git help rm. But sadly, my files were also deleted on execution, even though I had given cache option. How can I clear the index without losing the content?

Also it would be helpful if someone can explain the way this pipe operation works.

Body:
If you have a pristine repo (or HEAD isn't set)[1] you could simply

rm .git/index

Of course, this will require you to re-add the files that you did want to be added.

[1] Note (as explained in the comments) this would usually only happen when the repo is brand-new ("pristine") or if no commits have been made. More technically, whenever there is no checkout or work-tree.

Just making it more clear :)


问:
Javascript function not triggering on html page load/ refresh
I want a javascript function to give me the results as soon as the page loads in. It is returning the list of folder names. I am not a developer so this is something I am making to demo my research to a client and therefore I am running into small issues.
In my index.html I have incorporated a js function inside the  tag and I call that function in my <p> tag via a ID like this:</p>
```<code><script>
    var list_dir = function(){
      const path = require('path');
      const fs = require('fs');
      //joining path of directory
      const directoryPath = path.join(__dirname, 'Images');
      //passsing directoryPath and callback function
      fs.readdir(directoryPath, function (err, files) {
        //listing all files using forEach
        files.forEach(function (file) {
          // Do whatever you want to do with the file
          //let names=file
          console.log(file);
        });
      });
    }
    </script>
<p id="list_dir>list of folders:</p>

</code>```

答:
As Yugoslav Empire mentioned earlier, your script is embedded in the HTML file, so it runs on the client side.
You mentioned that you are making a demo for research, so I assume you will run the HTML file locally on your computer? Then this answer to similar question, may help you.

Indirect Solution

If you want to use command line to generate a list of HTML links, please try to run this command on the desired directory.

ls | awk '{print "" $1 "<\/a>
"}'
```
<p>and then paste the result to your HTML file</p>
<hr />
<p>example if you have <code>a.html</code> <code>b.html</code> in a certain directory, running the script to that directory will output:</p>
<pre class="lang-sh prettyprint-override"><code>a.html<br/>
href="./b.html">b.html<br/>
</code>```

which can be pasted to your HTML file?

Body:
I want a javascript function to give me the results as soon as the page loads in. It is returning the list of folder names. I am not a developer so this is something I am making to demo my research to a client and therefore I am running into small issues.
In my index.html I have incorporated a js function inside the  tag and I call that function in my
 tag via a ID like this:

list of folders:

Body:
As Yugoslav Empire mentioned earlier, your script is embedded in the HTML file, so it runs on the client side.
You mentioned that you are making a demo for research, so I assume you will run the HTML file locally on your computer? Then this answer to similar question, may help you.

Indirect Solution

If you want to use command line to generate a list of HTML links, please try to run this command on the desired directory.

ls | awk '{print "<a href=\".\/" $1 "\">" $1 "<\/a><br\/>"}'

and then paste the result to your HTML file

example if you have a.html b.html in a certain directory, running the script to that directory will output:

<a href="./a.html">a.html</a><br/>
<a href="./b.html">b.html</a><br/>

which can be pasted to your HTML file?


问:
Why catch error does not work when I have 401 error on refresh token request?
If any other request has 401 error refresh token executed and then I have 3 cases

If I send a valid refresh token works as expected

If I send a not valid refresh token I have 401 (from backend) and catchError does not work

If I send the wrong request (example: incorrect URL) I get 500 catchError work.

angular service

```<code>  refreshToken(refreshToken: string): Observable<any> {
    return <Observable<any>>(
      this.http.post('http://localhost:3000/auth/refresh-token', {refreshToken})
    );
  }
</code>```

angular interseptor

```<code>intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    let authReq = request;
    const token = this.storageService.getToken();
    if (token != null) {
      authReq = this.addTokenHeader(request, token);
    }
    return next.handle(authReq).pipe(catchError(error => {
      if (error instanceof HttpErrorResponse && error.status === 401) {
        return this.handle401Error(authReq, next);
      }
      return throwError(error);
    }));
  }

  private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);
      const token = this.storageService.getRefreshToken();
      if (token) {
        return this.authService.refreshToken(token).pipe(
          switchMap((token: any) => {
            this.isRefreshing = false;
            this.storageService.setToken(token.accessToken);
            this.storageService.setRefreshToken(token.refreshToken);
            this.refreshTokenSubject.next(token.accessToken);

            return next.handle(this.addTokenHeader(request, token.accessToken));
          }),
          catchError((err) => {
            this.isRefreshing = false;
            console.log('catchError');
            this.storageService.clearStorage();
            return throwError(err);
          })
        );
      }
    }
    return this.refreshTokenSubject.pipe(
      filter(token => token !== null),
      take(1),
      switchMap((token) => next.handle(this.addTokenHeader(request, token)))
    );
  }
</code>```

Please tell me what am I doing wrong and how to do it in a right way

答:
Add below code inside else statement:

```<code>return this.refreshTokenSubject.pipe(
  filter(token => token !== null),
  take(1),
  switchMap((token) => next.handle(this.addTokenHeader(request, token)))
);
</code>```

Body:
If any other request has 401 error refresh token executed and then I have 3 cases

If I send a valid refresh token works as expected

If I send a not valid refresh token I have 401 (from backend) and catchError does not work

If I send the wrong request (example: incorrect URL) I get 500 catchError work.

angular service

  refreshToken(refreshToken: string): Observable<any> {
    return <Observable<any>>(
      this.http.post('http://localhost:3000/auth/refresh-token', {refreshToken})
    );
  }

angular interseptor

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    let authReq = request;
    const token = this.storageService.getToken();
    if (token != null) {
      authReq = this.addTokenHeader(request, token);
    }
    return next.handle(authReq).pipe(catchError(error => {
      if (error instanceof HttpErrorResponse && error.status === 401) {
        return this.handle401Error(authReq, next);
      }
      return throwError(error);
    }));
  }

  private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);
      const token = this.storageService.getRefreshToken();
      if (token) {
        return this.authService.refreshToken(token).pipe(
          switchMap((token: any) => {
            this.isRefreshing = false;
            this.storageService.setToken(token.accessToken);
            this.storageService.setRefreshToken(token.refreshToken);
            this.refreshTokenSubject.next(token.accessToken);

            return next.handle(this.addTokenHeader(request, token.accessToken));
          }),
          catchError((err) => {
            this.isRefreshing = false;
            console.log('catchError');
            this.storageService.clearStorage();
            return throwError(err);
          })
        );
      }
    }
    return this.refreshTokenSubject.pipe(
      filter(token => token !== null),
      take(1),
      switchMap((token) => next.handle(this.addTokenHeader(request, token)))
    );
  }

Please tell me what am I doing wrong and how to do it in a right way

Body:
Add below code inside else statement:

return this.refreshTokenSubject.pipe(
  filter(token => token !== null),
  take(1),
  switchMap((token) => next.handle(this.addTokenHeader(request, token)))
);


问:
Moment returns wrong date for Unix timestamp
I want to save unixtime to a state of type Moment.moment.

If you use moment(timestamp), you will get a different date.

```<code>  const [date, setDate] = useState<moment.Moment | null>(null);
  const timestamp = Math.floor(date.getTime() / 1000);
  setDate(moment(timestamp));

</code>```

答:
You manipulated the date when you used Math.floor.

console.log(moment());
console.log('With Floor', moment.unix(   Math.floor((new Date()).getTime() /1000 )));
console.log('Without Floor', moment.unix((new Date()).getTime() /1000 ));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script></code>```

Good Read: You Don't Need MomentJS

Body:
I want to save unixtime to a state of type Moment.moment.

If you use moment(timestamp), you will get a different date.

  const [date, setDate] = useState<moment.Moment | null>(null);
  const timestamp = Math.floor(date.getTime() / 1000);
  setDate(moment(timestamp));

Body:
You manipulated the date when you used Math.floor.

console.log(moment());
console.log('With Floor', moment.unix(   Math.floor((new Date()).getTime() /1000 )));
console.log('Without Floor', moment.unix((new Date()).getTime() /1000 ));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Good Read: You Don't Need MomentJS


问:
Oracle - How to get number in varchar field with particular condition
I have this example table:

ID
DESCRIPTION

AD112
#21#

AD122
#8970#

AD124
NOT ALL SENT#115#

what should i use to get exact number between '#', like this:

ID
DESCRIPTION

AD112
21

AD122
8970

AD124
115

i've no clue to try code to, please help, thanks

答:
As you said - between two # signs:</p>
```<code>SQL> with test (id, description) as
  2    (select 'AD112', '#21#'               from dual union all
  3     select 'AD122', '#8970#'            from dual union all
  4     select 'AD124', 'NOT ALL SENT#115#' from dual
  5    )
  6  select id,
  7    substr(description, instr(description, '#', 1, 1) + 1,
  8                        instr(description, '#', 1, 2) - instr(description, '#', 1, 1) - 1
  9          ) description
 10  from test
 11  order by id;

ID    DESCRIPTION
----- -----------------
AD112 21
AD122 8970
AD124 115

SQL>
</code>```

Body:
As you said - between two # signs:

SQL> with test (id, description) as
  2    (select 'AD112', '#21#'               from dual union all
  3     select 'AD122', '#8970#'            from dual union all
  4     select 'AD124', 'NOT ALL SENT#115#' from dual
  5    )
  6  select id,
  7    substr(description, instr(description, '#', 1, 1) + 1,
  8                        instr(description, '#', 1, 2) - instr(description, '#', 1, 1) - 1
  9          ) description
 10  from test
 11  order by id;

ID    DESCRIPTION
----- -----------------
AD112 21
AD122 8970
AD124 115

SQL>


问:
'GoogleUtilities/GULURLSessionDataResponse.h' file not found
Trying to compile my project after adding some pods. While compiling it gives below error
'GoogleUtilities/GULURLSessionDataResponse.h' file not found

Podfile.lock:

```<code>- FBSDKCoreKit (9.1.0):
    - FBSDKCoreKit/Basics (= 9.1.0)
    - FBSDKCoreKit/Core (= 9.1.0)
  - FBSDKCoreKit/Basics (9.1.0)
  - FBSDKCoreKit/Core (9.1.0):
    - FBSDKCoreKit/Basics
  - Firebase/Analytics (3.6.0):
    - FirebaseAnalytics (= 3.4.2)
  - Firebase/Core (3.6.0):
    - Firebase/Analytics
  - Firebase/CoreOnly (7.9.0):
    - FirebaseCore (= 7.9.0)
  - Firebase/Crashlytics (7.9.0):
    - Firebase/CoreOnly
    - FirebaseCrashlytics (~> 7.9.0)
  - Firebase/Messaging (3.6.0):
    - Firebase/Analytics
    - FirebaseMessaging (= 1.2.0)
  - FirebaseAnalytics (3.4.2):
    - FirebaseInstanceID (~> 1.0)
    - GoogleInterchangeUtilities (~> 1.2)
    - GoogleSymbolUtilities (~> 1.1)
    - GoogleUtilities (~> 1.2)
  - FirebaseCore (7.9.0):
    - FirebaseCoreDiagnostics (~> 7.4)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/Logger (~> 7.0)
  - FirebaseCoreDiagnostics (7.9.0):
    - GoogleDataTransport (~> 8.0)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/Logger (~> 7.0)
    - nanopb (~> 2.30907.0)
  - FirebaseCrashlytics (7.9.0):
    - FirebaseCore (~> 7.0)
    - FirebaseInstallations (~> 7.0)
    - GoogleDataTransport (~> 8.0)
    - nanopb (~> 2.30907.0)
    - PromisesObjC (~> 1.2)
  - FirebaseInstallations (7.9.0):
    - FirebaseCore (~> 7.0)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/UserDefaults (~> 7.0)
    - PromisesObjC (~> 1.2)
  - FirebaseInstanceID (1.0.9)
  - FirebaseMessaging (1.2.0):
    - FirebaseAnalytics (~> 3.3)
    - FirebaseInstanceID (~> 1.0)
    - GoogleInterchangeUtilities (~> 1.2)
    - GoogleIPhoneUtilities (~> 1.2)
    - GoogleSymbolUtilities (~> 1.1)
  - Flurry-iOS-SDK (10.1.0):
    - Flurry-iOS-SDK/FlurrySDK (= 10.1.0)
  - Flurry-iOS-SDK/FlurrySDK (10.1.0)
  - GoogleDataTransport (8.3.0):
    - GoogleUtilities/Environment (~> 7.2)
    - nanopb (~> 2.30907.0)
    - PromisesObjC (~> 1.2)
  - GoogleInterchangeUtilities (1.2.2):
    - GoogleSymbolUtilities (~> 1.1)
  - GoogleIPhoneUtilities (1.2.1):
    - GoogleSymbolUtilities (~> 1.0)
    - GoogleUtilities (~> 1.0)
  - GoogleSymbolUtilities (1.1.2)
  - GoogleUtilities (1.3.2):
    - GoogleSymbolUtilities (~> 1.1)
  - GoogleUtilities/Environment (7.3.1):
    - PromisesObjC (~> 1.2)
  - GoogleUtilities/Logger (7.3.1):
    - GoogleUtilities/Environment
  - GoogleUtilities/UserDefaults (7.3.1):
    - GoogleUtilities/Logger

 - FBSDKCoreKit (9.1.0):
    - FBSDKCoreKit/Basics (= 9.1.0)
    - FBSDKCoreKit/Core (= 9.1.0)
  - FBSDKCoreKit/Basics (9.1.0)
  - FBSDKCoreKit/Core (9.1.0):
    - FBSDKCoreKit/Basics
  - Firebase/Analytics (3.6.0):
    - FirebaseAnalytics (= 3.4.2)
  - Firebase/Core (3.6.0):
    - Firebase/Analytics
  - Firebase/CoreOnly (7.9.0):
    - FirebaseCore (= 7.9.0)
  - Firebase/Crashlytics (7.9.0):
    - Firebase/CoreOnly
    - FirebaseCrashlytics (~> 7.9.0)
  - Firebase/Messaging (3.6.0):
    - Firebase/Analytics
    - FirebaseMessaging (= 1.2.0)
  - FirebaseAnalytics (3.4.2):
    - FirebaseInstanceID (~> 1.0)
    - GoogleInterchangeUtilities (~> 1.2)
    - GoogleSymbolUtilities (~> 1.1)
    - GoogleUtilities (~> 1.2)
  - FirebaseCore (7.9.0):
    - FirebaseCoreDiagnostics (~> 7.4)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/Logger (~> 7.0)
  - FirebaseCoreDiagnostics (7.9.0):
    - GoogleDataTransport (~> 8.0)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/Logger (~> 7.0)
    - nanopb (~> 2.30907.0)
  - FirebaseCrashlytics (7.9.0):
    - FirebaseCore (~> 7.0)
    - FirebaseInstallations (~> 7.0)
    - GoogleDataTransport (~> 8.0)
    - nanopb (~> 2.30907.0)
    - PromisesObjC (~> 1.2)
  - FirebaseInstallations (7.9.0):
    - FirebaseCore (~> 7.0)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/UserDefaults (~> 7.0)
    - PromisesObjC (~> 1.2)
  - FirebaseInstanceID (1.0.9)
  - FirebaseMessaging (1.2.0):
    - FirebaseAnalytics (~> 3.3)
    - FirebaseInstanceID (~> 1.0)
    - GoogleInterchangeUtilities (~> 1.2)
    - GoogleIPhoneUtilities (~> 1.2)
    - GoogleSymbolUtilities (~> 1.1)
  - Flurry-iOS-SDK (10.1.0):
    - Flurry-iOS-SDK/FlurrySDK (= 10.1.0)
  - Flurry-iOS-SDK/FlurrySDK (10.1.0)
  - GoogleDataTransport (8.3.0):
    - GoogleUtilities/Environment (~> 7.2)
    - nanopb (~> 2.30907.0)
    - PromisesObjC (~> 1.2)
  - GoogleInterchangeUtilities (1.2.2):
    - GoogleSymbolUtilities (~> 1.1)
  - GoogleIPhoneUtilities (1.2.1):
    - GoogleSymbolUtilities (~> 1.0)
    - GoogleUtilities (~> 1.0)
  - GoogleSymbolUtilities (1.1.2)
  - GoogleUtilities (1.3.2):
    - GoogleSymbolUtilities (~> 1.1)
  - GoogleUtilities/Environment (7.3.1):
    - PromisesObjC (~> 1.2)
  - GoogleUtilities/Logger (7.3.1):
    - GoogleUtilities/Environment
  - GoogleUtilities/UserDefaults (7.3.1):
    - GoogleUtilities/Logger
</code>```

Clean the project

Close the Xcode

Delete derived data

If you have
already installed the POD, kindly delete the “.xcworkspace” &
“Podfile.lock” files

Install pod again - Doesn't work

答:
For me the problem was to update to Firebase v8.x.x using the pod 'Firebase/Admob', then the GoogleUtilities missing file error appears. So I have replaced:

```<code>pod 'Firebase/AdMob'
</code>```

with

```<code>pod 'Google-Mobile-Ads-SDK', '~> 7.x'
</code>```

This allowed me to continue the build without errors and code changes, as the GoogleMobileAdSDK version 8 or 9 (January 2022) requires code migration, so this code migration is another post story.

Body:
Trying to compile my project after adding some pods. While compiling it gives below error
'GoogleUtilities/GULURLSessionDataResponse.h' file not found

Podfile.lock:

- FBSDKCoreKit (9.1.0):
    - FBSDKCoreKit/Basics (= 9.1.0)
    - FBSDKCoreKit/Core (= 9.1.0)
  - FBSDKCoreKit/Basics (9.1.0)
  - FBSDKCoreKit/Core (9.1.0):
    - FBSDKCoreKit/Basics
  - Firebase/Analytics (3.6.0):
    - FirebaseAnalytics (= 3.4.2)
  - Firebase/Core (3.6.0):
    - Firebase/Analytics
  - Firebase/CoreOnly (7.9.0):
    - FirebaseCore (= 7.9.0)
  - Firebase/Crashlytics (7.9.0):
    - Firebase/CoreOnly
    - FirebaseCrashlytics (~> 7.9.0)
  - Firebase/Messaging (3.6.0):
    - Firebase/Analytics
    - FirebaseMessaging (= 1.2.0)
  - FirebaseAnalytics (3.4.2):
    - FirebaseInstanceID (~> 1.0)
    - GoogleInterchangeUtilities (~> 1.2)
    - GoogleSymbolUtilities (~> 1.1)
    - GoogleUtilities (~> 1.2)
  - FirebaseCore (7.9.0):
    - FirebaseCoreDiagnostics (~> 7.4)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/Logger (~> 7.0)
  - FirebaseCoreDiagnostics (7.9.0):
    - GoogleDataTransport (~> 8.0)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/Logger (~> 7.0)
    - nanopb (~> 2.30907.0)
  - FirebaseCrashlytics (7.9.0):
    - FirebaseCore (~> 7.0)
    - FirebaseInstallations (~> 7.0)
    - GoogleDataTransport (~> 8.0)
    - nanopb (~> 2.30907.0)
    - PromisesObjC (~> 1.2)
  - FirebaseInstallations (7.9.0):
    - FirebaseCore (~> 7.0)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/UserDefaults (~> 7.0)
    - PromisesObjC (~> 1.2)
  - FirebaseInstanceID (1.0.9)
  - FirebaseMessaging (1.2.0):
    - FirebaseAnalytics (~> 3.3)
    - FirebaseInstanceID (~> 1.0)
    - GoogleInterchangeUtilities (~> 1.2)
    - GoogleIPhoneUtilities (~> 1.2)
    - GoogleSymbolUtilities (~> 1.1)
  - Flurry-iOS-SDK (10.1.0):
    - Flurry-iOS-SDK/FlurrySDK (= 10.1.0)
  - Flurry-iOS-SDK/FlurrySDK (10.1.0)
  - GoogleDataTransport (8.3.0):
    - GoogleUtilities/Environment (~> 7.2)
    - nanopb (~> 2.30907.0)
    - PromisesObjC (~> 1.2)
  - GoogleInterchangeUtilities (1.2.2):
    - GoogleSymbolUtilities (~> 1.1)
  - GoogleIPhoneUtilities (1.2.1):
    - GoogleSymbolUtilities (~> 1.0)
    - GoogleUtilities (~> 1.0)
  - GoogleSymbolUtilities (1.1.2)
  - GoogleUtilities (1.3.2):
    - GoogleSymbolUtilities (~> 1.1)
  - GoogleUtilities/Environment (7.3.1):
    - PromisesObjC (~> 1.2)
  - GoogleUtilities/Logger (7.3.1):
    - GoogleUtilities/Environment
  - GoogleUtilities/UserDefaults (7.3.1):
    - GoogleUtilities/Logger

 - FBSDKCoreKit (9.1.0):
    - FBSDKCoreKit/Basics (= 9.1.0)
    - FBSDKCoreKit/Core (= 9.1.0)
  - FBSDKCoreKit/Basics (9.1.0)
  - FBSDKCoreKit/Core (9.1.0):
    - FBSDKCoreKit/Basics
  - Firebase/Analytics (3.6.0):
    - FirebaseAnalytics (= 3.4.2)
  - Firebase/Core (3.6.0):
    - Firebase/Analytics
  - Firebase/CoreOnly (7.9.0):
    - FirebaseCore (= 7.9.0)
  - Firebase/Crashlytics (7.9.0):
    - Firebase/CoreOnly
    - FirebaseCrashlytics (~> 7.9.0)
  - Firebase/Messaging (3.6.0):
    - Firebase/Analytics
    - FirebaseMessaging (= 1.2.0)
  - FirebaseAnalytics (3.4.2):
    - FirebaseInstanceID (~> 1.0)
    - GoogleInterchangeUtilities (~> 1.2)
    - GoogleSymbolUtilities (~> 1.1)
    - GoogleUtilities (~> 1.2)
  - FirebaseCore (7.9.0):
    - FirebaseCoreDiagnostics (~> 7.4)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/Logger (~> 7.0)
  - FirebaseCoreDiagnostics (7.9.0):
    - GoogleDataTransport (~> 8.0)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/Logger (~> 7.0)
    - nanopb (~> 2.30907.0)
  - FirebaseCrashlytics (7.9.0):
    - FirebaseCore (~> 7.0)
    - FirebaseInstallations (~> 7.0)
    - GoogleDataTransport (~> 8.0)
    - nanopb (~> 2.30907.0)
    - PromisesObjC (~> 1.2)
  - FirebaseInstallations (7.9.0):
    - FirebaseCore (~> 7.0)
    - GoogleUtilities/Environment (~> 7.0)
    - GoogleUtilities/UserDefaults (~> 7.0)
    - PromisesObjC (~> 1.2)
  - FirebaseInstanceID (1.0.9)
  - FirebaseMessaging (1.2.0):
    - FirebaseAnalytics (~> 3.3)
    - FirebaseInstanceID (~> 1.0)
    - GoogleInterchangeUtilities (~> 1.2)
    - GoogleIPhoneUtilities (~> 1.2)
    - GoogleSymbolUtilities (~> 1.1)
  - Flurry-iOS-SDK (10.1.0):
    - Flurry-iOS-SDK/FlurrySDK (= 10.1.0)
  - Flurry-iOS-SDK/FlurrySDK (10.1.0)
  - GoogleDataTransport (8.3.0):
    - GoogleUtilities/Environment (~> 7.2)
    - nanopb (~> 2.30907.0)
    - PromisesObjC (~> 1.2)
  - GoogleInterchangeUtilities (1.2.2):
    - GoogleSymbolUtilities (~> 1.1)
  - GoogleIPhoneUtilities (1.2.1):
    - GoogleSymbolUtilities (~> 1.0)
    - GoogleUtilities (~> 1.0)
  - GoogleSymbolUtilities (1.1.2)
  - GoogleUtilities (1.3.2):
    - GoogleSymbolUtilities (~> 1.1)
  - GoogleUtilities/Environment (7.3.1):
    - PromisesObjC (~> 1.2)
  - GoogleUtilities/Logger (7.3.1):
    - GoogleUtilities/Environment
  - GoogleUtilities/UserDefaults (7.3.1):
    - GoogleUtilities/Logger

Clean the project

Close the Xcode

Delete derived data

If you have
already installed the POD, kindly delete the “.xcworkspace” &
“Podfile.lock” files

Install pod again - Doesn't work

Body:
For me the problem was to update to Firebase v8.x.x using the pod 'Firebase/Admob', then the GoogleUtilities missing file error appears. So I have replaced:

pod 'Firebase/AdMob'

with

pod 'Google-Mobile-Ads-SDK', '~> 7.x'

This allowed me to continue the build without errors and code changes, as the GoogleMobileAdSDK version 8 or 9 (January 2022) requires code migration, so this code migration is another post story.


问:
php - mysql avoid sql injections
I have many functions like

```<code>updateUser($id,$username,$email)
updateMusic($id, $music)
</code>```

etc...

Is there a generic function to avoid SQL injections ?

I just want to avoid using mysql_real_escape_string for each parameter I have

```<code>$username = mysql_real_escape_string($username);
$email= mysql_real_escape_string($email);
$music= mysql_real_escape_string($music);
</code>```

答:
You should use parameterization and let the database driver handle it for you, i.e. with PDO:

```<code>$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', $user, $password);
$stmt = $dbh->prepare('INSERT INTO REGISTRY (name, value) VALUES (:name, :value)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
</code>```

Code from  Bobby-Tables.

Title: php - mysql avoid sql injections

Body:
I have many functions like

updateUser($id,$username,$email)
updateMusic($id, $music)

etc...

Is there a generic function to avoid SQL injections ?

I just want to avoid using mysql_real_escape_string for each parameter I have

$username = mysql_real_escape_string($username);
$email= mysql_real_escape_string($email);
$music= mysql_real_escape_string($music);

Body:
You should use parameterization and let the database driver handle it for you, i.e. with PDO:

$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', $user, $password);
$stmt = $dbh->prepare('INSERT INTO REGISTRY (name, value) VALUES (:name, :value)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

Code from  Bobby-Tables.