问:
React 17.0.1: Invalid hook call. Hooks can only be called inside of the body of a function component
Very new react user here. I have been troubleshooting this error for hours now. I previously had this component working as a class, but it seems everyone is migrating towards functional components lately, so I'm trying to convert it. I did an intermediate conversion without using state and it worked fine, but I am having trouble converting username and password to state values.

When I use the following code, I get an error:

```<code>Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
</code>```

I have read through the linked troubleshooting page multiple times, and tried fixing all three possible causes with no success.

I am using react 17.0.1 and react-dom 17.0.1 in my devDependencies.

I have installed the eslint-plugin-react-hooks rule to identify if I am not using hooks correctly in my functional component.

I have used npm ls react and npm ls react-dom to confirm I do not have duplicate react versions.

LoginForm.jsx

import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
const $ = require('jquery');

const LoginForm = ({ onToken }) => {

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const submit = (event) => {
        // DO NOT POST PARAMS
        event.preventDefault();
        // AJAX username and password
        const loginData = {
            username: username,
            password: password
        };
        const options = {
            url: 'api/login',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: JSON.stringify(loginData),
            success: (data) => {
                console.log(data);
                onToken(data.token);
            }
        };

        $.ajax(options);

        console.log('Submitted!');
    };

    return (
        <form onSubmit={submit}>
            Username:

            <input value={username} onChange={e => setUsername(e.target.value)} type="text" id="username" name="username"/>

            Password:

            <input value={password} onChange={e => setPassword(e.target.value)} type="password" id="password" name="password"/>

            <input type="submit" value="Login"/>
        </form>
    );
};

LoginForm.propTypes = {
    onToken: PropTypes.func
};

export default LoginForm;
```

I have created a branch on my project's repository so you can view any other information:

Branch: https://github.com/GibsDev/node-password-manager/tree/login-conversion

Commit: https://github.com/GibsDev/node-password-manager/commit/e0714b16bdbbf339fabf1aa4f6eefacd6d053427

答:
I got similar error in my repo. And it started appearing when I started bumping react from 16 to 17.
Later I realised its due to react16 is being pulled by the different dependency into node_modules and removing that fixed my issue</p>

Body:
Very new react user here. I have been troubleshooting this error for hours now. I previously had this component working as a class, but it seems everyone is migrating towards functional components lately, so I'm trying to convert it. I did an intermediate conversion without using state and it worked fine, but I am having trouble converting username and password to state values.

When I use the following code, I get an error:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

I have read through the linked troubleshooting page multiple times, and tried fixing all three possible causes with no success.

I am using react 17.0.1 and react-dom 17.0.1 in my devDependencies.

I have installed the eslint-plugin-react-hooks rule to identify if I am not using hooks correctly in my functional component.

I have used npm ls react and npm ls react-dom to confirm I do not have duplicate react versions.

LoginForm.jsx

import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
const $ = require('jquery');

const LoginForm = ({ onToken }) => {

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const submit = (event) => {
        // DO NOT POST PARAMS
        event.preventDefault();
        // AJAX username and password
        const loginData = {
            username: username,
            password: password
        };
        const options = {
            url: 'api/login',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: JSON.stringify(loginData),
            success: (data) => {
                console.log(data);
                onToken(data.token);
            }
        };

        $.ajax(options);

        console.log('Submitted!');
    };

    return (
        <form onSubmit={submit}>
            Username:

            <input value={username} onChange={e => setUsername(e.target.value)} type="text" id="username" name="username"/>

            Password:

            <input value={password} onChange={e => setPassword(e.target.value)} type="password" id="password" name="password"/>

            <input type="submit" value="Login"/>
        </form>
    );
};

LoginForm.propTypes = {
    onToken: PropTypes.func
};

export default LoginForm;

I have created a branch on my project's repository so you can view any other information:

Branch: https://github.com/GibsDev/node-password-manager/tree/login-conversion

Commit: https://github.com/GibsDev/node-password-manager/commit/e0714b16bdbbf339fabf1aa4f6eefacd6d053427


来源: stackexchange

问:
Set view as percentage of width in portrait and percentage of height in landscape, in interface builder using autolayout
I am creating a launch screen that has a centered image. I want the image to be 0.7 of the width in portrait orientation and 0.7 of the height in landscape orientation, so the image is the same size in both orientations, but relative to device size. It would be smaller on iPhones and larger on iPads, while supporting both orientations on iPad.

I can do one of those constraints but not both. For example, if I make it 0.7 of the width in portrait then it looks good in portrait but then oversized in landscape, and vice versa.

How do I create such autolayout purely in interface builder? (I'm assuming launch screens must only use IB.)

答:
The trick is to add two sets of proportional width and height constraints...

First:

centerX

centerY

1:1 aspect ratio

Then:

width <= 0.7 @1000

width = 0.7 @750

height <= 0.7 @1000

height = 0.7 @750

So our constraints are saying:

try to make width and height each at 70% -- Priority: 750 (High, but not Required)

but keep the image view at 1:1 ratio -- Priority: 1000 (Required)

and neither width nor height can be greater than 70% -- Priority: 1000 (Required)

Here's how it looks in the Document Outline pane:

and here's what we get for iPad 9.7":

and iPhone 11:

ContentLicense: CC BY-SA 4.0


问:
Extracting timezone in windows
I am fairly new to windows batch file and I need to extract the timezone value.Is there anyway I can just extract +5:30 from below  command ?
Or any other way that  just gives me the timezone in +05:30 format.

```<code>systeminfo | findstr /C:"Time Zone"
</code>```

Time Zone:                 (UTC+05:30) Chennai, Kolkata, Mumbai, New
  Delhi

I can't user powershell for it

答:
Using a WMI-query works way faster than using SYSTEMINFO, as SYSTEMINFO scans for way more information and only "timezone" (or "Zeitzone" or whatever it's named) is used later on. That's why you have to use FINDSTR to just filter for "timezone".
Using a WMI-query has the additional advantage that it's language-independant, so you don't have to make changes to cover "timezone", "Zeitzone", "zona horaria" or whatever language your OS happens to run at the moment.

```<code>@echo off

for /F "eol=; tokens=2 delims=^(^)" %%I in ('wmic timezone get caption /format:list') do (
   set "daUtcTimeZone=%%I"
)

rem remove "UTC" from string
set "daUtcBiasHHMM=%daUtcTimeZone:UTC=%"

echo daUtcTimeZone: %daUtcTimeZone%
echo daUtcBiasHHMM: %daUtcBiasHHMM%

PAUSE
</code>```

Result:

```<code>daUtcTimeZone: UTC+01:00
daUtcBiasHHMM: +01:00
</code>```

Querying all WMI-values from "timezone" you get even more options to chose from... have a look by replacing "caption" with an asterisk to see them all:

```<code>wmic timezone get * /format:list
</code>```

Result:

```<code>Bias=60
Caption=(UTC+01:00) Amsterdam, Berlin, Bern, Rom, Stockholm, Wien
DaylightBias=-60
DaylightDay=5
DaylightDayOfWeek=0
DaylightHour=2
DaylightMillisecond=0
DaylightMinute=0
DaylightMonth=3
DaylightName=Mitteleuropäische Sommerzeit
DaylightSecond=0
DaylightYear=0
Description=(UTC+01:00) Amsterdam, Berlin, Bern, Rom, Stockholm, Wien
SettingID=
StandardBias=0
StandardDay=5
StandardDayOfWeek=0
StandardHour=3
StandardMillisecond=0
StandardMinute=0
StandardMonth=10
StandardName=Mitteleuropäische Zeit
StandardSecond=0
StandardYear=0
</code>```

So you can as well get the bias in minutes for example using...

```<code>for /F "eol=; tokens=2 delims==" %%I in ('wmic timezone get bias /format:list') do (
   set "daBias=%%I"
)
echo daBias: %daBias%
</code>```

Result:

```<code>daBias: 60
</code>```

WMI / WMIC is available in Windows since "Windows 2000".

Title: Extracting timezone in windows

Body:
I am fairly new to windows batch file and I need to extract the timezone value.Is there anyway I can just extract +5:30 from below  command ?
Or any other way that  just gives me the timezone in +05:30 format.

systeminfo | findstr /C:"Time Zone"

Time Zone:                 (UTC+05:30) Chennai, Kolkata, Mumbai, New
  Delhi

I can't user powershell for it

Body:
Using a WMI-query works way faster than using SYSTEMINFO, as SYSTEMINFO scans for way more information and only "timezone" (or "Zeitzone" or whatever it's named) is used later on. That's why you have to use FINDSTR to just filter for "timezone".
Using a WMI-query has the additional advantage that it's language-independant, so you don't have to make changes to cover "timezone", "Zeitzone", "zona horaria" or whatever language your OS happens to run at the moment.

@echo off

for /F "eol=; tokens=2 delims=^(^)" %%I in ('wmic timezone get caption /format:list') do (
   set "daUtcTimeZone=%%I"
)

rem remove "UTC" from string
set "daUtcBiasHHMM=%daUtcTimeZone:UTC=%"

echo daUtcTimeZone: %daUtcTimeZone%
echo daUtcBiasHHMM: %daUtcBiasHHMM%

PAUSE

Result:

daUtcTimeZone: UTC+01:00
daUtcBiasHHMM: +01:00

Querying all WMI-values from "timezone" you get even more options to chose from... have a look by replacing "caption" with an asterisk to see them all:

wmic timezone get * /format:list

Result:

Bias=60
Caption=(UTC+01:00) Amsterdam, Berlin, Bern, Rom, Stockholm, Wien
DaylightBias=-60
DaylightDay=5
DaylightDayOfWeek=0
DaylightHour=2
DaylightMillisecond=0
DaylightMinute=0
DaylightMonth=3
DaylightName=Mitteleuropäische Sommerzeit
DaylightSecond=0
DaylightYear=0
Description=(UTC+01:00) Amsterdam, Berlin, Bern, Rom, Stockholm, Wien
SettingID=
StandardBias=0
StandardDay=5
StandardDayOfWeek=0
StandardHour=3
StandardMillisecond=0
StandardMinute=0
StandardMonth=10
StandardName=Mitteleuropäische Zeit
StandardSecond=0
StandardYear=0

So you can as well get the bias in minutes for example using...

for /F "eol=; tokens=2 delims==" %%I in ('wmic timezone get bias /format:list') do (
   set "daBias=%%I"
)
echo daBias: %daBias%

Result:

daBias: 60

WMI / WMIC is available in Windows since "Windows 2000".


问:
Output of this javascript and the reason
```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();
</code>```

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

答:
When executed, function getCtr returns an inner anonymous function.
This function is now referenced by variable ctr
Because the anonymous function was created inside getCtr it will have access to getCtr private scope object, which contains variable 'i'. This is known as a closure.

```<code>var ctr = getCtr()
</code>```

Every time the anonymous function is executed it pre-increments i, and writes in in the console.

```<code>ctr()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

Body:
When executed, function getCtr returns an inner anonymous function.
This function is now referenced by variable ctr
Because the anonymous function was created inside getCtr it will have access to getCtr private scope object, which contains variable 'i'. This is known as a closure.

var ctr = getCtr()

Every time the anonymous function is executed it pre-increments i, and writes in in the console.

ctr()


问:
'set' object has no attribute 'get' CSV (in praw)
This code is supposed to get some information about a post like title, upvotes etc. And then write it in a CSV file. But when is run it I get this error:

```<code>Traceback (most recent call last):
  File "main.py", line 71, in <module>
    writer.writerow(data)
  File "/usr/lib/python3.8/csv.py", line 154, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/usr/lib/python3.8/csv.py", line 151, in <genexpr>
    return (rowdict.get(key, self.restval) for key in self.fieldnames)
AttributeError: 'set' object has no attribute 'get'
</code>```

And this is the code:

```<code>    import praw
    import random
    import time
    import csv
    #from keep_Aliv import keep_alive

    username = "XXXXXX"

    #keep_alive()

    print('AAAAAAA')

    reddit = praw.Reddit(client_id="XXXXXX",
                         client_secret="XXXXXX",
                         user_agent="bot",
                         username=username,
                         password='XXXXXX')

    subreddit = reddit.subreddit('all')

   with open('pdata.csv', 'a') as f:
    headers = [
        'ID', 'Date_utc', 'Upvotes', 'Number of Comments', 'Subthread name'
    ]
    writer = csv.DictWriter(f,
                            fieldnames=headers,
                            extrasaction='ignore',
                            dialect='excel')
    writer.writeheader()
    for post in subreddit.stream.submissions():
        #print(post.title)

        data = {
                "ID": post.id,
                "Date_utc": post.created_utc,
                "Upvotes": post.ups,
                "Number of comments": post.num_comments,
                "Subthread name": post.title,
                }
        writer.writerow(data)
        print(data)
</code>```

ok, so how am I supposed to fix this? pls tell if some other information is required.

Thanks :)

(The main problem is now fixed and the compiler is not throwing an error now, but on the other hand the program isn't writing anything in the csv file. There isn't any error detected by the compiler but it's still not doing what it's supposed to. How do I fix that? btw the code in the post the working code)

答:
data does not appear to be in the correct format:

Try the following:

data = {
    'ID' : post,
    'Date_utc' : post.created_utc,
    'Upvotes' : post.ups,
    'Number of comments' : post.num_comments,
    'Subthread name' : post.title
}
```
<p>Note: when using a dictwriter, you should also open you file with the <code>newline</code> parameter as follows:</p>
```with open('pdata.csv', 'a', newline='') as f:
```

This avoids extra newlines in the output.

Body:
This code is supposed to get some information about a post like title, upvotes etc. And then write it in a CSV file. But when is run it I get this error:

Traceback (most recent call last):
  File "main.py", line 71, in <module>
    writer.writerow(data)
  File "/usr/lib/python3.8/csv.py", line 154, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/usr/lib/python3.8/csv.py", line 151, in <genexpr>
    return (rowdict.get(key, self.restval) for key in self.fieldnames)
AttributeError: 'set' object has no attribute 'get'

And this is the code:

    import praw
    import random
    import time
    import csv
    #from keep_Aliv import keep_alive

    username = "XXXXXX"

    #keep_alive()

    print('AAAAAAA')

    reddit = praw.Reddit(client_id="XXXXXX",
                         client_secret="XXXXXX",
                         user_agent="bot",
                         username=username,
                         password='XXXXXX')

    subreddit = reddit.subreddit('all')

   with open('pdata.csv', 'a') as f:
    headers = [
        'ID', 'Date_utc', 'Upvotes', 'Number of Comments', 'Subthread name'
    ]
    writer = csv.DictWriter(f,
                            fieldnames=headers,
                            extrasaction='ignore',
                            dialect='excel')
    writer.writeheader()
    for post in subreddit.stream.submissions():
        #print(post.title)

        data = {
                "ID": post.id,
                "Date_utc": post.created_utc,
                "Upvotes": post.ups,
                "Number of comments": post.num_comments,
                "Subthread name": post.title,
                }
        writer.writerow(data)
        print(data)

ok, so how am I supposed to fix this? pls tell if some other information is required.

Thanks :)

(The main problem is now fixed and the compiler is not throwing an error now, but on the other hand the program isn't writing anything in the csv file. There isn't any error detected by the compiler but it's still not doing what it's supposed to. How do I fix that? btw the code in the post the working code)

Body:
data does not appear to be in the correct format:

Try the following:

data = {
    'ID' : post,
    'Date_utc' : post.created_utc,
    'Upvotes' : post.ups,
    'Number of comments' : post.num_comments,
    'Subthread name' : post.title
}

Note: when using a dictwriter, you should also open you file with the newline parameter as follows:

with open('pdata.csv', 'a', newline='') as f:

This avoids extra newlines in the output.


问:
MongoDB group by and SUM by array
I'm new in mongoDB.

This is one example of record from collection:

```<code>  {
    supplier: 1,
    type: "sale",
    items: [
      {
        "_id": ObjectId("60ee82dd2131c5032342070f"),
        "itemBuySum": 10
      },
      {
        "_id": ObjectId("60ee82dd2131c50323420710"),
        "itemBuySum": 10,

      },
      {
        "_id": ObjectId("60ee82dd2131c50323420713"),
        "itemBuySum": 10
      },
      {
        "_id": ObjectId("60ee82dd2131c50323420714"),
        "itemBuySum": 20
      }
    ]
  }
</code>```

I need to group by TYPE field and get the SUM. This is output I need:

```<code>{
    supplier: 1,
    sales: 90,
    returns: 170
}
</code>```

please check Mongo playground for better understand. Thank you!

答:
```<code>db.collection.aggregate([
  {
    $match: {
      supplier: 1
    },

  },
  {
    "$group": {
      "_id": "$ID",
      "supplier": {
        "$first": "$supplier"
      },
      "sale": {
        "$sum": {
          "$cond": {
            "if": {
              "$eq": [
                "$type",
                "sale"
              ]
            },
            "then": {
              "$sum": "$items.itemBuySum"
            },
            "else": {
              "$sum": 0
            }
          }
        }
      },
      "returns": {
        "$sum": {
          "$sum": {
            "$cond": {
              "if": {
                "$eq": [
                  "$type",
                  "return"
                ]
              },
              "then": {
                "$sum": "$items.itemBuySum"
              },
              "else": {
                "$sum": 0
              }
            }
          }
        }
      }
    }
  },
  {
    "$project": {
      _id: 0,
      supplier: 1,
      sale: 1,
      returns: 1
    }
  }
])
</code>```

Title: MongoDB group by and SUM by array

Body:
I'm new in mongoDB.

This is one example of record from collection:

  {
    supplier: 1,
    type: "sale",
    items: [
      {
        "_id": ObjectId("60ee82dd2131c5032342070f"),
        "itemBuySum": 10
      },
      {
        "_id": ObjectId("60ee82dd2131c50323420710"),
        "itemBuySum": 10,

      },
      {
        "_id": ObjectId("60ee82dd2131c50323420713"),
        "itemBuySum": 10
      },
      {
        "_id": ObjectId("60ee82dd2131c50323420714"),
        "itemBuySum": 20
      }
    ]
  }

I need to group by TYPE field and get the SUM. This is output I need:

{
    supplier: 1,
    sales: 90,
    returns: 170
}

please check Mongo playground for better understand. Thank you!


问:
Installing python packages in Pycharm and cmd
I want to install a package in PyCharm and it cant be installed, so instead I install in the CMD in Windows with the same Python version that I set as interpreter in PyCharm. Now, when I want to import the package from inside PyCharm, it doesn't work but importing it from the Windows terminal works fine.

How can I connect the installed packages of python from the CMD to PyCharm ?

答:
Use "Add Interpreter" button that can be found at bottom left corner of your editor. In System Interpreter tab, Select or enter your python interpreter location (exe file). Make sure that Pycharm is not using a virtual environment.
This will make Pycharm use your default installation of python that runs in your cmd, this means that your installed packages will be usable in Pycharm.</p>


问:
How to set Strict-Transport-Header for GRPC services
I was checking Strict Transport Header which Http endpoint serving to UI enables.

Does it make sense to have the headers in the GRPC services not exposed to internet or serving to UI directly?

If so, what will be the way to enable Strict Transport Header for GRPC services?

I have seen that Grpc trailing-metadata headers can be sent with the response.

But is it the correct way to add the header?

The services are written in Go and I am using GRPC.

答:
HTTP Strict Transport Security (HSTS) is only useful if the client also supports it. gRPC clients don't, so adding such headers doesn't add any value.

The reason why HSTS is not useful if the client does not support it, is because the headers only say "you should only access this resource over HTTPS", but if the client just ignores that, it can continue to make plain HTTP requests (assuming the server supports both HTTP and HTTPS).

In addition, HSTS only works after the client accessed the resource at least once and remembered the headers it received at that time. This isn't true for most server-to-server communications.

If you want to ensure that data to/from your gRPC services and clients is encrypted, you can use SSL/TLS as shown on https://grpc.io/docs/guides/auth/#using-client-side-ssltls.


问:
how to avoid preloading in Ecto Query Elixir
I have a table GateReportSubclass (embeddings) and GateReportEvent (deliveries). A GateReportSubclass can have multiple GateReportEvents such as

```<code>  schema "deliveries" do
    field(:cameraex, :string)
    field(:arrived_at, :utc_datetime)
    field(:left_at, :utc_datetime)

    belongs_to(:embedding_in, GateReportSubclass, foreign_key: :embedding_id_in)
    belongs_to(:embedding_out, GateReportSubclass, foreign_key: :embedding_id_out)
  end
</code>```

and in GateReportSubclass

```<code>  schema "embeddings" do
    field(:cameraex, :string)
    field(:embeddings, :map)

    has_many(:in_deliveries, GateReportEvent, foreign_key: :embedding_id_in)
    has_many(:out_deliveries, GateReportEvent, foreign_key: :embedding_id_out)
  end
</code>```

so, in deliveries there can be embeddings's id in embedding_id_in/embedding_id_out.

I am trying to query deliveries with arrived_at or left_at to get a subclass that occurred on a specific date's event.

I have this query

```<code>GateReportSubclass
|> join(:left, [s], d in GateReportEvent,
  on: d.embedding_id_in == s.id or d.embedding_id_out == s.id
)
|> where([s], s.cameraex == ^exid)
|> where(
  query,
  [s, d],
  date_compare(^period, ^timezone, d.arrived_at, ^date) or
    date_compare(^period, ^timezone, d.left_at, ^date)
)
|> preload([:in_deliveries, :out_deliveries])
|> distinct([s], s.id)
|> select([:id, :class, :subclass, :cameraex, :features])
</code>```

now this query works all fine. BUT

A GateReportSubclass can occur in more than 10K GateReportEvents such as

GateReportSubclass

in_deliveries [10k GateReportEvent]

out_deliveries [15k GateReportEvent]

In such cases query is very slow. and I want to get the sum of in_deliveries and out_deliveries as well. for that, I am doing this

```<code>subclasses =
  data.items
  |> Enum.reduce([], fn subclass, acc ->
    %{in_deliveries: in_deliveries, out_deliveries: out_deliveries} = subclass
    occurances = Enum.count(in_deliveries) + Enum.count(out_deliveries)
    elem = subclass |> Map.from_struct() |> Map.put(:occurances, occurances)
    [acc | [elem]]
  end)
  |> List.flatten()
</code>```

I want to avoid this preload but also want to count the number of the total in and out events as well. Can you guide me in this, I hope I explained it well. Thanks in advance

```<code>Map.put(data, :items, subclasses)
</code>```

答:
If you don't need the GateReportEvents preloaded, then remove the |> preload([:in_deliveries, :out_deliveries]) from your query.  You can use aggregate functions in the select statement, which will perform the aggregation functions on the database server, and not in your application code.  This will be MUCH faster and more efficient.

You might want to try something like this:

```<code>
from(
   grs in GateReportSubclass,

   left_join: gre in GateReportEvent,
   on: gre.embedding_id_in == grs.id or gre.embedding_id_out == grs.id,

   where: grs.cameraex == ^exid
   where: # put your date filtering clause here,

   select: %{
     id: grs.id,
     in_count: filter(sum(1), not is_nil(gre.embedding_id_in)),
     out_count: filter(sum(1), not is_nil(gre.embedding_id_out))
  }
) |> Repo.one()
</code>```

This may need some tweaking as I cant test it, but seems like it should work.

Body:
I have a table GateReportSubclass (embeddings) and GateReportEvent (deliveries). A GateReportSubclass can have multiple GateReportEvents such as

  schema "deliveries" do
    field(:cameraex, :string)
    field(:arrived_at, :utc_datetime)
    field(:left_at, :utc_datetime)

    belongs_to(:embedding_in, GateReportSubclass, foreign_key: :embedding_id_in)
    belongs_to(:embedding_out, GateReportSubclass, foreign_key: :embedding_id_out)
  end

and in GateReportSubclass

  schema "embeddings" do
    field(:cameraex, :string)
    field(:embeddings, :map)

    has_many(:in_deliveries, GateReportEvent, foreign_key: :embedding_id_in)
    has_many(:out_deliveries, GateReportEvent, foreign_key: :embedding_id_out)
  end

so, in deliveries there can be embeddings's id in embedding_id_in/embedding_id_out.

I am trying to query deliveries with arrived_at or left_at to get a subclass that occurred on a specific date's event.

I have this query

GateReportSubclass
|> join(:left, [s], d in GateReportEvent,
  on: d.embedding_id_in == s.id or d.embedding_id_out == s.id
)
|> where([s], s.cameraex == ^exid)
|> where(
  query,
  [s, d],
  date_compare(^period, ^timezone, d.arrived_at, ^date) or
    date_compare(^period, ^timezone, d.left_at, ^date)
)
|> preload([:in_deliveries, :out_deliveries])
|> distinct([s], s.id)
|> select([:id, :class, :subclass, :cameraex, :features])

now this query works all fine. BUT

A GateReportSubclass can occur in more than 10K GateReportEvents such as

GateReportSubclass

in_deliveries [10k GateReportEvent]

out_deliveries [15k GateReportEvent]

In such cases query is very slow. and I want to get the sum of in_deliveries and out_deliveries as well. for that, I am doing this

subclasses =
  data.items
  |> Enum.reduce([], fn subclass, acc ->
    %{in_deliveries: in_deliveries, out_deliveries: out_deliveries} = subclass
    occurances = Enum.count(in_deliveries) + Enum.count(out_deliveries)
    elem = subclass |> Map.from_struct() |> Map.put(:occurances, occurances)
    [acc | [elem]]
  end)
  |> List.flatten()

I want to avoid this preload but also want to count the number of the total in and out events as well. Can you guide me in this, I hope I explained it well. Thanks in advance

Map.put(data, :items, subclasses)

Body:
If you don't need the GateReportEvents preloaded, then remove the |> preload([:in_deliveries, :out_deliveries]) from your query.  You can use aggregate functions in the select statement, which will perform the aggregation functions on the database server, and not in your application code.  This will be MUCH faster and more efficient.

You might want to try something like this:

from(
   grs in GateReportSubclass,

   left_join: gre in GateReportEvent,
   on: gre.embedding_id_in == grs.id or gre.embedding_id_out == grs.id,

   where: grs.cameraex == ^exid
   where: # put your date filtering clause here,

   select: %{
     id: grs.id,
     in_count: filter(sum(1), not is_nil(gre.embedding_id_in)),
     out_count: filter(sum(1), not is_nil(gre.embedding_id_out))
  }
) |> Repo.one()

This may need some tweaking as I cant test it, but seems like it should work.


问:
Axios post-request doesn't send complete object
I need to send an object including a base64-encoded image to an API-endpoint in TS. I use this code to convert a file to Base64 and attach it to an object:

```<code>const file = values.beleg1;
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = async function () {
                    const result = reader.result.toString().split(',')[1];
                    await valuesObj.push({ name: 'base64Image', value: result });

                };
                reader.onerror = function (error) {
                    console.log('Error: ', error);
                };
</code>```

If I then log the object 'valuesObj' it does show that the base64-object is attached to the main-object.

However when I then I then use this object in the request like in the code below it is not shown in the payload when looking at the network-request

```<code>axios({
                url: 'http://localhost:8080/createPDF',
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                responseType: 'blob',
                data: valuesObj,
            })
                .then((response: AxiosResponse) => {
                    setLoadingText('');
                    const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
                    const objectUrl: string = window.URL.createObjectURL(blob);
                    window.open(objectUrl);
                })
                .catch((error) => {
                    console.log(error);
                });
</code>```

What is the reason for this? Does it have anything to do with the length/size of the string? Or is there another reason?

答:
What is happening is the reader hasn't finished reading before the Axios call proceeds. The reader executes asynchronously. Thus, the order of operations often ends up something like this:

Start the read operation.

Attach event handler onloaded.

Start the Axios request, which is probably sent immediately at this point.

Complete the read operation.

Complete the Axios request.

Because you aren't waiting for the load event to finish before sending the Axios request, the request does not include the new data. You need to make sure the load event is finished and the data is pushed onto your array before you proceed with the Axios call.

```<code>try {
    const file = values.beleg1;
    const reader = new FileReader();
    reader.readAsDataURL(file);

    // construct a promise that will resolve once loading is complete,
    //   and then wait for it, so that we don't make the axios call until
    //   after the loading is done.
    await new Promise<void>((resolve, reject) => {
        reader.onload = function () {
            const result = reader.result.toString().split(',')[1];
            valuesObj.push({ name: 'base64Image', value: result });
            // notify that the promise has completed its work
            resolve();
        };

        reader.onerror = function () {
            // notify that the promise failed and pass along the error object
            reject(reader.error);
        };
    });

    // I picked any since I don't want to define out the full type, but you probably should
    const response: any = await axios({
        url: 'http://localhost:8080/createPDF',
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
        },
        responseType: 'blob',
        data: valuesObj,
    });

    setLoadingText('');
    const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
    const objectUrl: string = window.URL.createObjectURL(blob);
    window.open(objectUrl);
} catch (error) {
    // all errors during the processing are caught in one place
    console.log('Error: ', error);
}
</code>```

Note that I put everything in async/await style, except the required Promise object, and I have a single try-catch block. If you want to process errors at a higher level of granularity, split it into multiple try-catch blocks.

When we make sure to await every asynchronous action, we ensure that we don't start the next one until we are done with the previous, so everything is done in order.

Body:
I need to send an object including a base64-encoded image to an API-endpoint in TS. I use this code to convert a file to Base64 and attach it to an object:

const file = values.beleg1;
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = async function () {
                    const result = reader.result.toString().split(',')[1];
                    await valuesObj.push({ name: 'base64Image', value: result });

                };
                reader.onerror = function (error) {
                    console.log('Error: ', error);
                };

If I then log the object 'valuesObj' it does show that the base64-object is attached to the main-object.

However when I then I then use this object in the request like in the code below it is not shown in the payload when looking at the network-request

axios({
                url: 'http://localhost:8080/createPDF',
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                responseType: 'blob',
                data: valuesObj,
            })
                .then((response: AxiosResponse) => {
                    setLoadingText('');
                    const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
                    const objectUrl: string = window.URL.createObjectURL(blob);
                    window.open(objectUrl);
                })
                .catch((error) => {
                    console.log(error);
                });

What is the reason for this? Does it have anything to do with the length/size of the string? Or is there another reason?

Body:
What is happening is the reader hasn't finished reading before the Axios call proceeds. The reader executes asynchronously. Thus, the order of operations often ends up something like this:

Start the read operation.

Attach event handler onloaded.

Start the Axios request, which is probably sent immediately at this point.

Complete the read operation.

Complete the Axios request.

Because you aren't waiting for the load event to finish before sending the Axios request, the request does not include the new data. You need to make sure the load event is finished and the data is pushed onto your array before you proceed with the Axios call.

try {
    const file = values.beleg1;
    const reader = new FileReader();
    reader.readAsDataURL(file);

    // construct a promise that will resolve once loading is complete,
    //   and then wait for it, so that we don't make the axios call until
    //   after the loading is done.
    await new Promise<void>((resolve, reject) => {
        reader.onload = function () {
            const result = reader.result.toString().split(',')[1];
            valuesObj.push({ name: 'base64Image', value: result });
            // notify that the promise has completed its work
            resolve();
        };

        reader.onerror = function () {
            // notify that the promise failed and pass along the error object
            reject(reader.error);
        };
    });

    // I picked any since I don't want to define out the full type, but you probably should
    const response: any = await axios({
        url: 'http://localhost:8080/createPDF',
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
        },
        responseType: 'blob',
        data: valuesObj,
    });

    setLoadingText('');
    const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
    const objectUrl: string = window.URL.createObjectURL(blob);
    window.open(objectUrl);
} catch (error) {
    // all errors during the processing are caught in one place
    console.log('Error: ', error);
}

Note that I put everything in async/await style, except the required Promise object, and I have a single try-catch block. If you want to process errors at a higher level of granularity, split it into multiple try-catch blocks.

When we make sure to await every asynchronous action, we ensure that we don't start the next one until we are done with the previous, so everything is done in order.


问:
Adhoc styling in Material-UI 5
Trying to upgrade from MUI 4 to 5. In MUI 4, I used to be able to introduce adhoc classes using makeStyles:

```<code>const useStyles = makeStyles((theme: Theme) => ({
    root: {
        cursor: 'pointer',
    },
}));

export const FakeLink = ({ children }) => {
    const classes = useStyles();

    return (
        <span className={classes.root}>
            {children}
        </span>
    );
};

</code>```

Now trying to put the same cursor: 'pointer' on an ImageListItem. How do I do this?

```<code><ImageListItem>
    <img ... />
</ImageListItem>
</code>```

I thought I could do it using sx, but it doesn't implement the cursor property. What am I missing?

答: The cursor property should be supposed by the sx and styled API. Maybe you are facing a TypeScript issue?</p>

Title: Adhoc styling in Material-UI 5

Body:
Trying to upgrade from MUI 4 to 5. In MUI 4, I used to be able to introduce adhoc classes using makeStyles:

const useStyles = makeStyles((theme: Theme) => ({
    root: {
        cursor: 'pointer',
    },
}));

export const FakeLink = ({ children }) => {
    const classes = useStyles();

    return (

            {children}

    );
};

Now trying to put the same cursor: 'pointer' on an ImageListItem. How do I do this?

<ImageListItem>

</ImageListItem>

I thought I could do it using sx, but it doesn't implement the cursor property. What am I missing?


问:
Split very long text into pages in Flutter
I have multiple text files with very long text  which I would like to split into pages to make it easier to read and navigate. Here's an example of this:

So given the container size for a page and the text (with specific font style) as input the result should be the total number of pages required to display this text.

I understand that the text can be displayed in a ListView as @pskink mentioned but I'd like to make the page static like in a Kindle and display in advance the total number of pages so one can switch to any page by index.

I also found an related Flutter framework issue which might be related to this question. Not sure if it's limiting or not.

Expose enough of LibTxt to make custom text layout practical

答:
I solved this by creating a custom widget MultiPageText that distributes the entire text across multiple pages based on available space.

Since laying out multiple paragraphs just to determine the cutoff point for each page is expensive, one would usually put the expensive _getPageText() function in a separate isolate. Unfortunately, that is currently not possible since non-main isolates cannot use dart:ui and the function is therefore executed in the main isolate.

Here's the full code including some comments that you can run in DartPad:

import 'dart:ui' as ui;
import 'dart:math' as math;

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Scaffold(
        body: Center(
          child: ExampleMultiPageText(),
        ),
      ),
    );
  }
}

class MultiPageText extends StatefulWidget {
  /// The entire text that has to be distributed across one or
  /// more pages.
  final String fullText;

  /// The [TextStyle] that is applied to the [fullText].
  final TextStyle textStyle;

  /// The size of the entire widget.
  ///
  /// This size's height is the upper limit for the [PageTextContainer]'s that contains
  /// each page text. If the [PageNavigatorMenu] is included (i.e. if
  /// [usePageNavigation] is `true`), its height (50 pixel) will be deducted
  /// leaving the only remaining height for the [PageTextContainer].
  final Size size;

  /// The padding that will be applied to the [PageTextContainer].
  final EdgeInsets paddingTextBox;

  /// Whether the [PageNavigatorMenu] will be rendered below the [PageTextContainer].
  final bool usePageNavigation;

  /// The [PageTextContainer]'s decoration.
  final BoxDecoration? decoration;

  /// Creates a widget that distributes the provided text across as many pages as necessary.
  ///
  /// Besides the TextContainer that holds the text for the given page, the widget can also
  /// contain a PageNavigatorMenu for navigating between the different pages.
  const MultiPageText({
    Key? key,
    required this.fullText,
    required this.size,
    this.textStyle = const TextStyle(
      fontSize: 10,
      color: Colors.white,
    ),
    this.paddingTextBox = const EdgeInsets.all(
      10,
    ),
    this.usePageNavigation = true,
    this.decoration,
  }) : super(key: key);

  @override
  State<MultiPageText> createState() => _MultiPageTextState();
}

class _MultiPageTextState extends State<MultiPageText> {
  int _currentPageIndex = 0;
  final double _pageNavigatorHeight = 40;
  final int _upperLayoutRunsLimit = 20;
  late List<String> _pages;
  late Size _availableSize;

  @override
  void initState() {
    _pages = _getPageTexts();
    super.initState();
  }

  List<String> _getPageTexts() {
    List<String> pages = <String>[];
    String remainingText = widget.fullText;
    _availableSize = _calculateAvailableSize(
      size: widget.size,
      padding: widget.paddingTextBox,
      usePageNavigation: widget.usePageNavigation,
    );
    double widthFactor = 0.5;
    int retries = 0;
    int pageCharacterLimit = _estimatePageCharacterLimit(
      size: _availableSize,
      textStyle: widget.textStyle,
      widthFactor: widthFactor,
    );
    while (remainingText.isNotEmpty) {
      final String pageTextEstimate = _getPageTextEstimate(
        text: remainingText,
        pageCharacterLimit: pageCharacterLimit,
      );
      final PageProperties pageProperties = _getPageText(
        text: pageTextEstimate,
        textStyle: widget.textStyle,
        size: _availableSize,
      );
      if (_shouldOptimizeEstimates(pageProperties.layoutRuns)) {
        // Optimize widthFactor for better pageTextEstimates
        widthFactor = _updateWidthFactor(
          widthFactor: widthFactor,
          layoutRuns: pageProperties.layoutRuns,
          upperLayoutRunsLimit: _upperLayoutRunsLimit,
        );
        // Update pageCharacterLimit
        pageCharacterLimit = _estimatePageCharacterLimit(
          size: _availableSize,
          textStyle: widget.textStyle,
          widthFactor: widthFactor,
        );
      }
      if (_performRetry(pageProperties.layoutRuns, retries)) {
        retries++;
        continue;
      }
      pages.add(pageProperties.text);
      remainingText =
          remainingText.substring(pageProperties.text.length).trimLeft();
      retries = 0;
    }
    return pages;
  }

  /// Calculates the available space for the [ui.ParagraphBuilder] (i.e. its width constraint).
  ///
  /// That means subtracting any padding of the enclosing [Container] as well as removing the
  /// height of the page navigation (only if [usePageNavigation] is `true`).
  Size _calculateAvailableSize({
    required Size size,
    required EdgeInsets padding,
    required bool usePageNavigation,
  }) {
    double availableHeight = size.height -
        (widget.paddingTextBox.top + widget.paddingTextBox.bottom);
    if (usePageNavigation) {
      availableHeight = availableHeight - _pageNavigatorHeight;
    }
    final double availableWidth =
        size.width - (widget.paddingTextBox.right + widget.paddingTextBox.left);
    return Size(availableWidth, availableHeight);
  }

  /// Updates the [widthFactor] based on the number of actual [layoutRuns].
  ///
  /// If the [upperLayoutRunsLimit] was exceeded, we want to tighten our character estimate
  /// (hence increase the [widthFactor] by `0.05`). Otherwise (i.e. if [layoutRuns] = `1`) the
  /// constraint should be loosened (decrease the [widthFactor] by `0.05`).
  double _updateWidthFactor({
    required double widthFactor,
    required int layoutRuns,
    required int upperLayoutRunsLimit,
  }) {
    final double newWidthFactor = layoutRuns >= upperLayoutRunsLimit
        ? widthFactor + 0.05
        : widthFactor - 0.05;
    return newWidthFactor;
  }

  /// (Over)Estimates the character limit for a given page.
  ///
  /// The [widthFactor] is automatically chosen and adjusted by the parent function
  /// so that the resulting maximum character will be slightly overestimated.
  int _estimatePageCharacterLimit({
    required Size size,
    required TextStyle textStyle,
    required double widthFactor,
  }) {
    final characterHeight = textStyle.fontSize!;
    final characterWidth = characterHeight * widthFactor;
    return ((size.height * size.width) / (characterHeight * characterWidth))
        .ceil();
  }

  /// Retrieves the part of the [text] that fits within the [pageCharacterLimit] starting
  /// from the beginning of the string.
  String _getPageTextEstimate({
    required String text,
    required int pageCharacterLimit,
  }) {
    final initialPageTextEstimate =
        text.substring(0, math.min(pageCharacterLimit + 1, text.length));
    final substringIndex =
        initialPageTextEstimate.lastIndexOf(RegExp(r"\s+\b|\b\s+|[\.?!]"));
    final pageTextEstimate =
        text.substring(0, math.min(substringIndex + 1, text.length));
    return pageTextEstimate;
  }

  /// Determines the final text for the given page and returns the respective
  /// [PageProperties] with the number of necessary `layoutRuns` for optimization
  /// and the [text] itself.
  PageProperties _getPageText({
    required String text,
    required TextStyle textStyle,
    required Size size,
  }) {
    double paragraphHeight = 10000;
    String currentText = text;
    int layoutRuns = 0;
    final RegExp regExp = RegExp(r"\S+[\W]*$");
    while (paragraphHeight > size.height) {
      final paragraph = ParagraphPainter.layoutParagraph(
          text: currentText, textStyle: textStyle, size: size);
      paragraphHeight = paragraph.height;
      if (paragraphHeight > size.height) {
        currentText = currentText.replaceFirst(regExp, '');
      }
      layoutRuns = layoutRuns + 1;
    }

    return PageProperties(currentText, layoutRuns);
  }

  bool _performRetry(int layoutRuns, int retries) {
    return layoutRuns == 1 && retries <= 0;
  }

  bool _shouldOptimizeEstimates(int layoutRuns) {
    return layoutRuns > _upperLayoutRunsLimit || layoutRuns == 1;
  }

  void _updatePageIndex(PageUpdateOperation pageUpdateOperation) {
    switch (pageUpdateOperation) {
      case PageUpdateOperation.first:
        setState(() {
          _currentPageIndex = 0;
        });
        break;
      case PageUpdateOperation.previous:
        setState(() {
          _currentPageIndex--;
        });
        break;
      case PageUpdateOperation.next:
        setState(() {
          _currentPageIndex++;
        });
        break;
      case PageUpdateOperation.last:
        setState(() {
          _currentPageIndex = _pages.length - 1;
        });
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    final pageTextContainer = PageTextContainer(
      text: _pages[_currentPageIndex],
      textStyle: widget.textStyle,
      padding: widget.paddingTextBox,
      size: _availableSize,
      decoration: widget.decoration,
    );
    return widget.usePageNavigation
        ? Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              pageTextContainer,
              PageNavigatorMenu(
                size: Size(widget.size.width, _pageNavigatorHeight),
                currentPageIndex: _currentPageIndex,
                pageCount: _pages.length,
                updatePageIndex: _updatePageIndex,
              ),
            ],
          )
        : pageTextContainer;
  }
}

class PageTextContainer extends StatelessWidget {
  final String text;
  final TextStyle textStyle;
  final EdgeInsets padding;
  final Size size;
  final BoxDecoration? decoration;

  const PageTextContainer({
    Key? key,
    required this.text,
    required this.textStyle,
    required this.padding,
    required this.size,
    this.decoration,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: padding,
      decoration: decoration,
      child: CustomPaint(
        painter: ParagraphPainter(
          pageText: text,
          textStyle: textStyle,
        ),
        child: SizedBox(
          height: size.height,
          width: size.width,
        ),
      ),
    );
  }
}

class PageNavigatorMenu extends StatelessWidget {
  final Size size;
  final int currentPageIndex;
  final int pageCount;
  final void Function(PageUpdateOperation) updatePageIndex;

  const PageNavigatorMenu({
    Key? key,
    required this.size,
    required this.currentPageIndex,
    required this.pageCount,
    required this.updatePageIndex,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: size.height,
      width: size.width,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(
            icon: const Icon(
              Icons.first_page,
            ),
            onPressed: currentPageIndex > 0
                ? () => updatePageIndex(
                      PageUpdateOperation.first,
                    )
                : null,
          ),
          IconButton(
            icon: const Icon(
              Icons.navigate_before,
            ),
            onPressed: currentPageIndex > 0
                ? () => updatePageIndex(
                      PageUpdateOperation.previous,
                    )
                : null,
          ),
          Flexible(
            child: FittedBox(
              fit: BoxFit.scaleDown,
              child: Text(
                'Page ${currentPageIndex + 1}',
              ),
            ),
          ),
          IconButton(
            icon: const Icon(
              Icons.navigate_next,
            ),
            onPressed: currentPageIndex < pageCount - 1
                ? () => updatePageIndex(
                      PageUpdateOperation.next,
                    )
                : null,
          ),
          IconButton(
            icon: const Icon(
              Icons.last_page,
            ),
            onPressed: currentPageIndex < pageCount - 1
                ? () => updatePageIndex(
                      PageUpdateOperation.last,
                    )
                : null,
          ),
        ],
      ),
    );
  }
}

class ParagraphPainter extends CustomPainter {
  final String pageText;
  final TextStyle textStyle;

  ParagraphPainter({
    required this.pageText,
    required this.textStyle,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paragraph = layoutParagraph(
      text: pageText,
      textStyle: textStyle,
      size: size,
    );
    canvas.drawParagraph(paragraph, Offset.zero);
  }

  static ui.Paragraph layoutParagraph({
    required String text,
    required TextStyle textStyle,
    required Size size,
  }) {
    final ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(
      ui.ParagraphStyle(
        fontSize: textStyle.fontSize,
        fontFamily: textStyle.fontFamily,
        fontStyle: textStyle.fontStyle,
        fontWeight: textStyle.fontWeight,
        textAlign: TextAlign.left,
      ),
    )
      ..pushStyle(textStyle.getTextStyle())
      ..addText(text);
    final ui.Paragraph paragraph = paragraphBuilder.build()
      ..layout(
        ui.ParagraphConstraints(width: size.width),
      );
    return paragraph;
  }

  @override
  bool shouldRepaint(ParagraphPainter oldDelegate) =>
      oldDelegate.pageText != pageText || oldDelegate.textStyle != textStyle;
}

class PageProperties {
  final String text;
  final int layoutRuns;

  PageProperties(this.text, this.layoutRuns);

  @override
  String toString() {
    return '''PageProperties(
$text,
$layoutRuns
)''';
  }
}

enum PageUpdateOperation {
  first,
  previous,
  next,
  last,
}

// Call the widget
class ExampleMultiPageText extends StatelessWidget {
  const ExampleMultiPageText({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: MultiPageText(
        textStyle: const TextStyle(
          fontSize: 10,
          color: Colors.white,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          border: Border.all(
            width: 1.0,
            color: Colors.grey,
          ),
        ),
        usePageNavigation: true,
        fullText:
            '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et mollis orci. Sed ullamcorper leo ipsum, sit amet feugiat neque aliquam at. Vestibulum vehicula elit eget metus iaculis ultrices. Nunc faucibus vehicula justo vitae portaPhasellus vestibulum lectus non tellus accumsan, non dictum tellus bibendum. Nulla ornare eros vitae bibendum pharetra. Fusce sit amet lobortis ex. Proin condimentum imperdiet erat, lacinia suscipit est efficitur sit amet. Nunc laoreet luctus tortor, in accumsan velit. Donec cursus velit vehicula maximus finibus. Donec quis euismod quam. In vel lacus fringilla, rhoncus eros nec, elementum massa. Donec luctus lobortis ullamcorper.

Aenean lacus ligula, rutrum ac felis in, dictum sagittis est. Integer finibus arcu magna, eget bibendum odio dignissim id. Mauris ornare ipsum maximus malesuada efficitur. Duis pulvinar neque a lectus fermentum accumsan non id arcu. Quisque congue lectus eu ante efficitur, ac semper lectus volutpat. Pellentesque dignissim turpis quam, venenatis facilisis sem rutrum non. Praesent tincidunt sodales dolor a maximus. Aliquam sit amet quam vel augue mattis luctus. Duis placerat condimentum aliquam. Quisque bibendum in ipsum non pretium. Nam lobortis libero quam, sed lacinia ex rhoncus non. Fusce viverra felis vitae finibus tincidunt. In hac habitasse platea dictumst. Praesent mollis, turpis at iaculis pulvinar, lectus enim feugiat mi, ultricies auctor lacus sapien sed ipsum.

Etiam ac mi risus. In dictum purus sapien, non tempus magna tempor vel. Suspendisse finibus lectus et sem laoreet dignissim.

Maecenas erat mi, ultrices non sollicitudin non, tristique a est. Vestibulum interdum diam nec justo eleifend tincidunt. Nulla non nulla at nulla suscipit congue.

Mauris est dui, molestie sed tempus ac, accumsan eget urna. Nullam sit amet bibendum lacus, a pellentesque nisl. Aliquam lorem eros, finibus id enim eget, faucibus ultricies erat. Sed sed pulvinar tellus, nec euismod lectus. Quisque libero metus, congue nec suscipit ut, tincidunt eget odio. Aliquam sit amet cursus magna. Nam aliquam ipsum at eleifend auctor. Fusce eu metus dui. Nulla non lacus eros. Cras elementum, ante et tristique faucibus, risus enim dignissim est, id iaculis augue turpis vel massa. Sed cursus ultricies lorem.''',
        size: const Size(
          200,
          350,
        ),
      ),
    );
  }
}
```


问:
How to get line chart to show 3 columns from CSV files?
i have a CSV file showcasing the reduction of Methane in the atmosphere from the UK over a 9 year period. I'm attempting to get the file to show the data visually while using matplotlib, later on, I hope to add more countries to the script so that I can showcase how counties have reduced their emissions throughout the years, but I can't seem to get the output to look quite right?

The script is functioning as expected but when I run the output it's showing each entry as one single output, so instead of showing a chart with a positive correlation, it's showcasing a single entry showcasing all of the results at once. Please see the attached code:

```<code>import matplotlib.pyplot as plt
from sklearn import linear_model

df = pd.read_csv(r'C:\Users\avalo\Desktop\Data.csv')
print (df)

X = list(df.iloc[:, 0])
Y = list(df.iloc[:, 1])

plt.plot(X, Y, color='b')
plt.title("Levels of Methane (CH4) Emissions (Tonnes)")
plt.xlabel("Years")
plt.ylabel("Number of Tonnes")

plt.show()
</code>```

It then shows this output:

The CSV file looks as follows:

Ideally, I would like it so that the line could be one colour so that I could add other data entries to the original CSV file and then into the script as different colours to better visualise the difference. Any and all help on this would be great! Thanks.

答:
You could reformat your dataframe after reading your csv and put the countryname into the columnname (Multiindex). This way you can plot multiple states against one time column in one plots with different colors using Dataframe.plot(x='Year'). I didnt test the pandas plot function, but this was my code to rearrange your dataframe.

```<code>import pandas as pd
from functools import reduce

data = [['UK', 2019, 10000],['UK', 2018, 20000],['GER', 2019, 10000],['GER', 2018, 30000]]
df = pd.DataFrame(data, columns = ['country','Year', 't/a'])

grouped = df.groupby('country')

dflist = []

for name, group in grouped:
    group.drop('country', 1 , inplace=True)
    group.columns = ['Year', f'{name} t/a']
    group.sort_values(by=['Year'], ascending=True, inplace=True)
    dflist.append(group)

dffinal = reduce(lambda df1,df2: pd.merge(df1,df2,on='Year'), dflist)
</code>```

If you get different files for each country you can drop the groupby and just read each file inside the for loop and do the reformating.
Sadly im not on a machine with python installed right now and the online ide couldnt handle df.plot somehow, but the pandas plot function is well documented on their website: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html?highlight=plot
dffinal.plot(x='Year',y=[all columnames here])  will probably give you a decent result

Body:
i have a CSV file showcasing the reduction of Methane in the atmosphere from the UK over a 9 year period. I'm attempting to get the file to show the data visually while using matplotlib, later on, I hope to add more countries to the script so that I can showcase how counties have reduced their emissions throughout the years, but I can't seem to get the output to look quite right?

The script is functioning as expected but when I run the output it's showing each entry as one single output, so instead of showing a chart with a positive correlation, it's showcasing a single entry showcasing all of the results at once. Please see the attached code:

import matplotlib.pyplot as plt
from sklearn import linear_model

df = pd.read_csv(r'C:\Users\avalo\Desktop\Data.csv')
print (df)

X = list(df.iloc[:, 0])
Y = list(df.iloc[:, 1])

plt.plot(X, Y, color='b')
plt.title("Levels of Methane (CH4) Emissions (Tonnes)")
plt.xlabel("Years")
plt.ylabel("Number of Tonnes")

plt.show()

It then shows this output:

The CSV file looks as follows:

Ideally, I would like it so that the line could be one colour so that I could add other data entries to the original CSV file and then into the script as different colours to better visualise the difference. Any and all help on this would be great! Thanks.

Body:
You could reformat your dataframe after reading your csv and put the countryname into the columnname (Multiindex). This way you can plot multiple states against one time column in one plots with different colors using Dataframe.plot(x='Year'). I didnt test the pandas plot function, but this was my code to rearrange your dataframe.

import pandas as pd
from functools import reduce

data = [['UK', 2019, 10000],['UK', 2018, 20000],['GER', 2019, 10000],['GER', 2018, 30000]]
df = pd.DataFrame(data, columns = ['country','Year', 't/a'])

grouped = df.groupby('country')

dflist = []

for name, group in grouped:
    group.drop('country', 1 , inplace=True)
    group.columns = ['Year', f'{name} t/a']
    group.sort_values(by=['Year'], ascending=True, inplace=True)
    dflist.append(group)

dffinal = reduce(lambda df1,df2: pd.merge(df1,df2,on='Year'), dflist)

If you get different files for each country you can drop the groupby and just read each file inside the for loop and do the reformating.
Sadly im not on a machine with python installed right now and the online ide couldnt handle df.plot somehow, but the pandas plot function is well documented on their website: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html?highlight=plot
dffinal.plot(x='Year',y=[all columnames here])  will probably give you a decent result


问:
Does if(this) {} else {} ever visit the else in JavaScript?
Is there any case where the condition if(this) {} fails? Because I couldn't think of a scenario where this is undefined.

This is not an important question nor something anyone would normally use, I'm just asking out of pure curiosity.

答:
Yes, in some execution contexts, this is undefined, which is falsy in JavaScript:

In strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example:

Here is at least one convoluted scenario in which the following conditions must be met:

global or function execution in strict mode

the function was defined at the top-level (effectively being a function of window)

that function was called directly without invoking its parent (i.e. foo() and not window.foo())

the function returned this

```<code>function foo() {
  'use strict'; // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
  return this;
}
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Body:
Yes, in some execution contexts, this is undefined, which is falsy in JavaScript:

In strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example:

Here is at least one convoluted scenario in which the following conditions must be met:

global or function execution in strict mode

the function was defined at the top-level (effectively being a function of window)

that function was called directly without invoking its parent (i.e. foo() and not window.foo())

the function returned this

function foo() {
  'use strict'; // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
  return this;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this


问:
Set margin on bootstrap cols without affecting width
I am trying to display a list of card width boostrap. I made my html like so :

```<code><div class="card-deck">
    <div class="card card-widget col-sm-2 m-2">
        <div class="card-body text-center">
            TEXT
        </div>
    </div>
    <div>
        etc...
    </div>
</div>
</code>```

The problem is, margin seems to expand the cards' width. So it makes someting like that... (it should display 4 cols)

screen 1

If I remove margins, it makes something like...

screen 2

Thanks for your help !

答:
(Bootstrap 5)

I was able to solve the problem by wrapping the card in a column first (which is what the documentation recommends). This appears to apply an mx-2 margin as a default, though I can't actually find out why this is the case. In any case it allowed me to get a margin between cards without breaking the grid.

```<code><div class="container">
  <div class="row">
    <div class="col-lg-4 my-2">
      <div class="card">
      </div>
    </div>
    <div class="col-lg-4 my-2">
      <div class="card">
      </div>
    </div>
    ...etc
  </div>
</div>
</code>```

Body:
I am trying to display a list of card width boostrap. I made my html like so :

            TEXT

        etc...

The problem is, margin seems to expand the cards' width. So it makes someting like that... (it should display 4 cols)

screen 1

If I remove margins, it makes something like...

screen 2

Thanks for your help !

Body:
(Bootstrap 5)

I was able to solve the problem by wrapping the card in a column first (which is what the documentation recommends). This appears to apply an mx-2 margin as a default, though I can't actually find out why this is the case. In any case it allowed me to get a margin between cards without breaking the grid.

<div class="container">
  <div class="row">
    <div class="col-lg-4 my-2">
      <div class="card">
      </div>
    </div>
    <div class="col-lg-4 my-2">
      <div class="card">
      </div>
    </div>
    ...etc
  </div>
</div>


问:
Should this RSS feed work?
Im making a website on a local environment. Im having trouble getting an RSS feed to work, but I think it may be due to my local environment not an issue with the code. For diagnostic purposes I decided to use the code from wikipedia:  </p>

```<code><?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
    <title>RSS Title</title>
    <description>This is an example of an RSS feed</description>
    <link>http://www.someexamplerssdomain.com/main.html</link>
    <lastBuildDate>Mon, 06 Sep 2010 00:01:00 +0000 </lastBuildDate>
    <pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>

    <item>
            <title>Example entry</title>
            <description>Here is some text containing an interesting description.</description>
            <link>http://www.wikipedia.org/</link>
            <guid>unique string per item</guid>
            <pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
    </item>

</channel>
</rss>
</code>```

<p>This is in a file called feed.feed. When I navigate to the file in a browser and view it with google reader I get the message 'The feed being requested cannot be found'. Is the code correct and does this defiantly mean its an issue with my environment set up?
Thanks </p>

答: If you're storing the file on your local hard drive and navigating to it with a file: URL, of course Google Reader can't access it. They need the feed to be published on the web somewhere; they don't have the ability to hack your local PC over the network and fetch your files (or, at least, they're not going to reveal that they have do this ability simply to display RSS feeds for you.)

Title: Should this RSS feed work?

Body:
Im making a website on a local environment. Im having trouble getting an RSS feed to work, but I think it may be due to my local environment not an issue with the code. For diagnostic purposes I decided to use the code from wikipedia:

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
    <title>RSS Title</title>
    <description>This is an example of an RSS feed</description>
    <link>http://www.someexamplerssdomain.com/main.html</link>
    <lastBuildDate>Mon, 06 Sep 2010 00:01:00 +0000 </lastBuildDate>
    <pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>

    <item>
            <title>Example entry</title>
            <description>Here is some text containing an interesting description.</description>
            <link>http://www.wikipedia.org/</link>
            <guid>unique string per item</guid>
            <pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
    </item>

</channel>
</rss>

This is in a file called feed.feed. When I navigate to the file in a browser and view it with google reader I get the message 'The feed being requested cannot be found'. Is the code correct and does this defiantly mean its an issue with my environment set up?
Thanks


问:
Is requestForLocationupdates a blocking call in Android?
I want to update the location every 5 mins till the lifecycle of the application. I know how to update the location. What I want to know is whether the requestForLocation is a blocking call or not.

I can do this in Service class but Service is run on main thread only and also Service can be stopped by the system anytime. I do not want this to happen. The location update should work till the application is in memory. If the application itself is killed then obviously the Service also gets killed.

What should be the approach for implementing this?

答: For some reason this requestLocationUpdates() call is really blocking, at least in the phone brands that I tested. The way to fix it is to use one of its overloads. Please see this answer in another post.


问:
AttributeError: 'NoneType' object has no attribute 'groups' in odoo 13
I am new to odoo-13 and I need help in debugging this error.
My motive is to create a custom module in odoo using python3. It is working in my local installed odoo but if I tried to install it in the other server installed oddo it produces the following error please help me solve this error. Thanks in future.</p>

```<code>Odoo Server Error
Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/http.py", line 619, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo/odoo/http.py", line 309, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/opt/odoo/odoo/odoo/tools/pycompat.py", line 14, in reraise
    raise value
  File "/opt/odoo/odoo/odoo/http.py", line 664, in dispatch
    result = self._call_function(**self.params)
  File "/opt/odoo/odoo/odoo/http.py", line 345, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/service/model.py", line 93, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/http.py", line 338, in checked_call
    result = self.endpoint(*a, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 910, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 510, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 1324, in call_button
    action = self._call_kw(model, method, args, kwargs)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 1312, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/opt/odoo/odoo/odoo/api.py", line 395, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/opt/odoo/odoo/odoo/api.py", line 382, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "<decorator-gen-58>", line 2, in button_immediate_install
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 72, in check_and_log
    return method(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 463, in button_immediate_install
    return self._button_immediate_function(type(self).button_install)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 573, in _button_immediate_function
    modules.registry.Registry.new(self._cr.dbname, update_module=True)
  File "/opt/odoo/odoo/odoo/modules/registry.py", line 85, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 420, in load_modules
    loaded_modules, update_module, models_to_check)
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 312, in load_marked_modules
    perform_checks=perform_checks, models_to_check=models_to_check
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 231, in load_module_graph
    module.with_context(overwrite=overwrite)._update_translations()
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 889, in _update_translations
    self.env['ir.translation']._load_module_terms(mod_names, filter_lang)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_translation.py", line 822, in _load_module_terms
    tools.trans_load(self._cr, trans_file, lang, verbose=False, module_name=module_name, context=context)
  File "/opt/odoo/odoo/odoo/tools/translate.py", line 1053, in trans_load
    result = trans_load_data(cr, fileobj, fileformat, lang, verbose=verbose, module_name=module_name, context=context)
  File "/opt/odoo/odoo/odoo/tools/translate.py", line 1103, in trans_load_data
    for row in reader:
  File "/opt/odoo/odoo/odoo/tools/translate.py", line 600, in __iter__
    _, module = match.groups()
AttributeError: 'NoneType' object has no attribute 'groups'
</code>```

答:
I was having the same issue and I also found where it was comming from.
It can be helpful if you don't want to delete your translation file.

This is due to a missing 'module' tag in the .po file. This is a typical example of a translation in a .po file.

```<code>#. module: sale
#: model:ir.actions.report,print_report_name:sale.action_report_pro_forma_invoice
msgid "'PRO-FORMA - %s' % (object.name)"
msgstr "'PRO-FORMA - %s' % (object.name)"
</code>```

Body:
I am new to odoo-13 and I need help in debugging this error.
My motive is to create a custom module in odoo using python3. It is working in my local installed odoo but if I tried to install it in the other server installed oddo it produces the following error please help me solve this error. Thanks in future.

Odoo Server Error
Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/http.py", line 619, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo/odoo/http.py", line 309, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/opt/odoo/odoo/odoo/tools/pycompat.py", line 14, in reraise
    raise value
  File "/opt/odoo/odoo/odoo/http.py", line 664, in dispatch
    result = self._call_function(**self.params)
  File "/opt/odoo/odoo/odoo/http.py", line 345, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/service/model.py", line 93, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/http.py", line 338, in checked_call
    result = self.endpoint(*a, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 910, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 510, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 1324, in call_button
    action = self._call_kw(model, method, args, kwargs)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 1312, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/opt/odoo/odoo/odoo/api.py", line 395, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/opt/odoo/odoo/odoo/api.py", line 382, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "<decorator-gen-58>", line 2, in button_immediate_install
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 72, in check_and_log
    return method(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 463, in button_immediate_install
    return self._button_immediate_function(type(self).button_install)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 573, in _button_immediate_function
    modules.registry.Registry.new(self._cr.dbname, update_module=True)
  File "/opt/odoo/odoo/odoo/modules/registry.py", line 85, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 420, in load_modules
    loaded_modules, update_module, models_to_check)
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 312, in load_marked_modules
    perform_checks=perform_checks, models_to_check=models_to_check
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 231, in load_module_graph
    module.with_context(overwrite=overwrite)._update_translations()
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 889, in _update_translations
    self.env['ir.translation']._load_module_terms(mod_names, filter_lang)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_translation.py", line 822, in _load_module_terms
    tools.trans_load(self._cr, trans_file, lang, verbose=False, module_name=module_name, context=context)
  File "/opt/odoo/odoo/odoo/tools/translate.py", line 1053, in trans_load
    result = trans_load_data(cr, fileobj, fileformat, lang, verbose=verbose, module_name=module_name, context=context)
  File "/opt/odoo/odoo/odoo/tools/translate.py", line 1103, in trans_load_data
    for row in reader:
  File "/opt/odoo/odoo/odoo/tools/translate.py", line 600, in __iter__
    _, module = match.groups()
AttributeError: 'NoneType' object has no attribute 'groups'

Body:
I was having the same issue and I also found where it was comming from.
It can be helpful if you don't want to delete your translation file.

This is due to a missing 'module' tag in the .po file. This is a typical example of a translation in a .po file.

#. module: sale
#: model:ir.actions.report,print_report_name:sale.action_report_pro_forma_invoice
msgid "'PRO-FORMA - %s' % (object.name)"
msgstr "'PRO-FORMA - %s' % (object.name)"


问:
Is testing in Gitlab Ci supported with Opensearch docker images as a service?
I have a Java app that is running integration tests with Elasticsearch in Gitlab.

.gitlab-ci.yml:

```<code>...

integration:
  stage: integration
  tags:
    - onprem
  services:
    - name: "docker.elastic.co/elasticsearch/elasticsearch:7.10.1"
      alias: "elasticsearch"
      command: [ "bin/elasticsearch", "-Expack.security.enabled=false", "-Ediscovery.type=single-node" ]
  script:
    - curl "http://elasticsearch:9200/_cat/health"
    - mvn -Dgroups="IntegrationTest" -DargLine="-Durl=elasticsearch" test

...
</code>```

Now I want to use Opensearch 1.1.0 because that is what we use on AWS. I tried working off the docker compose setup that Opensearch suggests for developers ( https://opensearch.org/docs/latest/opensearch/install/docker/#sample-docker-compose-file-for-development ), and came up with this:

```<code>...

integration:
  stage: integration
  tags:
    - onprem
  services:
    - name: "opensearchproject/opensearch:1.1.0"
      alias: "elasticsearch"
      command: [
          "./opensearch-docker-entrypoint.sh",
          "-Ecluster.name=opensearch-cluster",
          "-Enode.name=opensearch-node1",
          "-Ebootstrap.memory_lock=true",
          "-Ediscovery.type=single-node",
          "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m",
          "DISABLE_INSTALL_DEMO_CONFIG=true",
          "DISABLE_SECURITY_PLUGIN=true"
      ]
  script:
    - curl "http://elasticsearch:9200/_cat/health"
    - mvn -Dgroups="IntegrationTest" -DargLine="-Durl=elasticsearch" test

...
</code>```

The curl response:

```<code>$ curl "http://elasticsearch:9200/_cat/health"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:02 --:--:--     0curl: (7) Failed to connect to elasticsearch port 9200: No route to host
</code>```

One big difference seems to be that Elasticsearch disables security with an environment variable, but Opensearch does that with an argument through setup. I tried running Opensearch directly through the "bin/" directory, but that seems to give all sorts of additional errors. The Opensearch image is available on dockerhub ( https://hub.docker.com/layers/opensearchproject/opensearch/1.1.0/images/sha256-94254d215845723e73829f34cf7053ae9810db360cf73c954737a717e9cf031d?context=explore ) , but I have no access to the Dockerfile of the Elasticsearch image to compare.

I have numerous other failed setups: Tried moving different combinations of the arguments over as stage variables in gitlab-ci.

Am I misunderstanding what to do here, or is what I'm trying even supported at all?

答:
The final layer in opensearchproject/opensearch:1.1.0 is

```<code>CMD ["./opensearch-docker-entrypoint.sh"]
</code>```

which reconfigures opensearch based on environment variables, like DISABLE_SECURITY_PLUGIN, and populates opensearch startup options like -Eplugins.security.disabled=true

Even though such ENVs are accepted by Docker, bash does not allow export of environment variables like discovery.type=single-node, so the gitlab-ci job fails.

The CMD is refactored to ENTRYPOINT in later releases by this issue

One way to trick the CMD, is to set the variables before launching the script:

```<code>integration:
  stage: integration
  variables:
    OPENSEARCH_JAVA_OPTS: "-Xms512m -Xmx512m"
    DISABLE_INSTALL_DEMO_CONFIG: "true"
    DISABLE_SECURITY_PLUGIN: "true"
  services:
    - name: opensearchproject/opensearch:1.1.0
      alias: opensearch
      command: ["bash", "-c", "env 'discovery.type=single-node' 'cluster.name=opensearch' ./opensearch-docker-entrypoint.sh"]
  script:
    - curl -sS http://opensearch:9200/_cat/health
</code>```

Body:
I have a Java app that is running integration tests with Elasticsearch in Gitlab.

.gitlab-ci.yml:

...

integration:
  stage: integration
  tags:
    - onprem
  services:
    - name: "docker.elastic.co/elasticsearch/elasticsearch:7.10.1"
      alias: "elasticsearch"
      command: [ "bin/elasticsearch", "-Expack.security.enabled=false", "-Ediscovery.type=single-node" ]
  script:
    - curl "http://elasticsearch:9200/_cat/health"
    - mvn -Dgroups="IntegrationTest" -DargLine="-Durl=elasticsearch" test

...

Now I want to use Opensearch 1.1.0 because that is what we use on AWS. I tried working off the docker compose setup that Opensearch suggests for developers ( https://opensearch.org/docs/latest/opensearch/install/docker/#sample-docker-compose-file-for-development ), and came up with this:

...

integration:
  stage: integration
  tags:
    - onprem
  services:
    - name: "opensearchproject/opensearch:1.1.0"
      alias: "elasticsearch"
      command: [
          "./opensearch-docker-entrypoint.sh",
          "-Ecluster.name=opensearch-cluster",
          "-Enode.name=opensearch-node1",
          "-Ebootstrap.memory_lock=true",
          "-Ediscovery.type=single-node",
          "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m",
          "DISABLE_INSTALL_DEMO_CONFIG=true",
          "DISABLE_SECURITY_PLUGIN=true"
      ]
  script:
    - curl "http://elasticsearch:9200/_cat/health"
    - mvn -Dgroups="IntegrationTest" -DargLine="-Durl=elasticsearch" test

...

The curl response:

$ curl "http://elasticsearch:9200/_cat/health"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:02 --:--:--     0curl: (7) Failed to connect to elasticsearch port 9200: No route to host

One big difference seems to be that Elasticsearch disables security with an environment variable, but Opensearch does that with an argument through setup. I tried running Opensearch directly through the "bin/" directory, but that seems to give all sorts of additional errors. The Opensearch image is available on dockerhub ( https://hub.docker.com/layers/opensearchproject/opensearch/1.1.0/images/sha256-94254d215845723e73829f34cf7053ae9810db360cf73c954737a717e9cf031d?context=explore ) , but I have no access to the Dockerfile of the Elasticsearch image to compare.

I have numerous other failed setups: Tried moving different combinations of the arguments over as stage variables in gitlab-ci.

Am I misunderstanding what to do here, or is what I'm trying even supported at all?

Body:
The final layer in opensearchproject/opensearch:1.1.0 is

CMD ["./opensearch-docker-entrypoint.sh"]

which reconfigures opensearch based on environment variables, like DISABLE_SECURITY_PLUGIN, and populates opensearch startup options like -Eplugins.security.disabled=true

Even though such ENVs are accepted by Docker, bash does not allow export of environment variables like discovery.type=single-node, so the gitlab-ci job fails.

The CMD is refactored to ENTRYPOINT in later releases by this issue

One way to trick the CMD, is to set the variables before launching the script:

integration:
  stage: integration
  variables:
    OPENSEARCH_JAVA_OPTS: "-Xms512m -Xmx512m"
    DISABLE_INSTALL_DEMO_CONFIG: "true"
    DISABLE_SECURITY_PLUGIN: "true"
  services:
    - name: opensearchproject/opensearch:1.1.0
      alias: opensearch
      command: ["bash", "-c", "env 'discovery.type=single-node' 'cluster.name=opensearch' ./opensearch-docker-entrypoint.sh"]
  script:
    - curl -sS http://opensearch:9200/_cat/health


问:
Google Analytics API Authentication Speedup
I'm using a Google Analytics API Class in PHP made by Doug Tan to retrieve Analytics data from a specific profile.

Check the url here: http://code.google.com/intl/nl/apis/analytics/docs/gdata/gdataArticlesCode.html

When you create a new instance of the class you can add the profile id, your google account + password, a daterange and whatever dimensions and metrics you want to pick up from analytics.

For example i want to see how many people visited my website from different country's in 2009.

```<code>//make a new instance from the class
$ga = new GoogleAnalytics($email,$password);

//website profile example id
$ga->setProfile('ga:4329539');

//date range
$ga->setDateRange('2010-02-01','2010-03-08');

//array to receive data from metrics and dimensions
$array = $ga->getReport(
        array('dimensions'=>('ga:country'),
        'metrics'=>('ga:visits'),
        'sort'=>'-ga:visits'
        )
);
</code>```

Now you know how this API class works, i'd like to adress my problem.

Speed. It takes alot of time to retrieve multiple types of data from the analytics database, especially if you're building different arrays with different metrics/dimensions. How can i speed up this process?

Is it possible to store all the possible data in a cache so i am able to retrieve the data without loading it over and over again?

答:
Faced the same problem and decided to use a cronjob and save the data in a .json file I can use for the display.

```<code>        $globalTrendData = $client->runReport([
            'property' => 'properties/' . $property_id,
            'dateRanges' => [
                new DateRange([
                    'start_date' => '20daysAgo',
                    'end_date' => 'yesterday',
                ]),
            ],
            'dimensions' => [
                new Dimension(['name' => 'pagePath',]),
                new Dimension(['name' => 'pageTitle',]),
                new Dimension(['name' => 'city',]),
                new Dimension(['name' => 'sessionSource',]),
                new Dimension(['name' => 'date',])
            ],
            'metrics' => [
                new Metric(['name' => 'screenPageViews',]),
                new Metric(['name' => 'userEngagementDuration',]),
                new Metric(['name' => 'activeUsers',]),

            ]
        ]);

foreach ($globalTrendData->getRows() as $key => $row) {

            $saved['globalTrendData'][$key]['dimension']['pagePath'] = (array) $row->getDimensionValues()[0]->getValue() ;
            $saved['globalTrendData'][$key]['dimension']['pageTitle'] = (array) $row->getDimensionValues()[1]->getValue() ;
            $saved['globalTrendData'][$key]['dimension']['city'] = (array) $row->getDimensionValues()[2]->getValue() ;
            $saved['globalTrendData'][$key]['dimension']['source'] = (array) $row->getDimensionValues()[3]->getValue() ;
            $saved['globalTrendData'][$key]['dimension']['date'] = (array) $row->getDimensionValues()[4]->getValue() ;

            $saved['globalTrendData'][$key]['metric']['screenPageViews'] = (array) $row->getMetricValues()[0]->getValue() ;
            $saved['globalTrendData'][$key]['metric']['userEngagementDuration'] = (array) $row->getMetricValues()[1]->getValue() ;
            $saved['globalTrendData'][$key]['metric']['activeUsers'] = (array) $row->getMetricValues()[2]->getValue() ;

        }

      file_put_contents($GLOBALS['serverPath'].'/monitoring/statistics.json',json_encode($saved, JSON_PRETTY_PRINT)) ;
</code>```

Json file output exemple :

```<code>"globalTrendData": {
    "0": {
        "dimension": {
            "pagePath": {
                "0": "\/modeles-maison\/liste"
            },
            "pageTitle": {
                "0": "Plans de maisons 100% personnalisables - adapt\u00e9s \u00e0 votre style et \u00e0 votre budget"
            },
            "city": {
                "0": "(not set)"
            },
            "source": {
                "0": "(direct)"
            },
            "date": {
                "0": "20220128"
            }
        },
        "metric": {
            "screenPageViews": {
                "0": "18"
            },
            "userEngagementDuration": {
                "0": "152"
            },
            "activeUsers": {
                "0": "1"
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using a Google Analytics API Class in PHP made by Doug Tan to retrieve Analytics data from a specific profile.

Check the url here: http://code.google.com/intl/nl/apis/analytics/docs/gdata/gdataArticlesCode.html

When you create a new instance of the class you can add the profile id, your google account + password, a daterange and whatever dimensions and metrics you want to pick up from analytics.

For example i want to see how many people visited my website from different country's in 2009.

//make a new instance from the class
$ga = new GoogleAnalytics($email,$password);

//website profile example id
$ga->setProfile('ga:4329539');

//date range
$ga->setDateRange('2010-02-01','2010-03-08');

//array to receive data from metrics and dimensions
$array = $ga->getReport(
        array('dimensions'=>('ga:country'),
        'metrics'=>('ga:visits'),
        'sort'=>'-ga:visits'
        )
);

Now you know how this API class works, i'd like to adress my problem.

Speed. It takes alot of time to retrieve multiple types of data from the analytics database, especially if you're building different arrays with different metrics/dimensions. How can i speed up this process?

Is it possible to store all the possible data in a cache so i am able to retrieve the data without loading it over and over again?

Body:
Faced the same problem and decided to use a cronjob and save the data in a .json file I can use for the display.

        $globalTrendData = $client->runReport([
            'property' => 'properties/' . $property_id,
            'dateRanges' => [
                new DateRange([
                    'start_date' => '20daysAgo',
                    'end_date' => 'yesterday',
                ]),
            ],
            'dimensions' => [
                new Dimension(['name' => 'pagePath',]),
                new Dimension(['name' => 'pageTitle',]),
                new Dimension(['name' => 'city',]),
                new Dimension(['name' => 'sessionSource',]),
                new Dimension(['name' => 'date',])
            ],
            'metrics' => [
                new Metric(['name' => 'screenPageViews',]),
                new Metric(['name' => 'userEngagementDuration',]),
                new Metric(['name' => 'activeUsers',]),

            ]
        ]);

foreach ($globalTrendData->getRows() as $key => $row) {

            $saved['globalTrendData'][$key]['dimension']['pagePath'] = (array) $row->getDimensionValues()[0]->getValue() ;
            $saved['globalTrendData'][$key]['dimension']['pageTitle'] = (array) $row->getDimensionValues()[1]->getValue() ;
            $saved['globalTrendData'][$key]['dimension']['city'] = (array) $row->getDimensionValues()[2]->getValue() ;
            $saved['globalTrendData'][$key]['dimension']['source'] = (array) $row->getDimensionValues()[3]->getValue() ;
            $saved['globalTrendData'][$key]['dimension']['date'] = (array) $row->getDimensionValues()[4]->getValue() ;

            $saved['globalTrendData'][$key]['metric']['screenPageViews'] = (array) $row->getMetricValues()[0]->getValue() ;
            $saved['globalTrendData'][$key]['metric']['userEngagementDuration'] = (array) $row->getMetricValues()[1]->getValue() ;
            $saved['globalTrendData'][$key]['metric']['activeUsers'] = (array) $row->getMetricValues()[2]->getValue() ;

        }

      file_put_contents($GLOBALS['serverPath'].'/monitoring/statistics.json',json_encode($saved, JSON_PRETTY_PRINT)) ;

Json file output exemple :

"globalTrendData": {
    "0": {
        "dimension": {
            "pagePath": {
                "0": "\/modeles-maison\/liste"
            },
            "pageTitle": {
                "0": "Plans de maisons 100% personnalisables - adapt\u00e9s \u00e0 votre style et \u00e0 votre budget"
            },
            "city": {
                "0": "(not set)"
            },
            "source": {
                "0": "(direct)"
            },
            "date": {
                "0": "20220128"
            }
        },
        "metric": {
            "screenPageViews": {
                "0": "18"
            },
            "userEngagementDuration": {
                "0": "152"
            },
            "activeUsers": {
                "0": "1"
            }
        }
    }
}


答: Please go to Preferences > Project > Project Interpreter > Choose your project and the current Python Interpreter, then you'll see the packages below. If this is empty, click on the + sign and install the relevant packages.</p>

Title: Installing python packages in Pycharm and cmd

Body:
I want to install a package in PyCharm and it cant be installed, so instead I install in the CMD in Windows with the same Python version that I set as interpreter in PyCharm. Now, when I want to import the package from inside PyCharm, it doesn't work but importing it from the Windows terminal works fine.

How can I connect the installed packages of python from the CMD to PyCharm ?


问:
How to add +9 hours on my jQuery script?
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

```<code>$end = mktime(16, 54, 0, 8, 18, 2011);
</code>```

and the copy it below

Countdown Script

```<code><script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);

$(document).ready(function() {
    $("#time").countdown({
        date: end_date,
        onComplete: function( event ){
            $(this).html("completed");
        },
        leadingZero: true
    });
});
</script>

<p id="time" class="time"></p>
</code>```

Body:
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

$end = mktime(16, 54, 0, 8, 18, 2011);

and the copy it below

Countdown Script

Body: end_date = end_date + ((3600*1000)*9);