instruction stringlengths 0 30k ⌀ |
|---|
The following doesn't directly answer the question, so I'll not accept it. However it helped me to in understanding a critical point about Dafny's real numbers.
Why shouldn't `real` be called `rational` or some other number system whose axioms/properties we can prove `real` to satisfy? Wouldn't that be more natural than to state that Dafny's reals are indeed real numbers even though this fact doesn't seem to be usable?
My answer: Adding completeness axioms doesn't lead to contradictions (I hope!). If we `assume` completeness of a hypothetical `rational` type, we would be able to derive `false` by using completeness to get a "rational square root of 2" and then show that square root of 2 is not a rational number.
The other way around, we can't prove that `real` is actually the set of rational numbers, because we can't prove that irrational numbers are not in `real`. E.g. we can't prove `forall r: real :: exists p: nat, q: nat :: r == p as real / q as real`.
So even though apparently we can't prove that `real` is the set of real numbers, we can't prove that it is the set of rational numbers either. Furthermore, assuming completeness (hopefully) doesn't lead to contradictions, so there is an argument that `real` resembles the real numbers more than the rational numbers. |
Program doesn't run after DFU |
|c|embedded|stm32|stm32f4|dfu| |
null |
|c|memory-management|malloc| |
Setting a variable based on a condition is absolutely possible!
{% set variable = (condition == 1) ? 'this' : 'that' %}
The condition can be evaluated against `true`, `false`, or another variable as well. |
I am experimenting with the excellent Bootstrap DateTimePicker plugin but appear to have hit the buffers right at the start. The page control appears correctly but the calendar button is entirely unresponsive - no picker actually pops up. I have created [this fiddle][1] to illustrate the problem. Examining the console output for the fiddle does not reveal anything obviously wrong.
I noticed that the sample code uses jQuery 1.8.3 so I tried dropping back to that but to no avail. What am I getting wrong here?
The test markup I am using is quite straightforward - and copied directly from the Datetimepicker example docs
<div class="form-group">
<label for="dtp_singleshot" class="col-md-2 control-label">Choose</label>
<div class="input-group date form_datetime col-md-5" data-link-
field="dtp_singleshot">
<input class="form-control" size="16" type="text" value="" readonly>
<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
</div>
<input type="hidden" id="dtp_singleshot" value="" /><br/>
</div>
[1]: https://jsfiddle.net/0ff6jguv/5/ |
I'm trying the Episodic Semi-Gradient Sarsa from Sutton & Barto Chapter 10 (second edition) for the [CartPole problem using Gymnasium](https://gymnasium.farama.org/environments/classic_control/cart_pole/). For function approximation, I'm using neural networks with keras. However, implementing the algorithm faithfully forces me to use a batch size of 1 for fit and predict, and this results in extremely slow code. An alternative is to first run the code to collect data from gymnasium, and then use the data to train the neural network offline. Is that recommended - it'd be offline but still on-policy if I understand correctly)? Or is there some other standard way to use neural networks with Gymnasium without compromising on performance?
[![Episodic Semi-Gradient Sarsa from Sutton & Barto][1]][1]
Outline of my current attempt -
```py
import gymnasium as gym
from numpy.random import choice as random_choice
from numpy import array, argmax
```
I wrote the algorithm as the following python code:
```py
env = gym.make('CartPole-v1')
for ep_idx in range(num_episodes):
terminated = False
state, _ = env.reset()
action = env.action_space.sample()
while not terminated:
action_ = policy.take_action(state, qvalue, ep_idx)
state_, reward, terminated, _, _ = env.step(action_)
if terminated:
qvalue.update(state, action, reward, None, None)
else:
qvalue.update(state, action, reward, state_, action_)
state, action = state_, action_
```
For function approximation, I decided to use Keras. This is implemented inside the `qvalue.update` as follows:
```py
class QValueFunction:
def __init__(self, discount, learning_rate, num_actions, *state_vector_dim):
# not shown here for brevity
def __call__(self, state, action=None):
# not shown here for brevity
def update(self, s, a, r, s_, a_):
model = self._model # instance of keras.models.Model
gamma = self._discount # float
update_targets = self._update_targets # a pre-allocated numpy array
q = self
update_targets[:] = q(s, None)
self._s[:] = s
s = self._s
if s_ is None and a_ is None:
update_targets[0, a] = r
else:
update_targets[0, a] = r + gamma * q(s_, a_)
model.fit(s, update_targets, batch_size=1, verbose=0)
```
And `policy` is an instance of `EpsilonGreedyPolicy`:
```py
class EpsilonGreedyPolicy:
def __init__(self, epsilon):
self.eps = epsilon
def take_action(self, state, qvalue, ep=None):
num_actions = qvalue.num_actions
if callable(self.eps): eps = self.eps(ep+1)
else: eps = self.eps
if rand() < eps:
return random_choice(num_actions)
else:
qvalues = qvalue(state)
return argmax(qvalues)
```
The above code runs at about 1 episode per 10 seconds on my laptop (CPU only). To check how fast the code can actually run, I tried using a random policy (eps=1) to generate data for 1000 episodes generating 20000+ tuples of `(s, a, r, s_, a_)`. This required just about 10 seconds. Next, I used this data to train the neural network separately, this resulted in about 1 second per 10000 data points by passing all the data at once to the `model.predict` and `model.fit` of Keras. In essence, running the code faithfully to the algorithm using a batch size of 1 for model.fit and model.predict requires 10000s of seconds, while running it as (i) generate data first (ii) train neural network next requires 10s to 100s of seconds.
Is there any recommended way of using neural networks with Gymnasium to avoid such heavy overheads?
[1]: https://i.stack.imgur.com/iTSoD.png |
from sqlalchemy import create_engine, text
db_connection_str = "mysql+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
#Don't worry while running the code , I had replaced all the values in the db_connection_str with my values
engine = create_engine(
db_connection_str,
connect_args={
# "ssl": {
# "ssl_ca": "/etc/ssl/cert.pem",
# }
# "ssl": {
# "ca": "/home/gord/client-ssl/ca.pem",
# "cert": "/home/gord/client-ssl/client-cert.pem",
# "key": "/home/gord/client-ssl/client-key.pem"
# }
# I tried both of these methods and even without using connect_args but it still gives me an error
})
with engine.connect() as conn:
result = conn.execute(text("select * from jobs"))
print(result.all())
# **This is my entire code, When I try running it while the ssl_ca is uncommented or when I have not entered the connect_args dictionary itself, this is the error I get:**
Traceback (most recent call last):
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pymysql\connections.py", line 644, in connect
sock = socket.create_connection(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\socket.py", line 851, in create_connection
raise exceptions[0]
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\socket.py", line 836, in create_connection
sock.connect(sa)
TimeoutError: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 146, in __init__
self._dbapi_connection = engine.raw_connection()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 3304, in raw_connection
return self.pool.connect()
^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 449, in connect
return _ConnectionFairy._checkout(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 1263, in _checkout
fairy = _ConnectionRecord.checkout(pool)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 712, in checkout
rec = pool._do_get()
^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\impl.py", line 179, in _do_get
with util.safe_reraise():
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\util\langhelpers.py", line 146, in __exit__
raise exc_value.with_traceback(exc_tb)
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\impl.py", line 177, in _do_get
return self._create_connection()
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 390, in _create_connection
return _ConnectionRecord(self)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 674, in __init__
self.__connect()
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 900, in __connect
with util.safe_reraise():
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\util\langhelpers.py", line 146, in __exit__
raise exc_value.with_traceback(exc_tb)
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 896, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\create.py", line 643, in connect
return dialect.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\default.py", line 617, in connect
return self.loaded_dbapi.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pymysql\connections.py", line 358, in __init__
self.connect()
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pymysql\connections.py", line 711, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'jovian-careers-db-jovian-careers.a.aivencloud.com' (timed out)")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:\Gunkar\Coding\Self\Flask\Jovian-Careers-Website-V2\database.py", line 20, in <module>
with engine.connect() as conn:
^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 3280, in connect
return self._connection_cls(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 148, in __init__
Connection._handle_dbapi_exception_noconnection(
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 2444, in _handle_dbapi_exception_noconnection
raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 146, in __init__
self._dbapi_connection = engine.raw_connection()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 3304, in raw_connection
return self.pool.connect()
^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 449, in connect
return _ConnectionFairy._checkout(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 1263, in _checkout
fairy = _ConnectionRecord.checkout(pool)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 712, in checkout
rec = pool._do_get()
^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\impl.py", line 179, in _do_get
with util.safe_reraise():
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\util\langhelpers.py", line 146, in __exit__
raise exc_value.with_traceback(exc_tb)
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\impl.py", line 177, in _do_get
return self._create_connection()
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 390, in _create_connection
return _ConnectionRecord(self)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 674, in __init__
self.__connect()
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 900, in __connect
with util.safe_reraise():
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\util\langhelpers.py", line 146, in __exit__
raise exc_value.with_traceback(exc_tb)
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 896, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\create.py", line 643, in connect
return dialect.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\default.py", line 617, in connect
return self.loaded_dbapi.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pymysql\connections.py", line 358, in __init__
self.connect()
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pymysql\connections.py", line 711, in connect
raise exc
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'jovian-careers-db-jovian-careers.a.aivencloud.com' (timed out)")
(Background on this error at: https://sqlalche.me/e/20/e3q8)
# **And if I dont uncomment the ssl_ca thing and instead use the other method , then it just says this :
# **
Traceback (most recent call last):
File "E:\Gunkar\Coding\Self\Flask\Jovian-Careers-Website-V2\database.py", line 20, in <module>
with engine.connect() as conn:
^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 3280, in connect
return self._connection_cls(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 146, in __init__
self._dbapi_connection = engine.raw_connection()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\base.py", line 3304, in raw_connection
return self.pool.connect()
^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 449, in connect
return _ConnectionFairy._checkout(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 1263, in _checkout
fairy = _ConnectionRecord.checkout(pool)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 712, in checkout
rec = pool._do_get()
^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\impl.py", line 179, in _do_get
with util.safe_reraise():
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\util\langhelpers.py", line 146, in __exit__
raise exc_value.with_traceback(exc_tb)
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\impl.py", line 177, in _do_get
return self._create_connection()
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 390, in _create_connection
return _ConnectionRecord(self)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 674, in __init__
self.__connect()
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 900, in __connect
with util.safe_reraise():
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\util\langhelpers.py", line 146, in __exit__
raise exc_value.with_traceback(exc_tb)
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\pool\base.py", line 896, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\create.py", line 643, in connect
return dialect.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sqlalchemy\engine\default.py", line 617, in connect
return self.loaded_dbapi.connect(*cargs, **cparams)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pymysql\connections.py", line 289, in __init__
self.ctx = self._create_ssl_ctx(ssl)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ravin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pymysql\connections.py", line 373, in _create_ssl_ctx
ctx = ssl.create_default_context(cafile=ca, capath=capath)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\ssl.py", line 770, in create_default_context
context.load_verify_locations(cafile, capath, cadata)
FileNotFoundError: [Errno 2] No such file or directory
**I have mentioned whatever I tried above and what I was expecting is to get the information from one of my tables "jobs" but python didnt even reach that line.**
Also this is the tutorial I am following : "https://www.youtube.com/watch?v=yBDHkveJUf4&list=PLiAbjvVKX4Q-7ygi3CYBd8QOES3A3lyqd&index=2&t=8184s&ab_channel=freeCodeCamp.org"
start watching from 2:45:00
**He found his solution to this same problem as he was using another service for his web database called "PlanetScale", I did not use that because I found out it is paid now and the free service is no longer available.**
Also later I am going to integrate this in my flask website as per the tutorial
|
|blazor|syncfusion|csvhelper|csv-import| |
{"Voters":[{"Id":269970,"DisplayName":"esqew"},{"Id":3689450,"DisplayName":"VLAZ"},{"Id":3730754,"DisplayName":"LoicTheAztec"}]} |
I used focus and it works all text boxes just fine.
$('input[type=text]').focus(function(){ $(this).select() }) |
|python|path|file-permissions| |
How about try `asp-action` , like
<form id="FormActive" asp-action="Index">
</form>
Then in controller:
[HttpPost]
public IActionResult Index(int id)
{
return View();
}
result:
[![enter image description here][1]][1]
**Update**:
Try to use `<a>` tag without With Tag Form
<a asp-controller="Home" asp-action="Index2" asp-route-id="1"><button>1</button></a>
Then in controller;
[HttpGet]
public IActionResult Index2(int id)
{
return View();
}
result:
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/WNnI8.png
[2]: https://i.stack.imgur.com/LjdY6.png |
|pyarrow| |
{"Voters":[{"Id":9599344,"DisplayName":"uber.s1"}],"DeleteType":1} |
- In Desktop
(The emulator turns on automatically)
[npm start video](https://youtu.be/uUhNKguiao4)
[terminal(?) image](https://i.stack.imgur.com/k913N.png)
[emulator image](https://i.stack.imgur.com/GY4MG.png)
- On the laptop
After turning on the emulator
can activate the React-Native
Which program is the terminal image among the images?
(Powershell X, Azure X, cmd X, ...)
I want to use it like a desktop
- case of me
* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: No connected devices! |
For some loss functions, you will need to indicate extra parameters, you can specify them with ":" after the type of the loss function, for example:
model = CatBoostRegressor(loss_function='Lq:q=4')
In general, the parameters should be declared as such:
<Metric>[:<parameter 1>=<value>;..;<parameter N>=<value>]
For more information - [Catboost Implemented metrics][1]
[1]: https://catboost.ai/en/docs/features/loss-functions-desc |
I want to navigate to the next screen after bloc listener checks the state, but in my UI, the bloc listener does not know that the state has changed. Therefore, the state is changed on\<event\>((state,emit)) after emitting to the next state.
Here is my code:
1. Bloc
```flutter
import 'package:bloc/bloc.dart';
import 'package:bloctest/bloc/events.dart';
import 'package:bloctest/bloc/states.dart';
class AppBloc extends Bloc<AppEvent,AppState>{
AppBloc(AppState initialState):super(initialState){
on<AppStartEvent>((event, emit) {
emit(AppInitState());
});
on<NavigatorButtonPressed>((event, emit) {
emit(NavigationSucceedState());
print('navigation succeed');
});
}
}
```
2. Bloc Listener screen
```flutter
import 'package:bloctest/bloc/bloc.dart';
import 'package:bloctest/bloc/states.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'bloc/events.dart';
import 'main2.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isNavigationSuccess=false;
AppBloc appBloc=AppBloc(AppInitState());
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider<AppBloc>(
create: (context)=>AppBloc(AppInitState())..add(AppStartEvent()),
child: Scaffold(
body: BlocListener<AppBloc, AppState>(
listener: (context , state)async{
if(state is NavigationSucceedState){
await Future.delayed(const Duration(seconds: 1));
Navigator.push(context, MaterialPageRoute(builder: (context)=>MyApp2()));
}
},
child:BlocBuilder<AppBloc,AppState>(
builder:(context,state){
context.read<AppBloc>().add(AppStartEvent());
return state is AppStartingState?const Center(child: CircularProgressIndicator(),):
Scaffold(
body: SafeArea(child: Center(
child: ElevatedButton(
onPressed: () {
appBloc.add(NavigatorButtonPressed());
},
child: const Text('tap to go to next page')),
)),
);
}
),
),
),
)
);
}
}
``` |
Here's a concise polyfill using [`Array.prototype.reduce`][1]:
if(!Object.entries)
Object.entries = function(obj) {
return Object.keys(obj).reduce(function(arr, key) {
arr.push([key, obj[key]]);
return arr;
}, []);
}
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce |
My issue is that I want to create a registration form where the registrant can add as many delegates as he wants by clicking on "Add delegate". The problem is that the form works perfectly but it just takes into account only the first row to add the values in the database when clicking on submit.
I tried many ways on how to address this issue and am a bit lost now.
Below is the link of the form on my test website and the code that I am using.
[https://www.test.graincomevents.com/246479-2](https://stackoverflow.com)
`
```
<?php
// Template Name: Form Processor
get_header();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
global $wpdb;
// Check if the 'delegate' array is set in $_POST
if (isset($_POST['delegate']) && is_array($_POST['delegate'])) {
// Function to sanitize and validate input
function sanitize_input($data) {
return is_array($data) ? array_map('sanitize_input', $data) : sanitize_text_field($data);
}
// Sanitize and validate each delegate registration data
foreach ($_POST['delegate'] as $delegate) {
// Check if array keys exist before accessing them
if (
isset($delegate['company']) &&
isset($delegate['company_country']) &&
isset($delegate['first_name']) &&
isset($delegate['last_name']) &&
isset($delegate['designation']) &&
isset($delegate['email']) &&
isset($delegate['phone']) &&
isset($delegate['appear_on_list'])
) {
$delegate_data = sanitize_input($delegate);
// Insert delegate data into the database
$wpdb->insert(
'wp_685721_delegate_registration',
array(
'company' => $delegate_data['company'],
'company_country' => $delegate_data['company_country'],
'first_name' => $delegate_data['first_name'],
'last_name' => $delegate_data['last_name'],
'designation' => $delegate_data['designation'],
'email' => $delegate_data['email'],
'phone' => $delegate_data['phone'],
'appear_on_list' => $delegate_data['appear_on_list']
)
);
}
}
}
// Sanitize and validate billing information
$billing_info = array_map('sanitize_input', $_POST['billing_info']);
// Insert billing information into database
$wpdb->insert(
'wp_685721_billing_information',
array(
'billing_first_name' => $billing_info['billing_first_name'],
'billing_last_name' => $billing_info['billing_last_name'],
'billing_email' => $billing_info['billing_email'],
'billing_company' => $billing_info['billing_company'],
'billing_country' => $billing_info['billing_country'],
'billing_address' => $billing_info['billing_address'],
'billing_postcode' => $billing_info['billing_postcode'],
'billing_city' => $billing_info['billing_city'],
'billing_phone' => $billing_info['billing_phone'],
'billing_vat_number' => isset($billing_info['billing_vat_number']) ? $billing_info['billing_vat_number'] : '',
'billing_message' => isset($billing_info['billing_message']) ? $billing_info['billing_message'] : ''
)
);
// Display success message or redirect
echo '<p>Form submitted successfully!</p>';
} else {
// Display the form here
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration and Billing Information</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
border-bottom: 1px solid #ddd;
text-align: left;
}
th {
background-color: #f2f2f2;
}
input[type="text"], input[type="email"], input[type="tel"], select, textarea {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
input[type="submit"] {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body data-rsssl=1>
<h2>Delegate Registration Form and Billing Information</h2>
<form action="/246479-2" method="post">
<h3>Delegate Registration</h3>
<table id="delegateTable">
<tr>
<th>ID</th>
<th>Company*</th>
<th>Company Country*</th>
<th>First Name*</th>
<th>Last Name*</th>
<th>Designation/ Job Title*</th>
<th>Email Address*</th>
<th>Phone* (+XX)</th>
<th>Appear on the Delegate List*</th>
</tr>
<tr>
<td>Delegate 1</td>
<td><input type="text" name="delegate[0][company]" required></td>
<td><input type="text" name="delegate[0][company_country]" required></td>
<td><input type="text" name="delegate[0][first_name]" required></td>
<td><input type="text" name="delegate[0][last_name]" required></td>
<td><input type="text" name="delegate[0][designation]" required></td>
<td><input type="email" name="delegate[0][email]" required></td>
<td><input type="tel" name="delegate[0][phone]" required></td>
<td>
<select name="delegate[0][appear_on_list]" required>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</td>
</tr>
</table>
<button type="button" class="add-row" onclick="addDelegateRow()">Add Delegate</button>
<hr>
<h3>Billing Information</h3>
<table>
<tr>
<th>First Name*</th>
<th>Last Name*</th>
<th>Email Address*</th>
<th>Company*</th>
<th>Country*</th>
<th>Address*</th>
<th>Postcode*</th>
<th>Town/City*</th>
<th>Phone* (+XX)</th>
<th>VAT Number (optional)</th>
<th>Any message for GrainCom Team?</th>
</tr>
<tr>
<td><input type="text" name="billing_info[billing_first_name]" required></td>
<td><input type="text" name="billing_info[billing_last_name]" required></td>
<td><input type="email" name="billing_info[billing_email]" required></td>
<td><input type="text" name="billing_info[billing_company]" required></td>
<td><input type="text" name="billing_info[billing_country]" required></td>
<td><input type="text" name="billing_info[billing_address]" required></td>
<td><input type="text" name="billing_info[billing_postcode]" required></td>
<td><input type="text" name="billing_info[billing_city]" required></td>
<td><input type="tel" name="billing_info[billing_phone]" required></td>
<td><input type="text" name="billing_info[billing_vat_number]"></td>
<td><textarea name="billing_info[billing_message]"></textarea></td>
</tr>
</table>
<br>
<input type="submit" value="Submit Registration and Billing Information">
</form>
<script>
var delegateCount = 1;
function addDelegateRow() {
delegateCount++;
var table = document.getElementById("delegateTable");
var row = table.insertRow(-1); // Append row at the end of the table
var cell, input;
var headers = ["Company", "Company Country", "First Name", "Last Name", "Designation/ Job Title", "Email Address*", "Phone* (+XX)", "Appear on the Delegate List*"];
cell = row.insertCell(0);
cell.textContent = "Delegate " + delegateCount;
for (var i = 1; i <= headers.length; i++) {
cell = row.insertCell(i);
if (i == headers.length) { // Handle the "Appear on the Delegate List" field
var originalSelect = document.querySelector("#delegateTable select");
var clonedSelect = originalSelect.cloneNode(true);
clonedSelect.name = "delegate[" + (delegateCount - 1) + "][appear_on_list]";
// Set the value of the cloned select element to the currently selected value
var currentValue = originalSelect.options[originalSelect.selectedIndex].value;
clonedSelect.value = currentValue;
cell.appendChild(clonedSelect);
} else {
input = document.createElement("input");
input.type = "text";
input.name = "delegate[" + (delegateCount - 1) + "][" + headers[i - 1].toLowerCase().replace(/\s/g, '_') + "]";
input.required = true;
cell.appendChild(input);
}
}
}
</script>
</body>
</html>
<?php
}
get_footer();
?>
`
```
I tried chat GPT and I couldn't find a good solution as I am not a coder in PHP! |
How to add the dynamic new rows from my registration form in my database? |
|php|database|wordpress|forms|phpmyadmin| |
null |
s3cmd will do the job.
It allows multiple file upload, uploading in chuncks and even sync folder with s3 folder
https://docs.digitalocean.com/products/spaces/reference/s3cmd/ |
The accepted answer was not working for me.
I fixed this by adding a slash at the end of the index directive like so:
index index.htm index.html index.php /;
The way this works is I guess by looking for nothing in the root directory, not finding it and reporting a genuine 404. It can be any bogus page with a slash before, such as /404.html or /this_file_isnt_really_there or whatever.
What it does is to suppress 403 errors altogether, as if the directory weren't there at all, so there's no reason to log.
This comes with the advantage of hardening the installation, actual folder paths can no longer be identified.
However, I'm not sure how valid, safe or futureproof this approach may be, so use at your own peril.
Something like `log_not_allowed` would be much nicer i guess. |
I work in a windows form application. i wanna make a setting page for my program. in this form i have music for the total of my program and i have sound for my button, it sounds when you click on a button. i can off them and on them. my problem, is sounds of buttons. when i off the sound in the setting and it just off for the setting form, and when i go to another form and setting page is still open the sound of button is not off. and it sound when i click.
page setting:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
using WMPLib;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
WindowsMediaPlayer playerr = new WindowsMediaPlayer();
public WindowsMediaPlayer button = new WindowsMediaPlayer();
public bool s ;
public bool p ;
public Form1()
{
InitializeComponent();
this.StartPosition= FormStartPosition.Manual;
this.Location = new Point(300, 150);
}
private void Form1_Load(object sender, EventArgs e)
{
playerr.URL = "aurora_runaway.mp3";
playerr.controls.play();
}
private void button1_Click(object sender, EventArgs e)
{
if (pictureBox3.Visible == false && pictureBox4.Visible == true)
{
button.URL = "notifications-sound-127856.mp3";
button.controls.play();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
playerr.controls.play();
pictureBox1.Visible= false;
pictureBox2.Visible= true;
}
private void pictureBox2_Click(object sender, EventArgs e)
{
playerr.controls.stop();
pictureBox2.Visible = false;
pictureBox1.Visible =true;
}
private void pictureBox3_Click(object sender, EventArgs e)
{
pictureBox3.Visible = false;
pictureBox4.Visible = true;
s = true;
p = false;
}
private void pictureBox4_Click(object sender, EventArgs e)
{
pictureBox4.Visible = false;
pictureBox3.Visible = true;
s = false;
p = true;
}
private void button2_Click(object sender, EventArgs e)
{
new Form3().ShowDialog();
}
}
}
```
another page:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form3 : Form
{
Form1 ff = new Form1();
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (ff.p == true && ff.s == false)
{
ff.button.URL = "notifications-sound-127856.mp3";
ff.button.controls.play();
}
}
}
}
``` |
Recommended way to use Gymnasium with neural networks to avoid overheads in model.fit and model.predict |
|python|machine-learning|keras|neural-network|reinforcement-learning| |
Best options is to put this in an async function and call get token first, that's what I do in tests for example:
beforeEach(async () => {
const token = await getToken()
client = new Client({
url: 'http://localhost:4000/',
exchanges: [cacheExchange, fetchExchange],
fetchOptions: () => {
return {
headers: { authorization: token ? `Bearer ${token}` : '' },
};
},
})
}) |
I have a button called EXPORT and now I need to create a shortcut to export file to excel. The short cut is Ctrl+Alt+E. When I press the shortcut it have to call the function "onCommandExecution" which will check the ID condition and execute the function "onExportToExcel". I have been made debugging and I the ID was not called in the function. In other words the function onCommandExecution has not been called. The problem have to be either in view file or in manifest file but I see that both are correct!
**The problem is when I press the combination I do not get all of ctrl+alt+e. I get one of them in debugging.**
Does someone have a solution please?
Thank you
//Controller.js file
onCommandExecution: function(oEvent) {
var mSId = oEvent.getSource().getId();
if (mSId === "CE_EXPORT") {
this.onExportToExcel();
}
},
onExportToExcel: function() {
var mSId = oEvent.getSource().getId();
var oSettings, oSheet, aProducts;
var aCols = [];
aCols = this.createColumnConfig();
aProducts = this.byId("messageTable").getModel("oMessageModel").getProperty('/');
var oDate = new Date();
var regex = new RegExp(",", "g");
var aDateArr = oDate.toISOString().split("T")[0].split("-");
var sDate = aDateArr.join().replace(regex, "");
var aTimeArr = oDate.toISOString().split("T")[1].split(":");
var sSeconds = oDate.toISOString().split("T")[1].split(":")[2].split(".")[0];
var sTime = aTimeArr[0] + aTimeArr[1] + sSeconds;
oSettings = {
workbook: {
columns: aCols
},
dataSource: aProducts,
fileName: "export_" + sDate + sTime
};
if (mSId === "CE_EXPORT") {
oSheet = new Spreadsheet(oSettings);
oSheet.build()
.then(function() {
MessageToast.show(this.getOwnerComponent().getModel("i18n").getResourceBundle().getText("excelDownloadSuccessful"));
})
.finally(function() {
oSheet.destroy();
});
}
},
<View.xml file>
<Page>
<footer>
<OverflowToolbar >
<Button icon="sap-icon://excel-attachment" text="{i18n>exportToExcelBtn}" press="onExportToExcel" tooltip="{i18n>exportToExcelBtnTooltip}"/>
</OverflowToolbar>
</footer>
<dependents>
<core:CommandExecution id="CE_EXPORT" command="Export" enabled="true" execute="onCommandExecution" />
</dependents>
</Page>
<manifest.json file>
"sap.ui5": {
"rootView": {
"viewName": "com.volkswagen.ifdb.cc.sa.view.Main",
"type": "XML"
},
"dependencies": {
"minUI5Version": "1.65.0",
"libs": {
"sap.m": {},
"sap.ui.comp": {},
"sap.ui.core": {},
"sap.ui.layout": {},
"sap.ushell": {}
}
},
"contentDensities": {
"compact": true,
"cozy": true
},
"commands": {
"Export":{
"shortcut": "Ctrl+Alt+E"
}
},
[1]: https://port8089-workspaces-ws-m88sh.eu10.applicationstudio.cloud.sap/com.volkswagen.ifdb.plg.hlplnk/Component-preload.js |
null |
Tracking app usage and events for Android hybrid apps created in Phonegap is an easy affair if one uses Google Analytics. I implemented my own solution using [this Cordova plugin][1]. I had expected that implementing Piwik analytics would be just as easy. I started off with [this plugin][2] and then followed the instructions to write a little test app. I used the phonegap `jquery-mobile-starter` template whose `app.js` I modified along the following lines
$(document).on("deviceready", function()
{
deviceReadyDeferred.resolve();
alert('piwik track');
piwik.startTracker('https://example.com/piwik/piwik.php','siteID');
alert('Device Ready');
});
$(document).on("mobileinit", function ()
{
jqmReadyDeferred.resolve();
window.onerror = whenError;
$(document).on('pagecontainershow',pgcShow);
});
function pgcShow()
{
alert('Page Container now SHOWING!!');
$('#btn').click(doClick);
}
function doClick()
{
alert('Click Me');
piwik.trackEvent('click','I was clicked');
}
function whenError(e,u,l)
{
alert(e);
}
**Explanations**
- I have attempted to put in enough error handling to be sure that the failure of Piwik analytics is not down to something else in my test code.
- In the PageContainerShow event I hook up the click event for a button on my index.html page to send back a `trackEvent` message back to my Piwik API which is at `https://mypiwikserver.com/piwik/piwik.php'
- `siteID` is the ID of the *"website"* that I created for the purpose picked up from the **All Websites** list on my Piwik Admin console.
- For good measure I have modified the Phonegap `config.xml` file
access origin="*"
access origin="https://mypiwikserver.com"
Having done all of this I built the app, installed it on my Android phone, opened it and then went to my Piwik web console expecting to see an event logged in **Actions:Events**. However, I find it stays stubbornly blank. I have noted no error messages and all of my various `alerts` turn up as expected. What am I doing wrong here?
[1]: https://github.com/cmackay/google-analytics-plugin
[2]: https://github.com/kriserickson/cordova-piwik-plugin |
I have encountered this pattern of selecting all columns using * in DBT, when bringing the source data into the staging layer.
You can find it in the [dbt docs][1] about the staging layer but in [this dbt course][2].
The pattern goes like this:
with
source as (
select * from {{ source('stripe','payment') }}
),
transformed as (
select
id as payment_id,
orderid as order_id,
from source
)
select * from transformed
As far as I am concerned selecting * from any source is a bad idea. We are most likely selecting data that we do not need which can incur unnecessary costs but also slow down our queries. We most likely do not have control over the source data so we have absolutely no transparency of what we are selecting.
Does anyone see something wrong with my logic? I see how code looks very clean but how can this be a good idea from a cost/performance point of view?
[1]: https://docs.getdbt.com/best-practices/how-we-structure/2-staging
[2]: https://courses.getdbt.com/courses/take/refactoring-sql-for-modularity/lessons/27780504-5-1-centralizing-logic-in-staging-models |
DBT - Using SELECT * in the staging layer |
No options:

Installed packages:

Hi, I just downloaded Visual Studio 2022 and can't seem to find the add options, specifically add controller when I right click on add as shown in picture. I have installed just about all the packages and even the MVC 4 package as well but still no luck. This is driving me insane as its delaying my whole project. I have looked around but cant seem to find a way to fix this. Please help |
Firstly, Change `CMD ["java", "-jar", "./build/libs/app.jar"]` to
```
SHELL ["/bin/bash", "-c"]
CMD "java -jar ./build/libs/twitch-bot-*.jar"
```
As you noticed the output file is not called `app.jar` but instead as named as gradle does, roughly `{NAME}-{VERSION}.jar`. Changing to [shell format][1], while setting the shell to bash enables you to use standard bash-functionalities, like wild-cards to match a changing project version. This helps you maintain a stable, easily-updatable docker image in the future.
Secondly, (after you updated the question with the java console output),
```
Could not obtain connection to query metadata
```
indicated some connection problems. When using docker-compose together with the application.properties you provided:
`spring.datasource.url=jdbc:mysql://localhost:3306/twitch-bot` points to `localhost` inside your app container, not your host machine - where the SQL container is listening.
You could change this URL either:
```
spring.datasource.url=jdbc:mysql://mysql:3306/twitch-bot
```
or
```
spring.datasource.url=jdbc:mysql://host.docker.internal:3306/twitch-bot
```
The first would be preferred, as there is less overhead. The second one can come in handy if you need to communicate with the host machine.
[1]: https://docs.docker.com/engine/reference/builder/#shell-form
|
I have this simple playbook that reads a file content => fetches a value
=> append that to a local file,
I want to get a config value for different hosts stored in a local file.
```yml
---
- name: Check file content
hosts: all
become: true
tasks:
- name: Check if file exists
ansible.builtin.stat:
path: /mydir/myfile.ini
register: file_stat
- name: Fetch values and write to a local file
when: file_stat.stat.exists
block:
- name: Read file if it exists
ansible.builtin.slurp:
src: /mydir/myfile.ini
register: file_content
- name: Set value as a fact
ansible.builtin.set_fact:
my_setting: "{{ file_content.content | \
b64decode | regex_search('^setting_key\\s*?=\\s*?(.*)$', \
'\\1', multiline=True) | first | trim }}"
- name: Debug file content
ansible.builtin.debug:
msg: '{{ my_setting }}'
- name: Write fetch value to a file
become: false
ansible.builtin.lineinfile:
path: my_settings.txt
line: '{{ inventory_hostname }} - {{ my_setting }}'
create: true
mode: '644'
insertafter: 'EOF'
delegate_to: localhost
# when: >
# my_setting is defined and
# my_setting != "MY_SETT_VALUE"
# with_items: '{{ my_setting }}'
```
However, this playbook behaves inconsistently. If I run it against two hosts, sometimes there will be two lines in the output file `my_settings.txt`, one for each host, as expected.
But sometimes there will be only one line for one host(most of the time), and the other host’s value is missing.
Is this due to some race condition? How can I fix this issue?
The debug lines always show the correct values for different hosts, so the problem is not with reading or fetching the value.
Note: the source file is located in remote node,
|
I work in a windows form application. i wanna make a setting page for my program. in this form i have music for the total of my program and i have sound for my button, it sounds when you click on a button. i can off them and on them. my problem, is sounds of buttons. when i off the sound in the setting and it just off for the setting form, and when i go to another form and setting page is still open the sound of button is not off. and it sound when i click.
page setting:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
using WMPLib;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
WindowsMediaPlayer playerr = new WindowsMediaPlayer();
public WindowsMediaPlayer button = new WindowsMediaPlayer();
public bool s ;
public bool p ;
public Form1()
{
InitializeComponent();
this.StartPosition= FormStartPosition.Manual;
this.Location = new Point(300, 150);
}
private void Form1_Load(object sender, EventArgs e)
{
playerr.URL = "aurora_runaway.mp3";
playerr.controls.play();
}
private void button1_Click(object sender, EventArgs e)
{
if (pictureBox3.Visible == false && pictureBox4.Visible == true)
{
button.URL = "notifications-sound-127856.mp3";
button.controls.play();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
playerr.controls.play();
pictureBox1.Visible= false;
pictureBox2.Visible= true;
}
private void pictureBox2_Click(object sender, EventArgs e)
{
playerr.controls.stop();
pictureBox2.Visible = false;
pictureBox1.Visible =true;
}
private void pictureBox3_Click(object sender, EventArgs e)
{
pictureBox3.Visible = false;
pictureBox4.Visible = true;
s = true;
p = false;
}
private void pictureBox4_Click(object sender, EventArgs e)
{
pictureBox4.Visible = false;
pictureBox3.Visible = true;
s = false;
p = true;
}
private void button2_Click(object sender, EventArgs e)
{
new Form3().ShowDialog();
}
}
}
```
form3:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form3 : Form
{
Form1 ff = new Form1();
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (ff.p == true && ff.s == false)
{
ff.button.URL = "notifications-sound-127856.mp3";
ff.button.controls.play();
}
}
}
}
``` |
Was going thru unit of work pattern, with EF Core - if the work unit is large and involves 3,4 entities, will it slow down the performance, because it will have to take 3,4 db round trips and update each entity ?
Trying to search but did not get much links on this |
|sql|optimization|dbt|staging-table| |
1. The map draw polygons and markers but the polyline is not showing, the code is the following:
```
GoogleMap(
onMapCreated: _onMapCreated,
onCameraMove: _onCameraMove,
onCameraIdle: _onCameraIdle,
polygons: getPolygonList(zonesCubit.state.zonesCubit.data!, spotsCubit, zonesCubit) : {},
polylines: {
const Polyline(
points: [LatLng(-74.813255, 11.004145), LatLng(-74.81268, 11.003933), LatLng(-74.809933, 11.002921), LatLng(-74.809641, 11.002813)],
polylineId: PolylineId("howto"),
),
},
markers: Marker(
markerId: const MarkerId("CURRENT_USER"),
position: currentPosition,
icon: carIcon
),
initialCameraPosition:
CameraPosition(target: referencePoint, zoom: currentZoom),
),
```
2. the marker position that represents the user current position is not being updated on map, but when re-run the app the marker now is in the new position, but only when re-run the app, the code is the following:
```
Marker(
markerId: const MarkerId("CURRENT_USER"),
position: currentPosition,
icon: carIcon)
```
and to detect user position change i´m using [geolocator](https://pub.dev/packages/geolocator) , the code is the following:
```
@override
void initState() {
super.initState();
final locationSettings = LocationSettings(accuracy: LocationAccuracy.high, distanceFilter: 5);
Geolocator.getPositionStream(locationSettings: locationSettings).listen(
(Position position) {
setState(() {
currentPosition = LatLng(position.latitude, position.longitude);
});
getit<Logger>().i("current device location: $currentPosition");
print(position == null ? 'Unknown' : '${position.latitude}, ${position.longitude}');
}
);
}
```
what could be happening?
I´m expecting draw the polyline and update the marker when the position is being updated |
The Polyline is not showing in flutter but the directions api is enabled and the current position is not updating |
|flutter|google-maps|google-maps-flutter| |
null |
I have the basic tier of Azure Analysis service. I am trying to connect to a Blob storage container that is in the same VNET as the Azure Analysis Service.
I have set up an "on prem gateway" on a VM in the same vnet and am able to connect to the blob storage and pull a test file that is of size 18Bs.
The actual file I want to pull is 85MiB. If I have that file in the same blob container as the previous test file, and try to pull the 85MiB file I get the below error:
*Received error payload from gateway service with ID 320866: With compression algorithm, the compressed data size in a packet exceeds the max ServiceBus limit: GatewayCompressor - CompressedDataSize (11571280) of a non-compressed packet exceeds the maximum payload size of 8500000.*
Is a 85MiB file actually too big for Azure Analysis services??
I read it could be the Gateway API limit (I have seen in AWS is 10mb), can I increase the Gateway API limit?
I am surprised to already reach size limits.
|
Will it slow down the performance when Unit of work pattern is used with EF core |
|c#|entity-framework|design-patterns| |
null |
After contacting the OneSignal support, they have answered clearly that they removed this scheduling notifications functionality from OneSignal Flutter SDK starting from version 5, quoting from their support email:
> With that said, with the migration to version 5, we have removed the ability to send push from the SDK itself. To do this now, you would instead add the notification create request in as an HTTP request. |
I am currently trying to use SetDisplayConfig from winuser.h to immediately apply a "Preserve aspect ratio" display scaling mode for the active display mode, but I can't seem to get the settings to apply. I've tried many things, but nothing works. Can anybody point me in the right direction to implement this? Any help would be GREATLY appreciated.
Relevant APIs:
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setdisplayconfig
https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-displayconfig_path_info
https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-displayconfig_path_target_info
Article that got me started:
https://learn.microsoft.com/en-us/windows-hardware/drivers/display/scaling-the-desktop-image
I've tried using SetDisplayConfig with QueryDisplayConfig to change DISPLAYCONFIG_PATH_INFO -> DISPLAYCONFIG_PATH_TARGET_INFO.scaling, but it would not apply after calling SetDisplayConfig on the modified scaling value. |
How to immediately apply DISPLAYCONFIG_SCALING_ASPECTRATIOCENTEREDMAX display scaling mode with SetDisplayConfig and DISPLAYCONFIG_PATH_TARGET_INFO |
|c++|winapi|windows-10|implementation|windows-11| |
null |
You can do it by creating a function that changes the `fontSize` and add it on the `LocalStorage` every time a person clicks on it.
After that you can use the `window.onload()` to always check, when the page loads, if there is any `fontSize` on the `LocalStorage` and set it if there is.
Example:
**HTML**
<section class="sec">
<div class="content">
<div class="buttons">
<span class="btn" onclick="changeFontSize('1em')">A</span>
<span class="btn" onclick="changeFontSize('1.25em')">A</span>
<span class="btn" onclick="changeFontSize('1.75em')">A</span>
</div>
<div class="text" id="text">
<h3>i'm an h3</h3>
<p>i'm a paragraph</p>
</div>
</div>
</section>
**JavaScript**
const buttons = document.querySelector('.buttons');
const btn = buttons.querySelectorAll('.btn');
window.onload = function() {
const fontSize = localStorage.getItem('fontSize');
if (fontSize) {
document.getElementById('text').style.fontSize = fontSize;
}
}
function changeFontSize(size) {
localStorage.setItem('fontSize', size);
document.getElementById('text').style.fontSize = size;
}
for(let i = 0; i < btn.length; i++){
btn[i].addEventListener('click', function(){
let current = document.getElementsByClassName('clicked');
current[0].className = current[0].className.replace("clicked", "");
this.className += " clicked";
})
} |
I think "%s" are expecting additional string arguments, but you have only provided "sAux", "s1", and "s2". You should remove the extra "%s from the format string. Here's the code:
String sAux = getResources().getString(R.string.ShareText);
String s1 = "https://play.google.com/store/apps/details?id=";
String s2 = "your_app_package_name"; // Replace with your actual package name
String s = String.format("%s\n\n %s%s \n\n", sAux, s1, s2);
This should resolve the issue with the "String.format" function.
I think above code will help you.
|
I wrote a small python package that finds both the min and max value of an array fast:
https://github.com/nomonosound/numpy-minmax
Here's how to use it:
`pip install numpy-minmax`
```
import numpy_minmax
min_val, max_val = numpy_minmax.minmax(arr)
```
The algorithm is written in C and is optimized with SIMD instructions. According to my own crude measurements the **speedup is ~2.3x** compared to calling np.amin and np.amax (tested with numpy 1.26) |
I am having issues with my SQL statement below. The `NOT LIKE` and `OR` statement is producing `FALSE` statements, in that it is producing the output when it should not, since I am using a `NOT LIKE`. When I put the statement as a stand-alone (*without* the `OR` condition), it works as intended.
For example, I am still seeing 'automation' in my `ld.lead_name` column.
Any help would be greatly appreciated! I can't figure out why this is not working...
SQL Statement
SELECT
ld.status,
ld.lead_name
FROM
DATAWAREHOUSE.SFDC_STAGING.SFDC_LEAD AS ld
WHERE
ld.status <> 'Open'
AND (
ld.lead_name NOT LIKE '%test%'
OR ld.lead_name NOT LIKE '%t3st%'
OR ld.lead_name NOT LIKE '%auto%'
OR ld.lead_name NOT LIKE '%autoXmation%'
OR ld.lead_name NOT LIKE 'automation%'
)
;
|
In Vim, `<CR>` refers to the "Carriage Return" key, which is essentially the Enter or Return key on your keyboard.
So the sequence for jumping to the fist instance of `foo`: [Esc] -> `/foo` -> [Enter] -> `i`
In case you need 3rd instance of `foo`: [Esc] -> `/foo` -> [Enter] -> `n` -> `n` -> `n` -> `i`
General pattern:
1. enter command mode by pressing Esc
1. search with `/`, e.g. type in `/foo` in your case
1. press Enter to jump to the first found result
1. navigate b/w searches with `n` (forward), `N` backwards
1. enter the edit mode with pressing `i` while in command mode |
I am new to React & I have a bootstrap switch checkbox and for me the value is getting saved in the mongodb but my problem is when I open the document again, the checkbox is not in the position where it was last updated.
If I updated the document while it is true it wont be

The code is below:
```
const [flag, setFlag] = useState(false);
const checkHandler = () => {
setFlag(!flag);
};
useEffect(() => {
if (order) {
console.log("order is present in empty useEffect", order);
setFlag(order.flag);
}
}, [order]);
```
```
<div className="flagOrder">
<div class="form-check form-switch">
<input
class="form-check-input"
type="checkbox"
role="switch"
id="flexSwitchCheckDefault"
checked={flag}
onChange={checkHandler}
/>
<label
class="form-check-label"
for="flexSwitchCheckDefault"
>
Flag
</label>
</div>
</div>
```
The below function runs when update order button is clicked on page
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
const updateOrder = (order, items) => {
console.log("ofasdfrder in update order", order);
const updatedata = {
_id: order._id,
items: items,
customerNotes:
newCustomerNote.length > 0
? [...customerNotes, { notes: newCustomerNote, user: user._id }]
: customerNotes,
internalNotes:
newInternalNote.length > 0
? [...internalNotes, { notes: newInternalNote, user: user._id }]
: internalNotes,
paymentMade: partialPaymentMade,
newCustomerNote: newCustomerNote,
newInternalNote: newInternalNote,
paymentStatus: paymentStatus,
changePaymentStatus:
originalPaymentStatus === paymentStatus ? true : false,
sendToCustomerNotes: sendToCustomerNotes,
sendToInternalNotes: sendToInternalNotes,
subTotal: getSubTotal(items).toFixed(2),
totalAmount: (
getSubTotal(items) +
getTax(items) +
getShipping(items)
).toFixed(2),
shippingTotal: order ? getShipping(items) : 0,
taxTotal: getTax(items),
orderStatus: orderStatus,
flag: flag,
};
<!-- end snippet -->
|
I'm trying to insert a cylinder in the MCNP 6 code. I believe I defined the surfaces and planes correctly. What could be wrong?
Surfaces:
520 cz 435 1
5020 px 435
6020 px 450
Cells:
81 5 -1.2250E-3 (-520 5020 -6020)
99 5 -1.2250E-3 -3552 1050 -110
(110:-1050:-33:33:29:-35:36)
(110:-1050:-30:34:-35:36)
(110:-109:-29:30:-35:36)
(109:-1050:-29:30:31:-35)
(109:-1050:-29:30:-32:36)
(110:-1050:-33:29:-35:36)
(520:-5020:6020)
What could be wrong? |
MCNP 6 - Doubts about cells |
|algorithm|montecarlo| |
null |
The point of the `<const>` local variable attribute is to allow Lua to check, at "load" time (when you call `dofile` / `load` / `require` or similar), whether a local variable is not being mutated - that is, whether the only assignment is the initial one at declaration time. It is a tool to help programmers (1) express intent (2) get slightly more "load time" checking than just syntactic checks.
This works for `local` variables precisely because they are local. They are visible only within function scope. This means Lua has all the information it needs when you load a "chunk" of code (effectively a function body) to check whether it abides by the *static* (load time) rules of `<const>`.
"Globals" / "environmental variables" (as I like to call them) are effectively just syntactic sugar for accessing fields in the `_ENV` (usually `_G`) table. As such, they are much more dynamic than local variables. You could do `_G[some .. complex .. expression] = 42`, for example. With global variables, just as with any other table fields, Lua does not have all the information it needs at load time. To begin, it does not even know which fields your code will set or get. Even if it knew this, or limited itself to the `<name>` syntax, that would still be insufficient. Consider loading a file where a certain global variable that was not set yet is used (perhaps in some callback where the author knows it will be available in time). Lua can not warn about this at the time the file is loaded. (It could, at best, try to warn when the file containing the conflicting constant definitions was loaded, then warn when subsequent files are loaded.)
As ESkri has said, you can implement run-time checks to guard against accessing constant global variables via a metatable. That could look something like this:
```lua
local constants = {pi = math.pi}
setmetatable(_G, {__index = constants, __newindex = function(_, key) error("attempt to change constant global variable " .. key) end})
print(pi) -- runs fine
pi = 3 -- errors
```
However, this is probably a bad idea:
* It's likely to confuse (future) you as well as whatever static analysis tools you may choose to use. (This could be alleviated to an extent using a different implementation however.)
* It incurs a performance penalty.
* It's still only a runtime check. If you don't hit a code path in your testing, you don't get an error or warning.
Instead, I would recommend the use of *static analysis tools* such as *Luacheck*, which lets you specify [*read-only global variables* in its [configuration file](https://luacheck.readthedocs.io/en/stable/config.html), and also supports a `new read globals` inline option to add read-only global variables, similar to a "constant" definition. Example:
```lua
-- luacheck: globals pi
pi = math.pi
-- luacheck: new read globals pi
pi = 3
```
it should be noted that while options are limited in scope to files, the `read_global` configuration field is per-"project" (folder) you're running Luacheck in. To establish `pi` as a read-only global project-wide, you could set `read_globals = {"pi"}`, then use `-- luacheck: globals pi` to make an exception where `pi` is defined (followed by `-- luacheck: new read globals pi` to revoke that exception afterwards). |
Making canvas background transparent |
I want to display Geojson data on a map to draw polygons and points
I used Flutter_map library: ^4.0.0
I tried converting from geojson to latlng and did not find a way
The libraries that should help me are very old
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [longitude, latitude]
},
"properties": {
"name": "point name",
"description": "point desc"
}
}
]
} |
View Geojson on flutter_map |
|flutter|dart|dictionary|geojson|fluttermap| |
null |
For me, adding an `autoFocus` prop did the trick:
```html
<input autoFocus {...} />
``` |
I am performing unsupervised clustering with PCA.
The first 7 Components contain 50, 13, 9, 8, 5, 3, 3% of the variance.
There is no feature that stands out in PC1. However there are some stand out features in the remaining PCs in terms of the loadings.
When I compare my results to the ground truth, the clustering is poor. If I exclude PC1, my results improve a bit.
Why is it that my clustering algorithm discriminates better when I exclude PC1 scores from the input data?
And is this okay to do - ie: leaving out 50% variance of the original data.
Thanks
Clustering with PCA with and without PC1 included in the input data. |
Principal Component Analysis and Clustering - Better Discrimination between Classes |
|cluster-analysis|pca| |
null |
|typescript|react-native| |
null |
|reactjs|typescript|react-native| |
I dont know if this will help but maybe there's a problem in matching the frontend routing in you 'response'.
const response = await api.get('/dog-profile/dogprofile', {
headers: {
'x-auth-token': token
}
try removing /dog-profile |
1. I have a table of groups.
2. I'm searching for a way so that "Group 2" will get updated when "Group 1" changes.

Please note that
* I want this without any Script or HelperColumn.
* I don't want to use Named Ranged in dropdown criteria. (a named range would work, if it automatically read the name from the leftside cell containing the dynamic name of Group 1)
Thanks in advance.
Sample File:
https://docs.google.com/spreadsheets/d/1PowepsBJLymzZSr6ODR_Gxioxvn3WDDYGctwZVHbvqg/edit?usp=sharing |
1. I have a table of groups.
2. I'm searching for a way so that "Group 2" will get updated when "Group 1" changes.

Please note that
* I want this without any Script or HelperColumn.
* I don't want to use Named Ranged in dropdown criteria.
(a named range would work, if it automatically read the name from the left side cell containing the dynamic name of Group 1)
Thanks in advance.
Sample File:
https://docs.google.com/spreadsheets/d/1PowepsBJLymzZSr6ODR_Gxioxvn3WDDYGctwZVHbvqg/edit?usp=sharing |
Azure Analysis Service, with an on prem gateway, in vnet |
|azure|powerbi|azure-application-gateway|vnet| |
You can set the encapsulation strategy using **ViewEncapsulation.None**.
**Beware**:
> The styles of components are added to the <head> of the document,
> making them available throughout the application, so are completely
> global and affect any matching elements within the document.
To avoid that, you can include it in a component’css selector to define the css style:
**Exemple** :
// component
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
encapsulation: ViewEncapsulation.None,
})....
// styles
my-app {
mat-menu {
.mat-mdc-menu-panel {
.mat-mdc-menu-content {
button {
min-height: 24px;
}
}
}
}
}
|
> Do you have any clue how to achieve this in MySQL?
Yes, go by foot and make the xml yourself with `CONCAT` strings. Try
`SELECT concat('<orders><employee emp_id="', emp_id, '"><customer cust_id="', cust_id, '" region="', region, '"/></employee></orders>') FROM table`
I took this from a 2009 answer [How to convert a MySQL DB to XML?](https://stackoverflow.com/a/1420227/11154841) and it still seems to work. Not very handy, and if you have large trees per item, they will all be in one concatenated value of the root item, but it works, see this test with dummies:
`SELECT concat('<orders><employee emp_id="', 1, '"><customer cust_id="', 2, '" region="', 3, '"/></employee></orders>') FROM DUAL`
gives
`<orders><employee emp_id="1"><customer cust_id="2" region="3"/></employee></orders>`
With "manual coding" you can get to this structure.
```xml
<?xml version="1.0"?>
<orders>
<employee emp_id="1">
<customer cust_id="2" region="3" />
</employee>
</orders>
```
I checked this with a larger tree per root item and it worked, but I had to run an additional Python code on it to get rid of the too many openings and closings generated when you have medium level nodes in an xml path. It is possible using backward-looking lists together with entries in a temporary set, and I got it done, but an object oriented way would be more professional. I just coded to drop the last x items from the list as soon as a new head item was found, and some other tricks for nested branches. Worked.
I puzzled out a Regex that found each text between tags:
```python
string = " <some tag><another tag>test string<another tag></some tag>"
pattern = r'(?:^\s*)?(?:(?:<[^\/]*?)>)?(.*?)?(?:(?:<\/[^>]*)>)?'
p = re.compile(pattern)
val = r''.join(p.findall(string))
val_escaped = escape(val)
if val_escaped != val:
string.replace(val, val_escaped)
```
This Regex helps you to access the text between the tags. If you are allowed to use CDATA, it is easiest to use that everywhere. Just make the content "CDATA" (character data) already in MySQL:
```sql
<Title><![CDATA[', t.title, ']]></Title>
```
And you will not have any issues anymore except for very strange characters like (U+001A) which you should replace already in MySQL. You then do not need to care for escaping and replacing the rest of the special characters at all. Worked for me on a 1 Mio. lines xml file with heavy use of special characters.
Yet: you should validate the file against the needed xml schema file using Python's module `xmlschema`. It will alert you when you are not allowed to use that CDATA trick.
If you need a fully UTF-8 formatted content without CDATA, which might often be the task, you can reach that even in a 1 Mio lines file by validating the code output (= xml output) step by step against the xml schema file (xsd that is the aim). It is a bit fiddly work, but it can be done with some patience.
Replacements are possible with:
- MySQL using replace()
- Python using string.replace()
- Python using Regex replace (though I did not need it in the end, it *would* look like: `re.sub(re.escape(val), 'xyz', i)`)
- string.encode(encoding = 'UTF-8', errors = 'strict')
Mind that encoding as utf-8 is the most powerful step, it could even put aside all three other replacement ways above. Mind also: It makes the text binary, you then need to treat it as binary b'...' and you can thus write it to a file only in binary mode using `wb`.
As the end of it all, you may open the XML output in a normal browser like Firefox for a final check and watch the XML at work. Or check it in vscode/codium with an xml Extension. But these checks are not needed, in my case the xmlschema module has shown everything very well. Mind also that vscode/codium can can handle xml problems quite easily and still show a tree when Firefox cannot, therefore, you will need a validator or a browser to see all xml errors.
Quite a huge project could be done using this xml-building-with-mysql, at the end there was a triple nested xml tree with many repeating tags inside parent nodes, all made from a two-dimensional MySQL output.
#### PS
Instead of MySQL, you might be better of with built-in tools of MSSQL server and the like. This answer was about the mere handycraft of XML building, but there are better tools nowadays. Export to a file and work on it in another SQL if puzzling the XML together takes too much time and nerves. |
```
def quickSort(arr):
if len(arr) <= 1:
return arr
pivot = arr[int(len(arr)/2)]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quickSort(left) + middle + quickSort(right)
def binSearch(sorted_arr, target):
cen = int(len(sorted_arr)/2)
if sorted_arr[cen] == target:
return cen
elif sorted_arr[cen] < target:
return binSearch(sorted_arr[0:cen], target)
else:
return binSearch(sorted_arr[cen:len(sorted_arr)], target)
my_array = [11, 9, 12, 7, 3, 8, 10, 2, 5, 1, 4, 6]
result = binSearch(quickSort(my_array), 13)
if result == -1:
print("Element not found")
else:
print(f"Element found at index {result}")
```
This is my code and this is the error I am encountering...
```
line 12, in binSearch
if sorted_arr[cen] == target:
IndexError: list index out of range
```
Now I know what that error means. It is just that I don't understand how I am encountering this error. I tried to visualize it myself and it turns out perfectly fine! |
Binary Search Error while trying to search through list |
|python|binary-search| |
null |
Windows 11
I would like to filter double values.
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/ZckkI.png
[2]: https://i.stack.imgur.com/ICCrr.png
1. testo = text
2. numerico = numeric
3. valuta = currency
I can filter Strings
Dim srchStr As String = Me.TextBox1.text
Dim strFilter As String = "MyCol1 LIKE '*" & srchStr.Replace("'", "''") & "*'"
dv.RowFilter = strFilter
I can filter Integers
Dim srchStr As String = Me.TextBox1.Text
Dim id As Integer
If Integer.TryParse(srchStr, id) Then
dv.RowFilter = "code = " & id
Else
MessageBox.Show("Error: ........")
End If
Dim strFilter As String = "code = " & id
dv.RowFilter = strFilter
but I can not filter a double value.
I actually use this code to filter strings in my DataGridView
Private Sub MyTabDataGridView_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyTabDataGridView.DoubleClick
Try
'MyRow
Dim row As Integer = MyTabDataGridView.CurrentRow.Index
'MyColumn
Dim column As Integer = MyTabDataGridView.CurrentCell.ColumnIndex
'MyColumn and MyRow
Dim ColumnRow As String = MyTabDataGridView(column, row).FormattedValue.ToString
'Header Text
Dim HeaderText As String = MyTabDataGridView.Columns(column).HeaderText
'I exclude the errors
If HeaderText = "id" Or HeaderText = "MyCol3" Or HeaderText = "MyCol4" Or HeaderText = "MyCol5" Then
Exit Sub
End If
'Ready to filter
Dim strFilter As String = HeaderText & " Like '*" & ColomnRow.Replace("'", "''") & "*'"
dv.RowFilter = strFilter
Catch ex As Exception
End Try
Any suggestion will be highly appreciated.
|
I can't load two static images into a container via DecorationImage
[![][1]][1]
I tried to load through an additional column, but in my opinion this is very bad for the developer. Perhaps there is a better result
```
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class Profile extends StatelessWidget {
const Profile({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Container(
width: 341,
height: 91,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
shape: BoxShape.rectangle,
color: Color.fromRGBO(5, 96, 250, 1),
image: DecorationImage(
alignment: Alignment.bottomLeft,
image: AssetImage('assets/images/elips2.png'),
),
),
child: Column(
children: [
Flexible(
flex: 1,
child: Align(
alignment: Alignment.topRight,
child: Image.asset('assets/images/elips1.png')),
),
// Align(
// alignment: Alignment.bottomLeft,
// child: Image.asset('assets/images/elips2.png')),
],
),
),
),
);
}
}
```
[1]: https://i.stack.imgur.com/8Dy2x.png |
null |
> I think it probably requires to use index_sequence but I'm not sure
> how.
Yes, it's very easy to do this using `index_sequence`:
template<typename... Args, std::size_t... Is>
void foo(const Args&... args, std::index_sequence<Is...>)
{
using typeLists = std::tuple<Args...>;
bar( SomeClass<Args, std::tuple_element_t<Is, typeLists>> { args }... );
}
template<typename... Args>
void foo(const Args&... args)
{
bar( args..., std::index_sequence_for<Args...>{} );
} |
I have one GET API which is having array in the input.
I want to call that API through in my node.js project.
I have tried many options but none worked.
This is my REST Request.
let request = await Request.get(
`url?arr=1234,1235`,
{
headers: {"Content-Type": "application/json" }
}
);
But getting bad request.
This is the CURL I received.
curl --location --request GET 'url' \
--header 'Content-Type: application/json' \
--data '
{
"arr":["1234","1235"]
}
Please help.
I tried with POST request instead of GET.
I tried `url?arr[]=1234,1235`
I tried `url?arr=["1234","1235"]`
I tried `url?arr="1234","1235"`
I tried `url?params={arr:["12551138844"]` |
To change the arrow size in the React application using the `react-sigma` library, you need to directly manipulate the Sigma.js instance to apply custom settings. Here's how you can do it:
1. **Extend Sigma.js with Custom Settings**: You need to create a custom Sigma.js component that extends the functionality of `Sigma.js` and allows you to apply custom settings.
2. **Access Sigma.js Instance**: Within this custom component, you can access the Sigma.js instance and apply custom settings such as arrow size.
Here's how you can implement these steps:
```javascript
import React, { useState, useRef, useEffect } from 'react';
import { Sigma, EdgeShapes, ForceAtlas2, NOverlap, RelativeSize } from 'react-sigma';
import sigma from 'sigma';
// Custom Sigma Component
function MyCustomSigma({ data }) {
const sigmaRef = useRef(null);
useEffect(() => {
if (sigmaRef.current) {
// Access Sigma instance
const s = sigmaRef.current.getInstances()[0];
// Apply custom settings
s.settings('edgeLabelSize', 5); // Example: Change arrow size
// Refresh Sigma instance
s.refresh();
}
}, [data]);
return (
<Sigma renderer="canvas" settings={{ enableEdgeHovering: true }} ref={sigmaRef}>
<EdgeShapes default="arrow" />
<ForceAtlas2 worker barnesHutOptimize barnesHutTheta={0.6} />
<NOverlap gridSize={20} maxIterations={50} />
<RelativeSize initialSize={15} />
</Sigma>
);
}
// Main Component
export default function GraphRepresentation() {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch your data or set it as you're doing
setData(yourDataHere);
}, []);
return (
<div style={{ height: '100vh', width: '100vw' }}>
{data && <MyCustomSigma data={data} />}
</div>
);
}
```
In this example:
- We create a custom Sigma component `MyCustomSigma`.
- Inside this component, we use `useRef` to get a reference to the Sigma.js instance.
- We use `useEffect` to apply custom settings whenever the data changes.
- Within the `useEffect`, we access the Sigma instance using `getInstances()` method.
- We apply custom settings using `settings()` method.
- Finally, we refresh the Sigma instance to reflect the changes.
Make sure to replace `'yourDataHere'` with your actual graph data. This example assumes you're using React hooks for managing state. Adjust the code as per your application structure. |
Dears...this is part of my chatbot.when user click button nothing happens.please help
import streamlit as st
from streamlit_chat import message
if user_input := st.chat_input("You:"):
st.write(f"User: {user_input}")
bot_reply = "Test bot reply"
st.write(f"Bot: {bot_reply}")
button_info_list = [{"title": "Title", "payload": "Foo"}, {"title": "Another title","payload": "Payload"}]
for button_info in button_info_list:
button_title = button_info.get("title", "")
payload = button_info.get("payload", "").lstrip("/")
if st.button(button_title):
st.write("After clicking {button_title")
|
button click not working inside if statement |
|if-statement|checkbox|onclick| |
I have read about `notnull `constraint in C# and it was written that "This allows either value types or non-nullable reference types but not nullable reference types."
I tried checking this constraint in the code below:
```
MyTestClass<int?> instance1 = new MyTestClass<int?>();
MyTestClass<string?> instance2 = new MyTestClass<string?>();
public class MyTestClass<T> where T : notnull
{
T Value { get; set; }
public MyTestClass()
{
Value = default(T);
if (Value == null)
Console.WriteLine($"Type of T is {typeof(T)} and its default value is 'Null'");
else
Console.WriteLine($"Type of T is {typeof(T)} and its default value is {Value}");
}
}
```
as you can see I instantiated my generic class with nullable types `int?` (nullable value type) and `string?` (nullable reference type) and it still works for me.
It also prints the output like this for me:
```
Type of T is System.Nullable`1[System.Int32] and its default value is 'Null'
Type of T is System.String and its default value is 'Null'
Type of T is System.Int32 and its default value is 0
Type of T is System.String and its default value is 'Null'"
```
It behaves 'string?' as 'string' and detects both as non-nullable.
what can be the reason for these to happen? |
C# notnull constraint with nullable types have unexpected behavior |