问:
How to optimize a GROUP BY query
I am given a task to optimize the following query (not written by me)

SELECT
  "u"."email" as email,
  r.url as "domain",
  "u"."id" as "requesterId",
  s.total * 100 / count("r"."id") as "rate",
  count(("r"."url", "u"."email", "u"."id", s."total")) OVER () as total
FROM
  (
    SELECT
      url,
      id,
      "requesterId",
      created_at
    FROM
      (
        SELECT
          url,
          id,
          "requesterId",
          created_at,
          row_number() over (partition by main_request_uuid) as row_number
        FROM
          "requests" "request"
        GROUP BY
          main_request_uuid,
          retry_number,
          url,
          id,
          "requesterId",
          created_at
        ORDER BY
          main_request_uuid ASC,
          retry_number DESC
      ) "request_"
    WHERE
      request_.row_number = 1
  ) "r"
  INNER JOIN (
    SELECT
      "requesterId",
      url,
      count(created_at) AS "total"
    FROM
      (
        SELECT
          url,
          status,
          created_at,
          "requesterId"
        FROM
          (
            SELECT
              url,
              status,
              created_at,
              "requesterId",
              row_number() over (partition by main_request_uuid) as row_number
            FROM
              "requests" "request"
            GROUP BY
              main_request_uuid,
              retry_number,
              url,
              status,
              created_at,
              "requesterId"
            ORDER BY
              main_request_uuid ASC,
              retry_number DESC
          ) "request_"
        WHERE
          request_.row_number = 1
      ) "s"
    WHERE
      status IN ('success')
      AND s."created_at" :: date >= '2022-01-07' :: date
      AND s."created_at" :: date <= '2022-02-07' :: date
    GROUP BY
      s.url,
      s."requesterId"
  ) "s" ON s."requesterId" = r."requesterId"
  AND s.url = r.url
  INNER JOIN "users" "u" ON "u"."id" = r."requesterId"
WHERE
  r."created_at" :: date >= '2022-01-07' :: date
  AND r."created_at" :: date <= '2022-02-07' :: date
GROUP BY
  r.url,
  "u"."email",
  "u"."id",
  s.total
LIMIT
  10
```
<p>So there is the <code>requests</code> table, which stores some API requests and there is a mechanism to retry a request if it fails, which is repeated 5 times, while keeping separate rows for each retry. If after 5 times it still fails, it's not continued anymore. This is the reason for the <code>partition by</code> subquery, which selects only the main requests.</p>
<p>What the query should return is the total number of requests and success rate, grouped by the <code>url</code> and <code>requesterId</code>. The query I was given is not only wrong, but also takes huge amounts of time to execute, so I came up with the optimized version below</p>
<pre class="lang-sql prettyprint-override"><code>WITH a AS (SELECT url,
                  id,
                  status,
                  "requesterId",
                  created_at
           FROM (
                    SELECT url,
                           id,
                           status,
                           "requesterId",
                           created_at,
                           row_number() over (partition by main_request_uuid) as row_number
                    FROM "requests" "request"
                    WHERE
                    created_at:: date >= '2022-01-07' :: date
                    AND created_at :: date <= '2022-02-07' :: date
                    GROUP BY main_request_uuid,
                             retry_number,
                             url,
                             id,
                             status,
                             "requesterId",
                             created_at
                    ORDER BY
                             main_request_uuid ASC,
                             retry_number DESC
                ) "request_"
           WHERE request_.row_number = 1),
     b AS (SELECT count(*) total, a2.url as url, a2."requesterId" FROM a a2 GROUP BY a2.url, a2."requesterId"),
     c AS (SELECT count(*) success, a3.url as url, a3."requesterId"
           FROM a a3
           WHERE status IN ('success')
           GROUP BY a3.url, a3."requesterId")
SELECT success * 100 / total as rate, b.url, b."requesterId", total, email
FROM b
         JOIN c ON b.url = c.url AND b."requesterId" = c."requesterId" JOIN users u ON b."requesterId" = u.id
LIMIT 10;
</code>```

What the new version basically does is select all the main requests, and count the successful ones and the total count. The new version still takes a lot of time to execute (around 60s on a table with 4 million requests).

Is there a way to optimize this further?

You can see the table structure below. The table has no relevant indexes, but adding one on (url, requesterId) had no effect

column_name
data_type

id
bigint

requesterId
bigint

proxyId
bigint

url
character varying

status
USER-DEFINED

time_spent
integer

created_at
timestamp with time zone

request_information
jsonb

retry_number
smallint

main_request_uuid
character varying

And here is the execution plan on a backup table with 100k rows. It's taking 1.1s for 100k rows, but it would be more desired to at least cut it down to 200ms for this case

```<code>Limit  (cost=15196.40..15204.56 rows=1 width=77) (actual time=749.664..1095.476 rows=10 loops=1)
  CTE a
    ->  Subquery Scan on request_  (cost=15107.66..15195.96 rows=3 width=159) (actual time=226.805..591.188 rows=49474 loops=1)
          Filter: (request_.row_number = 1)
          Rows Removed by Filter: 70962
          ->  WindowAgg  (cost=15107.66..15188.44 rows=602 width=206) (actual time=226.802..571.185 rows=120436 loops=1)
                ->  Group  (cost=15107.66..15179.41 rows=602 width=198) (actual time=226.797..435.340 rows=120436 loops=1)
"                      Group Key: request.main_request_uuid, request.retry_number, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                      ->  Gather Merge  (cost=15107.66..15170.62 rows=502 width=198) (actual time=226.795..386.198 rows=120436 loops=1)
                            Workers Planned: 2
                            Workers Launched: 2
                            ->  Group  (cost=14107.64..14112.66 rows=251 width=198) (actual time=212.749..269.504 rows=40145 loops=3)
"                                  Group Key: request.main_request_uuid, request.retry_number, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                                  ->  Sort  (cost=14107.64..14108.27 rows=251 width=198) (actual time=212.744..250.031 rows=40145 loops=3)
"                                        Sort Key: request.main_request_uuid, request.retry_number DESC, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                                        Sort Method: external merge  Disk: 7952kB
                                        Worker 0:  Sort Method: external merge  Disk: 8568kB
                                        Worker 1:  Sort Method: external merge  Disk: 9072kB
                                        ->  Parallel Seq Scan on requests request  (cost=0.00..14097.63 rows=251 width=198) (actual time=0.024..44.013 rows=40145 loops=3)
                                              Filter: (((created_at)::date >= '2022-01-07'::date) AND ((created_at)::date <= '2022-02-07'::date))
  ->  Nested Loop  (cost=0.43..8.59 rows=1 width=77) (actual time=749.662..1095.364 rows=10 loops=1)
"        Join Filter: (a2.""requesterId"" = u.id)"
        ->  Nested Loop  (cost=0.16..0.28 rows=1 width=64) (actual time=749.630..1095.163 rows=10 loops=1)
"              Join Filter: (((a2.url)::text = (a3.url)::text) AND (a2.""requesterId"" = a3.""requesterId""))"
              Rows Removed by Join Filter: 69
              ->  HashAggregate  (cost=0.08..0.09 rows=1 width=48) (actual time=703.128..703.139 rows=10 loops=1)
"                    Group Key: a3.url, a3.""requesterId"""
                    Batches: 5  Memory Usage: 4297kB  Disk Usage: 7040kB
                    ->  CTE Scan on a a3  (cost=0.00..0.07 rows=1 width=40) (actual time=226.808..648.251 rows=41278 loops=1)
                          Filter: (status = 'success'::requests_status_enum)
                          Rows Removed by Filter: 8196
              ->  HashAggregate  (cost=0.08..0.11 rows=3 width=48) (actual time=38.103..38.105 rows=8 loops=10)
"                    Group Key: a2.url, a2.""requesterId"""
                    Batches: 41  Memory Usage: 4297kB  Disk Usage: 7328kB
                    ->  CTE Scan on a a2  (cost=0.00..0.06 rows=3 width=40) (actual time=0.005..7.419 rows=49474 loops=10)
"        ->  Index Scan using ""PK_a3ffb1c0c8416b9fc6f907b7433"" on users u  (cost=0.28..8.29 rows=1 width=29) (actual time=0.015..0.015 rows=1 loops=10)"
"              Index Cond: (id = a3.""requesterId"")"
Planning Time: 1.494 ms
Execution Time: 1102.488 ms
</code>```

答:
Writing query efficiently is one of the major part for query optimization specially for handling huge data set. Always avoiding unnecessary GROUP BY or ORDER BY or explicit type casting or too many joins or extra subquery or limit/limit without order by (if possible) if handling large volume of data and meet desired requirement. Create an index in created_at column. If LEFT JOIN used in your given query then query pattern would be changed. My observations are

```<code>-- avoid unnecessary GROUP BY (no aggregate function use) or ORDER BY
SELECT url
         , id
         , status
         , "requesterId"
         , created_at
    FROM (SELECT url
               , id
               , status
               , "requesterId"
               , created_at
               , row_number() over (partition by main_request_uuid order by retry_number DESC) as row_number
         FROM "requests" "request"
         WHERE (created_at:: date >= '2022-01-07'
             AND created_at :: date <= '2022-02-07')) "request_"
         WHERE request_.row_number = 1
</code>```

N.B.: if created_at column data type is timestamp without time zone then no need to extra casting. Follow the below statement

```<code>(created_at >= '2022-01-07'
                 AND created_at <= '2022-02-07')

-- Combine two CTE into one as per requirement
SELECT url, "requesterId", COUNT(1) total
         , COUNT(1) FILTER (WHERE status = 'success') success
        FROM a
        -- WHERE status IN ('success')
        GROUP BY url, "requesterId"
</code>```

So the final query as like below

```<code>WITH a AS (
    SELECT url
         , id
         , status
         , "requesterId"
         , created_at
    FROM (SELECT url
               , id
               , status
               , "requesterId"
               , created_at
               , row_number() over (partition by main_request_uuid order by retry_number DESC) as row_number
         FROM "requests" "request"
         WHERE (created_at:: date >= '2022-01-07'
             AND created_at :: date <= '2022-02-07')) "request_"
         WHERE request_.row_number = 1
), b as (
    SELECT url, "requesterId", COUNT(1) total
         , COUNT(1) FILTER (WHERE status = 'success') success
        FROM a
        -- WHERE status IN ('success')
        GROUP BY url, "requesterId"
) select (success * 100) / total as rate
       , b.url, b."requesterId", total, email
from b
JOIN users u
  ON u.id = b."requesterId"
limit 10;
</code>```

If above query doesn't meet requirement then try below query. But this query will perfect if using LEFT JOIN instead of INNER JOIN

```<code>WITH a AS (
    SELECT url
         , id
         , status
         , "requesterId"
         , created_at
    FROM (SELECT url
               , id
               , status
               , "requesterId"
               , created_at
               , row_number() over (partition by main_request_uuid order by retry_number DESC) as row_number
         FROM "requests" "request"
         WHERE (created_at:: date >= '2022-01-07'
             AND created_at :: date <= '2022-02-07')) "request_"
         WHERE request_.row_number = 1
), b as (
    SELECT count(1) total, a2.url as url, a2."requesterId"
    FROM a a2
    GROUP BY a2.url, a2."requesterId"
), c AS (SELECT count(1) success, a3.url as url, a3."requesterId"
         FROM a a3
         WHERE status = 'success'
         GROUP BY a3.url, a3."requesterId")
SELECT success * 100 / total as rate, b.url, b."requesterId", total, email
FROM b
JOIN c
  ON b.url = c.url AND b."requesterId" = c."requesterId"
JOIN users u
  ON b."requesterId" = u.id
LIMIT 10;

 select (success * 100) / total as rate
       , b.url, b."requesterId", total, email
from b
JOIN users u
  ON u.id = b."requesterId"
limit 10;
</code>```

Title: How to optimize a GROUP BY query

Body:
I am given a task to optimize the following query (not written by me)

SELECT
  "u"."email" as email,
  r.url as "domain",
  "u"."id" as "requesterId",
  s.total * 100 / count("r"."id") as "rate",
  count(("r"."url", "u"."email", "u"."id", s."total")) OVER () as total
FROM
  (
    SELECT
      url,
      id,
      "requesterId",
      created_at
    FROM
      (
        SELECT
          url,
          id,
          "requesterId",
          created_at,
          row_number() over (partition by main_request_uuid) as row_number
        FROM
          "requests" "request"
        GROUP BY
          main_request_uuid,
          retry_number,
          url,
          id,
          "requesterId",
          created_at
        ORDER BY
          main_request_uuid ASC,
          retry_number DESC
      ) "request_"
    WHERE
      request_.row_number = 1
  ) "r"
  INNER JOIN (
    SELECT
      "requesterId",
      url,
      count(created_at) AS "total"
    FROM
      (
        SELECT
          url,
          status,
          created_at,
          "requesterId"
        FROM
          (
            SELECT
              url,
              status,
              created_at,
              "requesterId",
              row_number() over (partition by main_request_uuid) as row_number
            FROM
              "requests" "request"
            GROUP BY
              main_request_uuid,
              retry_number,
              url,
              status,
              created_at,
              "requesterId"
            ORDER BY
              main_request_uuid ASC,
              retry_number DESC
          ) "request_"
        WHERE
          request_.row_number = 1
      ) "s"
    WHERE
      status IN ('success')
      AND s."created_at" :: date >= '2022-01-07' :: date
      AND s."created_at" :: date <= '2022-02-07' :: date
    GROUP BY
      s.url,
      s."requesterId"
  ) "s" ON s."requesterId" = r."requesterId"
  AND s.url = r.url
  INNER JOIN "users" "u" ON "u"."id" = r."requesterId"
WHERE
  r."created_at" :: date >= '2022-01-07' :: date
  AND r."created_at" :: date <= '2022-02-07' :: date
GROUP BY
  r.url,
  "u"."email",
  "u"."id",
  s.total
LIMIT
  10

So there is the requests table, which stores some API requests and there is a mechanism to retry a request if it fails, which is repeated 5 times, while keeping separate rows for each retry. If after 5 times it still fails, it's not continued anymore. This is the reason for the partition by subquery, which selects only the main requests.

What the query should return is the total number of requests and success rate, grouped by the url and requesterId. The query I was given is not only wrong, but also takes huge amounts of time to execute, so I came up with the optimized version below

WITH a AS (SELECT url,
                  id,
                  status,
                  "requesterId",
                  created_at
           FROM (
                    SELECT url,
                           id,
                           status,
                           "requesterId",
                           created_at,
                           row_number() over (partition by main_request_uuid) as row_number
                    FROM "requests" "request"
                    WHERE
                    created_at:: date >= '2022-01-07' :: date
                    AND created_at :: date <= '2022-02-07' :: date
                    GROUP BY main_request_uuid,
                             retry_number,
                             url,
                             id,
                             status,
                             "requesterId",
                             created_at
                    ORDER BY
                             main_request_uuid ASC,
                             retry_number DESC
                ) "request_"
           WHERE request_.row_number = 1),
     b AS (SELECT count(*) total, a2.url as url, a2."requesterId" FROM a a2 GROUP BY a2.url, a2."requesterId"),
     c AS (SELECT count(*) success, a3.url as url, a3."requesterId"
           FROM a a3
           WHERE status IN ('success')
           GROUP BY a3.url, a3."requesterId")
SELECT success * 100 / total as rate, b.url, b."requesterId", total, email
FROM b
         JOIN c ON b.url = c.url AND b."requesterId" = c."requesterId" JOIN users u ON b."requesterId" = u.id
LIMIT 10;

What the new version basically does is select all the main requests, and count the successful ones and the total count. The new version still takes a lot of time to execute (around 60s on a table with 4 million requests).

Is there a way to optimize this further?

You can see the table structure below. The table has no relevant indexes, but adding one on (url, requesterId) had no effect

column_name
data_type

id
bigint

requesterId
bigint

proxyId
bigint

url
character varying

status
USER-DEFINED

time_spent
integer

created_at
timestamp with time zone

request_information
jsonb

retry_number
smallint

main_request_uuid
character varying

And here is the execution plan on a backup table with 100k rows. It's taking 1.1s for 100k rows, but it would be more desired to at least cut it down to 200ms for this case

Limit  (cost=15196.40..15204.56 rows=1 width=77) (actual time=749.664..1095.476 rows=10 loops=1)
  CTE a
    ->  Subquery Scan on request_  (cost=15107.66..15195.96 rows=3 width=159) (actual time=226.805..591.188 rows=49474 loops=1)
          Filter: (request_.row_number = 1)
          Rows Removed by Filter: 70962
          ->  WindowAgg  (cost=15107.66..15188.44 rows=602 width=206) (actual time=226.802..571.185 rows=120436 loops=1)
                ->  Group  (cost=15107.66..15179.41 rows=602 width=198) (actual time=226.797..435.340 rows=120436 loops=1)
"                      Group Key: request.main_request_uuid, request.retry_number, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                      ->  Gather Merge  (cost=15107.66..15170.62 rows=502 width=198) (actual time=226.795..386.198 rows=120436 loops=1)
                            Workers Planned: 2
                            Workers Launched: 2
                            ->  Group  (cost=14107.64..14112.66 rows=251 width=198) (actual time=212.749..269.504 rows=40145 loops=3)
"                                  Group Key: request.main_request_uuid, request.retry_number, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                                  ->  Sort  (cost=14107.64..14108.27 rows=251 width=198) (actual time=212.744..250.031 rows=40145 loops=3)
"                                        Sort Key: request.main_request_uuid, request.retry_number DESC, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                                        Sort Method: external merge  Disk: 7952kB
                                        Worker 0:  Sort Method: external merge  Disk: 8568kB
                                        Worker 1:  Sort Method: external merge  Disk: 9072kB
                                        ->  Parallel Seq Scan on requests request  (cost=0.00..14097.63 rows=251 width=198) (actual time=0.024..44.013 rows=40145 loops=3)
                                              Filter: (((created_at)::date >= '2022-01-07'::date) AND ((created_at)::date <= '2022-02-07'::date))
  ->  Nested Loop  (cost=0.43..8.59 rows=1 width=77) (actual time=749.662..1095.364 rows=10 loops=1)
"        Join Filter: (a2.""requesterId"" = u.id)"
        ->  Nested Loop  (cost=0.16..0.28 rows=1 width=64) (actual time=749.630..1095.163 rows=10 loops=1)
"              Join Filter: (((a2.url)::text = (a3.url)::text) AND (a2.""requesterId"" = a3.""requesterId""))"
              Rows Removed by Join Filter: 69
              ->  HashAggregate  (cost=0.08..0.09 rows=1 width=48) (actual time=703.128..703.139 rows=10 loops=1)
"                    Group Key: a3.url, a3.""requesterId"""
                    Batches: 5  Memory Usage: 4297kB  Disk Usage: 7040kB
                    ->  CTE Scan on a a3  (cost=0.00..0.07 rows=1 width=40) (actual time=226.808..648.251 rows=41278 loops=1)
                          Filter: (status = 'success'::requests_status_enum)
                          Rows Removed by Filter: 8196
              ->  HashAggregate  (cost=0.08..0.11 rows=3 width=48) (actual time=38.103..38.105 rows=8 loops=10)
"                    Group Key: a2.url, a2.""requesterId"""
                    Batches: 41  Memory Usage: 4297kB  Disk Usage: 7328kB
                    ->  CTE Scan on a a2  (cost=0.00..0.06 rows=3 width=40) (actual time=0.005..7.419 rows=49474 loops=10)
"        ->  Index Scan using ""PK_a3ffb1c0c8416b9fc6f907b7433"" on users u  (cost=0.28..8.29 rows=1 width=29) (actual time=0.015..0.015 rows=1 loops=10)"
"              Index Cond: (id = a3.""requesterId"")"
Planning Time: 1.494 ms
Execution Time: 1102.488 ms

Body:
Writing query efficiently is one of the major part for query optimization specially for handling huge data set. Always avoiding unnecessary GROUP BY or ORDER BY or explicit type casting or too many joins or extra subquery or limit/limit without order by (if possible) if handling large volume of data and meet desired requirement. Create an index in created_at column. If LEFT JOIN used in your given query then query pattern would be changed. My observations are

-- avoid unnecessary GROUP BY (no aggregate function use) or ORDER BY
SELECT url
         , id
         , status
         , "requesterId"
         , created_at
    FROM (SELECT url
               , id
               , status
               , "requesterId"
               , created_at
               , row_number() over (partition by main_request_uuid order by retry_number DESC) as row_number
         FROM "requests" "request"
         WHERE (created_at:: date >= '2022-01-07'
             AND created_at :: date <= '2022-02-07')) "request_"
         WHERE request_.row_number = 1

N.B.: if created_at column data type is timestamp without time zone then no need to extra casting. Follow the below statement

(created_at >= '2022-01-07'
                 AND created_at <= '2022-02-07')

-- Combine two CTE into one as per requirement
SELECT url, "requesterId", COUNT(1) total
         , COUNT(1) FILTER (WHERE status = 'success') success
        FROM a
        -- WHERE status IN ('success')
        GROUP BY url, "requesterId"

So the final query as like below

WITH a AS (
    SELECT url
         , id
         , status
         , "requesterId"
         , created_at
    FROM (SELECT url
               , id
               , status
               , "requesterId"
               , created_at
               , row_number() over (partition by main_request_uuid order by retry_number DESC) as row_number
         FROM "requests" "request"
         WHERE (created_at:: date >= '2022-01-07'
             AND created_at :: date <= '2022-02-07')) "request_"
         WHERE request_.row_number = 1
), b as (
    SELECT url, "requesterId", COUNT(1) total
         , COUNT(1) FILTER (WHERE status = 'success') success
        FROM a
        -- WHERE status IN ('success')
        GROUP BY url, "requesterId"
) select (success * 100) / total as rate
       , b.url, b."requesterId", total, email
from b
JOIN users u
  ON u.id = b."requesterId"
limit 10;

If above query doesn't meet requirement then try below query. But this query will perfect if using LEFT JOIN instead of INNER JOIN

WITH a AS (
    SELECT url
         , id
         , status
         , "requesterId"
         , created_at
    FROM (SELECT url
               , id
               , status
               , "requesterId"
               , created_at
               , row_number() over (partition by main_request_uuid order by retry_number DESC) as row_number
         FROM "requests" "request"
         WHERE (created_at:: date >= '2022-01-07'
             AND created_at :: date <= '2022-02-07')) "request_"
         WHERE request_.row_number = 1
), b as (
    SELECT count(1) total, a2.url as url, a2."requesterId"
    FROM a a2
    GROUP BY a2.url, a2."requesterId"
), c AS (SELECT count(1) success, a3.url as url, a3."requesterId"
         FROM a a3
         WHERE status = 'success'
         GROUP BY a3.url, a3."requesterId")
SELECT success * 100 / total as rate, b.url, b."requesterId", total, email
FROM b
JOIN c
  ON b.url = c.url AND b."requesterId" = c."requesterId"
JOIN users u
  ON b."requesterId" = u.id
LIMIT 10;

 select (success * 100) / total as rate
       , b.url, b."requesterId", total, email
from b
JOIN users u
  ON u.id = b."requesterId"
limit 10;


来源: stackexchange

问:
How to get column and values dictionary in SQLAlchemy model?
I have the following table:

```<code>Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String(255))
    email = Column(String(255))
</code>```

Is it possible to get a dictionary that for empty record will return something like:

```<code>{'id': None, 'username': None, 'email': None}
</code>```

And if I do:

```<code>user = User()
user.username = "testuser"
user.email = "test@example.com"
</code>```

I want to be able to get the dictionary with the corresponding values. Of course if I save the record I'd expect it to have the id there as well.

答:
You can use the following method which is inspired by the answer alecxe gave.

```<code>def get_model_dict(model, row):
    if isinstance(row, model):
        columns = [x.name for x in list(model.__table__.columns)]
        return {x: getattr(row, x) for x in columns}
    else:
        raise ValueError(f"The provided row is not of type {model.__table__.name.title()}")
</code>```

Now all you have to do is pass the model and the row of the same models to get the dictionary representation of the data.

ContentLicense: CC BY-SA 3.0

Body:
I have the following table:

Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String(255))
    email = Column(String(255))

Is it possible to get a dictionary that for empty record will return something like:

{'id': None, 'username': None, 'email': None}

And if I do:

user = User()
user.username = "testuser"
user.email = "test@example.com"

I want to be able to get the dictionary with the corresponding values. Of course if I save the record I'd expect it to have the id there as well.

Body:
You can use the following method which is inspired by the answer alecxe gave.

def get_model_dict(model, row):
    if isinstance(row, model):
        columns = [x.name for x in list(model.__table__.columns)]
        return {x: getattr(row, x) for x in columns}
    else:
        raise ValueError(f"The provided row is not of type {model.__table__.name.title()}")

Now all you have to do is pass the model and the row of the same models to get the dictionary representation of the data.

ContentLicense: CC BY-SA 4.0


问:
Replacing text in Pandas "Python"
PAT['HFZ'].replace('1','HFZ',inplace=True)

^ This is the code I'm dealing with

I want to change '1' to 'HFZ'

I tried to do it but an error accrue

答:
In case you have a Pandas dataframe, the easiest way to do it is the following:

df['range'].replace(',','-',inplace=True)

Which I understand it is what you tried. If it does not replace what you are trying to replace is because str values do not match and no replacement occurs.

According to the docs we see this description:

str or regex: str: string exactly matching to_replace will be replaced with value

Title: Replacing text in Pandas "Python"


问:
ASP Web API Large Runtimes Folder
I have 2 projects, an ASP MVC project and an ASP Web API project using .NET Framework 4.7.2

From a coding perspective both of these project types are very similar.

Yet the MVC project publishes to <100MB and the API project to 500MB+, despite the MVC project containing numerous JS libraries and other content.

This seems to be down to a folder the Web API project includes called "runtimes". Is this folder necessary, can it be optionalised, are there some optimisation options I can set?

答:
This is the framework which is published because of the settings in your publish profile.

Publishing your app as self-contained produces an application that includes the .NET runtime and libraries, and your application and its dependencies. Users of the application can run it on a machine that doesn't have the .NET runtime installed.
Publishing your app as framework-dependent produces an application that includes only your application itself and its dependencies. Users of the application have to separately install the .NET runtime.

https://learn.microsoft.com/en-us/dotnet/core/deploying/

Title: ASP Web API Large Runtimes Folder


问:
Multi-project test dependencies with gradle
I have a multi-project configuration and I want to use gradle.

My projects are like this:

Project A

-> src/main/java

-> src/test/java

Project B

-> src/main/java (depends on src/main/java on Project A)

-> src/test/java (depends on src/test/java on Project A)

My Project B build.gradle file is like this:

```<code>apply plugin: 'java'
dependencies {
  compile project(':ProjectA')
}
</code>```

The task compileJava work great but the compileTestJava does not compile the test file from Project A.

答:
If you are struggling to adapt the solution to the Gradle Kotlin DSL this is the equivalent:</p>
```<code>configurations {
    register("testClasses") {
        extendsFrom(testImplementation.get())
    }
}
val testJar = tasks.register<Jar>("testJar") {
    archiveClassifier.set("test")
    from(sourceSets.test)
}
artifacts.add("testClasses", testJar)
</code>```

Body:
I have a multi-project configuration and I want to use gradle.

My projects are like this:

Project A

-> src/main/java

-> src/test/java

Project B

-> src/main/java (depends on src/main/java on Project A)

-> src/test/java (depends on src/test/java on Project A)

My Project B build.gradle file is like this:

apply plugin: 'java'
dependencies {
  compile project(':ProjectA')
}

The task compileJava work great but the compileTestJava does not compile the test file from Project A.

Body:
If you are struggling to adapt the solution to the Gradle Kotlin DSL this is the equivalent:

configurations {
    register("testClasses") {
        extendsFrom(testImplementation.get())
    }
}
val testJar = tasks.register<Jar>("testJar") {
    archiveClassifier.set("test")
    from(sourceSets.test)
}
artifacts.add("testClasses", testJar)


问:
How to fetch private data using Googlesheets API to my website using nodeJs
I need to access some data from a private Google Sheets document that only my google account has access to – it is not shared with anyone else.

From here: https://developers.google.com/sheets/guides/authorizing

When your application requests private data, the request must be
authorized by an authenticated user who has access to that data.

Again, that user would be me – the application developer. The users of my application will not have these sheets shared with them.

From what I’m reading in the Google API docs, I’m not sure this is possible – but it seems to me like it should be. I am using nodeJs.

Can anyone help me out?

答:
Service account with domain-wide delegation:

The only way to avoid user interaction when accessing user private data is to use a service account with domain-wide delegation to impersonate your regular account.

That requires being a domain admin, though, so I'm not sure this option is available to you.

Sharing the spreadsheet with a service account:

Another option would be to share the spreadsheet with the service account, so you can access it using that account. Service accounts are not linked to a specific user, and so follow a different OAuth flow which doesn't require user interaction. See reference below.

Otherwise:

If you are not a domain admin and you don't want to share the spreadsheet with a service account, you are left with the web server workflow, which requires user interaction: you just cannot bypass this interaction.

I'd suggest you to read the references linked below.

Reference:

Using OAuth 2.0 for Web Server Applications

Using OAuth 2.0 for Server to Server Applications


问:
Passing JavaScript variable inside the function
I'm facing a problem that with my Laravel project in JavaScript part.

My issue is that I have a form and when taking the variable outside the function it becomes empty ("") and works only inside the function

```<code><form method="POST" action="#">
  @csrf

  <label for="package">إختر الباقة:</label>
  <div class="card-deck mb-4 text-center">
    <div class="card shadow-sm">
    <div class="card-header bg-dark-1">

                            <h6 class="my-0 text-white">اشتراك شهري</h6>

                        </div>
                        <div class="card-body">

                            <h1 class="card-title">$20</h1>

                            <div class="form-check">

                                <input type="radio" onclick="setPrice()" class="form-check-input" id="package"
                                    name="package" class="radios" value="20" />
                                <label class="form-check-label" for="package">إختر هذه الباقة</label>

                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm">
                        <div class="card-header bg-dark-1">
                            <h6 class="my-0 text-white">نصف سنوي</h6>
                        </div>
                        <div class="card-body">
                            <h1 class="card-title">$50</h1>
                            <div class="form-check">
                                <input type="radio" class="form-check-input" onclick="setPrice()" id="package"
                                    name="package" value="50" class="radios" />
                                <label class="form-check-label" for="package">إختر هذه الباقة</label>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm">
                        <div class="card-header bg-dark-1">
                            <h6 class="my-0 text-white">اشتراك سنوي</h6>
                        </div>
                        <div class="card-body">
                            <h1 class="card-title">$100</h1>
                            <div class="form-check">
                                <input type="radio" class="form-check-input" onclick="setPrice()" id="package"
                                    name="package" value="100" class="radios" />
                                <label class="form-check-label" for="package">إختر هذه الباقة</label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <input type="text" name="name" onclick="setName()" class="form-control" id="name" required
                        data-error="الرجاء ادخال الاسم الكامل" placeholder="الاسم الكامل" />
                    @if ($errors->has('name'))
                        <span class="help-block">
                            <strong>{{ $errors->first('name') }}</strong>
                        </span>
                    @endif
                </div>
                <div class="form-group">
                    <input type="text" name="phone" onchange="setPhone()" class="form-control" id="phone" required
                        data-error="الرجاء ادخال رقم الهاتف" placeholder="رقم الهاتف" />
                    @if ($errors->has('phone'))
                        <span class="help-block">
                            <strong>{{ $errors->first('phone') }}</strong>
                        </span>
                    @endif
                </div>
                <div class="form-group">
                    <input type="email" name="email" onchange="setEmail()" class="form-control" id="email" required
                        data-error="الرجاء ادخال البريد الالكتروني" placeholder="البريد الالكتروني" />
                    @if ($errors->has('email'))
                        <span class="help-block">
                            <strong>{{ $errors->first('email') }}</strong>
                        </span>
                    @endif
                </div>
                <div class="form-group">
                    <input type="password" onchange="setPassword()" name="password" class="form-control" id="password"
                        required data-error="الرجاء ادخال كلمة السر" placeholder="كلمة السر" />
                    @if ($errors->has('password'))
                        <span class="help-block">
                            <strong>{{ $errors->first('password') }}</strong>
                        </span>
                    @endif
                </div>
                <div class="form-group">
                    <input type="password" name="password_confirmation" class="form-control" id="password-confirm"
                        required data-error="الرجاء ادخال تأكيد كلمة السر" placeholder="تأكيد كلمة السر" />
                    @if ($errors->has('password_confirmation'))
                        <span class="help-block">
                            <strong>{{ $errors->first('password_confirmation') }}</strong>
                        </span>
                    @endif
                </div>
                <button class="default-btn confirm_payment" name="submit" onclick="Checkout.showPaymentPage();"
                    id="form-submit">تسجيل</button>
</code>```

SHOW

and when taking a variable only works inside the function and outside always empty
here's my script part:

```<code><script type="text/javascript">
    var package1 = $('input[name="package"]:checked').val();
    var name1 = $('input[name="name"]').val(); //name
    var phone1 = $('input[name="phone"]').val(); //phone
    var email1 = $('input[name="email"]').val(); //email
    var password1 = $('input[name="password"]').val(); //password
    $("#show").click(function() {
        console.warn(name1);//result ""

        // if i write var package1 = $('input[name="package"]:checked').val(); and others inside the function here it works.
     });
 </script>
</code>```

答:
Try in this way

```<code>$(document).ready(function(){
// Get value on button click and show alert
$("#myBtn").click(function(){
    var str = $("#myInput").val();
    alert(str);
});
</code>```

});

Body:
I'm facing a problem that with my Laravel project in JavaScript part.

My issue is that I have a form and when taking the variable outside the function it becomes empty ("") and works only inside the function

<form method="POST" action="#">
  @csrf

  إختر الباقة:

اشتراك شهري

$20

                                <input type="radio" onclick="setPrice()" class="form-check-input" id="package"
                                    name="package" class="radios" value="20" />
                                إختر هذه الباقة

نصف سنوي

$50

                                <input type="radio" class="form-check-input" onclick="setPrice()" id="package"
                                    name="package" value="50" class="radios" />
                                إختر هذه الباقة

اشتراك سنوي

$100

                                <input type="radio" class="form-check-input" onclick="setPrice()" id="package"
                                    name="package" value="100" class="radios" />
                                إختر هذه الباقة

                    <input type="text" name="name" onclick="setName()" class="form-control" id="name" required
                        data-error="الرجاء ادخال الاسم الكامل" placeholder="الاسم الكامل" />
                    @if ($errors->has('name'))

                            {{ $errors->first('name') }}

                    @endif

                    <input type="text" name="phone" onchange="setPhone()" class="form-control" id="phone" required
                        data-error="الرجاء ادخال رقم الهاتف" placeholder="رقم الهاتف" />
                    @if ($errors->has('phone'))

                            {{ $errors->first('phone') }}

                    @endif

                    <input type="email" name="email" onchange="setEmail()" class="form-control" id="email" required
                        data-error="الرجاء ادخال البريد الالكتروني" placeholder="البريد الالكتروني" />
                    @if ($errors->has('email'))

                            {{ $errors->first('email') }}

                    @endif

                    <input type="password" onchange="setPassword()" name="password" class="form-control" id="password"
                        required data-error="الرجاء ادخال كلمة السر" placeholder="كلمة السر" />
                    @if ($errors->has('password'))

                            {{ $errors->first('password') }}

                    @endif

                    <input type="password" name="password_confirmation" class="form-control" id="password-confirm"
                        required data-error="الرجاء ادخال تأكيد كلمة السر" placeholder="تأكيد كلمة السر" />
                    @if ($errors->has('password_confirmation'))

                            {{ $errors->first('password_confirmation') }}

                    @endif

                <button class="default-btn confirm_payment" name="submit" onclick="Checkout.showPaymentPage();"
                    id="form-submit">تسجيل</button>

SHOW

and when taking a variable only works inside the function and outside always empty
here's my script part:

Body:
Try in this way

$(document).ready(function(){
// Get value on button click and show alert
$("#myBtn").click(function(){
    var str = $("#myInput").val();
    alert(str);
});

});


问:
how to connect to mongodb from express?
Tried to connect To mongodb, it says connection not found.  can someone point out what error I have made in code, is there any problem in db connect URI

```<code>const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");

dotenv.config();

const db =
  "mongodb+srv://<sumit>:<sumit>@bike-ecommerce.u7sod.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";

console.log(db);
mongoose
  .connect(db)
  .then(() => {
    console.log("connection successful");
  })
  .catch((err) => console.log(err));

app.use(express.json());

//importing routes

const authRoute = require("./routes/auth");

//route middle wares
app.use("/api/user", authRoute);

app.listen(3000, () => console.log("gg server is running"));
</code>```

答:
Finally found a solution.
Thanks for the help @ahmed ali.

In db uri, username and password should be written without angular brackets and replace the first database with your database name created.

Title: how to connect to mongodb from express?

Body:
Tried to connect To mongodb, it says connection not found.  can someone point out what error I have made in code, is there any problem in db connect URI

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");

dotenv.config();

const db =
  "mongodb+srv://<sumit>:<sumit>@bike-ecommerce.u7sod.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";

console.log(db);
mongoose
  .connect(db)
  .then(() => {
    console.log("connection successful");
  })
  .catch((err) => console.log(err));

app.use(express.json());

//importing routes

const authRoute = require("./routes/auth");

//route middle wares
app.use("/api/user", authRoute);

app.listen(3000, () => console.log("gg server is running"));


问:
Why is "a =(b>0)?1:0" better than "if-else" version in CUDA?
Could you tell me why

```<code>a =(b>0)?1:0
</code>```

is better than

```<code>if (b>0)a=1; else a =0;
</code>```

version in CUDA? Please give details. Many thanks.

Yik

答: In general you need to avoid branches in CUDA code, otherwise you may get warp divergence which can result in a big performance hit. if/else clauses will normally result in branches based on a test of an expression. One way of eliminating branches is to use an expression which can be implemented without branches if the compiler is smart enough - that way all the threads in a warp follow the same code path.

Body:
Could you tell me why

a =(b>0)?1:0

is better than

if (b>0)a=1; else a =0;

version in CUDA? Please give details. Many thanks.

Yik


问:
How to use markes on a line graph in Observable Plot?
While working with Observable Plot, I stumbled across the markers section in the API documentation.

Yet, I cannot figure out how to make it work.

Imagine I have the following mark:

```<code>Plot.line(data, {x: "timestamp", y: "val", curve: "natural"})
</code>```

How can I add markers to every data point on this line? I cannot extract that information from the API documentation (an example would be nice). Following versions do not work

```<code>Plot.line(data, {x: "timestamp", y: "val", curve: "natural", marker: true, markerEnd: "circle"})
Plot.line(data, {x: "timestamp", y: "val", curve: "natural", marker: "circle"})
</code>```

Remark: I am not looking for a solution using an additional Plot.dot.

Remark 2: Cross-posted to the ObservableHQ forum

答:
Following answer was received on the ObservableHQ forum:

Markers have been available in main for just a week, but not yet pushed to npm and Observable.

If you need them now, here’s how you can build Plot from source:

```<code>git clone https://github.com/observablehq/plot.git
cd plot
yarn
yarn prepublishOnly
</code>```

The files will then be available in the dist/ folder. Upload dist/plot.umd.js as a File Attachment, then create a cell with:

```<code>Plot = require(await FileAttachment(“plot.umd.js”).url())
</code>```

Thus, either wait for a new release to be published or build the source yourself at the moment.

Body:
While working with Observable Plot, I stumbled across the markers section in the API documentation.

Yet, I cannot figure out how to make it work.

Imagine I have the following mark:

Plot.line(data, {x: "timestamp", y: "val", curve: "natural"})

How can I add markers to every data point on this line? I cannot extract that information from the API documentation (an example would be nice). Following versions do not work

Plot.line(data, {x: "timestamp", y: "val", curve: "natural", marker: true, markerEnd: "circle"})
Plot.line(data, {x: "timestamp", y: "val", curve: "natural", marker: "circle"})

Remark: I am not looking for a solution using an additional Plot.dot.

Remark 2: Cross-posted to the ObservableHQ forum

Body:
Following answer was received on the ObservableHQ forum:

Markers have been available in main for just a week, but not yet pushed to npm and Observable.

If you need them now, here’s how you can build Plot from source:

git clone https://github.com/observablehq/plot.git
cd plot
yarn
yarn prepublishOnly

The files will then be available in the dist/ folder. Upload dist/plot.umd.js as a File Attachment, then create a cell with:

Plot = require(await FileAttachment(“plot.umd.js”).url())

Thus, either wait for a new release to be published or build the source yourself at the moment.


问:
How can I scroll down to the end of a dynamically loading webpage?
We are talking about a webpage which as much as your scrolling down new elements coming up, up to a point.

I have try:

1.WebUI.scrollToElement(findTestObject('footer'), 30)

2.WebUI.executeJavaScript('window.scrollTo(0, document.documentElement.scrollHeight)', [])

3.WebUI.executeJavaScript('window.scrollTo(0, document.body.scrollHeight)', [])

4.WebUI.executeJavaScript(‘window.scrollTo(0, **923** )’, [])

…But none of this goes to the end of page. Any other idea?

答:
I found this script which does the "job":</p>
```<code>try {
  long lastHeight=((Number) WebUI.executeJavaScript("return document.body.scrollHeight", null)).longValue();

  while (true) {
    WebUI.executeJavaScript("window.scrollTo(0, document.body.scrollHeight);", null);
    Thread.sleep(2000);
    long newHeight = ((Number)WebUI.executeJavaScript("return document.body.scrollHeight", null)).longValue();
    if (newHeight == lastHeight) {
      break;
    }
    lastHeight = newHeight;
  }
} catch (InterruptedException e) {
 e.printStackTrace();
}
</code>```

Body:
I found this script which does the "job":

try {
  long lastHeight=((Number) WebUI.executeJavaScript("return document.body.scrollHeight", null)).longValue();

  while (true) {
    WebUI.executeJavaScript("window.scrollTo(0, document.body.scrollHeight);", null);
    Thread.sleep(2000);
    long newHeight = ((Number)WebUI.executeJavaScript("return document.body.scrollHeight", null)).longValue();
    if (newHeight == lastHeight) {
      break;
    }
    lastHeight = newHeight;
  }
} catch (InterruptedException e) {
 e.printStackTrace();
}


问:
`npm install` fails on node-gyp rebuild with `gyp: No Xcode or CLT version detected!`
Every time I try npm install. I get the following error. How do I fix it?

```<code>gyp: No Xcode or CLT version detected!
</code>```

I am on node -v → v8.8.0 & npm -v → v6.11.3

I tried to run it on VSCode terminal and iTerm, but both ended up getting the same error. (both are updated to the latest version). The only new thing I did is updating my macOS to the latest version (Catalina 10.15.3 today).

```<code>$ npm install          Fri Mar  6 17:22:40 2020

> fsevents@1.2.11 install /Users/synapse/Documents/synapsefi-dev-ui/node_modules/watchpack/node_modules/fsevents
> node-gyp rebuild

No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/Users/synapse/.nvm/versions/node/v8.8.0/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:344:16)
gyp ERR! stack     at emitTwo (events.js:125:13)
gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 19.3.0
gyp ERR! command "/Users/synapse/.nvm/versions/node/v8.8.0/bin/node" "/Users/synapse/.nvm/versions/node/v8.8.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/synapse/Documents/synapsefi-dev-ui/node_modules/watchpack/node_modules/fsevents
gyp ERR! node -v v8.8.0
gyp ERR! node-gyp -v v5.0.3
gyp ERR! not ok
npm WARN synapsefi-dev-ui@2.0.20 No repository field.
npm WARN The package country-data is included as both a dev and production dependency.
npm WARN The package react-dropzone is included as both a dev and production dependency.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 (node_modules/watchpack/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
</code>```

答: I tried everything and nothing worked. Personally, even if the problem was gyp, it was Next that bugged. So I downgraded in my node.js version. to install next.js and return to the latest version.</p>

Body:
Every time I try npm install. I get the following error. How do I fix it?

gyp: No Xcode or CLT version detected!

I am on node -v → v8.8.0 & npm -v → v6.11.3

I tried to run it on VSCode terminal and iTerm, but both ended up getting the same error. (both are updated to the latest version). The only new thing I did is updating my macOS to the latest version (Catalina 10.15.3 today).

$ npm install          Fri Mar  6 17:22:40 2020

> fsevents@1.2.11 install /Users/synapse/Documents/synapsefi-dev-ui/node_modules/watchpack/node_modules/fsevents
> node-gyp rebuild

No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/Users/synapse/.nvm/versions/node/v8.8.0/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:344:16)
gyp ERR! stack     at emitTwo (events.js:125:13)
gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 19.3.0
gyp ERR! command "/Users/synapse/.nvm/versions/node/v8.8.0/bin/node" "/Users/synapse/.nvm/versions/node/v8.8.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/synapse/Documents/synapsefi-dev-ui/node_modules/watchpack/node_modules/fsevents
gyp ERR! node -v v8.8.0
gyp ERR! node-gyp -v v5.0.3
gyp ERR! not ok
npm WARN synapsefi-dev-ui@2.0.20 No repository field.
npm WARN The package country-data is included as both a dev and production dependency.
npm WARN The package react-dropzone is included as both a dev and production dependency.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 (node_modules/watchpack/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1


问:
Is there a way to use python in android applications programming?
I am working on an application that uses eye-tracking technology to detect eye movements..
what I want to ask, is there any way to use python to develop Android application? or integrate it with android studio?

and what is best language to develop an application with an eye tracking feature?

答:
Try these platforms for Python Android Development:

QPython

PySide

It is possible to develop Android apps using Python, but won't recommend it as it won’t be as efficient as Android apps that are developed by using Java or Kotlin.


问:
Multiple time allocation and release
I am creating a quiz app for iPhone/iPad(universal app).It is working fine on simulator but on real device there are some problem i am facing..

I am creating UILabels and UIButtons programmatically and i am using them so many times for displaying questions and answers one by one.

problem is when i reach around question 20 to 22 the application crashes. I don't know why. there is no memory leak i found. I release all the labels and buttons at the -dealloc function.

may be it happens because 22 questions takes some memory and not release till dealloc function call.

What i want is , Is there any way to release labels and buttons after every question and then it will allocate again? or any way in which i can use less memory for allocation labels and buttons??

I am using this code :

```<code>//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];
</code>```

Any help??

Thank you.

答:
1) Simple rule, you release whatever you alloced or retained, copied...All other variable you have will be autoreleased. In your code you are allocing all labels, but not Buttons.. You must release all Labels after adding it to subView. Buttons you just add to subView, not release afterwords as you are not allocating it.. Since you are asking similiar question for 2 days I just worked on your code

```<code>//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
[self.view addSubview:ans1];

//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
[self.view addSubview:ans2];

//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
[self.view addSubview:ans3];

//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
[self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonOne) forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button];

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:@selector(buttonTwo) forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button2];

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self action:@selector(buttonThree) forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button3];

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self action:@selector(buttonFour) forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button4];

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[rightans sizeToFit];
[rightans setHidden:YES];
[self.view addSubview:rightans];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[Description setHidden:YES];
[self.view addSubview:Description];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[ContainerView setHidden:YES];
[self.view addSubview:ContainerView];
[ContainerView release];
</code>```

Some other points of note.

1) A variable name should always start with a small letter.. It is not a written rule, but a good practice, easier for yourself and for others (like us) reviewing it. Variable name like "Description" and "Question" are not good.

2) Never repost your question.. If you just formatted the code better, you should have got answer in your previous question itself..

Title: Multiple time allocation and release

Body:
I am creating a quiz app for iPhone/iPad(universal app).It is working fine on simulator but on real device there are some problem i am facing..

I am creating UILabels and UIButtons programmatically and i am using them so many times for displaying questions and answers one by one.

problem is when i reach around question 20 to 22 the application crashes. I don't know why. there is no memory leak i found. I release all the labels and buttons at the -dealloc function.

may be it happens because 22 questions takes some memory and not release till dealloc function call.

What i want is , Is there any way to release labels and buttons after every question and then it will allocate again? or any way in which i can use less memory for allocation labels and buttons??

I am using this code :

//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];

Any help??

Thank you.

Body:
1) Simple rule, you release whatever you alloced or retained, copied...All other variable you have will be autoreleased. In your code you are allocing all labels, but not Buttons.. You must release all Labels after adding it to subView. Buttons you just add to subView, not release afterwords as you are not allocating it.. Since you are asking similiar question for 2 days I just worked on your code

//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
[self.view addSubview:ans1];

//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
[self.view addSubview:ans2];

//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
[self.view addSubview:ans3];

//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
[self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonOne) forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button];

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:@selector(buttonTwo) forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button2];

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self action:@selector(buttonThree) forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button3];

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self action:@selector(buttonFour) forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button4];

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[rightans sizeToFit];
[rightans setHidden:YES];
[self.view addSubview:rightans];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[Description setHidden:YES];
[self.view addSubview:Description];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[ContainerView setHidden:YES];
[self.view addSubview:ContainerView];
[ContainerView release];

Some other points of note.

1) A variable name should always start with a small letter.. It is not a written rule, but a good practice, easier for yourself and for others (like us) reviewing it. Variable name like "Description" and "Question" are not good.

2) Never repost your question.. If you just formatted the code better, you should have got answer in your previous question itself..


问:
Make passed Android Tests visible in Android Studio
I'm using Android Studio (0.8.9) and have several unit tests. When I run them with an Android Test Run Configuration they only show up in the test report window if the test fails.

I'd also like to see them when they pass. (It makes me happy :-) Is it possible to configure this somewhere?

答: On newer AndroidStudio version, toggle the "tick" icon will show/hide passed test


问:
In C++ How can I read in different types of data in one instream of the same cin object
I wrote a custom class CMyistream_iterator. Its constructor has an argument of an istream object.

```<code>template <class T>
class CMyistream_iterator
{

private:
    T valArray[100];
    int pos;
public:
    CMyistream_iterator(istream& in):pos(0){
        T n;
        int i=0;
        while(in>>n){
            *(valArray+i) = n;
            ++i;
        }
    }
    T operator*();
};
</code>```

But I meet some problems when I enter the data.

```<code> int main(){
       CMyistream_iterator<int> inputInt(cin);
       //...somecode...
       CMyistream_iterator<string> inputStr(cin);
       //...somecode...
    }
</code>```

Data is entered like this:

22 33 44 tom jack+'\n'

The second class can't be constructed as it can't read in the next two strings.

It seems that when the integer iterator comes to the character 't', it was converted into EOF.

How can I solve this problem?

答:
It seems that when the integer iterator comes to the character 't', it was converted into EOF.

That is not what happens. When cin >> n in the int iterator encounters the character 't', it fails to read in an int value, and thus puts cin into an error state that you need to explicitly reset with cin.clear() before you can continue reading from cin.

Also, your iterator is not allocating memory for valArray to point at. You should consider using std::vector and let it manage the memory for you.

Body:
I wrote a custom class CMyistream_iterator. Its constructor has an argument of an istream object.

template <class T>
class CMyistream_iterator
{

private:
    T valArray[100];
    int pos;
public:
    CMyistream_iterator(istream& in):pos(0){
        T n;
        int i=0;
        while(in>>n){
            *(valArray+i) = n;
            ++i;
        }
    }
    T operator*();
};

But I meet some problems when I enter the data.

 int main(){
       CMyistream_iterator<int> inputInt(cin);
       //...somecode...
       CMyistream_iterator<string> inputStr(cin);
       //...somecode...
    }

Data is entered like this:

22 33 44 tom jack+'\n'

The second class can't be constructed as it can't read in the next two strings.

It seems that when the integer iterator comes to the character 't', it was converted into EOF.

How can I solve this problem?


问:
Reading file only after function is done
I have a function doSmth that creates a file "data.json" by the end. (the file IS created by the end of running the script.) However, when I try to fs.readFileSync it using await and then, it says

```<code>Error: ENOENT: no such file or directory, open 'data.json'
</code>```

here is my code

```<code>const doSmth = async() => {
    await zip.forEach(async(relativePath: any, file: any) => {
        const fs = require("fs");
        let fileExists = fs.existsSync('data.json');
        if (fileExists) {
            fs.readFileSync('data.json')
            console.log("file already exists")
            fs.writeFileSync("data.json", JSON.stringify(""))
        } else {
            console.log("file didnt exist")
            fs.writeFileSync("data.json", JSON.stringify(""))
        }
    })
}

await doSmth().then(async () => {
    const fs = require("fs");
    console.log("reached")
    fs.readFileSync("data.json")
})
</code>```

how do I wait for the data.json file to be created before reading it

Edit:
from the comments changed my code to this and works

```<code>const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(resolve => {
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}
</code>```

but now I have an await inside and it causes the same data.file not found error

```<code>const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(async resolve => {
            const eachFile = await zip.file(file.name).async("string")
            const jsonObject = JSON.parse(eachFile)
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}
</code>```

答:
Don't mix and match async/await with then. It looks like you want to do somthing like this.

const fs = require('fs');

async function main() {
  await doSmth();
  console.log('reached');
  fs.readFileSync('data.json');
}

main();```

Body:
I have a function doSmth that creates a file "data.json" by the end. (the file IS created by the end of running the script.) However, when I try to fs.readFileSync it using await and then, it says

Error: ENOENT: no such file or directory, open 'data.json'

here is my code

const doSmth = async() => {
    await zip.forEach(async(relativePath: any, file: any) => {
        const fs = require("fs");
        let fileExists = fs.existsSync('data.json');
        if (fileExists) {
            fs.readFileSync('data.json')
            console.log("file already exists")
            fs.writeFileSync("data.json", JSON.stringify(""))
        } else {
            console.log("file didnt exist")
            fs.writeFileSync("data.json", JSON.stringify(""))
        }
    })
}

await doSmth().then(async () => {
    const fs = require("fs");
    console.log("reached")
    fs.readFileSync("data.json")
})

how do I wait for the data.json file to be created before reading it

Edit:
from the comments changed my code to this and works

const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(resolve => {
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}

but now I have an await inside and it causes the same data.file not found error

const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(async resolve => {
            const eachFile = await zip.file(file.name).async("string")
            const jsonObject = JSON.parse(eachFile)
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}