问:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: mytable
Sorry for the messy code, I got a little lost in trial and error stage (I run out of coffee).

I try to build a dashboard. to track my orders, revenue etc. to do this, I created a database that include all the related data.
After that, I download a "flask dashboard template" and started editing it.
I can collect all my order data and able using it in the index.html via curly bracelets.

When I try to sum all revenue rows in IDLE;

```<code>from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from sqlalchemy import func

engine = create_engine('sqlite:///transactions.db', echo=True)
conn = engine.connect()

global b
a = text('SELECT * FROM mytable')
b = conn.execute(a).fetchall()

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + 'transactions.db'

db = SQLAlchemy(app)
revenue = db.engine.execute('select sum(total) from mytable').scalar()
revenue = int(revenue)
print(revenue)
</code>```

it works without an issue, but when I try to implement it in my route file like this;

```<code># -*- encoding: utf-8 -*-

from app.home import blueprint
from flask import Flask, render_template, redirect, url_for
from flask_login import login_required, current_user
from app import login_manager
from jinja2 import TemplateNotFound
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.sql import text

# custom block
from sqlalchemy import create_engine

engine = create_engine('sqlite:///transactions.db', echo=True)
conn = engine.connect()

global b
global revenue

a = text('SELECT * FROM mytable')
b = conn.execute(a).fetchall()

app = Flask(__name__)
dborder = SQLAlchemy(app)
db = SQLAlchemy(app)

#revenue
engin = create_engine('sqlite:///transactions.db', echo=True)
coni = engine.connect()

db1 = SQLAlchemy(app)
revenue = db1.engine.execute('select sum(total) from mytable').scalar()
revenue = int(revenue)
#revenue

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + 'transactions.db'

class mytable(dborder.Model):
    name = dborder.Column(dborder.Integer, primary_key=True)
    add = dborder.Column(dborder.String)

# end custom block

@blueprint.route('/index')
@login_required
def index():

    #if not current_user.is_authenticated:
    #    return redirect(url_for('base_blueprint.login'))

    global b
    orderlist = b

    return render_template('index.html', orderlist = orderlist, revenue = revenue)

@blueprint.route('/<template>')
def route_template(template):

    if not current_user.is_authenticated:
        return redirect(url_for('base_blueprint.login'))

    try:

        return render_template(template + '.html')

    except TemplateNotFound:
        return render_template('page-404.html'), 404

    except:
        return render_template('page-500.html'), 500
</code>```

I'm getting an error;

```<code>2020-05-29 00:41:13,977 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2020-05-29 00:41:13,977 INFO sqlalchemy.engine.base.Engine ()
2020-05-29 00:41:13,978 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2020-05-29 00:41:13,978 INFO sqlalchemy.engine.base.Engine ()
2020-05-29 00:41:13,979 INFO sqlalchemy.engine.base.Engine SELECT * FROM mytable
2020-05-29 00:41:13,979 INFO sqlalchemy.engine.base.Engine ()
C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py:808: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
  warnings.warn(
C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py:829: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py:829: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py:829: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
Traceback (most recent call last):
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1283, in _execute_context
    self.dialect.do_execute(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\default.py", line 590, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: mytable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "run.py", line 21, in <module>
    app = create_app(config_mode)
  File "C:\Users\Ozgur\Documents\python-colleect\admin panel\flask-material-dashboard\app\__init__.py", line 81, in create_app
    register_blueprints(app)
  File "C:\Users\Ozgur\Documents\python-colleect\admin panel\flask-material-dashboard\app\__init__.py", line 24, in register_blueprints
    module = import_module('app.{}.routes'.format(module_name))
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Ozgur\Documents\python-colleect\admin panel\flask-material-dashboard\app\home\routes.py", line 44, in <module>
    revenue = db1.engine.execute('select sum(total) from mytable').scalar()
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 2244, in execute
    return connection.execute(statement, *multiparams, **params)
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1012, in execute
    return self._execute_text(object_, multiparams, params)
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1181, in _execute_text
    ret = self._execute_context(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1323, in _execute_context
    self._handle_dbapi_exception(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1517, in _handle_dbapi_exception
    util.raise_(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\util\compat.py", line 178, in raise_
    raise exception
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1283, in _execute_context
    self.dialect.do_execute(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\default.py", line 590, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: mytable
[SQL: select sum(total) from mytable]
(Background on this error at: http://sqlalche.me/e/e3q8)
</code>```

答:
I think you have to put

```<code>app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + 'transactions.db'
</code>```

before

```<code>db1 = SQLAlchemy(app)
</code>```

Explanation

when your code wants to execute this line:

```<code>revenue = db1.engine.execute('select sum(total) from mytable').scalar()
</code>```

SQLAlchemy needs to know the database that contains mytable. So you have to specify the URI to your database before executing this line.

Body:
Sorry for the messy code, I got a little lost in trial and error stage (I run out of coffee).

I try to build a dashboard. to track my orders, revenue etc. to do this, I created a database that include all the related data.
After that, I download a "flask dashboard template" and started editing it.
I can collect all my order data and able using it in the index.html via curly bracelets.

When I try to sum all revenue rows in IDLE;

from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from sqlalchemy import func

engine = create_engine('sqlite:///transactions.db', echo=True)
conn = engine.connect()

global b
a = text('SELECT * FROM mytable')
b = conn.execute(a).fetchall()

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + 'transactions.db'

db = SQLAlchemy(app)
revenue = db.engine.execute('select sum(total) from mytable').scalar()
revenue = int(revenue)
print(revenue)

it works without an issue, but when I try to implement it in my route file like this;

# -*- encoding: utf-8 -*-

from app.home import blueprint
from flask import Flask, render_template, redirect, url_for
from flask_login import login_required, current_user
from app import login_manager
from jinja2 import TemplateNotFound
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.sql import text

# custom block
from sqlalchemy import create_engine

engine = create_engine('sqlite:///transactions.db', echo=True)
conn = engine.connect()

global b
global revenue

a = text('SELECT * FROM mytable')
b = conn.execute(a).fetchall()

app = Flask(__name__)
dborder = SQLAlchemy(app)
db = SQLAlchemy(app)

#revenue
engin = create_engine('sqlite:///transactions.db', echo=True)
coni = engine.connect()

db1 = SQLAlchemy(app)
revenue = db1.engine.execute('select sum(total) from mytable').scalar()
revenue = int(revenue)
#revenue

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + 'transactions.db'

class mytable(dborder.Model):
    name = dborder.Column(dborder.Integer, primary_key=True)
    add = dborder.Column(dborder.String)

# end custom block

@blueprint.route('/index')
@login_required
def index():

    #if not current_user.is_authenticated:
    #    return redirect(url_for('base_blueprint.login'))

    global b
    orderlist = b

    return render_template('index.html', orderlist = orderlist, revenue = revenue)

@blueprint.route('/<template>')
def route_template(template):

    if not current_user.is_authenticated:
        return redirect(url_for('base_blueprint.login'))

    try:

        return render_template(template + '.html')

    except TemplateNotFound:
        return render_template('page-404.html'), 404

    except:
        return render_template('page-500.html'), 500

I'm getting an error;

2020-05-29 00:41:13,977 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2020-05-29 00:41:13,977 INFO sqlalchemy.engine.base.Engine ()
2020-05-29 00:41:13,978 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2020-05-29 00:41:13,978 INFO sqlalchemy.engine.base.Engine ()
2020-05-29 00:41:13,979 INFO sqlalchemy.engine.base.Engine SELECT * FROM mytable
2020-05-29 00:41:13,979 INFO sqlalchemy.engine.base.Engine ()
C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py:808: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
  warnings.warn(
C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py:829: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py:829: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_sqlalchemy\__init__.py:829: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
Traceback (most recent call last):
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1283, in _execute_context
    self.dialect.do_execute(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\default.py", line 590, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: mytable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "run.py", line 21, in <module>
    app = create_app(config_mode)
  File "C:\Users\Ozgur\Documents\python-colleect\admin panel\flask-material-dashboard\app\__init__.py", line 81, in create_app
    register_blueprints(app)
  File "C:\Users\Ozgur\Documents\python-colleect\admin panel\flask-material-dashboard\app\__init__.py", line 24, in register_blueprints
    module = import_module('app.{}.routes'.format(module_name))
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Ozgur\Documents\python-colleect\admin panel\flask-material-dashboard\app\home\routes.py", line 44, in <module>
    revenue = db1.engine.execute('select sum(total) from mytable').scalar()
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 2244, in execute
    return connection.execute(statement, *multiparams, **params)
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1012, in execute
    return self._execute_text(object_, multiparams, params)
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1181, in _execute_text
    ret = self._execute_context(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1323, in _execute_context
    self._handle_dbapi_exception(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1517, in _handle_dbapi_exception
    util.raise_(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\util\compat.py", line 178, in raise_
    raise exception
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\base.py", line 1283, in _execute_context
    self.dialect.do_execute(
  File "C:\Users\Ozgur\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sqlalchemy\engine\default.py", line 590, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: mytable
[SQL: select sum(total) from mytable]
(Background on this error at: http://sqlalche.me/e/e3q8)

Body:
I think you have to put

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + 'transactions.db'

before

db1 = SQLAlchemy(app)

Explanation

when your code wants to execute this line:

revenue = db1.engine.execute('select sum(total) from mytable').scalar()

SQLAlchemy needs to know the database that contains mytable. So you have to specify the URI to your database before executing this line.


来源: stackexchange

问:
Wix InstallExecuteSequence throws error on supporting 47th msi instance
The error is thrown while supporting the 47th instance. It runs fine if I remove the action SetMyInstance_Instance47. I need to support 100 instances. The code snippet is as below.

```<code><InstallExecuteSequence>
 <Custom Action="SetMyInstance_Instance46" After="SetMyInstance_Instance45"><![CDATA[ACTION = "INSTALL" AND MYINSTANCE = "DontUseThis" AND  (INSTANCE46INSTALLEDPRODUCTCODE = "" AND INSTANCE46INSTALLEDPRODUCTCODE64 = ""  AND INSTANCE46INSTALLEDPRODUCTCODE32 = "")  AND SECONDEXECUTE <> 1 ]]></Custom>
      <Custom Action="SetMyInstance_Instance47" After="SetMyInstance_Instance46"><![CDATA[ACTION = "INSTALL" AND MYINSTANCE = "DontUseThis" AND  (INSTANCE47INSTALLEDPRODUCTCODE = "" AND INSTANCE47INSTALLEDPRODUCTCODE64 = ""  AND INSTANCE47INSTALLEDPRODUCTCODE32 = "")  AND SECONDEXECUTE <> 1 ]]></Custom>
 </InstallExecuteSequence>
</code>```

Wix Error:
The InstallExecuteSequence table contains an action 'SetMsiNewInstance' which cannot have a unique sequence number because it is scheduled before or after action 'AppSearch'.  There is not enough room before or after this action to assign a unique sequence number.  Please schedule one of the actions differently so that it will be in a position with more sequence numbers available.  Please note that sequence numbers must be an integer in the range 1 - 32767 (inclusive).

答:
For diagnosis - first of all (before any fix), please try this:

Open your MSI in Orca or equivalent editor

Go to the InstallExecuteSequence, sort by Sequence (right column).

What numbers do you see? Notice the gaps in the numbers. Those gaps are to allow other actions "in between" the standard actions. If you run out of "gaps" then you will probably get the message you receive.

There are "default numbers" used for the standard actions and they seem to be defined in a file called actions.xml (please do visit that link).

=> Conclusion? You need bigger gaps between the standard actions. At least that is ONE of the things you need. What you really need to do is to stop using so many instances :-).

You can try to manually set the sequence number AND you can assign new numbers to the standard actions:

```<code><InstallExecuteSequence>

   <..>

     <!-- Redefine standard action numbers -->

      <LaunchConditions Sequence='300'></LaunchConditions>
      <FindRelatedProducts Sequence='2'></FindRelatedProducts>

   <..>

     <!-- Manually assign custom action sequence numbers -->

       <Custom Sequence="44" Action='SomethingDoneHere1' />
       <Custom Sequence="45" Action='SomethingDoneHere2' />

   <..>

</InstallExecuteSequence>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The error is thrown while supporting the 47th instance. It runs fine if I remove the action SetMyInstance_Instance47. I need to support 100 instances. The code snippet is as below.

<InstallExecuteSequence>
 <Custom Action="SetMyInstance_Instance46" After="SetMyInstance_Instance45"><![CDATA[ACTION = "INSTALL" AND MYINSTANCE = "DontUseThis" AND  (INSTANCE46INSTALLEDPRODUCTCODE = "" AND INSTANCE46INSTALLEDPRODUCTCODE64 = ""  AND INSTANCE46INSTALLEDPRODUCTCODE32 = "")  AND SECONDEXECUTE <> 1 ]]></Custom>
      <Custom Action="SetMyInstance_Instance47" After="SetMyInstance_Instance46"><![CDATA[ACTION = "INSTALL" AND MYINSTANCE = "DontUseThis" AND  (INSTANCE47INSTALLEDPRODUCTCODE = "" AND INSTANCE47INSTALLEDPRODUCTCODE64 = ""  AND INSTANCE47INSTALLEDPRODUCTCODE32 = "")  AND SECONDEXECUTE <> 1 ]]></Custom>
 </InstallExecuteSequence>

Wix Error:
The InstallExecuteSequence table contains an action 'SetMsiNewInstance' which cannot have a unique sequence number because it is scheduled before or after action 'AppSearch'.  There is not enough room before or after this action to assign a unique sequence number.  Please schedule one of the actions differently so that it will be in a position with more sequence numbers available.  Please note that sequence numbers must be an integer in the range 1 - 32767 (inclusive).

Body:
For diagnosis - first of all (before any fix), please try this:

Open your MSI in Orca or equivalent editor

Go to the InstallExecuteSequence, sort by Sequence (right column).

What numbers do you see? Notice the gaps in the numbers. Those gaps are to allow other actions "in between" the standard actions. If you run out of "gaps" then you will probably get the message you receive.

There are "default numbers" used for the standard actions and they seem to be defined in a file called actions.xml (please do visit that link).

=> Conclusion? You need bigger gaps between the standard actions. At least that is ONE of the things you need. What you really need to do is to stop using so many instances :-).

You can try to manually set the sequence number AND you can assign new numbers to the standard actions:

<InstallExecuteSequence>

   <..>

     <!-- Redefine standard action numbers -->

      <LaunchConditions Sequence='300'></LaunchConditions>
      <FindRelatedProducts Sequence='2'></FindRelatedProducts>

   <..>

     <!-- Manually assign custom action sequence numbers -->

       <Custom Sequence="44" Action='SomethingDoneHere1' />
       <Custom Sequence="45" Action='SomethingDoneHere2' />

   <..>

</InstallExecuteSequence>


问:
Need Guidance for designing database Table - (confuse for 1 column)
I have two tables. 1.Products 2. Combo

Product Table has column like (product_id, product_name).

Combo Table has column like (combo_id, combo_name, combo_included_products /* combo might have 2 or more products from product table*/)

Rule: 1 Combo can have many products.

```<code>Product Table
product_id  product_name
1           Pen
2           Pencil
3           Pen Holders
4           Sharpeners
</code>```

-

```<code>Combo Table
combo_id    combo_name    this_combo_includes_below_products
1           Big_combo     (1,2,3,4) => big combo includes all products
2           Small_combo   (2,4) => this combo only includes product 2,4
3           test_combo    (1,2)
4           Other_combo   (1,4)
</code>```

So How can I insert multiple products ids in third column of combo table?

I am thinking to store data like 1,2,3,4 and 2,4 and so on. Then problem will be to write join query. i.e

select combo.combo_id, combo.combo_name, product.product.id from combo join product ON combo.this_combo_included_products_id = product.product_id <= As there will be multiple product ids, It will not possible.

I am also thinking make a script where I will first fetch combo table as it is, then I will split third cloumn by "," and will run iterate (select * from combo where product id=this_combo_included_item_id[i]) <= I am not sure this is good idea however this can be a alternate solution which require some coding afterwards.
(I use phpmysql to fetch data anyways - so I can process that after fetching.)

```<code>$sql = "SELECT *  FROM combo";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
  // I can run other query here
  $child_query = "select combo.combo_id, combo.combo_name, product.product.id from combo join product
                 ON combo.this_combo_included_products_id = product.product_id";

}
</code>```

However Is there anything else I can do while designing Database table. Thanks.

答:
Don't store multiple values in a single row. Don't store numbers as strings. The accepted answer to famous SO question gives great insights on how bad this is.

You have a many to many relationship between products and combos: each product may appear in may combos, and each combo may contain many products. From normalization perspective, the proper way to represent it is to create another table, called a bridge table, to store the relations.

```<code>create table product_combo (
    product_id int references product(product_id),
    combo_id int references combo(combo_id),
    primary key (product_id, combo_id)
);
</code>```

For your sample data, the bridge table would contain:

```<code>product_id    combo_id
1             1
1             2
1             3
1             4
2             2
2             4
3             1
3             2
4             1
4             4
</code>```

With this set-up in place, say that you want to select a given combo along with all its associated products, then you would go:

```<code>select c.*, p.*
from combos c
inner join product_combos pc on pc.combo_id = c.combo_id
inner join products p on p.product_id = pc.product_id
where c.combo_id = ?
</code>```

And if you really want to, you can even rebuild the csv lists of products for each combo:

```<code>select c.combo_id, c.combo_name, group_concat(p.product_name) product_names
from products p
inner join product_combos pc on pc.product_id = p.product_id
inner jon combos c on c.combo_id = pc.combo_id
group by c.combo_id, c.combo_name
</code>```

Body:
I have two tables. 1.Products 2. Combo

Product Table has column like (product_id, product_name).

Combo Table has column like (combo_id, combo_name, combo_included_products /* combo might have 2 or more products from product table*/)

Rule: 1 Combo can have many products.

Product Table
product_id  product_name
1           Pen
2           Pencil
3           Pen Holders
4           Sharpeners

-

Combo Table
combo_id    combo_name    this_combo_includes_below_products
1           Big_combo     (1,2,3,4) => big combo includes all products
2           Small_combo   (2,4) => this combo only includes product 2,4
3           test_combo    (1,2)
4           Other_combo   (1,4)

So How can I insert multiple products ids in third column of combo table?

I am thinking to store data like 1,2,3,4 and 2,4 and so on. Then problem will be to write join query. i.e

select combo.combo_id, combo.combo_name, product.product.id from combo join product ON combo.this_combo_included_products_id = product.product_id <= As there will be multiple product ids, It will not possible.

I am also thinking make a script where I will first fetch combo table as it is, then I will split third cloumn by "," and will run iterate (select * from combo where product id=this_combo_included_item_id[i]) <= I am not sure this is good idea however this can be a alternate solution which require some coding afterwards.
(I use phpmysql to fetch data anyways - so I can process that after fetching.)

$sql = "SELECT *  FROM combo";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
  // I can run other query here
  $child_query = "select combo.combo_id, combo.combo_name, product.product.id from combo join product
                 ON combo.this_combo_included_products_id = product.product_id";

}

However Is there anything else I can do while designing Database table. Thanks.

Body:
Don't store multiple values in a single row. Don't store numbers as strings. The accepted answer to famous SO question gives great insights on how bad this is.

You have a many to many relationship between products and combos: each product may appear in may combos, and each combo may contain many products. From normalization perspective, the proper way to represent it is to create another table, called a bridge table, to store the relations.

create table product_combo (
    product_id int references product(product_id),
    combo_id int references combo(combo_id),
    primary key (product_id, combo_id)
);

For your sample data, the bridge table would contain:

product_id    combo_id
1             1
1             2
1             3
1             4
2             2
2             4
3             1
3             2
4             1
4             4

With this set-up in place, say that you want to select a given combo along with all its associated products, then you would go:

select c.*, p.*
from combos c
inner join product_combos pc on pc.combo_id = c.combo_id
inner join products p on p.product_id = pc.product_id
where c.combo_id = ?

And if you really want to, you can even rebuild the csv lists of products for each combo:

select c.combo_id, c.combo_name, group_concat(p.product_name) product_names
from products p
inner join product_combos pc on pc.product_id = p.product_id
inner jon combos c on c.combo_id = pc.combo_id
group by c.combo_id, c.combo_name


问:
Android get dialer package name
I need to get package name of an app which post notification about a missed call. As far as I understand it makes dialer app of a device. Can I get package name of dialer app on the device, I need it from API 19?</p>

答:
To get an app's package (and activity name) you can use adb command.

Launch the app and then:

```<code>adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'
</code>```

From the output:

```<code>mFocusedApp=AppWindowToken{
  e224f9d token=Token{
    d8b2e74 ActivityRecord{
      1d97647 u0 com.android.dialer/.app.DialtactsActivity t1078
    }
  }
}
</code>```

You can say the app's package is com.android.dialer and activity name is .app.DialtactsActivity

ContentLicense: CC BY-SA 3.0

Title: Android get dialer package name

Body:
To get an app's package (and activity name) you can use adb command.

Launch the app and then:

adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'

From the output:

mFocusedApp=AppWindowToken{
  e224f9d token=Token{
    d8b2e74 ActivityRecord{
      1d97647 u0 com.android.dialer/.app.DialtactsActivity t1078
    }
  }
}

You can say the app's package is com.android.dialer and activity name is .app.DialtactsActivity


问:
How can ı login instagram via c#
I try to log in to Instagram using c# but there one thing that ı can't solve.

When ı look at the login ajax request, ı can see username and enc_password but ı have no idea about how to create an enc_password field in c#.

enc_password looks like this
https://i.stack.imgur.com/7soog.png

ı have some solutions for other languages but ı can't convert c#
https://github.com/dilame/instagram-private-api/issues/1010

What should ı do? Thx for helping.

答: enc_password contains: encryption version, unixtime and base64 encoded string with aes-256-gcm encryption. Cipher contains additional data (time), thats why Ashish Sharma function is not the same and not solve your issue. </p>

Title: How can ı login instagram via c#


问:
Kohana 3.1 ORM: Empty model property value saved as 0 (zero) instead of NULL
I have two models, Product and Product_Methodology. In my product edit view I have a select form field to select one of many methodologies or none (empty first option). In my products table I have a INT(10) methodology_id property that gets saved with the id of the methodology selected from the select form field. Everything worked OK until today that I had to make an adjustment to the system in which since now selecting a methodology can be optional. So I changed the methodology_id field of the products table to allow NULL value and removed the not_empty validation rule on the model.

The problem is that now when I save the model selecting the empty option, instead of the expected NULL, I get a 0 (zero) value.

Any clue on this?
Thanks a lot and let me know if it's not so clear.

答:
What form input are you using for choosing the methodology? is it <select> ?
If so, the value of choosen option is probably set to 0 when no methodology is choosen, and send with other form data.

In such cases I make a custom filter withing model's filters() method, to set the value to NULL (as PHP treats it) when it's empty(), something like this:

```<code>public function filters()
{
    return array(
        'methodology_id' => array(
            array('Filter::null', array(':value')),
        ),
    );
}
</code>```

Where Filter is helper class with static methods. like...:

```<code>class Kohana_Filter {

    public static function null($value)
    {
        return (empty($value) ? NULL : $value);
    }

}
</code>```

Hope this helps :)

Body:
What form input are you using for choosing the methodology? is it <select> ?
If so, the value of choosen option is probably set to 0 when no methodology is choosen, and send with other form data.

In such cases I make a custom filter withing model's filters() method, to set the value to NULL (as PHP treats it) when it's empty(), something like this:

public function filters()
{
    return array(
        'methodology_id' => array(
            array('Filter::null', array(':value')),
        ),
    );
}

Where Filter is helper class with static methods. like...:

class Kohana_Filter {

    public static function null($value)
    {
        return (empty($value) ? NULL : $value);
    }

}

Hope this helps :)


问:
How to encode input for a tensorflow model having encoded_image_string_tensor as input
I trained an object detection model on Google AI platform and downloaded the model. It's a standard saved_model.pb file which I want to load in python and provide one image for inference.
The problem is that the input of this model is defined as encoded_image_string_tensor which expects a base64 encoded string. How can I encode an image file in this format in python?

```<code>print(model.inputs)
print(model.output_dtypes)
print(model.output_shapes)

[<tf.Tensor 'encoded_image_string_tensor:0' shape=(None,) dtype=string>, <tf.Tensor 'key:0' shape=(None,) dtype=string>, <tf.Tensor 'global_step:0' shape=() dtype=resource>]
{'detection_scores': tf.float32, 'detection_classes': tf.float32, 'num_detections': tf.float32, 'key': tf.string, 'detection_boxes': tf.float32}
{'detection_scores': TensorShape([None, 100]), 'detection_classes': TensorShape([None, 100]), 'num_detections': TensorShape([None]), 'key': TensorShape([None]), 'detection_boxes': TensorShape([None, 100, 4])}
</code>```

The existing examples in tensorflow/models/research show how to do it with an image_tensor type of input:

```<code>  image = np.asarray(image)
  # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
  input_tensor = tf.convert_to_tensor(image)
  # The model expects a batch of images, so add an axis with `tf.newaxis`.
  input_tensor = input_tensor[tf.newaxis,...]
</code>```

When I run this code on the model with encoded_image_string_tensor as an input it produces the following error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in
      1 for i in range(1):
----> 2     show_inference(model, TEST_IMAGE_PATHS[i])

 in show_inference(model, image_path)
     39 #   print(image_np)
     40   # Actual detection.
---> 41   output_dict = run_inference_for_single_image(model, image_np)
     42   # Visualization of the results of a detection.
     43   print(output_dict['detection_scores'][:3])

 in run_inference_for_single_image(model, image)
      7
      8   # Run inference
----> 9   output_dict = model(input_tensor)
     10
     11   # All outputs are batches tensors.

~\anaconda3\envs\tf2\lib\site-packages\tensorflow\python\eager\function.py in __call__(self, *args, **kwargs)
   1603       TypeError: For invalid positional/keyword argument combinations.
   1604     """
-> 1605     return self._call_impl(args, kwargs)
   1606
   1607   def _call_impl(self, args, kwargs, cancellation_manager=None):

~\anaconda3\envs\tf2\lib\site-packages\tensorflow\python\eager\function.py in _call_impl(self, args, kwargs, cancellation_manager)
   1622            "of {}), got {}. When calling a concrete function, positional "
   1623            "arguments may not be bound to Tensors within nested structures."
-> 1624           ).format(self._num_positional_args, self._arg_keywords, args))
   1625     args = list(args)
   1626     for keyword in self._arg_keywords[len(args):]:

TypeError: Expected at most 0 positional arguments (and the rest keywords, of ['encoded_image', 'key']), got (,). When calling a concrete function, positional arguments may not be bound to Tensors within nested structures.
</code>```

答:
You can easily adapt the run_inference_for_single_image() function from the object_detection_tutorial.ipynb notebook (which you seem to use in your example), by using tf.io.encode_jpeg() to encode the image.

The built-in object detection model from Google AI platform also requires a key (any string-tensor with dimension of batch-size) as input, which I've also added to the model() call in the example below .

def run_inference_for_single_image(model, image):
    image = np.asarray(image)

    # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
    input_tensor = tf.convert_to_tensor(image)

    # Encode the (numerical) tensor into an "encoded_image"
    encoded_image = tf.io.encode_jpeg(input_tensor)

    # The model expects a batch of images, so add an axis with `tf.newaxis`.
    encoded_image = encoded_image[tf.newaxis,...]

    # Run inference (the SavedModel downloaded from AI platform also requires a "key" as input.)
    output_dict = model(encoded_image = encoded_image, key = tf.expand_dims(tf.convert_to_tensor("test_key"), 0))

    # ...
```

Body:
I trained an object detection model on Google AI platform and downloaded the model. It's a standard saved_model.pb file which I want to load in python and provide one image for inference.
The problem is that the input of this model is defined as encoded_image_string_tensor which expects a base64 encoded string. How can I encode an image file in this format in python?

print(model.inputs)
print(model.output_dtypes)
print(model.output_shapes)

[<tf.Tensor 'encoded_image_string_tensor:0' shape=(None,) dtype=string>, <tf.Tensor 'key:0' shape=(None,) dtype=string>, <tf.Tensor 'global_step:0' shape=() dtype=resource>]
{'detection_scores': tf.float32, 'detection_classes': tf.float32, 'num_detections': tf.float32, 'key': tf.string, 'detection_boxes': tf.float32}
{'detection_scores': TensorShape([None, 100]), 'detection_classes': TensorShape([None, 100]), 'num_detections': TensorShape([None]), 'key': TensorShape([None]), 'detection_boxes': TensorShape([None, 100, 4])}

The existing examples in tensorflow/models/research show how to do it with an image_tensor type of input:

  image = np.asarray(image)
  # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
  input_tensor = tf.convert_to_tensor(image)
  # The model expects a batch of images, so add an axis with `tf.newaxis`.
  input_tensor = input_tensor[tf.newaxis,...]

When I run this code on the model with encoded_image_string_tensor as an input it produces the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in
      1 for i in range(1):
----> 2     show_inference(model, TEST_IMAGE_PATHS[i])

 in show_inference(model, image_path)
     39 #   print(image_np)
     40   # Actual detection.
---> 41   output_dict = run_inference_for_single_image(model, image_np)
     42   # Visualization of the results of a detection.
     43   print(output_dict['detection_scores'][:3])

 in run_inference_for_single_image(model, image)
      7
      8   # Run inference
----> 9   output_dict = model(input_tensor)
     10
     11   # All outputs are batches tensors.

~\anaconda3\envs\tf2\lib\site-packages\tensorflow\python\eager\function.py in __call__(self, *args, **kwargs)
   1603       TypeError: For invalid positional/keyword argument combinations.
   1604     """
-> 1605     return self._call_impl(args, kwargs)
   1606
   1607   def _call_impl(self, args, kwargs, cancellation_manager=None):

~\anaconda3\envs\tf2\lib\site-packages\tensorflow\python\eager\function.py in _call_impl(self, args, kwargs, cancellation_manager)
   1622            "of {}), got {}. When calling a concrete function, positional "
   1623            "arguments may not be bound to Tensors within nested structures."
-> 1624           ).format(self._num_positional_args, self._arg_keywords, args))
   1625     args = list(args)
   1626     for keyword in self._arg_keywords[len(args):]:

TypeError: Expected at most 0 positional arguments (and the rest keywords, of ['encoded_image', 'key']), got (,). When calling a concrete function, positional arguments may not be bound to Tensors within nested structures.


问:
Toolbar with Gradient Background set title background transparent
I defined a Gradient Drawable:

```<code><?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:endColor="#2F3F59"
        android:startColor="#4078A7"
        android:type="linear"
        android:angle="90" />

</shape>
</code>```

And I set it on my Toolbar:

```<code><style name="AppTheme.Toolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:textColorPrimary">@color/textcolorsecundary</item>
    <item name="actionMenuTextColor">@color/textcolorsecundary</item>
    <item name="android:textColorSecondary">@color/textcolorsecundary</item>
    <item name="android:background">@drawable/custom_background_blue</item>
</style>
</code>```

This is working! BUT:

This is what happens with the title. It gets the same gradient. This looks really ugly so I have to change this. How can I set the background of that info text to be transparent?

答:
Changing the background color to transparent in the style section should fix the issue

```<code><style name="AppTheme.Toolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#00000000</item>
</style>
</code>```

The question How to make title background transparent on android app had similar issue above solution did the trick. The android app was for Renesas RX130 and Texas Instrument CC2650 BLE solution. Bellow is solution after the fix.

Body:
I defined a Gradient Drawable:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:endColor="#2F3F59"
        android:startColor="#4078A7"
        android:type="linear"
        android:angle="90" />

</shape>

And I set it on my Toolbar:

This is working! BUT:

This is what happens with the title. It gets the same gradient. This looks really ugly so I have to change this. How can I set the background of that info text to be transparent?

Body:
Changing the background color to transparent in the style section should fix the issue

<style name="AppTheme.Toolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#00000000</item>
</style>

The question How to make title background transparent on android app had similar issue above solution did the trick. The android app was for Renesas RX130 and Texas Instrument CC2650 BLE solution. Bellow is solution after the fix.


问:
Arranging Divs to minimize spaces
Here's my problem: I have a group of divs which have varying amounts of content. They're floated left and I want them to line up so there's no vertical space between them (apart from the 10px margin I added.

here's an example on  jsFiddle

it's a bit like this question but i couldn't quite follow the suggestions

1st, is this possible? CSS or jQuery? If you know how to do this, please explain it to me.

Thanks

Si-Fi

答:
Only one think what you can do here closer:

Click here

Title: Arranging Divs to minimize spaces


问:
TouchableOpacity is not working inside ScrollView
I am trying to implement A suggestion box for a text field. While entering input the suggestion box should appear just below to current text field and over the next input filed,
This suggestion should scroll after a maxHeight.
I am have implemented everything just the Touchable is not working inside ScrollView, if I replace ScrollView with simple View Touchable Works but the container will not scroll of course.

How to deal with this?

import React from 'react';
import {
  View,
  StatusBar,
  ScrollView,
  TextInput,
  Text,
  SafeAreaView,
  TouchableOpacity,
} from 'react-native';
const TestScreen = () => {
  const [val, setVal] = React.useState('');
  const [show, setShow] = React.useState(false);
  return (
    <>
      <SafeAreaView style={{flex: 1}}>
        <TextInput
          placeholder="Text"
          value={val}
          style={{zIndex: 1}}
          onFocus={() => setShow(true)}
          onBlur={() => setShow(false)}
          onChangeText={t => {
            setShow(true);
            setVal(t);
          }}
        />
        <TextInput placeholder="Text" value={val} style={{zIndex: 1}} />
        {show && (
          <View style={{position: 'absolute', top: 50}}>
            <ScrollView
              style={{
                elevation: 5,
                zIndex: 5,
                backgroundColor: 'white',
                width: 100,
                maxHeight: 50,
              }}>
              <TouchableOpacity onPress={() => setVal('Item1')}>
                <Text>Item1</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => setVal('Item2')}>
                <Text>Item2</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => setVal('Item3')}>
                <Text>Item3</Text>
              </TouchableOpacity>
            </ScrollView>
          </View>
        )}
      </SafeAreaView>
    </>
  );
};

export default TestScreen;```

Please let me know where I am wrong.

答:
So If you are looking for the answer to this problem.
Just remove the onBlur function props from TextField component.
Here you go, you got your own custom textfield suggestion box.

Here the solution code that helped to get this done. I still don't know it is the best idea but It worked for me atleast.

import React from 'react';
import {
  View,
  StatusBar,
  ScrollView,
  TextInput,
  Text,
  SafeAreaView,
  TouchableOpacity,
} from 'react-native';
import {Button} from 'native-base';
const TestScreen = () => {
  const [val, setVal] = React.useState('');
  const [show, setShow] = React.useState(false);
  return (
    <>
      <SafeAreaView style={{flex: 1}}>
        <TouchableOpacity
          style={{flex: 1}}
          activeOpacity={1}
          onPress={() => {
            if (show) {
              setShow(false);
            }
          }}>
          <TextInput
            placeholder="Text"
            value={val}
            style={{zIndex: 1}}
            onFocus={() => setShow(true)}
            onChangeText={t => {
              setShow(true);
              setVal(t);
            }}
          />
          <TextInput placeholder="Text" value={val} style={{zIndex: 1}} />
          {show && (
            <View
              style={{
                position: 'absolute',
                top: 50,
              }}>
              <ScrollView
                style={{
                  elevation: 5,
                  zIndex: 5,
                  backgroundColor: 'white',
                  width: 100,
                  maxHeight: 50,
                }}>
                <TouchableOpacity
                  onPress={() => {
                    setShow(false);
                    setVal('Item1');
                  }}>
                  <Text>Item1</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => setVal('Item2')}>
                  <Text>Item2</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => setVal('Item3')}>
                  <Text>Item3</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => setVal('Item4')}>
                  <Text>Item4</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => setVal('Item5')}>
                  <Text>Item5</Text>
                </TouchableOpacity>
              </ScrollView>
            </View>
          )}
        </TouchableOpacity>
      </SafeAreaView>
    </>
  );
};

export default TestScreen;```

Body:
I am trying to implement A suggestion box for a text field. While entering input the suggestion box should appear just below to current text field and over the next input filed,
This suggestion should scroll after a maxHeight.
I am have implemented everything just the Touchable is not working inside ScrollView, if I replace ScrollView with simple View Touchable Works but the container will not scroll of course.

How to deal with this?

import React from 'react';
import {
  View,
  StatusBar,
  ScrollView,
  TextInput,
  Text,
  SafeAreaView,
  TouchableOpacity,
} from 'react-native';
const TestScreen = () => {
  const [val, setVal] = React.useState('');
  const [show, setShow] = React.useState(false);
  return (
    <>
      <SafeAreaView style={{flex: 1}}>
        <TextInput
          placeholder="Text"
          value={val}
          style={{zIndex: 1}}
          onFocus={() => setShow(true)}
          onBlur={() => setShow(false)}
          onChangeText={t => {
            setShow(true);
            setVal(t);
          }}
        />
        <TextInput placeholder="Text" value={val} style={{zIndex: 1}} />
        {show && (
          <View style={{position: 'absolute', top: 50}}>
            <ScrollView
              style={{
                elevation: 5,
                zIndex: 5,
                backgroundColor: 'white',
                width: 100,
                maxHeight: 50,
              }}>
              <TouchableOpacity onPress={() => setVal('Item1')}>
                <Text>Item1</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => setVal('Item2')}>
                <Text>Item2</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => setVal('Item3')}>
                <Text>Item3</Text>
              </TouchableOpacity>
            </ScrollView>
          </View>
        )}
      </SafeAreaView>
    </>
  );
};

export default TestScreen;

Please let me know where I am wrong.


问:
std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?
I have two use cases.

A. I want to synchronise access to a queue for two threads.

B. I want to synchronise access to a queue for two threads and use a condition variable because one of the threads will wait on content to be stored into the queue by the other thread.

For use case A I see code example using std::lock_guard<>. For use case B I see code example using std::unique_lock<>.

What is the difference between the two and which one should I use in which use case?

答:
They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes  :

lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

And

unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

Here is an example implemetation :

```<code>#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>

using namespace std::chrono;

class Product{

   public:

       Product(int data):mdata(data){
       }

       virtual~Product(){
       }

       bool isReady(){
       return flag;
       }

       void showData(){

        std::cout<<mdata<<std::endl;
       }

       void read(){

         std::this_thread::sleep_for(milliseconds(2000));

         std::lock_guard<std::mutex> guard(mmutex);

         flag = true;

         std::cout<<"Data is ready"<<std::endl;

         cvar.notify_one();

       }

       void task(){

       std::unique_lock<std::mutex> lock(mmutex);

       cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });

       mdata+=1;

       }

   protected:

    std::condition_variable cvar;
    std::mutex mmutex;
    int mdata;
    bool flag = false;

};

int main(){

     int a = 0;
     Product product(a);

     std::thread reading(product.read, &product);
     std::thread setting(product.task, &product);

     reading.join();
     setting.join();

     product.showData();
    return 0;
}
</code>```

In this example, i used the unique_lock<muType> with condition variable

Body:
They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes  :

lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

And

unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

Here is an example implemetation :

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>

using namespace std::chrono;

class Product{

   public:

       Product(int data):mdata(data){
       }

       virtual~Product(){
       }

       bool isReady(){
       return flag;
       }

       void showData(){

        std::cout<<mdata<<std::endl;
       }

       void read(){

         std::this_thread::sleep_for(milliseconds(2000));

         std::lock_guard<std::mutex> guard(mmutex);

         flag = true;

         std::cout<<"Data is ready"<<std::endl;

         cvar.notify_one();

       }

       void task(){

       std::unique_lock<std::mutex> lock(mmutex);

       cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });

       mdata+=1;

       }

   protected:

    std::condition_variable cvar;
    std::mutex mmutex;
    int mdata;
    bool flag = false;

};

int main(){

     int a = 0;
     Product product(a);

     std::thread reading(product.read, &product);
     std::thread setting(product.task, &product);

     reading.join();
     setting.join();

     product.showData();
    return 0;
}

In this example, i used the unique_lock<muType> with condition variable


问:
gRPC C++ client blocking when I set a deadline time
In my grpc client, it sends a keepalive packet every second.The code like this:

```<code>bool FcrConfigClient::SendHealthCheckRpc(const grpc::string& service_name)
{
    CtlHealthCheckRequest request;
    unsigned int client_connection_timeout = HEALTH_CHECK_TIMER_OUT;
    CtlHealthCheckResponse response;
    ClientContext context;
    CtlFcrStatus *fcr_status;
    std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::seconds(client_connection_timeout);
    context.set_deadline(deadline);

    request.set_service(service_name);
    request.set_requestoffline(requestOffline);
    fcr_status = request.mutable_fcr_status();
    fcr_status->set_prober_status(global_grpc_shm_config->proberResult);
    fcr_status->set_offline_flag(global_grpc_shm_config->offline);

    Status s = stub_->check(&context, request, &response);
    ......
</code>```

When I config iptables in Linux to drop all the grpc packets, the grpc channel was blocked. The stack is:

```<code>(gdb) bt
#0  0x00007ffff5e8f873 in epoll_wait () from /lib64/libc.so.6
#1  0x00007ffff69164c8 in pollable_epoll (deadline=<optimized out>, p=0x7fffe4001890)
    at src/core/lib/iomgr/ev_epollex_linux.cc:823
#2  pollset_work (pollset=0x808570, worker_hdl=<optimized out>, deadline=<optimized out>)
    at src/core/lib/iomgr/ev_epollex_linux.cc:1010
#3  0x00007ffff693a651 in cq_pluck (cq=0x808470, tag=0x7fffffffd990, deadline=..., reserved=<optimized out>)
    at src/core/lib/surface/completion_queue.cc:1172
#4  0x00007ffff693a9db in grpc_completion_queue_pluck (cq=<optimized out>, tag=<optimized out>, deadline=...,
    reserved=<optimized out>) at src/core/lib/surface/completion_queue.cc:1199
#5  0x00007ffff750a9d8 in grpc::CoreCodegen::grpc_completion_queue_pluck (this=<optimized out>,
    cq=<optimized out>, tag=<optimized out>, deadline=..., reserved=<optimized out>)
    at src/cpp/common/core_codegen.cc:70
#6  0x0000000000477662 in grpc::CompletionQueue::Pluck (this=0x7fffffffd950, tag=0x7fffffffd990)
    at /usr/local/include/grpcpp/impl/codegen/completion_queue.h:297
#7  0x00000000004f83c2 in grpc::internal::BlockingUnaryCallImpl<fcrctlservice::CtlHealthCheckRequest, fcrctlservice::CtlHealthCheckResponse>::BlockingUnaryCallImpl (this=0x7fffffffdb00, channel=0x7fffe00103c0, method=...,
    context=0x7fffffffdbd0, request=..., result=0x7fffffffdd70)
    at /usr/local/include/grpcpp/impl/codegen/client_unary_call.h:72
#8  0x00000000004f5bd9 in grpc::internal::BlockingUnaryCall<fcrctlservice::CtlHealthCheckRequest, fcrctlservice::CtlHealthCheckResponse> (channel=0x7fffe00103c0, method=..., context=0x7fffffffdbd0, request=...,
    result=0x7fffffffdd70) at /usr/local/include/grpcpp/impl/codegen/client_unary_call.h:43
#9  0x00000000004f3eca in fcrctlservice::FcrCtlService::Stub::check (this=0x7fffe0006450, context=0x7fffffffdbd0,
    request=..., response=0x7fffffffdd70) at fcr_config_client.grpc.pb.cc:73
#10 0x00000000004bdd17 in FcrConfigClient::SendHealthCheckRpc (this=0x7fffe0006290, service_name="16.2.6.138")
    at fcr_config_grpc.cc:380
#11 0x00000000004cc315 in fcr_grpc_health_check_timer (t=0x7fffffffdff0) at fcr_config_grpc.cc:3045
#12 0x00007ffff7274295 in thread_call (thread=0x7fffffffdff0) at lib/thread.c:1542
#13 0x00000000004cfb0b in RunGrpcServer () at fcr_config_grpc.cc:4205
#14 0x00000000004d037b in main (argc=1, argv=0x7fffffffe3d0) at fcr_config_grpc.cc:4378
(gdb)
</code>```

I search the grpc::CompletionQueue::Pluck function in source code, it defines like this:

```<code>  bool Pluck(internal::CompletionQueueTag* tag) {
    auto deadline =
        g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME);
    auto ev = g_core_codegen_interface->grpc_completion_queue_pluck(
        cq_, tag, deadline, nullptr);
    bool ok = ev.success != 0;
    void* ignored = tag;
    GPR_CODEGEN_ASSERT(tag->FinalizeResult(&ignored, &ok));
    GPR_CODEGEN_ASSERT(ignored == tag);
    // Ignore mutations by FinalizeResult: Pluck returns the C API status
    return ev.success != 0;
  }
</code>```

The deadline which I set in my code doesn't be used in Pluck function. So my question is why the grpc client blocked, did deadline time not take effect?

答:
You might be running into the same issue as https://github.com/grpc/grpc/issues/15889.

Please make sure the KEEPALIVE_TIMEOUT setting (GRPC_ARG_KEEPALIVE_TIMEOUT_MS) is configured properly.

Body:
In my grpc client, it sends a keepalive packet every second.The code like this:

bool FcrConfigClient::SendHealthCheckRpc(const grpc::string& service_name)
{
    CtlHealthCheckRequest request;
    unsigned int client_connection_timeout = HEALTH_CHECK_TIMER_OUT;
    CtlHealthCheckResponse response;
    ClientContext context;
    CtlFcrStatus *fcr_status;
    std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::seconds(client_connection_timeout);
    context.set_deadline(deadline);

    request.set_service(service_name);
    request.set_requestoffline(requestOffline);
    fcr_status = request.mutable_fcr_status();
    fcr_status->set_prober_status(global_grpc_shm_config->proberResult);
    fcr_status->set_offline_flag(global_grpc_shm_config->offline);

    Status s = stub_->check(&context, request, &response);
    ......

When I config iptables in Linux to drop all the grpc packets, the grpc channel was blocked. The stack is:

(gdb) bt
#0  0x00007ffff5e8f873 in epoll_wait () from /lib64/libc.so.6
#1  0x00007ffff69164c8 in pollable_epoll (deadline=<optimized out>, p=0x7fffe4001890)
    at src/core/lib/iomgr/ev_epollex_linux.cc:823
#2  pollset_work (pollset=0x808570, worker_hdl=<optimized out>, deadline=<optimized out>)
    at src/core/lib/iomgr/ev_epollex_linux.cc:1010
#3  0x00007ffff693a651 in cq_pluck (cq=0x808470, tag=0x7fffffffd990, deadline=..., reserved=<optimized out>)
    at src/core/lib/surface/completion_queue.cc:1172
#4  0x00007ffff693a9db in grpc_completion_queue_pluck (cq=<optimized out>, tag=<optimized out>, deadline=...,
    reserved=<optimized out>) at src/core/lib/surface/completion_queue.cc:1199
#5  0x00007ffff750a9d8 in grpc::CoreCodegen::grpc_completion_queue_pluck (this=<optimized out>,
    cq=<optimized out>, tag=<optimized out>, deadline=..., reserved=<optimized out>)
    at src/cpp/common/core_codegen.cc:70
#6  0x0000000000477662 in grpc::CompletionQueue::Pluck (this=0x7fffffffd950, tag=0x7fffffffd990)
    at /usr/local/include/grpcpp/impl/codegen/completion_queue.h:297
#7  0x00000000004f83c2 in grpc::internal::BlockingUnaryCallImpl<fcrctlservice::CtlHealthCheckRequest, fcrctlservice::CtlHealthCheckResponse>::BlockingUnaryCallImpl (this=0x7fffffffdb00, channel=0x7fffe00103c0, method=...,
    context=0x7fffffffdbd0, request=..., result=0x7fffffffdd70)
    at /usr/local/include/grpcpp/impl/codegen/client_unary_call.h:72
#8  0x00000000004f5bd9 in grpc::internal::BlockingUnaryCall<fcrctlservice::CtlHealthCheckRequest, fcrctlservice::CtlHealthCheckResponse> (channel=0x7fffe00103c0, method=..., context=0x7fffffffdbd0, request=...,
    result=0x7fffffffdd70) at /usr/local/include/grpcpp/impl/codegen/client_unary_call.h:43
#9  0x00000000004f3eca in fcrctlservice::FcrCtlService::Stub::check (this=0x7fffe0006450, context=0x7fffffffdbd0,
    request=..., response=0x7fffffffdd70) at fcr_config_client.grpc.pb.cc:73
#10 0x00000000004bdd17 in FcrConfigClient::SendHealthCheckRpc (this=0x7fffe0006290, service_name="16.2.6.138")
    at fcr_config_grpc.cc:380
#11 0x00000000004cc315 in fcr_grpc_health_check_timer (t=0x7fffffffdff0) at fcr_config_grpc.cc:3045
#12 0x00007ffff7274295 in thread_call (thread=0x7fffffffdff0) at lib/thread.c:1542
#13 0x00000000004cfb0b in RunGrpcServer () at fcr_config_grpc.cc:4205
#14 0x00000000004d037b in main (argc=1, argv=0x7fffffffe3d0) at fcr_config_grpc.cc:4378
(gdb)

I search the grpc::CompletionQueue::Pluck function in source code, it defines like this:

  bool Pluck(internal::CompletionQueueTag* tag) {
    auto deadline =
        g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME);
    auto ev = g_core_codegen_interface->grpc_completion_queue_pluck(
        cq_, tag, deadline, nullptr);
    bool ok = ev.success != 0;
    void* ignored = tag;
    GPR_CODEGEN_ASSERT(tag->FinalizeResult(&ignored, &ok));
    GPR_CODEGEN_ASSERT(ignored == tag);
    // Ignore mutations by FinalizeResult: Pluck returns the C API status
    return ev.success != 0;
  }

The deadline which I set in my code doesn't be used in Pluck function. So my question is why the grpc client blocked, did deadline time not take effect?


问:
I need an XMPP library for PHP
And I can't use composer (the server is behind a firewall, and PHP-download.com does not work)

In particular, I need to export the user list with their groups

I have tried https://code.google.com/archive/p/xmpphp/ but it is not compatible with PHP 7

答:
So you can't use composer on the server OK but why you don't use composer on your machine load the dependencies and upload the vendor folder. Then you have all you need.

Composer download all dependencies to the vendor folder and generate some autoloading files. When you upload the hole project it should work.

Title: I need an XMPP library for PHP


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答: As already mentioned the keeping references around will lead to increasing memory usage over time. An easy way to get into this situation is with events. If you had a long living object with some event that your other objects listen to, if the listeners are never removed then the event on the long lived object will keep those other instances alive long after they are no longer needed.</p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Memory Leak in C#

LastEditorDisplayName: strager

OwnerDisplayName: Jeremy Wilde


问:
Moving a div into another div
i have 2 main div:

```<code>    <div id="div1">
<div id="minidiv1">a</div>
<div id="minidiv2">b</div>
   </div>
   <div id="div2"></div>
</code>```

I want move the minidiv1 into the div2 with jquery

how can i do?

答:
Luca, did Paul's answer actually work for you?  I think you need to be referencing the jQuery object like so:

```<code>$($('#minidiv1')).appendTo('#div2');
// or
$('#div2').append($('#minidiv1'));
</code>```

Otherwise, jQuery will just append the string "#minidiv1" to #div2, rather than moving your existing div.

Title: Moving a div into another div

Body:
i have 2 main div:

a

b

I want move the minidiv1 into the div2 with jquery

how can i do?

Body:
Luca, did Paul's answer actually work for you?  I think you need to be referencing the jQuery object like so:

$($('#minidiv1')).appendTo('#div2');
// or
$('#div2').append($('#minidiv1'));

Otherwise, jQuery will just append the string "#minidiv1" to #div2, rather than moving your existing div.


问:
jq - How to iterate through keys of different names
I've got JSON that looks like this

```<code>{
  "keyword1": {
    "identifier1": 16
  },
  "keyword2": {
    "identifier2": 16
  }
}
</code>```

and I need to loop through the keywords to get the identifiers (not sure if I'm using the right terminology here). Seems pretty simple, but because the keywords are all named different, I don't know how to handle that.

答:
I'd think something along these lines would work well:

```<code>jq '. | to_entries | .[].key'
</code>```

see https://stedolan.github.io/jq/manual/#to_entries,from_entries,with_entries

or if you wanted to get the values from a variable:

```<code>JSON_DATA={main:{k1:v1,k2:v2}}
result=$(jq -n "$JSON_DATA" | jq '.main | to_entries | .[].value' --raw-output)
echo $result

##outputs: v1 v2
</code>```

Body:
I've got JSON that looks like this

{
  "keyword1": {
    "identifier1": 16
  },
  "keyword2": {
    "identifier2": 16
  }
}

and I need to loop through the keywords to get the identifiers (not sure if I'm using the right terminology here). Seems pretty simple, but because the keywords are all named different, I don't know how to handle that.

Body:
I'd think something along these lines would work well:

jq '. | to_entries | .[].key'

see https://stedolan.github.io/jq/manual/#to_entries,from_entries,with_entries

or if you wanted to get the values from a variable:

JSON_DATA={main:{k1:v1,k2:v2}}
result=$(jq -n "$JSON_DATA" | jq '.main | to_entries | .[].value' --raw-output)
echo $result

##outputs: v1 v2


问:
Error Code: 1366. Incorrect integer value: '#N/A' for column 'Length' at row 21
In my dataset, there are many nonsense values of "#N/A". I create a new table and load the local CSV file into my new table. But because of the nonsense value, it shows the error as shown in the headline. How can I load a dataset successfully without the nonsense values?

Here is my code:

```<code>CREATE TABLE movies (
    Yearnum INT NOT NULL,
    Length INT,
    Title VARCHAR(255) NOT NULL,
    Subjct VARCHAR(255) NOT NULL,
    Actor VARCHAR(255) NOT NULL,
    Actress VARCHAR(255) ,
    Director VARCHAR(255) ,
    Popularity VARCHAR(255),
    Awards VARCHAR(255) NOT NULL
);
LOAD DATA INFILE  'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/movies - movies.csv'
INTO TABLE movies
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
</code>```

Here is my link url of dataset:https://docs.google.com/spreadsheets/d/1J17LYPJZaW5QWQuQVJQonpJXGUbPGOJjg5bxj3SMupQ/edit?usp=sharing

答:
You can work around this by using a column list with variables in the place of columns whose data might not be valid in the CSV file; the column values can then be made valid using a SET clause. For your example:

```<code>LOAD DATA INFILE  'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/movies - movies.csv'
INTO TABLE movies
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(Yearnum, @length, Title, Subjct, Actor, Actress, Director, Popularity, Awards)
SET Length = CASE WHEN @length = '#N/A' THEN 0 ELSE @length END
</code>```

See the manual for more details.

Body:
In my dataset, there are many nonsense values of "#N/A". I create a new table and load the local CSV file into my new table. But because of the nonsense value, it shows the error as shown in the headline. How can I load a dataset successfully without the nonsense values?

Here is my code:

CREATE TABLE movies (
    Yearnum INT NOT NULL,
    Length INT,
    Title VARCHAR(255) NOT NULL,
    Subjct VARCHAR(255) NOT NULL,
    Actor VARCHAR(255) NOT NULL,
    Actress VARCHAR(255) ,
    Director VARCHAR(255) ,
    Popularity VARCHAR(255),
    Awards VARCHAR(255) NOT NULL
);
LOAD DATA INFILE  'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/movies - movies.csv'
INTO TABLE movies
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;

Here is my link url of dataset:https://docs.google.com/spreadsheets/d/1J17LYPJZaW5QWQuQVJQonpJXGUbPGOJjg5bxj3SMupQ/edit?usp=sharing

Body:
You can work around this by using a column list with variables in the place of columns whose data might not be valid in the CSV file; the column values can then be made valid using a SET clause. For your example:

LOAD DATA INFILE  'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/movies - movies.csv'
INTO TABLE movies
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(Yearnum, @length, Title, Subjct, Actor, Actress, Director, Popularity, Awards)
SET Length = CASE WHEN @length = '#N/A' THEN 0 ELSE @length END

See the manual for more details.


问:
Does Azure storage premium account support block blob?
just created a few premium azure storage accounts with general-purpose v2, but it seem doesn't support block blob, when I try to upload from either Portal or Data Explorer, only option is page blob. but according document, general purpose v2 should support all 3 blob types. </p>

答:
Premium V2 storage accounts do not support Block Blobs. They only support Page Blobs and local redundancy level (LRS). If you need support for all kinds of blobs (Append, Block and Page) in a single storage account, you would need to create a "Standard" kind of account.

You would need to create a BlockBlobStorage kind of account if you want premium performance for Block blobs. Please note that this kind of account only supports Block blobs.

You can read more about it here: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-performance-tiers.