问:
how we can run multiple queries on Firebase/firestore to get filtered data in flutter?
how we can run multiple queries on  Firebase/ firestore to get filtered data in flutter or any other possible solution? there is a picture storing dummy data in goal and title and wanna users according to the goals and titles filters.

答:
By looking at your Firestore database it is clear that you want to filter the documents based on two array fields goals and titles.

Firestore supports the arrayContains filter in the where clause by which you can filter data from an array inside Firestore. So you may think of doing something like this -

```<code>var filter1 = 'Hire Employees';
   var filter2 = 'CEO';
   FirebaseFirestore.instance
       .collection('collectionId')
       .where('goals', arrayContains: filter1)
       .where('titles', arrayContains: filter2)
       .get()
       .then((QuerySnapshot docs) => {
             for (var element in docs.docs) {print(element.data())}
           });
</code>```

But the above will throw an error saying that You cannot use 'array-contains' filters more than once. This is because Firestore has a limitation that you can use at most one array-contains clause per query which is documented here. So it is not possible to do something like the above.

I am not very sure of your use case, but as a workaround, you can restructure the database structure by making any one of the array field to a map, something like the following -

By making the structure like the above you can use multiple where clauses with one arrayContains filter and one isEqualTo filter which will look something like this -

```<code>   var filter1 = 'Hire Employees';
   var filter2 = 'CEO';
   FirebaseFirestore.instance
       .collection('collectionId')
       .where('goals.$filter1', isEqualTo: true)
       .where('titles', arrayContains: filter2)
       .get()
       .then((QuerySnapshot docs) => {
             for (var element in docs.docs) {print(element.data())}
           });
</code>```

As the idea of allowing multiple arrayContains filters is currently not supported, but could be valid, I would recommend you file a feature request.

Body:
By looking at your Firestore database it is clear that you want to filter the documents based on two array fields goals and titles.

Firestore supports the arrayContains filter in the where clause by which you can filter data from an array inside Firestore. So you may think of doing something like this -

var filter1 = 'Hire Employees';
   var filter2 = 'CEO';
   FirebaseFirestore.instance
       .collection('collectionId')
       .where('goals', arrayContains: filter1)
       .where('titles', arrayContains: filter2)
       .get()
       .then((QuerySnapshot docs) => {
             for (var element in docs.docs) {print(element.data())}
           });

But the above will throw an error saying that You cannot use 'array-contains' filters more than once. This is because Firestore has a limitation that you can use at most one array-contains clause per query which is documented here. So it is not possible to do something like the above.

I am not very sure of your use case, but as a workaround, you can restructure the database structure by making any one of the array field to a map, something like the following -

By making the structure like the above you can use multiple where clauses with one arrayContains filter and one isEqualTo filter which will look something like this -

   var filter1 = 'Hire Employees';
   var filter2 = 'CEO';
   FirebaseFirestore.instance
       .collection('collectionId')
       .where('goals.$filter1', isEqualTo: true)
       .where('titles', arrayContains: filter2)
       .get()
       .then((QuerySnapshot docs) => {
             for (var element in docs.docs) {print(element.data())}
           });

As the idea of allowing multiple arrayContains filters is currently not supported, but could be valid, I would recommend you file a feature request.


来源: stackexchange

问:
React - a route that sends a 200 status code
I want to have a /status page that returns a 200 status code.

I create a route along with a page, however when I access it I see a 304 code as the response.

Any ideas how I can set the route to just return a 200.

```<code>    <Router>
      <Layout>
        <Routes>
          <Route path="/status" element={<AppStatus />} />
        </Routes>
      </Layout>
    </Router>
</code>```

I'm using v6 of the react-router-dom.

Any ideas?

Thanks.

答:
React can be used on both single-page applications (for example create-react-app) and for server-side rendering (for example NextJS). A http status is sent once per http request.

This means that if your app is a single-page application and you first go to / and then click a link to go to /status, then you won't make a new http request (the full app is loaded on the initial request to /) and so you will not get a http status at all when changing the path. If your initial top-level navigation is directly to /status, then the browser will download the app (like it does when you went to / in the last example) and a status code will be sent at the same time.

If the status code is 304, then it means that your app has been cached. To deal with this, force your backend to set cache headers on the request for the actual resource (the html entrypoint) which indicate that the response must not be cached.

If you're using server-side rendering, then, depending on the framework, you could trigger the /status path to be dynamic and require rerendering on the backend every time, in which case you will get a 200 status every time if nothing unforseen happens.

Are you trying to configure a health endpoint for a load balancer or something?

ContentLicense: CC BY-SA 4.0

Body:
I want to have a /status page that returns a 200 status code.

I create a route along with a page, however when I access it I see a 304 code as the response.

Any ideas how I can set the route to just return a 200.

    <Router>
      <Layout>
        <Routes>
          <Route path="/status" element={<AppStatus />} />
        </Routes>
      </Layout>
    </Router>

I'm using v6 of the react-router-dom.

Any ideas?

Thanks.


问:
Insert Data to a SQL DB using multiple threads
I am trying to write a code that makes records in a SQL DB.

The data I'll be inserting will be received real time(at least 10,000 and up to 80,000 per minute) and one crucial thing is that the exact time the data was received is also recorded.

I understand that a code using a single thread dealing with that much data might overload the core so I'm trying to figure out a better way to write a code.

From searching the web, this is what I came up with.

Have a main thread receive the data and also make record of the time.

Divide the received data into multiple threads.

Make those multiple threads insert to a single DB in a batch.

As I am not familiar with codes using multiple threads, I am not sure how to implement this or if this is even OK.
If it is not, what would be a better way? If it is, what method or class should I use to execute each step?

答:
If your constraints  .i.e RDBMS , realtime inserts are taken out you have a better set of choices.

NoSQL DB geared
a. towards heavy writes (and no/less updates) -- Cassandra.
b. More read intensive than write - Hbase
c. Mongodb / Dynamodb etc...

For no realtime inserts - queue/bulk ingestion for performance.
Also , if you do not need to maintain Read consistency or isolation , NoSQL becomes an easy choice.

If you have to choose an RDBMS you are looking at multiple areas to take care of.

Concurrency on insert points --- partitioning the table and spreading it in the same instance and then distributing those across shards.

Connections to database and total sessions --- choice and configuration of load-balancer.

Type of inserts - long or short (how much data.) - table design

Storage subsystem/ scalability
Storage subsystem will determine your latency and throughput.
Retention of data will determine your growth and scalability.

Each session to the database will have a memory footprint, so you have to provision your database and hosts accordingly.

Type of workload -- only inserts or mixture of insert/update.
SELECT statements (read) will need to be offloaded to replica/Read only standby.

RDBMS will have ACID properties of which D is for durability - it follows WAL (write-ahead protocol) -- will generate transaction logs/ redo logs/ WAL logs/binlog (different names based on the RDBMS you choose)...these are disk hungry files. Management of these is critical for recovery.Also management of these files are not trivial. Heavy inserts will create heavy transactions logs.

Expecting a 24X7 high frequency transactions will limit you from planning schema changes easily , DDL operations like creating indexes and other maintenance work on the table that is taking high frequency transactions. Changes to database gets imperative to launch new features. Most modern RDBMS supports JSON and some other formats for storing data like XML , Hstore.
You might like to implement schemaless transactional system. Something like
https://eng.uber.com/schemaless-part-one-mysql-datastore/
https://backchannel.org/blog/friendfeed-schemaless-mysql

http://gotocon.com/dl/goto-aar-2014/slides/MartyWeiner_ScalingPinterest.pdf

Fault tolerance features on load-balancers for shards.

Some other teams in the downstream like analytics / datawarehouse
will require the data at some duration , say hourly / daily ... The
data might be provided by various methods:

downstream pull.

publish and downstream subscribe

CDC capture through WAL/REDO/BIN/Transation logs....


问:
How do I get the full list list sent via telegram when web scrapping
I have managed to get the text I want but I can't seem to send the entire list to a telegram message. I only manage to send the first line.

```<code>service = Service(executable_path=ChromeDriverManager().install())

driver = webdriver.Chrome(service=service)

driver.get("")

Source = driver.page_source

soup = BeautifulSoup(Source, "html.parser")

for cars in soup.findAll(class_="car-title"):
    print(cars.text)

driver.close()

def telegram_bot_sendtext(bot_message):
    bot_token = ''
    bot_chatID = ''
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message

    response = requests.get(send_text)

    return response.json()

test = telegram_bot_sendtext(cars.text)
</code>```

The print function gives me this

```<code>AUDI E-TRON
MERCEDES-BENZ EQC
TESLA MODEL 3
NISSAN LEAF
MERCEDES-BENZ EQV
AUDI E-TRON
</code>```

At some point I would like to add a function to check for updates and if there any changes then send a push message to telegram. If someone could point me in the right direction I would be grateful.

答:
What happens?

Your sending one line, cause you do not store the results anywhere and only the last result from iterating is in memory.

How to fix?

Asuming you want to send text as in the question, you should store results in variable - Iterate over resultset, extract text and join() results by newline character:

```<code>cars = '\n'.join([cars.text for cars in soup.find_all(class_="car-title")])
</code>```

Example

```<code>...
cars = '\n'.join([cars.text for cars in soup.find_all(class_="car-title")])

def telegram_bot_sendtext(bot_message):
    bot_token = ''
    bot_chatID = ''
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message

    response = requests.get(send_text)

    return response.json()

test = telegram_bot_sendtext(cars)
</code>```

Body:
I have managed to get the text I want but I can't seem to send the entire list to a telegram message. I only manage to send the first line.

service = Service(executable_path=ChromeDriverManager().install())

driver = webdriver.Chrome(service=service)

driver.get("")

Source = driver.page_source

soup = BeautifulSoup(Source, "html.parser")

for cars in soup.findAll(class_="car-title"):
    print(cars.text)

driver.close()

def telegram_bot_sendtext(bot_message):
    bot_token = ''
    bot_chatID = ''
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message

    response = requests.get(send_text)

    return response.json()

test = telegram_bot_sendtext(cars.text)

The print function gives me this

AUDI E-TRON
MERCEDES-BENZ EQC
TESLA MODEL 3
NISSAN LEAF
MERCEDES-BENZ EQV
AUDI E-TRON

At some point I would like to add a function to check for updates and if there any changes then send a push message to telegram. If someone could point me in the right direction I would be grateful.

Body:
What happens?

Your sending one line, cause you do not store the results anywhere and only the last result from iterating is in memory.

How to fix?

Asuming you want to send text as in the question, you should store results in variable - Iterate over resultset, extract text and join() results by newline character:

cars = '\n'.join([cars.text for cars in soup.find_all(class_="car-title")])

Example

...
cars = '\n'.join([cars.text for cars in soup.find_all(class_="car-title")])

def telegram_bot_sendtext(bot_message):
    bot_token = ''
    bot_chatID = ''
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message

    response = requests.get(send_text)

    return response.json()

test = telegram_bot_sendtext(cars)


问:
If else in Jquery
i am a noob to jquery and i want to know how to make use of if else for the following:

on the server side there is a  if for number of rows is equal to 0 and else some JSON part.

```<code>$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
  if ($age_num_rows==0)
  {
   echo "true";
  }
  else
  {
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
     {
$abc_output = array('title' => $row['title'],'age' => $row['age']);
     }
echo json_encode($abc_output);
  }
</code>```

Now coming to Jquery part :

If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.

```<code>   $(document).ready(function(){
      $("#button1").click(function(){
        $.getJSON('script_1.php',function(data){
            if (data=='true') {
                 alert ('hello')
            }
            else {
                $.post('script_1.php',
                    { id: $('input[name="id"]', '#myForm').val() },
                    function(json) {
                        $("input[name='title']").val(json.title);
                        $("input[name='age']").val(json.age);
                    },
                    "json");
            }
      });
  });
</code>```

Edited:

```<code>  $(document).ready(function(){
$("#button1").click(function(){
    $.post(
        'script.php',
        { id: $('input[name="id"]', '#myForm').val() },
        function(json) {
            var data = JSON.parse(json);
            if (data.length === 0){
             alert('no data');
            }
            else{
            $("input[name='title']").val(json.title);
                    $("input[name='age']").val(json.age);

            }},
        "json"
    );
});
});
</code>```

PHP side

```<code>$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row=  array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}
</code>```

答:
There seem to be a few problems:

You are treating the data returned from getJSON as if it is plain
text

The php that you are calling from javascript does not always
return json

You are doing 2 ajax requests; getJSON and post where you only need one: The first call to getJSON without any data will never reach the else condition

By the way, where does $name come from in your php script? For your second ajax call to work, it needs to be something like mysql_real_escape_string($_POST['id']) or (int) $_POST['id'] if it is an integer.

Edit: I think it would be easiest to get rid of the .post and just use the first ajax call. So you will need to change:

```<code>$.getJSON('script_1.php',function(data){
</code>```

to something like:

```<code>$.getJSON('script_1.php?id=' + $('input[name="id"]').val(), function(data) {
</code>```

and in your php you need to use something like:

```<code>$name = mysql_real_escape_string($_GET['id']);
</code>```

ContentLicense: CC BY-SA 3.0

Title: If else in Jquery

Body:
i am a noob to jquery and i want to know how to make use of if else for the following:

on the server side there is a  if for number of rows is equal to 0 and else some JSON part.

$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
  if ($age_num_rows==0)
  {
   echo "true";
  }
  else
  {
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
     {
$abc_output = array('title' => $row['title'],'age' => $row['age']);
     }
echo json_encode($abc_output);
  }

Now coming to Jquery part :

If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.

   $(document).ready(function(){
      $("#button1").click(function(){
        $.getJSON('script_1.php',function(data){
            if (data=='true') {
                 alert ('hello')
            }
            else {
                $.post('script_1.php',
                    { id: $('input[name="id"]', '#myForm').val() },
                    function(json) {
                        $("input[name='title']").val(json.title);
                        $("input[name='age']").val(json.age);
                    },
                    "json");
            }
      });
  });

Edited:

  $(document).ready(function(){
$("#button1").click(function(){
    $.post(
        'script.php',
        { id: $('input[name="id"]', '#myForm').val() },
        function(json) {
            var data = JSON.parse(json);
            if (data.length === 0){
             alert('no data');
            }
            else{
            $("input[name='title']").val(json.title);
                    $("input[name='age']").val(json.age);

            }},
        "json"
    );
});
});

PHP side

$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row=  array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}

Body:
There seem to be a few problems:

You are treating the data returned from getJSON as if it is plain
text

The php that you are calling from javascript does not always
return json

You are doing 2 ajax requests; getJSON and post where you only need one: The first call to getJSON without any data will never reach the else condition

By the way, where does $name come from in your php script? For your second ajax call to work, it needs to be something like mysql_real_escape_string($_POST['id']) or (int) $_POST['id'] if it is an integer.

Edit: I think it would be easiest to get rid of the .post and just use the first ajax call. So you will need to change:

$.getJSON('script_1.php',function(data){

to something like:

$.getJSON('script_1.php?id=' + $('input[name="id"]').val(), function(data) {

and in your php you need to use something like:

$name = mysql_real_escape_string($_GET['id']);


问:
Is it possible to alter Math Equations in a loop?
Take this array of math expressions, which are NOT strings:

```<code>let eqs = [ 1+n, 2+n, 3+n]
</code>```

Is it possible to loop through these equations and modify them WITHOUT evaluating them in javascript somehow?

```<code>eqs.map(eq => eq + 1)
</code>```

...and return this:

```<code>// [ 1+n+1, 2+n+1, 3+n+1]
</code>```

Is something like that even possible at all? Doesn't have to be .map() just using that as an example. Doesn't have to be that syntax, i just can't imagine what the syntax for something like that might be is all...

Been googling around but I haven't found much yet...but I am getting the feeling that this might NOT be possible...is that the case?

Thank you for any assistance :-)

答:
You can do that

let eqs = ['1+n', '2+n', '3+n']
console.log(eqs.map(eq => `${eq}+1`))```

If you want another things . Comment below.

Body:
Take this array of math expressions, which are NOT strings:

let eqs = [ 1+n, 2+n, 3+n]

Is it possible to loop through these equations and modify them WITHOUT evaluating them in javascript somehow?

eqs.map(eq => eq + 1)

...and return this:

// [ 1+n+1, 2+n+1, 3+n+1]

Is something like that even possible at all? Doesn't have to be .map() just using that as an example. Doesn't have to be that syntax, i just can't imagine what the syntax for something like that might be is all...

Been googling around but I haven't found much yet...but I am getting the feeling that this might NOT be possible...is that the case?

Thank you for any assistance :-)

Body:
You can do that

let eqs = ['1+n', '2+n', '3+n']
console.log(eqs.map(eq => `${eq}+1`))

If you want another things . Comment below.


问:
How to listen for changes to platformBrightness in Flutter?
I'm setting up a system where when the user changes the system theme to dark mode, it changes the theme and with Flutter, it works all well and good! However, when the user changes the system theme, the system navigation and status bar don't change their colors. I have code running on the home page inside the build method but that doesn't seem to do it. Here's the code inside the home page build method:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Brightness sysBrightness = MediaQuery.of(context).platformBrightness;
    if (sysBrightness == Brightness.dark)
      Themes.setDarkSystemColors();
    else
      Themes.setLightSystemColors();

    return Scaffold(
      appBar: CustomAppBar(title: "Home"),
      drawer: CustomDrawer(),
      body: SizedBox(),
    );
  }
}
```

<p>Here's the code in the main app with <code>theme:</code> and <code>darkTheme:</code>:</p>

<pre class="lang-dart prettyprint-override"><code>    return MaterialApp(
      initialRoute: '/',
      routes: routes,
      navigatorObservers: [_routeObserver],
      theme: Themes.lightTheme,
      darkTheme: Themes.darkTheme,
      debugShowCheckedModeBanner: false,
      title: 'School Life',
    );
</code>```

答:
[Feb 2022] - Working fine for me.

Use - final Brightness brightness = MediaQuery.platformBrightnessOf(context);.

This will listen to theme changes. You can render differently based on this change.

```<code> @override
  Widget build(BuildContext context) {
    final Brightness brightness = MediaQuery.platformBrightnessOf(context);
    bool isDarkMode = brightness == Brightness.dark;
</code>```

Later in the Widgets render based on isDarkMode

For Example:

AssetImage(isDarkMode ? darkBgImage : lightBgImage)

```<code>Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(isDarkMode ? darkBgImage : lightBgImage),
                  fit: BoxFit.cover,
                  colorFilter:
                      const ColorFilter.mode(Colors.black45, BlendMode.darken),
                ),
              ),
            ),
</code>```

Body:
I'm setting up a system where when the user changes the system theme to dark mode, it changes the theme and with Flutter, it works all well and good! However, when the user changes the system theme, the system navigation and status bar don't change their colors. I have code running on the home page inside the build method but that doesn't seem to do it. Here's the code inside the home page build method:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Brightness sysBrightness = MediaQuery.of(context).platformBrightness;
    if (sysBrightness == Brightness.dark)
      Themes.setDarkSystemColors();
    else
      Themes.setLightSystemColors();

    return Scaffold(
      appBar: CustomAppBar(title: "Home"),
      drawer: CustomDrawer(),
      body: SizedBox(),
    );
  }
}

Here's the code in the main app with theme: and darkTheme::

    return MaterialApp(
      initialRoute: '/',
      routes: routes,
      navigatorObservers: [_routeObserver],
      theme: Themes.lightTheme,
      darkTheme: Themes.darkTheme,
      debugShowCheckedModeBanner: false,
      title: 'School Life',
    );

Body:
[Feb 2022] - Working fine for me.

Use - final Brightness brightness = MediaQuery.platformBrightnessOf(context);.

This will listen to theme changes. You can render differently based on this change.

 @override
  Widget build(BuildContext context) {
    final Brightness brightness = MediaQuery.platformBrightnessOf(context);
    bool isDarkMode = brightness == Brightness.dark;

Later in the Widgets render based on isDarkMode

For Example:

AssetImage(isDarkMode ? darkBgImage : lightBgImage)

Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(isDarkMode ? darkBgImage : lightBgImage),
                  fit: BoxFit.cover,
                  colorFilter:
                      const ColorFilter.mode(Colors.black45, BlendMode.darken),
                ),
              ),
            ),


问:
C++ vector's insert & push_back difference
I want to know what are difference(s) between vector's push_back and insert functions.

Is there a structural difference(s)?

Is there a really big performance difference(s)?

答:
I didn't see it in any of the comments above but it is important to know:

If we wish to add a new element to a given vector and the new size of the vector (including the new element) surpasses the current vector capacity it will cause an automatic reallocation of the allocated storage space.
And Beacuse memory allocation is an action we wish to minimize it will increase the capacity both in push_back and insert in the same way (for a vector with n elemeny will add about n/2).

So in terms of memory efficiency it is safe to say, use what ever you like best.
for example:

```<code>std::vector<int> test_Insert = { 1,2,3,4,5,6,7 };
std::vector<int> test_Push_Back = { 1,2,3,4,5,6,7 };

std::cout << test_Insert.capacity() << std::endl;
std::cout << test_Push_Back.capacity() << std::endl;

test_Insert.push_back(8);
test_Push_Back.insert(test_Push_Back.end(), 8);

std::cout << test_Insert.capacity() << std::endl;
std::cout << test_Push_Back.capacity() << std::endl;
</code>```

This code will print:

7

7

10

10

Body:
I didn't see it in any of the comments above but it is important to know:

If we wish to add a new element to a given vector and the new size of the vector (including the new element) surpasses the current vector capacity it will cause an automatic reallocation of the allocated storage space.
And Beacuse memory allocation is an action we wish to minimize it will increase the capacity both in push_back and insert in the same way (for a vector with n elemeny will add about n/2).

So in terms of memory efficiency it is safe to say, use what ever you like best.
for example:

std::vector<int> test_Insert = { 1,2,3,4,5,6,7 };
std::vector<int> test_Push_Back = { 1,2,3,4,5,6,7 };

std::cout << test_Insert.capacity() << std::endl;
std::cout << test_Push_Back.capacity() << std::endl;

test_Insert.push_back(8);
test_Push_Back.insert(test_Push_Back.end(), 8);

std::cout << test_Insert.capacity() << std::endl;
std::cout << test_Push_Back.capacity() << std::endl;

This code will print:

7

7

10

10


问:
Play video when mouse hovers trigger object
I'm designing a page where i want the video for each post to play when the user hovers the post. I've set it up like this:

```<code><div class="project-link-block">
<div class="video-cover">
<video class="playonhover"height="100%" width="100%" muted playsinline loop data-object-fit="cover">

<source src="https://player.vimeo.com/progressive_redirect/playback/671122426/rendition/720p?loc=external&signature=e1562e4b2a73a9f37492359547fef09f8a3ed47a9d12fd77089930fc656a7d8e" type="video/mp4">
Your browser doesn't support HTML5 video tag.
</video>

</div>
</div>
</code>```
```<code><script>
$(document).ready(function() {
  $(".playonhover").on("mouseover", function(event) {
    this.play();

  }).on('mouseout', function(event) {
    this.pause();

  });
})
</script>
</code>```

This works, but I actually want the video to play when the top div (class .project-link-block) is hovered, not the video itself. Is there any way to do this? Switching the class in the JS didn't work. Using Webflow for this, in case it's relevant.

答:
See if this code below achieves your expected result. Then convert to JQuery (if required).</p>
```<code><!DOCTYPE html>
<html>
<body>

<div class="project-link-block">
<div class="video-cover">
<video class="playonhover"height="100%" width="100%" muted playsinline loop data-object-fit="cover">

<!-- <source src="https://www.w3schools.com/tags/movie.mp4" type="video/mp4"> -->
<source type="video/mp4"
src="https://player.vimeo.com/progressive_redirect/playback/671122426/rendition/720p?loc=external&signature=e1562e4b2a73a9f37492359547fef09f8a3ed47a9d12fd77089930fc656a7d8e"
>

Your browser doesn't support HTML5 video tag.
</video>

</div>
</div>

<script>

window.addEventListener( "load", on_documentReady );

function on_documentReady()
{
    //const myTargets = document.getElementsByClassName("playonhover");
    const myTargets = document.getElementsByClassName("project-link-block");

    for (var i = 0; i < myTargets.length; i++)
    {
        myTargets[i].onmouseover = handle_mouseOver;
        myTargets[i].onmouseout = handle_mouseOut;
    }
}

function handle_mouseOver( evt )
{
    //alert( "## was rolled over" );
    evt.target.play();
}

function handle_mouseOut( evt )
{
    //alert( "## was rolled out" );
    evt.target.pause();
}

</script>

</body>
</html>
</code>```

Body:
I'm designing a page where i want the video for each post to play when the user hovers the post. I've set it up like this:

<video class="playonhover"height="100%" width="100%" muted playsinline loop data-object-fit="cover">

<source src="https://player.vimeo.com/progressive_redirect/playback/671122426/rendition/720p?loc=external&signature=e1562e4b2a73a9f37492359547fef09f8a3ed47a9d12fd77089930fc656a7d8e" type="video/mp4">
Your browser doesn't support HTML5 video tag.
</video>

This works, but I actually want the video to play when the top div (class .project-link-block) is hovered, not the video itself. Is there any way to do this? Switching the class in the JS didn't work. Using Webflow for this, in case it's relevant.

Body:
See if this code below achieves your expected result. Then convert to JQuery (if required).

<!DOCTYPE html>
<html>
<body>

<div class="project-link-block">
<div class="video-cover">
<video class="playonhover"height="100%" width="100%" muted playsinline loop data-object-fit="cover">

<!-- <source src="https://www.w3schools.com/tags/movie.mp4" type="video/mp4"> -->
<source type="video/mp4"
src="https://player.vimeo.com/progressive_redirect/playback/671122426/rendition/720p?loc=external&signature=e1562e4b2a73a9f37492359547fef09f8a3ed47a9d12fd77089930fc656a7d8e"
>

Your browser doesn't support HTML5 video tag.
</video>

</div>
</div>

<script>

window.addEventListener( "load", on_documentReady );

function on_documentReady()
{
    //const myTargets = document.getElementsByClassName("playonhover");
    const myTargets = document.getElementsByClassName("project-link-block");

    for (var i = 0; i < myTargets.length; i++)
    {
        myTargets[i].onmouseover = handle_mouseOver;
        myTargets[i].onmouseout = handle_mouseOut;
    }
}

function handle_mouseOver( evt )
{
    //alert( "## was rolled over" );
    evt.target.play();
}

function handle_mouseOut( evt )
{
    //alert( "## was rolled out" );
    evt.target.pause();
}

</script>

</body>
</html>


问:
LEFT JOIN not working if I use WHERE condition
I have two table called tbl_calendar and tbl_affiliates_link_history, tbl_calendar I am using for fill missing dates in result.
If I use query like below its work fine

```<code>SELECT dates as date,COUNT(a.id)AS total_visits FROM tbl_calendar as c LEFT JOIN tbl_affiliates_link_history as a ON c.dates = DATE(a.link_visit_time) WHERE c.dates > '2022-02-01' AND c.dates < '2022-02-13' GROUP BY c.dates
</code>```

and giving me result like below

But if I add one additional where condition in my query called a.affiliate_id='wilson'

It's giving me only one result instead of full result like first image

My second query is like this

```<code>SELECT dates as date,COUNT(a.id)AS total_visits FROM tbl_calendar as c LEFT JOIN tbl_affiliates_link_history as a ON c.dates = DATE(a.link_visit_time) WHERE c.dates > '2022-02-01' AND c.dates < '2022-02-13'AND a.affiliate_id='wilson' GROUP BY c.dates
</code>```

答:
According to the LEFT JOIN properties, if the record doesn't join with another record into the joining table, all fields of the logical table created with the join are NULL.

This means if you search anything on the joined table on NULL field the search automatically excludes the NULL fields and at this point you are using the LEFT JOIN as an INNER JOIN.

To solve this, you need to add  OR field IS NULL to the WHERE condition to keep the NULL results. The second query should be:

```<code>SELECT dates as date, COUNT(a.id) AS total_visits
FROM tbl_calendar as c
LEFT JOIN tbl_affiliates_link_history as a ON c.dates = DATE(a.link_visit_time)
WHERE c.dates > '2022-02-01' AND c.dates < '2022-02-13' AND
      (a.affiliate_id='wilson' OR a.affiliate_id IS NULL)
GROUP BY c.dates
</code>```

Body:
I have two table called tbl_calendar and tbl_affiliates_link_history, tbl_calendar I am using for fill missing dates in result.
If I use query like below its work fine

SELECT dates as date,COUNT(a.id)AS total_visits FROM tbl_calendar as c LEFT JOIN tbl_affiliates_link_history as a ON c.dates = DATE(a.link_visit_time) WHERE c.dates > '2022-02-01' AND c.dates < '2022-02-13' GROUP BY c.dates

and giving me result like below

But if I add one additional where condition in my query called a.affiliate_id='wilson'

It's giving me only one result instead of full result like first image

My second query is like this

SELECT dates as date,COUNT(a.id)AS total_visits FROM tbl_calendar as c LEFT JOIN tbl_affiliates_link_history as a ON c.dates = DATE(a.link_visit_time) WHERE c.dates > '2022-02-01' AND c.dates < '2022-02-13'AND a.affiliate_id='wilson' GROUP BY c.dates

Body:
According to the LEFT JOIN properties, if the record doesn't join with another record into the joining table, all fields of the logical table created with the join are NULL.

This means if you search anything on the joined table on NULL field the search automatically excludes the NULL fields and at this point you are using the LEFT JOIN as an INNER JOIN.

To solve this, you need to add  OR field IS NULL to the WHERE condition to keep the NULL results. The second query should be:

SELECT dates as date, COUNT(a.id) AS total_visits
FROM tbl_calendar as c
LEFT JOIN tbl_affiliates_link_history as a ON c.dates = DATE(a.link_visit_time)
WHERE c.dates > '2022-02-01' AND c.dates < '2022-02-13' AND
      (a.affiliate_id='wilson' OR a.affiliate_id IS NULL)
GROUP BY c.dates


问:
css - centering ul li in mobile

I want to center li in ul.
It looks centered but slightly not.
Left portion and Right portion is not exactly same.

How can I fix this problem?

.test-box {
  border: 1px solid blue;
}

.test-ul {
  text-align: center;
  list-style-type: none;
  border: 1px solid red;
}

.test-li {
  display: inline-block;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test-box">
  <ul class="test-ul">
    <li class="test-li">real time</li>
    <li class="test-li">real time</li>
  </ul>
</div></code>```

答:
 elements have left padding by default.

```<code>.test-ul
{
    padding-left: 0;
}
</code>```

.test-box {
  border: 1px solid blue;
}

.test-ul {
  text-align: center;
  list-style-type: none;
  border: 1px solid red;
  padding-left: 0;
}

.test-li {
  display: inline-block;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test-box">
  <ul class="test-ul">
    <li class="test-li">real time</li>
    <li class="test-li">real time</li>
  </ul>
</div></code>```

vs

Title: css - centering ul li in mobile

Body:
I want to center li in ul.
It looks centered but slightly not.
Left portion and Right portion is not exactly same.

How can I fix this problem?

.test-box {
  border: 1px solid blue;
}

.test-ul {
  text-align: center;
  list-style-type: none;
  border: 1px solid red;
}

.test-li {
  display: inline-block;
  border: 1px solid green;
}

real time

real time

Body:
<ul> elements have left padding by default.

.test-ul
{
    padding-left: 0;
}

.test-box {
  border: 1px solid blue;
}

.test-ul {
  text-align: center;
  list-style-type: none;
  border: 1px solid red;
  padding-left: 0;
}

.test-li {
  display: inline-block;
  border: 1px solid green;
}

<div class="test-box">
  <ul class="test-ul">
    <li class="test-li">real time</li>
    <li class="test-li">real time</li>
  </ul>
</div>

vs


问:
Eclipse: exporting configurations from one workspace to another
There is a lot of effort involved in configuring the checkstyle/findbug/codestyle etc in a workspace, so repeating the same for another workspace consumes a lot of time.

Is there any way in which I can simply export the preferences from one workspace to another in eclipse ?

答: Some (but unfortunately not all) of the settings you mention can be exported to and imported from an xml file.</p>


问:
How do I generate a random sample of data in SPARQL?
Is it possible to generate a random sample of triples using SPARQL?
I thought it might be via the SAMPLE function but this returns a single SAMPLE.

My workaround would be to generate a random number to use with the OFFSET keyword and use the LIMIT keyword to return the desired sample size. I'll just hardcode the random number for offset to 200 for ease like so:

```<code>SELECT *
WHERE {
?s ?p ?o
}
OFFSET 200 #random number variable
LIMIT 100
</code>```

Any better suggestions to generate a random sample of 100 data triples from a  SPARQL endpoint?

答:
The accepted answer may work but is not optimal as the suggested approach may lead to errors on some triple stores (e.g. on Apache Jena).

As pointed out in the ticket and by @Joshua-Taylor in the comment section above, a better answer is:

```<code>SELECT ... WHERE
{
  ...
  BIND(RAND() AS ?sortKey)
} ORDER BY ?sortKey ...
</code>```

Body:
Is it possible to generate a random sample of triples using SPARQL?
I thought it might be via the SAMPLE function but this returns a single SAMPLE.

My workaround would be to generate a random number to use with the OFFSET keyword and use the LIMIT keyword to return the desired sample size. I'll just hardcode the random number for offset to 200 for ease like so:

SELECT *
WHERE {
?s ?p ?o
}
OFFSET 200 #random number variable
LIMIT 100

Any better suggestions to generate a random sample of 100 data triples from a  SPARQL endpoint?

Body:
The accepted answer may work but is not optimal as the suggested approach may lead to errors on some triple stores (e.g. on Apache Jena).

As pointed out in the ticket and by @Joshua-Taylor in the comment section above, a better answer is:

SELECT ... WHERE
{
  ...
  BIND(RAND() AS ?sortKey)
} ORDER BY ?sortKey ...


问:
Flutter downloader fails everytime. Sometimes there is a progress of 97
I try to download a image from a website with the help of flutter_downloader. The download fails everytime immediately after starting. I dont know why.

I tried to keep the code as small as possible so somethings are missing but they arent important for my problem
This is my code:

```<code>int progress = 0;
ReceivePort receivePort = ReceivePort();

@override
void initState() {
  IsolateNameServer.registerPortWithName(receivePort.sendPort, "downloadingvideo");
  receivePort.listen((dynamic data) {
    String id = data[0];
    DownloadTaskStatus status =
    data[1]; int progress = data[2];
    print("Id: ${id}, Status: ${status}, Progress: ${progress},");
  });
  FlutterDownloader.registerCallback(downloadCallback);
  // TODO: implement initState
  super.initState();
}
@override
void dispose() {
  IsolateNameServer.removePortNameMapping("downloadingvideo");
  super.dispose();
}
static downloadCallback(String id, DownloadTaskStatus status, int progress){
  final SendPort sendPort = IsolateNameServer.lookupPortByName("downloadingvideo")!;
  sendPort.send([id, status, progress]);
}
void _download(String url, String title) async {
  final status = await Permission.storage.request();
  if(status.isGranted){
    final externalDir = await getExternalStorageDirectory();
    final id = await FlutterDownloader.enqueue(
      url: url, savedDir: externalDir!.path,
      fileName: title,
      showNotification: true,
      openFileFromNotification: true,
      saveInPublicStorage: true,
    );
} else{
  print("Permission denied!");
}
}
@override
Widget build(BuildContext context) {
  return Center(
    child: Container(
      child: FlatButton(
        onPressed: () {
           _download("https://www.bergfreunde.de/out/pictures/promo/bs-teaser_y22_1.jpg", "name.png");
        },
      child: Text("Download"),
     ),
    )
   );
  }
}
</code>```

This is the new error I get:

```<code>W/System.err(21506): java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.example.musicanywhere_app.flutter_downloader.provider
W/System.err(21506):    at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:662)
W/System.err(21506):    at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:635)
W/System.err(21506):    at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:441)
W/System.err(21506):    at vn.hunghd.flutterdownloader.IntentUtils.buildIntent(IntentUtils.java:23)
W/System.err(21506):    at vn.hunghd.flutterdownloader.IntentUtils.validatedFileIntent(IntentUtils.java:35)
W/System.err(21506):    at vn.hunghd.flutterdownloader.DownloadWorker.downloadFile(DownloadWorker.java:441)
W/System.err(21506):    at vn.hunghd.flutterdownloader.DownloadWorker.doWork(DownloadWorker.java:235)
W/System.err(21506):    at androidx.work.Worker$1.run(Worker.java:86)
W/System.err(21506):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err(21506):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err(21506):    at java.lang.Thread.run(Thread.java:923)
I/WM-WorkerWrapper(21506): Worker result FAILURE for Work [ id=54727eb0-aa34-4bc5-94fd-558debd43804, tags={ flutter_download_task, vn.hunghd.flutterdownloader.DownloadWorker } ]
</code>```

Thanks for your help.

答:
The error in your stack trace reads:

java.net.MalformedURLException: no protocol:
musikschulemarsulm.de/static/css/marsheader_white_smal.png

And in your code you have:

```<code>_download("musikschulemarsulm.de/static/css/marsheader_white_smal.png", "name.png");
</code>```

There needs to be a protocol for the url you are giving for the image.

You are either missing http or https from the url.

```<code>_download("https://musikschulemarsulm.de/static/css/marsheader_white_smal.png", "name.png");
</code>```

Body:
I try to download a image from a website with the help of flutter_downloader. The download fails everytime immediately after starting. I dont know why.

I tried to keep the code as small as possible so somethings are missing but they arent important for my problem
This is my code:

int progress = 0;
ReceivePort receivePort = ReceivePort();

@override
void initState() {
  IsolateNameServer.registerPortWithName(receivePort.sendPort, "downloadingvideo");
  receivePort.listen((dynamic data) {
    String id = data[0];
    DownloadTaskStatus status =
    data[1]; int progress = data[2];
    print("Id: ${id}, Status: ${status}, Progress: ${progress},");
  });
  FlutterDownloader.registerCallback(downloadCallback);
  // TODO: implement initState
  super.initState();
}
@override
void dispose() {
  IsolateNameServer.removePortNameMapping("downloadingvideo");
  super.dispose();
}
static downloadCallback(String id, DownloadTaskStatus status, int progress){
  final SendPort sendPort = IsolateNameServer.lookupPortByName("downloadingvideo")!;
  sendPort.send([id, status, progress]);
}
void _download(String url, String title) async {
  final status = await Permission.storage.request();
  if(status.isGranted){
    final externalDir = await getExternalStorageDirectory();
    final id = await FlutterDownloader.enqueue(
      url: url, savedDir: externalDir!.path,
      fileName: title,
      showNotification: true,
      openFileFromNotification: true,
      saveInPublicStorage: true,
    );
} else{
  print("Permission denied!");
}
}
@override
Widget build(BuildContext context) {
  return Center(
    child: Container(
      child: FlatButton(
        onPressed: () {
           _download("https://www.bergfreunde.de/out/pictures/promo/bs-teaser_y22_1.jpg", "name.png");
        },
      child: Text("Download"),
     ),
    )
   );
  }
}

This is the new error I get:

W/System.err(21506): java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.example.musicanywhere_app.flutter_downloader.provider
W/System.err(21506):    at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:662)
W/System.err(21506):    at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:635)
W/System.err(21506):    at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:441)
W/System.err(21506):    at vn.hunghd.flutterdownloader.IntentUtils.buildIntent(IntentUtils.java:23)
W/System.err(21506):    at vn.hunghd.flutterdownloader.IntentUtils.validatedFileIntent(IntentUtils.java:35)
W/System.err(21506):    at vn.hunghd.flutterdownloader.DownloadWorker.downloadFile(DownloadWorker.java:441)
W/System.err(21506):    at vn.hunghd.flutterdownloader.DownloadWorker.doWork(DownloadWorker.java:235)
W/System.err(21506):    at androidx.work.Worker$1.run(Worker.java:86)
W/System.err(21506):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err(21506):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err(21506):    at java.lang.Thread.run(Thread.java:923)
I/WM-WorkerWrapper(21506): Worker result FAILURE for Work [ id=54727eb0-aa34-4bc5-94fd-558debd43804, tags={ flutter_download_task, vn.hunghd.flutterdownloader.DownloadWorker } ]

Thanks for your help.

Body:
The error in your stack trace reads:

java.net.MalformedURLException: no protocol:
musikschulemarsulm.de/static/css/marsheader_white_smal.png

And in your code you have:

_download("musikschulemarsulm.de/static/css/marsheader_white_smal.png", "name.png");

There needs to be a protocol for the url you are giving for the image.

You are either missing http or https from the url.

_download("https://musikschulemarsulm.de/static/css/marsheader_white_smal.png", "name.png");


问:
shorter way to pause a video if it is fully out of view
I have this code to pause a video if it is fully out of view

it works, but I want to make it shorter

for example, to avoid  forEach loop, because this is the only video on page

also - maybe to avoid a separate modify function - but place el.pause() inside the first block of js code

I tried on various ways and getting various errors in console

pls help

```<code><video id='vsingle' src='lorem.mp4' poster='lorem.jpg' controls></video>

let io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if(!entry.isIntersecting){modify(entry.target);}
  });
});

function modify(el){el.pause();}

$(document).ready(function(){
  io.observe(document.querySelector('#vsingle'));
});
</code>```

答:
You could simplify this code a little by removing the modify function:

```<code>let io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if(!entry.isIntersecting){
      entry.target.pause()
    }
  });
});
</code>```

Body:
I have this code to pause a video if it is fully out of view

it works, but I want to make it shorter

for example, to avoid  forEach loop, because this is the only video on page

also - maybe to avoid a separate modify function - but place el.pause() inside the first block of js code

I tried on various ways and getting various errors in console

pls help

<video id='vsingle' src='lorem.mp4' poster='lorem.jpg' controls></video>

let io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if(!entry.isIntersecting){modify(entry.target);}
  });
});

function modify(el){el.pause();}

$(document).ready(function(){
  io.observe(document.querySelector('#vsingle'));
});

Body:
You could simplify this code a little by removing the modify function:

let io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if(!entry.isIntersecting){
      entry.target.pause()
    }
  });
});


问:
How do I get hex blocks from a base 64 encoded string?
In this article and this XKCD, they both show the password data as groupings of hexadecimal.

However, in the file it's base64 encoded. What could I use to match that output with bash scripting? I've tried:

```<code>echo -n "7WkoOEfwfTTioxG6CatHBw==" | base64 -d
echo -n "7WkoOEfwfTTioxG6CatHBw==" | openssl enc -d -base64
</code>```

What is it they are doing, and how do I decode them to hex blocks?

答:
Output the hex code without newline:

echo "<BASE64>" | base64 -d | hexdump -v -e '/1 "%02x" '

Body:
In this article and this XKCD, they both show the password data as groupings of hexadecimal.

However, in the file it's base64 encoded. What could I use to match that output with bash scripting? I've tried:

echo -n "7WkoOEfwfTTioxG6CatHBw==" | base64 -d
echo -n "7WkoOEfwfTTioxG6CatHBw==" | openssl enc -d -base64

What is it they are doing, and how do I decode them to hex blocks?


问:
Remove Kubernetes Readiness Probe
My deployment had a readinessProbe configured like:

```<code> readinessProbe:
    port: 8080
    path: /ready
    initialDelaySeconds: 30
    failureThreshold: 60
    periodSeconds: 10
    timeoutSeconds: 15
</code>```

I want to remove the probe for some reason. However, after removing it from my YML file my deployment is not successful because look like the pod is never considered ready. Checking in GCP I discover that the result YML file has a readiness probe that points to some "default values" that I haven't set nowhere:

```<code>    readinessProbe:
      failureThreshold: 3
      httpGet:
        path: /ready
        port: 80
        scheme: HTTP
      initialDelaySeconds: 5
      periodSeconds: 10
      successThreshold: 1
      timeoutSeconds: 5
</code>```

Is there a way to actually remove a ReadinessProbe for good?

答:
One possible way to remove the probe would be to modify changes to the configuration file(yaml file) and disable the Readiness Probe.

You can do this, by adding enabled: false to the configuration file. For example,

```<code>readinessProbe:
   enabled: false
   path: /ready
   initialDelaySeconds: 30
   failureThreshold: 60
   periodSeconds: 10
   timeoutSeconds: 15
</code>```

If you are unable to modify the configuration file then, as mentioned by @G. Rafael try re-creating the deployment and apply the deployment configuration file to the cluster.

Title: Remove Kubernetes Readiness Probe

Body:
My deployment had a readinessProbe configured like:

 readinessProbe:
    port: 8080
    path: /ready
    initialDelaySeconds: 30
    failureThreshold: 60
    periodSeconds: 10
    timeoutSeconds: 15

I want to remove the probe for some reason. However, after removing it from my YML file my deployment is not successful because look like the pod is never considered ready. Checking in GCP I discover that the result YML file has a readiness probe that points to some "default values" that I haven't set nowhere:

    readinessProbe:
      failureThreshold: 3
      httpGet:
        path: /ready
        port: 80
        scheme: HTTP
      initialDelaySeconds: 5
      periodSeconds: 10
      successThreshold: 1
      timeoutSeconds: 5

Is there a way to actually remove a ReadinessProbe for good?

Body:
One possible way to remove the probe would be to modify changes to the configuration file(yaml file) and disable the Readiness Probe.

You can do this, by adding enabled: false to the configuration file. For example,

readinessProbe:
   enabled: false
   path: /ready
   initialDelaySeconds: 30
   failureThreshold: 60
   periodSeconds: 10
   timeoutSeconds: 15

If you are unable to modify the configuration file then, as mentioned by @G. Rafael try re-creating the deployment and apply the deployment configuration file to the cluster.


问:
Error: "SDK emulator directory is missing" in Android Studio on Linux
I'm trying to install android studio on linux manjaro but it shows me following error:

SDK emulator directory is missing

How i can to fix it?

The error mesage:

答:
My problem is that I was using a wrong proxy.

disable internet

open android studio

it would be a pop up for "setup proxy"

choose "no proxy"

enable internet

start android studio


问:
collision detection code in pygame doesn't work properly
I am working on a game based on a 1973 arcade game called space race (more info: https://en.wikipedia.org/wiki/Space_Race_(video_game)) using pygame, but it doesn't give the results I expected. it is supposed to send the player's rocket back to the spawning point when it collides with an asteroid, it doesn't give any syntax errors, but it still goes right through the rocket.

I've tried messing around with the code, however, it still won't do what I want it to.

Here is the code for the whole program.

```<code>import random as r
import pygame as pg
pg.init ()

screen = pg.display.set_mode ((960, 720))

pg.display.set_caption ("space race!")
icon = pg.image.load ("icon.png")
pg.display.set_icon (icon)

score1num = 0
font1 = pg.font.Font ("freesansbold.ttf", 50)

score2num = 0
font2 = pg.font.Font ("freesansbold.ttf", 50)

player1_img = pg.image.load ("player1.png")
player1_x = 430
player1_y = 580
player1_y_change = 0

player2_img = pg.image.load ("player2.png")
player2_x = 530
player2_y = 580
player2_y_change = 0

timer_img = pg.image.load ("timer.png")
timer_x = 480
timer_y = 0
timer_y_change = 0.02

bullet1_img = pg.image.load ("bullet.png")
bullet1_x = 480
bullet1_y = 0
bullet1_x_change = -0.5

def player1 (x, y):
    screen.blit (player1_img, (x, y))

def player2 (x, y):
    screen.blit (player2_img, (x, y))

def score1 (x, y):
    display_score = font1.render("wasd score: " + str(score1num), True, (255, 255, 255))
    screen.blit(display_score, (x, y))

def score2 (x, y):
    display_score = font2.render("ijkl score: " + str(score2num), True, (255, 255, 255))
    screen.blit(display_score, (x, y))

def timer (x, y):
    screen.blit (timer_img, (x, y))

def bullet1 (x, y):
    screen.blit (bullet1_img, (x, y))

def gameover (x, y):
    gameoverfont = pg.font.Font ("freesansbold.ttf", 100)
    display_gameover = gameoverfont.render ("game over!", True, (255, 255, 255))
    screen.blit (display_gameover, (x, y))

execute = True
while execute:
    screen.fill ((0, 0, 0))
    for event in pg.event.get ():
        if event.type == pg.QUIT:
            execute = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_w:
                player1_y_change = -0.5

            if event.key == pg.K_s:
                player1_y_change = 0.5

            if event.key == pg.K_i:
                player2_y_change = -0.5

            if event.key == pg.K_k:
                player2_y_change = 0.5

        if event.type == pg.KEYUP:
            player1_y_change = 0
            player2_y_change = 0

    if timer_y >= 720:
        break
    if player1_y > 592:
        player1_y = 592
    if player2_y > 592:
        player2_y = 592
    if player1_y < -64:
        player1_y = 580
        score1num = score1num + 1
    if player2_y < -64:
        player2_y = 580
        score2num = score2num + 1

    if bullet1_x == 0:
        bullet1_x = 960
        bullet1_y = r.randint (10, 550)

    if player1_x >= bullet1_x and player1_y >= bullet1_y:
        if player1_x + 32 <= bullet1_x + 25 and player1_y + 128 <= bullet1_y + 25:
            player1_y = 580

    player1 (player1_x, player1_y)
    player2 (player2_x, player2_y)
    timer (timer_x, timer_y)
    score1 (100, 100)
    score2 (560, 100)
    bullet1 (bullet1_x, bullet1_y)

    player1_y = player1_y + player1_y_change
    player2_y = player2_y + player2_y_change
    timer_y = timer_y + timer_y_change
    bullet1_x = bullet1_x + bullet1_x_change
    pg.display.update ()

while execute:
    screen.fill ((0, 0, 0))
    for event in pg.event.get ():
        if event.type == pg.QUIT:
            execute = False
    gameover (220, 360)
    pg.display.update ()

</code>```

also the sizes of the images:
player1 and player2 - 32x128,
timer - 25x960,
bullet - 25x25.

答:
To test if 2 rectangles (x1, y1, w1, h1) and (x2, y2, w2, h2) intersect you need to test if:

x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1
```
<p>In your code this means:</p>
<pre class="lang-py prettyprint-override"><code>if (player1_x < bullet1_x+25 and bullet1_x < player1_x + 32 and
    player1_y < player1_y+25 and bullet1_y < player1_y + 128):
    player1_y = 580
</code>```

However, see How do I detect collision in pygame? In pygame you can simplify this code with pygame.Rect objects and colliderect:

player_rect = pygame.Rect(player1_x, player1_y, 32, 128)
bullet_rect = pygame.Rect(bullet1_x, player1_y, 25, 25)
if player_rect.colliderect(bullet_rect):
    player1_y = 580
```

Body:
I am working on a game based on a 1973 arcade game called space race (more info: https://en.wikipedia.org/wiki/Space_Race_(video_game)) using pygame, but it doesn't give the results I expected. it is supposed to send the player's rocket back to the spawning point when it collides with an asteroid, it doesn't give any syntax errors, but it still goes right through the rocket.

I've tried messing around with the code, however, it still won't do what I want it to.

Here is the code for the whole program.

import random as r
import pygame as pg
pg.init ()

screen = pg.display.set_mode ((960, 720))

pg.display.set_caption ("space race!")
icon = pg.image.load ("icon.png")
pg.display.set_icon (icon)

score1num = 0
font1 = pg.font.Font ("freesansbold.ttf", 50)

score2num = 0
font2 = pg.font.Font ("freesansbold.ttf", 50)

player1_img = pg.image.load ("player1.png")
player1_x = 430
player1_y = 580
player1_y_change = 0

player2_img = pg.image.load ("player2.png")
player2_x = 530
player2_y = 580
player2_y_change = 0

timer_img = pg.image.load ("timer.png")
timer_x = 480
timer_y = 0
timer_y_change = 0.02

bullet1_img = pg.image.load ("bullet.png")
bullet1_x = 480
bullet1_y = 0
bullet1_x_change = -0.5

def player1 (x, y):
    screen.blit (player1_img, (x, y))

def player2 (x, y):
    screen.blit (player2_img, (x, y))

def score1 (x, y):
    display_score = font1.render("wasd score: " + str(score1num), True, (255, 255, 255))
    screen.blit(display_score, (x, y))

def score2 (x, y):
    display_score = font2.render("ijkl score: " + str(score2num), True, (255, 255, 255))
    screen.blit(display_score, (x, y))

def timer (x, y):
    screen.blit (timer_img, (x, y))

def bullet1 (x, y):
    screen.blit (bullet1_img, (x, y))

def gameover (x, y):
    gameoverfont = pg.font.Font ("freesansbold.ttf", 100)
    display_gameover = gameoverfont.render ("game over!", True, (255, 255, 255))
    screen.blit (display_gameover, (x, y))

execute = True
while execute:
    screen.fill ((0, 0, 0))
    for event in pg.event.get ():
        if event.type == pg.QUIT:
            execute = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_w:
                player1_y_change = -0.5

            if event.key == pg.K_s:
                player1_y_change = 0.5

            if event.key == pg.K_i:
                player2_y_change = -0.5

            if event.key == pg.K_k:
                player2_y_change = 0.5

        if event.type == pg.KEYUP:
            player1_y_change = 0
            player2_y_change = 0

    if timer_y >= 720:
        break
    if player1_y > 592:
        player1_y = 592
    if player2_y > 592:
        player2_y = 592
    if player1_y < -64:
        player1_y = 580
        score1num = score1num + 1
    if player2_y < -64:
        player2_y = 580
        score2num = score2num + 1

    if bullet1_x == 0:
        bullet1_x = 960
        bullet1_y = r.randint (10, 550)

    if player1_x >= bullet1_x and player1_y >= bullet1_y:
        if player1_x + 32 <= bullet1_x + 25 and player1_y + 128 <= bullet1_y + 25:
            player1_y = 580

    player1 (player1_x, player1_y)
    player2 (player2_x, player2_y)
    timer (timer_x, timer_y)
    score1 (100, 100)
    score2 (560, 100)
    bullet1 (bullet1_x, bullet1_y)

    player1_y = player1_y + player1_y_change
    player2_y = player2_y + player2_y_change
    timer_y = timer_y + timer_y_change
    bullet1_x = bullet1_x + bullet1_x_change
    pg.display.update ()

while execute:
    screen.fill ((0, 0, 0))
    for event in pg.event.get ():
        if event.type == pg.QUIT:
            execute = False
    gameover (220, 360)
    pg.display.update ()

also the sizes of the images:
player1 and player2 - 32x128,
timer - 25x960,
bullet - 25x25.

Body:
To test if 2 rectangles (x1, y1, w1, h1) and (x2, y2, w2, h2) intersect you need to test if:

x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1

In your code this means:

if (player1_x < bullet1_x+25 and bullet1_x < player1_x + 32 and
    player1_y < player1_y+25 and bullet1_y < player1_y + 128):
    player1_y = 580

However, see How do I detect collision in pygame? In pygame you can simplify this code with pygame.Rect objects and colliderect:

player_rect = pygame.Rect(player1_x, player1_y, 32, 128)
bullet_rect = pygame.Rect(bullet1_x, player1_y, 25, 25)
if player_rect.colliderect(bullet_rect):
    player1_y = 580


问:
How datacards receive value from listbox
I have two screens in powerapps, one is 'Port of Loading' and another is 'Editscreen1' for survey usage.

In 'port of loading', it will have a list of value in listbox3 which can pass the value to 'editscreen1' datacardvalue10.
Navigate(EditScreen1,ScreenTransition.None, {DataCardValue10:ListBox3.SelectedItems})

But my datacardvalue10 canot receive data from listbox3, how to solve it?

答:
You can’t set an item directly. Instead, try:

```<code>Navigate(
  YourPage,
  YourTransition,
  {
    ValueForCard: Gallery.selected
  }
)
</code>```

You data card should contain the ValueForCard variable as the default.

Body:
You can’t set an item directly. Instead, try:

Navigate(
  YourPage,
  YourTransition,
  {
    ValueForCard: Gallery.selected
  }
)

You data card should contain the ValueForCard variable as the default.


问:
The results of running `which $0` with bash and ./ are different, what causes this difference?
I have the following bash file (test_para.sh):

#!/bin/bash
echo $(dirname `which $0`)
```

When I run this file with bash test_para.sh, the terminal outputs the following errors:

dirname: missing operand

Try 'dirname --help' for more information.

However, when I run this bash scripts wiht ./test_para.sh, there is no error, and the output is .

As we all know, bash command and ./ command are both running in a child shell, why the running abovementioned scritp shows different results in these two ways?

答:
When you're trying to understand what's happening in a shell script, it's often helpful to put the command set -x before the problem section to see what's actually happening as the script runs. If you add that to your script (right after the shebang), and run it both ways, you'll see something like this:

```<code>$ ./test_para.sh
+++ which ./test_para.sh
++ dirname ./test_para.sh
+ echo .
.

$ bash test_para.sh
+++ which test_para.sh
++ dirname
dirname: missing operand
Try 'dirname --help' for more information.
+ echo
</code>```

The first run does pretty much what you probably expect -- $0 is "./test_para.sh", so which just prints that, dirname splits off the ".", and echo prints that (BTW, the echo $( ) thing is unnecessary and irrelevant -- I'll get back to this).

In the second run, $0 is just "test_para.sh", because that's the name you gave bash. But what which does is search the directories in $PATH for something by that name, and of course it's not in any of the PATH directories, it's in the current working directory. So which can't find it, and therefore doesn't print anything. dirname then complains that it wasn't given anything to get the directory part of, and you get that error (and no output).

The basic problem here is that which is not an all-purpose find-the-program tool, it specifically searches $PATH directories. Here's what its man page says:

which returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as  commands  in a strictly POSIX-conformant shell.  It does this by searching the PATH for executable files matching the names of the arguments.

..so if you execute a script in some other way (like with the bash command), it's not too surprising that it doesn't work.

If you're trying to find a general solution to locating the script's directory, it's actually surprisingly hard, and sometimes impossible (or even meaningless). See "How can I get the source directory of a Bash script from within the script itself?" and BashFAQ #28: "How do I determine the location of my script? I want to read some config files from the same place."

BTW, your script has several mistakes/bad practices; I recommend running it (and any other scripts you write) through shellcheck.net and fixing what it points out. In this script, you should use $( ) instead of backticks, double-quote variable and command substitutions, and don't use echo $( ) (the echo and the $( ) basically cancel each other out). Here's the script with these cleaned up (but the original problem still there):

```<code>#!/bin/bash
dirname "$(which "$0")"
</code>```

Body:
I have the following bash file (test_para.sh):

#!/bin/bash
echo $(dirname `which $0`)

When I run this file with bash test_para.sh, the terminal outputs the following errors:

dirname: missing operand

Try 'dirname --help' for more information.

However, when I run this bash scripts wiht ./test_para.sh, there is no error, and the output is .

As we all know, bash command and ./ command are both running in a child shell, why the running abovementioned scritp shows different results in these two ways?

Body:
When you're trying to understand what's happening in a shell script, it's often helpful to put the command set -x before the problem section to see what's actually happening as the script runs. If you add that to your script (right after the shebang), and run it both ways, you'll see something like this:

$ ./test_para.sh
+++ which ./test_para.sh
++ dirname ./test_para.sh
+ echo .
.

$ bash test_para.sh
+++ which test_para.sh
++ dirname
dirname: missing operand
Try 'dirname --help' for more information.
+ echo

The first run does pretty much what you probably expect -- $0 is "./test_para.sh", so which just prints that, dirname splits off the ".", and echo prints that (BTW, the echo $( ) thing is unnecessary and irrelevant -- I'll get back to this).

In the second run, $0 is just "test_para.sh", because that's the name you gave bash. But what which does is search the directories in $PATH for something by that name, and of course it's not in any of the PATH directories, it's in the current working directory. So which can't find it, and therefore doesn't print anything. dirname then complains that it wasn't given anything to get the directory part of, and you get that error (and no output).

The basic problem here is that which is not an all-purpose find-the-program tool, it specifically searches $PATH directories. Here's what its man page says:

which returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as  commands  in a strictly POSIX-conformant shell.  It does this by searching the PATH for executable files matching the names of the arguments.

..so if you execute a script in some other way (like with the bash command), it's not too surprising that it doesn't work.

If you're trying to find a general solution to locating the script's directory, it's actually surprisingly hard, and sometimes impossible (or even meaningless). See "How can I get the source directory of a Bash script from within the script itself?" and BashFAQ #28: "How do I determine the location of my script? I want to read some config files from the same place."

BTW, your script has several mistakes/bad practices; I recommend running it (and any other scripts you write) through shellcheck.net and fixing what it points out. In this script, you should use $( ) instead of backticks, double-quote variable and command substitutions, and don't use echo $( ) (the echo and the $( ) basically cancel each other out). Here's the script with these cleaned up (but the original problem still there):

#!/bin/bash
dirname "$(which "$0")"


问:
Is the Random Generator from Delphi the same calculation as C# if fed the same seed?
I'm translating some Delphi code into c# code when I ran into this. I don't have an environment setup for Delphi so I can't test it myself.

Delphi:

```<code>RandSeed := var1;
Result := Random($FF);
</code>```

c#:

```<code>Random RandSeed = new Random(var1);
Result = RandSeed.Next(255);
</code>```

Would these put the same value in Result? If not, any ideas on a way to do so?

答:
For Java Developers</p>

```<code>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.delphi;

/**
 *
 * @author ulmum
 * Using Code for C# from Barry Kelly http://stackoverflow.com/users/3712/barry-kelly
 */
class DelphiRandom {

    int _seed;

    public DelphiRandom(int seed) {
        _seed = seed;
    }

    int GetNext() // note: returns negative numbers too
    {
        _seed = _seed * 0x08088405 + 1;
        return _seed;
    }

    public int Next(int maxValue) {
        long result = (long) (int) GetNext() * (long) (int) maxValue;
        return ((int) (result >> 32) & 0xff); //Here Prevent Negative Numbers
    }
}

class App {

    public static void main(String[] args) {
        DelphiRandom r = new DelphiRandom(0);
        for (int i = 0; i < 10; ++i) {
            System.out.println(r.Next(256));
        }
    }
}
</code>```

OwnerDisplayName: GluedHands

ContentLicense: CC BY-SA 2.5

Body:
I'm translating some Delphi code into c# code when I ran into this. I don't have an environment setup for Delphi so I can't test it myself.

Delphi:

RandSeed := var1;
Result := Random($FF);

c#:

Random RandSeed = new Random(var1);
Result = RandSeed.Next(255);

Would these put the same value in Result? If not, any ideas on a way to do so?

LastEditorDisplayName: schnaader

Body:
For Java Developers

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.delphi;

/**
 *
 * @author ulmum
 * Using Code for C# from Barry Kelly http://stackoverflow.com/users/3712/barry-kelly
 */
class DelphiRandom {

    int _seed;

    public DelphiRandom(int seed) {
        _seed = seed;
    }

    int GetNext() // note: returns negative numbers too
    {
        _seed = _seed * 0x08088405 + 1;
        return _seed;
    }

    public int Next(int maxValue) {
        long result = (long) (int) GetNext() * (long) (int) maxValue;
        return ((int) (result >> 32) & 0xff); //Here Prevent Negative Numbers
    }
}

class App {

    public static void main(String[] args) {
        DelphiRandom r = new DelphiRandom(0);
        for (int i = 0; i < 10; ++i) {
            System.out.println(r.Next(256));
        }
    }
}


问:
Does using limit clause in pyspark reader always result in only 1 partition?
I have noticed that the output to the following code spark.read.format("csv").option("header",True).schema(schema).load(path).limit(nrows).rdd.getNumPartitions() is always 1 notwithstanding the argument nrows. Does using limit clause always result in only 1 partition?

I haven't been able to find anything mentioned about such constraint

答:
I don't understand the background of this. But for this statement, the result will always be 1 as you tried to collect result.

```<code>>>> df3.limit(1000000).explain()
== Physical Plan ==
CollectLimit 1000000
+- FileScan csv
</code>```

But for LimitExec which is physical leaf node for limit operation. It has several implementation such as GlobalLimitExec, LocalLimitExec. For some implementations, it could use same partition num to parrellel fetch enough records, or pick subsets of partitions iteratively. Generally, you don't need to care how is doing.

Body:
I don't understand the background of this. But for this statement, the result will always be 1 as you tried to collect result.

>>> df3.limit(1000000).explain()
== Physical Plan ==
CollectLimit 1000000
+- FileScan csv

But for LimitExec which is physical leaf node for limit operation. It has several implementation such as GlobalLimitExec, LocalLimitExec. For some implementations, it could use same partition num to parrellel fetch enough records, or pick subsets of partitions iteratively. Generally, you don't need to care how is doing.


问:
In Angular, how to pass value from one component to another when the components are not parent/child?
I am new in Angular2+ and reading a lot of materials inclusive of Angular site.

From angular, for parent/child we can use @Input()
https://angular.io/guide/template-syntax#input-and-output-properties

But in my code, I have two different modules, and each one has one component.

How to pass, object value from the component1 of the Module1 to the component2 of the Module2?

I have tried with @Input() but no success, and from the Argular link above @Input() refers to parent/child which this is not my case, well, from my understanding it's not :)

I can send through Route, string and number values, but not objects, that's the reason I need a different approach.

Thanks for any comments
Ademir

答:
Let's begin with creating a class (type);

This is a small example for people like me for whom it's difficult to understand the concept initially

Now let's create a service.

shared-data.service.ts

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { SharedData } from './sharedData';

@Injectable()
export class SharedDataService {
  sharedData: SharedData = { prop1: '', prop2: '' };
  private detailSource = new BehaviorSubject<SharedData>(this.sharedData);
  currentDetail = this.detailSource.asObservable();

  constructor() {}

  changeDetail(sharedData: SharedData) {
    this.detailSource.next(sharedData);
  }
}
</code>```

Now, we will create a component where from you will trigger the message, ( or the message/data that you want to pass on to another component..

space-one.component.ts

```<code>import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { SharedDataService } from '../shared/shared-data.service';
import { SharedData } from '../shared/sharedData';

@Component({
  selector: 'app-space-one',
  template: `<p>Component:1, button <br>
  <button (click)="passValue()">pass value</button>
  </p>`,
  styleUrls: ['./space-one.component.css'],
})
export class SpaceOneComponent implements OnInit, OnDestroy {

  constructor(private router: Router, private sharedDataService: SharedDataService) {}

  sharedData: SharedData;
  subscription: Subscription;

  ngOnInit() {
    this.subscription = this.sharedDataService.currentDetail.subscribe(message => this.sharedData =message)

  }

  passValue() {
    let newData = new SharedData();
    newData.prop1 = "new message 1";
    newData.prop2 = "new message 2";
    this.sharedDataService.changeDetail(newData);
    this.router.navigate(['spacetwo'])
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
</code>```

Now turn for the second component to receive the data,

space-two.component.ts

```<code>import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { SharedDataService } from '../shared/shared-data.service';
import { SharedData } from '../shared/sharedData';

@Component({
  selector: 'app-space-two',
  templateUrl: './space-two.component.html',
  styleUrls: ['./space-two.component.css'],
})
export class SpaceTwoComponent implements OnInit, OnDestroy {
  sharedData: SharedData;
  subscription: Subscription;
  //for elucidation only
  prop1: string;
  prop2: string;
  constructor(private sharedDataService: SharedDataService) {}

  ngOnInit() {
    this.subscription = this.sharedDataService.currentDetail.subscribe(
      (data) => (this.sharedData = data)
    );
    //for elucidation
    this.prop1 = this.sharedData.prop1;
    this.prop2 = this.sharedData.prop2;
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
</code>```

output as in stackblitz, a small fully functional, with routing enabled has been implemented here

Body:
Let's begin with creating a class (type);

This is a small example for people like me for whom it's difficult to understand the concept initially

Now let's create a service.

shared-data.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { SharedData } from './sharedData';

@Injectable()
export class SharedDataService {
  sharedData: SharedData = { prop1: '', prop2: '' };
  private detailSource = new BehaviorSubject<SharedData>(this.sharedData);
  currentDetail = this.detailSource.asObservable();

  constructor() {}

  changeDetail(sharedData: SharedData) {
    this.detailSource.next(sharedData);
  }
}

Now, we will create a component where from you will trigger the message, ( or the message/data that you want to pass on to another component..

space-one.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { SharedDataService } from '../shared/shared-data.service';
import { SharedData } from '../shared/sharedData';

@Component({
  selector: 'app-space-one',
  template: `<p>Component:1, button <br>
  <button (click)="passValue()">pass value</button>
  </p>`,
  styleUrls: ['./space-one.component.css'],
})
export class SpaceOneComponent implements OnInit, OnDestroy {

  constructor(private router: Router, private sharedDataService: SharedDataService) {}

  sharedData: SharedData;
  subscription: Subscription;

  ngOnInit() {
    this.subscription = this.sharedDataService.currentDetail.subscribe(message => this.sharedData =message)

  }

  passValue() {
    let newData = new SharedData();
    newData.prop1 = "new message 1";
    newData.prop2 = "new message 2";
    this.sharedDataService.changeDetail(newData);
    this.router.navigate(['spacetwo'])
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Now turn for the second component to receive the data,

space-two.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { SharedDataService } from '../shared/shared-data.service';
import { SharedData } from '../shared/sharedData';

@Component({
  selector: 'app-space-two',
  templateUrl: './space-two.component.html',
  styleUrls: ['./space-two.component.css'],
})
export class SpaceTwoComponent implements OnInit, OnDestroy {
  sharedData: SharedData;
  subscription: Subscription;
  //for elucidation only
  prop1: string;
  prop2: string;
  constructor(private sharedDataService: SharedDataService) {}

  ngOnInit() {
    this.subscription = this.sharedDataService.currentDetail.subscribe(
      (data) => (this.sharedData = data)
    );
    //for elucidation
    this.prop1 = this.sharedData.prop1;
    this.prop2 = this.sharedData.prop2;
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

output as in stackblitz, a small fully functional, with routing enabled has been implemented here


问:
The variable declared in for-loop of c++ is not initialised
```<code>#include <iostream>
#include <Windows.h>

void selection_sort(int*,int);
void output_array(int*, int);

int main() {
    using namespace std;
    int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
    int length = 10;

    selection_sort(numbers, length);
    output_array(numbers, length);

    Sleep(10000);
    return 0;
}

void output_array(int* start, int length) {
    for (int i = 0; i < length; i++) {
        std::cout << *(start + i) << " ";
    }
    std::cout << std::endl;
}

void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE
            *(start + k) = *(start + k + 1);
        }
        *(start + length - i) = max;
    }
}
</code>```

Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant?
Variables
Program at this step
This doesn't make sense to me.

When it comes to the second largest number, k behaves as expected.

答:
In the following line:

```<code>*(start + length - i) = max;
</code>```

i has the range 0 to length - 1 this means the above line evaluates at the extreme values of i to:

```<code>*(start + 1) = max;
</code>```

And:

```<code>*(start + length) = max;
</code>```

This means you both never write to the first element in your array and you also write after the last element in the array. The latter means your program has undefined behaviour, in this particular case as start is on the stack it will likely cause other variables on the stack to be corrupted.

The correct code is:

```<code>*(start + length - i - 1) = max;
</code>```

Which results in:

```<code>*(start) = max;
</code>```

And:

```<code>*(start + length - 1) = max;
</code>```

On an unrelated note you can also use the simpler syntax:

```<code>start[length - i - 1] = max;
</code>```

Body:
#include <iostream>
#include <Windows.h>

void selection_sort(int*,int);
void output_array(int*, int);

int main() {
    using namespace std;
    int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
    int length = 10;

    selection_sort(numbers, length);
    output_array(numbers, length);

    Sleep(10000);
    return 0;
}

void output_array(int* start, int length) {
    for (int i = 0; i < length; i++) {
        std::cout << *(start + i) << " ";
    }
    std::cout << std::endl;
}

void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE
            *(start + k) = *(start + k + 1);
        }
        *(start + length - i) = max;
    }
}

Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant?
Variables
Program at this step
This doesn't make sense to me.

When it comes to the second largest number, k behaves as expected.

Body:
In the following line:

*(start + length - i) = max;

i has the range 0 to length - 1 this means the above line evaluates at the extreme values of i to:

*(start + 1) = max;

And:

*(start + length) = max;

This means you both never write to the first element in your array and you also write after the last element in the array. The latter means your program has undefined behaviour, in this particular case as start is on the stack it will likely cause other variables on the stack to be corrupted.

The correct code is:

*(start + length - i - 1) = max;

Which results in:

*(start) = max;

And:

*(start + length - 1) = max;

On an unrelated note you can also use the simpler syntax:

start[length - i - 1] = max;


问:
Flutter- CSV file to Map
I need to convert a CSV file to a Map<String, String> and I'm using this package for the task. The problem is that the output of the map is returning a space before every key, as you can see:

```<code>{ 001: Visto de Trabalho,  002: Carta de Pesados,  003: Medicina do Trabalho,  004: Título de Residente]}
</code>```

This is my code:

```<code>HashMap _refHashMap;

Future<HashMap> convertCSV() async {
  _refHashMap = await CSV_HashMap().hashMapConvertor(
      refList: ["id", "name"], csvPath: 'assets/document_types.csv');

  return _refHashMap;
}

Map<String, String> loadDocTypes() {
  convertCSV();

  var ids = _refHashMap["id"];
  var names = _refHashMap["name"];

  var map = Map.fromIterables(ids, names);

  var convertedMap = Map<String, String>.from(map);

  return convertedMap;
}
</code>```

Can you help me?
Thank you in advance

答:
It can be done in such a simple way.

Not very elegant, but this will work as long as the CSV file is as expected by this algorithm (header and records).

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final data = _fast_csv.parse(_source);
  final keys = data.first;
  final list = data.skip(1).map((e) => Map.fromIterables(keys, e)).toList();
  print(list.first);
  print(list[1]['Name']);
}

const _source = '''
Name,Total Cores,Processor Base Frequency
"Intel® Celeron® Processor G530 2M Cache, 2.40 GHz",2,2.40 GHz
"Intel® Core™ i5-3470 Processor 6M Cache, up to 3.60 GHz",4,3.20 GHz
"Intel® Core™ i3-10100F Processor 6M Cache, up to 4.30 GHz",4,3.60 GHz
''';
```

Output:

{Name: Intel® Celeron® Processor G530 2M Cache, 2.40 GHz, Total Cores: 2, Processor Base Frequency: 2.40 GHz}
Intel® Core™ i5-3470 Processor 6M Cache, up to 3.60 GHz

Title: Flutter- CSV file to Map

Body:
I need to convert a CSV file to a Map<String, String> and I'm using this package for the task. The problem is that the output of the map is returning a space before every key, as you can see:

{ 001: Visto de Trabalho,  002: Carta de Pesados,  003: Medicina do Trabalho,  004: Título de Residente]}

This is my code:

HashMap _refHashMap;

Future<HashMap> convertCSV() async {
  _refHashMap = await CSV_HashMap().hashMapConvertor(
      refList: ["id", "name"], csvPath: 'assets/document_types.csv');

  return _refHashMap;
}

Map<String, String> loadDocTypes() {
  convertCSV();

  var ids = _refHashMap["id"];
  var names = _refHashMap["name"];

  var map = Map.fromIterables(ids, names);

  var convertedMap = Map<String, String>.from(map);

  return convertedMap;
}

Can you help me?
Thank you in advance

Body:
It can be done in such a simple way.

Not very elegant, but this will work as long as the CSV file is as expected by this algorithm (header and records).

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final data = _fast_csv.parse(_source);
  final keys = data.first;
  final list = data.skip(1).map((e) => Map.fromIterables(keys, e)).toList();
  print(list.first);
  print(list[1]['Name']);
}

const _source = '''
Name,Total Cores,Processor Base Frequency
"Intel® Celeron® Processor G530 2M Cache, 2.40 GHz",2,2.40 GHz
"Intel® Core™ i5-3470 Processor 6M Cache, up to 3.60 GHz",4,3.20 GHz
"Intel® Core™ i3-10100F Processor 6M Cache, up to 4.30 GHz",4,3.60 GHz
''';

Output:

{Name: Intel® Celeron® Processor G530 2M Cache, 2.40 GHz, Total Cores: 2, Processor Base Frequency: 2.40 GHz}
Intel® Core™ i5-3470 Processor 6M Cache, up to 3.60 GHz


问:
Uncaught (in promise) FirebaseError: Firebase Storage: Object 'images/38564af7conno.PNG' does not exist. (storage/object-not-found) react js
I am using react js to upload images in firebase alongside its post contents so far I have managed to upload an image and its doc but the problem is when I try to put image URL along doc it says the image does not exist and when I check back in my console account I find the uploaded image

down below is my upload codes

```<code>const createPost = async () => {
if(image == null){
  const cover = "default";
  await addDoc(postsCollectionRef, {
    title,
    postContent,
    created_at,
    cover,
    author: {name: auth.currentUser.displayName, id: auth.currentUser.uid}
  });
}else{
  const cover = addOn+image.name;
  const storage = getStorage();
  var storageRef = await ref(storage, `images/${cover}`);
  const upload = uploadBytesResumable(storageRef,image,image);
  upload.on("state_changed" , alert("success") , alert);
  await getDownloadURL(storageRef).then(function(url){
    console.log(url);

  addDoc(postsCollectionRef, {
    title,
    postContent,
    created_at,
    cover: {cover, url},
    author: {name: auth.currentUser.displayName, id: auth.currentUser.uid}
  });
  });
}
navigate("/");};
</code>```

If I can get relevant examples it will be very helpful some says that the problem is that i am calling url before the image is not upload so i tried to add await but still does not work

答:
Thanksful to image url
that i saw where the problem was it was so simple as I was not considering code flow arrangement

if you come across this problem know that you should take image url inside the then() function as you can see the chane in my codes below

```<code>else{
  const cover = addOn+image.name;
  const storage = getStorage();
  var storageRef = await ref(storage, `images/${cover}`);
  const upload = uploadBytesResumable(storageRef,image,image).then(
    () =>{
      getDownloadURL(storageRef).then(function(url){
        console.log(url);

      addDoc(postsCollectionRef, {
        title,
        postContent,
        created_at,
        cover: {cover, url},
        author: {name: auth.currentUser.displayName, id: auth.currentUser.uid}
      });
    }
  );
  });
}
</code>```

Thank you very much for the participating

Body:
I am using react js to upload images in firebase alongside its post contents so far I have managed to upload an image and its doc but the problem is when I try to put image URL along doc it says the image does not exist and when I check back in my console account I find the uploaded image

down below is my upload codes

const createPost = async () => {
if(image == null){
  const cover = "default";
  await addDoc(postsCollectionRef, {
    title,
    postContent,
    created_at,
    cover,
    author: {name: auth.currentUser.displayName, id: auth.currentUser.uid}
  });
}else{
  const cover = addOn+image.name;
  const storage = getStorage();
  var storageRef = await ref(storage, `images/${cover}`);
  const upload = uploadBytesResumable(storageRef,image,image);
  upload.on("state_changed" , alert("success") , alert);
  await getDownloadURL(storageRef).then(function(url){
    console.log(url);

  addDoc(postsCollectionRef, {
    title,
    postContent,
    created_at,
    cover: {cover, url},
    author: {name: auth.currentUser.displayName, id: auth.currentUser.uid}
  });
  });
}
navigate("/");};

If I can get relevant examples it will be very helpful some says that the problem is that i am calling url before the image is not upload so i tried to add await but still does not work

Body:
Thanksful to image url
that i saw where the problem was it was so simple as I was not considering code flow arrangement

if you come across this problem know that you should take image url inside the then() function as you can see the chane in my codes below

else{
  const cover = addOn+image.name;
  const storage = getStorage();
  var storageRef = await ref(storage, `images/${cover}`);
  const upload = uploadBytesResumable(storageRef,image,image).then(
    () =>{
      getDownloadURL(storageRef).then(function(url){
        console.log(url);

      addDoc(postsCollectionRef, {
        title,
        postContent,
        created_at,
        cover: {cover, url},
        author: {name: auth.currentUser.displayName, id: auth.currentUser.uid}
      });
    }
  );
  });
}

Thank you very much for the participating


问:
How do I apply opacity to a CSS color variable?
I am designing an app in electron, so I have access to CSS variables. I have defined a color variable in vars.css:

:root {
  --color: #f0f0f0;
}
```

<p>I want to use this color in <code>main.css</code>, but with some opacity applied:</p>

<pre class="lang-css prettyprint-override"><code>#element {
  background: (somehow use var(--color) at some opacity);
}
</code>```

How would I go about doing this? I am not using any preprocessor, only CSS. I would prefer an all-CSS answer, but I will accept JavaScript/jQuery.

I cannot use opacity because I am using a background image that should not be transparent.

答:
Relative color syntax

 caniuse support table

With this new CSS ability (css-color-5) which allows color format transformations, it also will also allow adding opacity to any color in any format, for example, to RGB (relative transformations can be done to any other format):

html { --color: blue }
.with-opacity { background: rgb(from var(--color) r g b / 50%) }
```

(As of writing, not yet available in browsers. Will update once arrives)

 Codepen demo

Body:
I am designing an app in electron, so I have access to CSS variables. I have defined a color variable in vars.css:

:root {
  --color: #f0f0f0;
}

I want to use this color in main.css, but with some opacity applied:

#element {
  background: (somehow use var(--color) at some opacity);
}

How would I go about doing this? I am not using any preprocessor, only CSS. I would prefer an all-CSS answer, but I will accept JavaScript/jQuery.

I cannot use opacity because I am using a background image that should not be transparent.

Body:
Relative color syntax

 caniuse support table

With this new CSS ability (css-color-5) which allows color format transformations, it also will also allow adding opacity to any color in any format, for example, to RGB (relative transformations can be done to any other format):

html { --color: blue }
.with-opacity { background: rgb(from var(--color) r g b / 50%) }

(As of writing, not yet available in browsers. Will update once arrives)

 Codepen demo