instruction
stringlengths 0
30k
⌀ |
---|
In my .NET 8 Core API app, when I run `dotnet run`, everything is working. But Im using a docker-compose, and there come the problems.
When I run my app with `docker-compose up --build`, my IDE stops to resolve the NuGet packages installed in all the projects of my solution. And, important point : it builds well, I never meet build issues.
So let's say I have imported 2 packages :
using AutoMapper;
using Microsoft.EntityFrameworkCore;
before building with docker-compose, no issue at all.
After building, I would have this issue : `Cannot resolve symbol 'EntityFrameworkCore'`.
And so on for all NuGet packages.
I've tried lots of things to try to fix the issue :
- Invalidate IDE cache
- change from Rider to VS
- Clone solution in another computer
But it has never fixed the issue. When I do `dotnet resolve`, it works, but only temporarily: after a new rebuilt, the error appears again. |
I tried this solution and it's worked for me :
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.telephony.SmsManager
import android.telephony.SmsMessage
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val phoneNumber = "Your friend's phone number"
val message = "Your SMS message"
sendSMS(phoneNumber, message)
}
private fun sendSMS(phoneNumber: String, message: String) {
val sentIntent = PendingIntent.getBroadcast(this, 0, Intent("SMS_SENT"), PendingIntent.FLAG_IMMUTABLE)
val deliveredIntent = PendingIntent.getBroadcast(this, 0, Intent("SMS_DELIVERED"), PendingIntent.FLAG_IMMUTABLE)
val smsManager = SmsManager.getDefault()
smsManager.sendTextMessage(phoneNumber, null, message, sentIntent, deliveredIntent)
}
override fun onResume() {
super.onResume()
registerReceiver(sentReceiver, IntentFilter("SMS_SENT"))
registerReceiver(deliveredReceiver, IntentFilter("SMS_DELIVERED"))
}
override fun onPause() {
super.onPause()
unregisterReceiver(sentReceiver)
unregisterReceiver(deliveredReceiver)
}
private val sentReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (resultCode) {
AppCompatActivity.RESULT_OK -> {
// SMS sent successfully
// You can update UI or show a toast here
}
SmsManager.RESULT_ERROR_GENERIC_FAILURE -> {
// Failed to send SMS
// You can update UI or show a toast here
}
SmsManager.RESULT_ERROR_NO_SERVICE -> {
// No service available
// You can update UI or show a toast here
}
SmsManager.RESULT_ERROR_NULL_PDU -> {
// Null PDU
// You can update UI or show a toast here
}
SmsManager.RESULT_ERROR_RADIO_OFF -> {
// Radio off
// You can update UI or show a toast here
}
}
}
}
private val deliveredReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (resultCode) {
AppCompatActivity.RESULT_OK -> {
// SMS delivered successfully
// You can update UI or show a toast here
}
AppCompatActivity.RESULT_CANCELED -> {
// SMS not delivered
// You can update UI or show a toast here
}
}
}
}
}
if you get this error : `RESULT_ERROR_GENERIC_FAILURE `, i tried this solution : [Soluion of merovingen][1]
[1]: https://stackoverflow.com/a/31022549/15772513 |
I am using googleapis in my node.js project. At first I was using raw api which was working, but when I switched to googleapis package, the list of people.connections.list is returning me an empty object, and I have some contact saved in my account, which was showing up when I was using raw apis.
Here is the code that I wrote from the documentation.
const getContacts = async (req, res, next) => {
try {
const peopleServices = google.people({
version: "v1",
});
const auth = new google.auth.GoogleAuth({
keyFile: "./gmail-api-nodejs-399211-9be0ced71d07.json",
scopes: [
"https://www.googleapis.com/auth/contacts",
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/directory.readonly",
"https://www.googleapis.com/auth/profile.agerange.read",
"https://www.googleapis.com/auth/profile.emails.read",
"https://www.googleapis.com/auth/profile.language.read",
"profile"
],
});
const authClient = await auth.getClient();
google.options({ auth: authClient });
const resourceName = "people/me";
const result = await peopleServices.people.connections.list({
resourceName: resourceName,
personFields: "names,emailAddresses",
});
console.log(result.data);
return res.json(result.data);
} catch (error) {
console.log(error);
return res.status(400).json(error);
}
} |
google people api is returning empty list of contacts |
|javascript|node.js|google-api| |
I know the function works for the button and it does get number, and I can print the `Num` variable but when I set it as the output string it seems to not show up in the output text. I'm guessing I'm doing something wrong with the output_str.set function or the `textvariable` function, but I can't figure out what exactly.
Does not throw any errors btw.
```
import tkinter as tk
def clicked():
num = (entry_int.get())
Num = num * 0.45
output_str.set = (Num)
window = tk.Tk()
window.title("Pounds to kilos")
window.geometry('350x200')
title = tk.Label(window, text = "Pounds to Kg", font = "helvectica" )
title.place(x = 115)
entry_int = tk.IntVar()
txt = tk.Entry(window, width = 15, textvariable = entry_int)
txt.place(x= 129, y= 30)
output_str = tk.StringVar()
output = tk.Label(window, fg = "blue", textvariable = output_str, font = "helvectic")
output.place(x= 126, y= 50)
btn = tk.Button(window, text = "Calculate",fg = "red", command = clicked )
btn.place(x = 240, y = 26)
window.mainloop()
```
I tested the output text and tested that it was actually getting the input numbers.
I'm expecting the `Num` variable to be displayed in the output label. |
It depends on what definitions are necessary in the header.
Basically you may be able to use your own forward declarations of your own types.
Otherwise you should typically use the PIMPL idiom, in this context also known as "compilation firewalling". |
|php|wordpress| |
null |
How can I convert the Android BLE Code Lines to XCode Obj-C ????
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
boolean bleRes = tstBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromstring("00001108-0000-2000-9000-00906fab34fb"));
if (descriptor != null) {
descriptor.setvalue(BluetoothGattDescriptor.ENALE_NOTIFICATION_VALUE);
bleRes = tstBluetoothGatt.writeDescriptor(descriptor);
}
}
I am trying BLE usages for reading Descibing UUID Data , in iOS and iOS Unity |
How to set Value the descriptor of iOS BLE in XCode Obj-C? |
|ios|objective-c|xcode|bluetooth| |
null |
I'm learning C# and SQL databases, but mostly C#. I'm working in a project in which we need to write down some data into a SQL database. This is my connection string:
```
<configuration>
<connectionStrings>
<add name="conexionServidorHotel" connectionString="Data Source=DESKTOP-QG08OQQ\\SQLEXPRESS;Initial Catalog=Script_RESORTSUNED;Integrated Security=True;"/>
</connectionStrings>
</configuration>
```
And this is the code I'm currently using:
```
using Entidades;
using System.Configuration;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Diagnostics;
namespace AccesoDatos
{
public class HotelAD
{
private string cadenaConexion;
public HotelAD()
{
cadenaConexion = ConfigurationManager.ConnectionStrings["conexionServidorHotel"].ConnectionString;
}
public bool RegistrarHotel(Hotel NuevoHotel)
{
bool hotelregistrado = false;
try
{
SqlConnection conexion;
SqlCommand comando = new SqlCommand();
using (conexion = new SqlConnection(cadenaConexion))
{
string instruccion = " Insert Into Hotel (IdHotel, Nombre, Direccion, Estado, Telefono)" +
" Values (@IdHotel, @Nombre, @Direccion, @Estado, @Telefono)";
comando.CommandType = CommandType.Text;
comando.CommandText = instruccion;
comando.Connection = conexion;
comando.Parameters.AddWithValue("@IdHotel", NuevoHotel.IDHotel);
comando.Parameters.AddWithValue("@Nombre", NuevoHotel.NombreHotel);
comando.Parameters.AddWithValue("@Direccion", NuevoHotel.DireccionHotel);
comando.Parameters.AddWithValue("@Estado", NuevoHotel.StatusHotel);
comando.Parameters.AddWithValue("@Telefono", NuevoHotel.TelefonoHotel);
conexion.Open();
Debug.WriteLine("Aqui voy bien 7");
hotelregistrado = comando.ExecuteNonQuery() > 0;
}
}
catch (InvalidOperationException)
{
Debug.WriteLine("No puedo escribir en la base de datos");
}
return hotelregistrado;
}
```
My project is in Spanish. That is why variable names are in Spanish. When I run my code, and I input the data for the Hotel object, works fine untils conexion.Open(). Something tells me there's something wrong with that command but not sure what. Is throwing me the message from the title of my question.
I reviewed the connectionString sequence and it looks good to me. The SQL file I have is not in the same directory as the C# solution but one directory before. I'm not sure if using Microsoft. Data.Sqlclient could be affecting too. |
Using Testcontainers, is it possible to make a request to an external REST API service? |
> Regex Match a pattern that only contains one set of numerals, and not more
I would start by writing a _grammar_ for the "forgiving parser" you are coding. It is not clear from your examples, for instance, whether `<2112` is acceptable. Must the brackets be paired? Ditto for quotes, etc.
Assuming that brackets and quotes do not need to be paired, you might have the following grammar:
##### _sign_
`+` | `-`
##### _digit_
`0` | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9`
##### _non-digit_
_any-character-that-is-not-a-digit_
##### _integer_
[ _sign_ ] _digit_ { _digit_ }
##### _prefix_
_any-sequence-without-a-sign-or-digit_
[ _prefix_ ] _sign_ _non-digit_ [ _any-sequence-without-a-sign-or-digit_ ]
##### _suffix_
_any-sequence-without-a-digit_
##### _forgiving-integer_
[ _prefix_ ] _integer_ [ _suffix_ ]
Notes:
- Items within square brackets are optional. They may appear either 0 or 1 time.
- Items within curly braces are optional. They may appear 0 or more times.
- Items separated by `|` are alternatives from which 1 must be chosen
- Items on separate lines are alternatives from which 1 must be chosen
One subtlety of this grammar is that integers can have only one sign. When more than one sign is present, all except the last are treated as part of the _prefix_, and, thus, are ignored.
Are the following interpretations acceptable? If not, then the grammar must be altered.
- `++42` parses as `+42`
- `--42` parses as `-42`
- `+-42` parses as `-42`
- `-+42` parses as `+42`
Another subtlety is that whitespace following a sign causes the sign to be treated as part of the prefix, and, thus, to be ignored. This is perhaps counterintuitive, and, frankly, may be unacceptable. Nevertheless, it is how the grammar works.
In the example below, the negative sign is ignored, because it is part of the prefix.
- `- 42` parses as `42`
### A solution without `std::regex`
With a grammar in hand, it should be easier to figure out an appropriate regular expression.
My solution, however, is to avoid the inefficiencies of `std::regex`, in favor of coding a simple "parser."
In the following program, function `validate_integer` implements the foregoing grammar. When `validate_integer` succeeds, it returns the integer it parsed. When it fails, it throws a `std::runtime_error`.
Because `validate_integer` uses `std::from_chars` to convert the integer sequence, it will not convert the test case `2112.0` from the OP. The trailing `.0` is treated as a second integer. All the other test cases work as expected.
The only tricky part is the initial loop that skips over non-numeric characters. When it encounters a sign (`+` or `-`), it has to check the following character to decide whether the sign should be interpreted as the start of a numeric sequence. That is reflected in the "tricky" grammar for _prefix_ given above, where a _sign_ must be followed by a _non-digit_, if it is to be treated as part of the prefix.
```lang-cpp
// main.cpp
#include <cctype>
#include <charconv>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>
bool is_digit(unsigned const char c) {
return std::isdigit(c);
}
bool is_sign(const char c) {
return c == '+' || c == '-';
}
int validate_integer(std::string const& s)
{
enum : std::string::size_type { one = 1u };
std::string::size_type i{};
// skip over prefix
while (i < s.length())
{
if (is_digit(s[i]) || is_sign(s[i])
&& i + one < s.length()
&& is_digit(s[i + one]))
break;
++i;
}
// throw if nothing remains
if (i == s.length())
throw std::runtime_error("validation failed");
// parse integer
// due to foregoing checks, this cannot fail
if (s[i] == '+')
++i; // `std::from_chars` does not accept leading plus sign.
auto const first{ &s[i] };
auto const last{ &s[s.length() - one] + one };
int n;
auto [end, ec] { std::from_chars(first, last, n) };
i += end - first;
// skip over suffix
while (i < s.length() && !is_digit(s[i]))
++i;
// throw if anything remains
if (i != s.length())
throw std::runtime_error("validation failed");
return n;
}
void test(std::ostream& log, bool const expect, std::string s)
{
std::streamsize w{ 46 };
try {
auto n = validate_integer(s);
log << std::setw(w) << s << " : " << n << '\n';
}
catch (std::exception const& e) {
auto const msg{ e.what() };
log << std::setw(w) << s << " : " << e.what()
<< ( expect ? "" : " (as expected)")
<< '\n';
}
}
int main()
{
auto& log{ std::cout };
log << std::left;
test(log, true, "<2112>");
test(log, true, "[(2112)]");
test(log, true, "\"2112, \"");
test(log, true, "-2112");
test(log, true, ".2112");
test(log, true, "<span style = \"numeral\">2112</span>");
log.put('\n');
test(log, true, "++42");
test(log, true, "--42");
test(log, true, "+-42");
test(log, true, "-+42");
test(log, true, "- 42");
log.put('\n');
test(log, false, "2112.0");
test(log, false, "");
test(log, false, "21,12");
test(log, false, "\"21\",\"12, \"");
test(log, false, "<span style = \"font - size:18.0pt\">2112</span>");
log.put('\n');
return 0;
}
// end file: main.cpp
```
### Output
The "hole" in the output, below the entry for 2112.0, is the failed conversion of the null-string.
```lang-none
<2112> : 2112
[(2112)] : 2112
"2112, " : 2112
-2112 : -2112
.2112 : 2112
<span style = "numeral">2112</span> : 2112
++42 : 42
--42 : -42
+-42 : -42
-+42 : 42
- 42 : 42
2112.0 : validation failed (as expected)
: validation failed (as expected)
21,12 : validation failed (as expected)
"21","12, " : validation failed (as expected)
<span style = "font - size:18.0pt">2112</span> : validation failed (as expected)
```
|
**INTRO**
I am writing a class `stalker<Obj>` that holds inside a variable of type `Obj`. I want `stalker<Obj>` to pretend that it is the same as `Obj` (from the user's perspective). Thus, I expect that `stalker<Obj>` is constructible like `Obj`.
```C++
template <typename Obj>
class stalker {
Obj obj;
// other variables
public:
template <typename... Args>
stalker(Args&&... args) : obj(std::forward<Args>(args)...) {
}
};
```
P.S. I implement only copy & move constructors additionally
P.P.S. `stalker<Obj>` also has other variable(s) which require some specific logiс (independent from `Obj`) when created
P.P.P.S. `Obj` can be marked `final`
**PROBLEM**
However, my approach fails on distinguishing `std::initialiser_list` and curly brackets object. The compiler says: *"No matching constructor for initialization of 'std::vector\<int\>'"*.
```C++
int main() {
stalker<std::vector<int>> v = {1, 2, 3}; // CE
stalker<std::vector<int>> v({1, 2, 3}); // CE
return 0;
}
```
*How to reach `stalker<Obj>` maximal imitation of `Obj` in terms of construction?*
**APPROACHES**
Creating constructors from `const Obj&` and `Obj&&` fails: sometimes the compiler cannot conclude which of these constructors fits the best and in other cases it does not try to adapt `{...} -> std::init_list -> Obj` at all (just `{...} -> Obj`).
I think of creating constructor(s) from `std::initialiser_list` but *what are the pitfalls? And how to do this accurately (I have 0 experience here)?*
**EDIT (1):**
I added these constructors (is `std::is_constructible` enough?):
```C++
template <typename T>
requires (std::is_constructible_v<Obj, const std::initializer_list<T>&>)
stalker(const std::initializer_list<T>& init_list) : obj(init_list) {
}
template <typename T>
requires (std::is_constructible_v<Obj, std::initializer_list<T>&&>)
stalker(std::initializer_list<T>&& init_list) : obj(std::move(init_list)) {
}
```
However, now it compiles with `std::vector` but shows an error (and it does work with the raised error after all!):
```C++
struct A {
int val;
};
int main() {
stalker<A> a = {1}; // compiler does not like this but still works
return 0;
}
```
**EDIT (2):**
Fail - it does not convert inner `{...}` to `std::initialiser_list`.
```C++
int main() {
stalker<std::vector<std::vector<int>>> v = {{1, 2, 3, 4},
{5, 6, 7},
{8, 9},
{10}}; // CE
return 0;
}
``` |
|x11|xdotool| |
Python is kinda like english so when you say
```python
while not name:
input("Enter your name")
```
It basically says that it would repeat until it's not the name variable, which is None.. Summary: It says to repeat UNTIL the variable name is not None |
I am working on a Java application where I need to execute a batch of SQL queries using JDBC's PreparedStatement. I have encountered an issue where the PreparedStatement seems to clear the batch every time it is initialized with a new query. Here is the relevant portion of my code:
```java
@Transactional
public int[] executeBatchQuery(String code, List<String> queries, List<List<String>> parametersList) throws Exception {
Map<String, String> errorMap = new HashMap<>();
int[] count = {};
if (queries.size() != parametersList.size()) {
logger.info("Both lists length is not equal");
return null;
}
PreparedStatement pstmt = null;
Connection connection = null;
try {
connection = dataSource.getConnectionByCode(code);
for (int i = 0; i < queries.size(); i++) {
String query = queries.get(i);
List<String> parameters = parametersList.get(i);
pstmt = connection.prepareStatement(query);
// Set parameters for the prepared statement
for (int j = 0; j < parameters.size(); j++) {
pstmt.setString(j + 1, parameters.get(j));
}
pstmt.addBatch();
}
if (pstmt != null) {
count = pstmt.executeBatch();
}
else {
throw new SQLException();
}
}
catch (SQLException exception) {
logger.info("Roll back successfully executed");
logger.info("printing StackTrace: ");
exception.printStackTrace();
errorMap.put("mBoolean", "true");
errorMap.put("errorMessage", exception.getMessage());
}
finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return count;
}
```
> In the list of queries, each query is different, with varying columns, WHERE clauses, and sometimes different tables
I have noticed that every time I initialize the PreparedStatement with a new query, it clears the batch. This behavior is not desirable for my application, as I need to execute multiple queries in a batch. Can someone suggest a workaround or an alternative approach to prevent the PreparedStatement from clearing the batch every time it is initialized with a new query?
I attempted to execute a batch of SQL queries using JDBC's PreparedStatement in a Java application. The goal was to add multiple queries to the batch and execute them together for efficiency.
Specifically, I initialized a PreparedStatement object and iterated through a list of queries, adding each query to the batch using the addBatch() method. I then expected the PreparedStatement to retain all the queries in the batch, allowing me to execute them in one go.
However, despite adding multiple queries to the batch, I observed that only the last query added to the batch was being executed. It seems that each time the PreparedStatement was initialized with a new query, it cleared the batch, resulting in only the latest query being executed.
I expected all the queries in the batch to be executed sequentially, but this was not the case. Instead, only the last query in the batch was executed, disregarding the previous queries. |
Exception thrown: 'System.InvalidOperationException' in Microsoft.Data.SqlClient.dll |
|c#|sql-server|exception| |
null |
Apple say "When the video zoom factor increases and crosses a camera’s switch-over zoom factor, this camera becomes eligible to set as the activePrimaryConstituentDevice." in this document: [Apple document][1]
So if you want your app can switch to ultra.wide camera when move iPhone close and switch to Angle Camera when fay away, you need set you device.videoZoomFactor = device.virtualDeviceSwitchOverVideoZoomFactors.first.
guard let virtualDeviceSwitchOverVideoZoomFactor =
input.device.virtualDeviceSwitchOverVideoZoomFactors.first as? CGFloat else {
return
}
try? input.device.lockForConfiguration()
input.device.videoZoomFactor = virtualDeviceSwitchOverVideoZoomFactor
input.device.unlockForConfiguration()
If you write like this, you can find you App can switch camera like iPhone Native Camera App.
[1]: https://developer.apple.com/documentation/avfoundation/avcaptureprimaryconstituentdevicerestrictedswitchingbehaviorconditions |
`read` by default trims leading and trailing whitespace and consumes backslashes. You can disable those by setting `IFS` to empty string and invoking `read` with the `-r` flag respectively.
```
$ echo ' \" ' | while read i; do echo ${#i}; done
1
$ echo ' \" ' | while IFS= read -r i; do echo ${#i}; done
4
```
Note that `wc -c` would print `5` but that's not an error, `wc` counts the terminating newline too while `read` trims it regardless of the value of `IFS`. |
Use html.unescape():
import html
print(html.unescape('l''))
It works for me |
{"Voters":[{"Id":446594,"DisplayName":"DarkBee"},{"Id":2571021,"DisplayName":"Dijkgraaf"},{"Id":1431750,"DisplayName":"aneroid"}],"SiteSpecificCloseReasonIds":[18]} |
Apple say "When the video zoom factor increases and crosses a camera’s switch-over zoom factor, this camera becomes eligible to set as the activePrimaryConstituentDevice." in this document: [https://developer.apple.com/documentation/avfoundation/avcaptureprimaryconstituentdevicerestrictedswitchingbehaviorconditions][1]
So if you want your app can switch to ultra.wide camera when move iPhone close and switch to Angle Camera when fay away, you need set you device.videoZoomFactor = device.virtualDeviceSwitchOverVideoZoomFactors.first.
guard let virtualDeviceSwitchOverVideoZoomFactor =
input.device.virtualDeviceSwitchOverVideoZoomFactors.first as? CGFloat else {
return
}
try? input.device.lockForConfiguration()
input.device.videoZoomFactor = virtualDeviceSwitchOverVideoZoomFactor
input.device.unlockForConfiguration()
If you write like this, you can find you App can switch camera like iPhone Native Camera App.
[1]: https://developer.apple.com/documentation/avfoundation/avcaptureprimaryconstituentdevicerestrictedswitchingbehaviorconditions |
This error commonly occurs when the API request does not have the necessary permissions to verify ownership of the URL |
In My case, worked for me when I signed out and signed back in from Visual Studio Code > Accounts.
As previously I signed in for VSCode with my older github account on which copilot was not activated.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/4wNFL.png |
I am trying to solve a ML problem if a person will deliver an order or not. Highly Imbalance dataset. Here is the glimpse of my dataset
```
[{'order_id': '1bjhtj', 'Delivery Guy': 'John', 'Target': 0},
{'order_id': '1aec', 'Delivery Guy': 'John', 'Target': 0},
{'order_id': '1cgfd', 'Delivery Guy': 'John', 'Target': 0},
{'order_id': '1bceg', 'Delivery Guy': 'Tom', 'Target': 0},
{'order_id': '1a2fg', 'Delivery Guy': 'Tom', 'Target': 0},
{'order_id': '1cbsf', 'Delivery Guy': 'Tom', 'Target': 1},
{'order_id': '1bc5', 'Delivery Guy': 'Jay', 'Target': 0},
{'order_id': '1a22', 'Delivery Guy': 'Jay', 'Target': 0},
{'order_id': '1bzc5', 'Delivery Guy': 'Jay', 'Target': 0},
{'order_id': '1av22', 'Delivery Guy': 'Jay', 'Target': 0},
{'order_id': '1bsc5', 'Delivery Guy': 'Jay', 'Target': 1},
{'order_id': '1a2t2', 'Delivery Guy': 'Jay', 'Target': 0},
{'order_id': '1bc5b', 'Delivery Guy': 'Jay', 'Target': 0},
{'order_id': '1a22a', 'Delivery Guy': 'Mary', 'Target': 0},
{'order_id': '1c5bv', 'Delivery Guy': 'Mary', 'Target': 0},
{'order_id': 'vb2er', 'Delivery Guy': 'Mary', 'Target': 0},
{'order_id': '1bs5s', 'Delivery Guy': 'Mary', 'Target': 0},
{'order_id': '1a22n', 'Delivery Guy': 'Mary', 'Target': 0},
{'order_id': '122a', 'Delivery Guy': 'James', 'Target': 1},
{'order_id': '1cw5bv', 'Delivery Guy': 'James', 'Target': 0},
{'order_id': 'vb=er', 'Delivery Guy': 'James', 'Target': 0},
{'order_id': '1b5s', 'Delivery Guy': 'James', 'Target': 0},
{'order_id': '1a2n', 'Delivery Guy': 'James', 'Target': 1}]
```
This is my table :
```
| order_id | Delivery Guy | Target |
|----------|--------------|--------|
| 1bjhtj | John | 0 |
| 1aec | John | 0 |
| 1cgfd | John | 0 |
| 1bceg | Tom | 0 |
| 1a2fg | Tom | 0 |
| 1cbsf | Tom | 1 |
| 1bc5 | Jay | 0 |
| 1a22 | Jay | 0 |
| 1bzc5 | Jay | 0 |
| 1av22 | Jay | 0 |
| 1bsc5 | Jay | 1 |
| 1a2t2 | Jay | 0 |
| 1bc5b | Jay | 0 |
| 1a22a | Mary | 0 |
| 1c5bv | Mary | 0 |
| vb2er | Mary | 0 |
| 1bs5s | Mary | 0 |
| 1a22n | Mary | 0 |
| 122a | James | 1 |
| 1cw5bv | James | 0 |
| vb=er | James | 0 |
| 1b5s | James | 0 |
| 1a2n | James | 1 |
```
I want my machine learning model to understand each person attributes and predict these two
cases:
will deliver "0" and
will not deliver "1"
I want to split my train and test in such a way that it should preserver few rows of name and few rows of Target class so that it learns all the patterns.
I have used this so far
```
X = df.drop(columns = "Target")
y = df.Target
X_train,X_test,y_train,y_test=train_test_split(X,y,train_size=0.7,stratify=y)
```
It does give me output of each Delivery Guy but it misses the part where we can split 'James' in such way that "1" will be there in train another "1" will be in test.
Could anyone help me approach this problem in different way. |
|bash|xterm| |
I am trying to learn Dart language along with flutter. I have come across the following piece of code (taken from here: https://github.com/ppicas/flutter-android-background/blob/master/lib/counter_service.dart) :
```
import 'package:flutter/foundation.dart';
import 'counter.dart';
class CounterService {
factory CounterService.instance() => _instance;
CounterService._internal(); <<====================== Why is this line here ? What does it do?
static final _instance = CounterService._internal();
final _counter = Counter();
ValueListenable<int> get count => _counter.count;
void startCounting() {
Stream.periodic(Duration(seconds: 1)).listen((_) {
_counter.increment();
print('Counter incremented: ${_counter.count.value}');
});
}
}
```
I could not figure out why the line of code is required there. I understand that we force returning a single instance of this class by implemented a private constructor and the only instance is created in the following line. So, why do we really have to have that line there?
I'd appreciate if a dart expert shed some light over it. Thanks |
why do they instantiate the class and then throw that instance away? |
|flutter|dart|service| |
null |
|javascript|reactjs|react-doc-viewer| |
I want to make a layout in which pie chart also scrolls along with expandable list view just like an analysis and reports screen however with this layout only 1st item of expandable list view is visible and not able to scroll expandable list view tried:
android:nestedScrollingEnabled="true"
but this only enables scolling for expandable list view and not pie chart (it should as i want to make it appear as a normal screen)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".DashboardFragment">
<Spinner
android:id="@+id/scheduleSpinner"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/scheduleSpinner">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/pieChart_view"
android:layout_width="match_parent"
android:layout_height="400dp" />
<ExpandableListView
android:id="@+id/expandableListOverview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:layoutDirection="rtl"
android:nestedScrollingEnabled="false"/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
|
Expandable scroll view not scrolling |
|android|xml|android-layout|scrollview|expandablelistview| |
|javascript|next.js|javascript-framework| |
Finally, I got a solution: in Linux keep in mind the difference between forward slash '/' and backward slash '\' and instead of creating a folder inside the war file use any Linux directory like (/tmp or /opt), so the code will remain same as I mentioned above, the only thing I changed is the directory path and it works fine:
String filePath = "/tmp/reports/";
File f = new File(filePath);
if (!f.exists()) {
boolean b=f.mkdir();
if(b) {
File xlFile = new File(filePath+ File.separator + "report.xlsx");
}
} |
I'm using Riverpod with StateProvider for my app.
The home page will change based on tabs clicked.
When i click the ListTile tab to trigger the ref.read, it rebuild super fast:
But when i click the leading IconButton in Appbar which trigger `ref.read(countProvider.notifier).state = 0;` it takes me fews seconds to reload the back to 0. How do i fix this?
Full code:
layout.dart:
```
Set<Widget> _pages = {
const HomeUI(),
const FAQ(),
const Setting(),
};
class Layout extends ConsumerStatefulWidget {
const Layout({super.key});
@override
LayoutState createState() => LayoutState();
}
class LayoutState extends ConsumerState<Layout> {
bool isHome = true;
@override
Widget build(BuildContext context) {
final tab = ref.watch(countProvider);
if (tab != 0) {
isHome = false;
} else {
isHome = true;
}
return Scaffold(
drawer: const Sidebar(),
appBar: isHome
? AppBar(
leading: Builder(builder: (context) {
return IconButton(
icon: const Icon(FontAwesomeIcons.bars),
color: CustomColors.mainText,
onPressed: () {
Scaffold.of(context).openDrawer();
},
);
}),
actions: [
Padding(
padding: const EdgeInsets.only(right: 20),
child: IconButton(
icon: const Icon(FontAwesomeIcons.magnifyingGlass),
color: CustomColors.mainText,
onPressed: () {},
),
),
],
backgroundColor: Colors.transparent,
)
: null,
backgroundColor: CustomColors.background,
body: Stack(children: <Widget>[
_pages.elementAt(tab),
const MiniPlayer(),
]),
);
}
}
```
faq_screen.dart
```
class FAQ extends StatelessWidget {
const FAQ({super.key});
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, ref, child) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
ref.read(countProvider.notifier).state = 0;
},
),
title: const Text('FAQ'),
),
body: const Center(
child: Text('FAQ'),
),
);
},
);
}
}
```
sidebar.dart
```
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../utilities/color.dart';
import '../utilities/provider.dart';
class Sidebar extends StatelessWidget {
const Sidebar({super.key});
@override
Widget build(BuildContext context) {
return Drawer(
backgroundColor: CustomColors.background,
child: Consumer(
builder: (context, ref, child) => ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
accountName: const Text("Wolhaiksong",
style: TextStyle(
color: Colors.white,
fontFamily: 'Gilroy',
fontWeight: CustomColors.semiBold)),
accountEmail: const Text("deptraicojsai@gmail.com",
style: TextStyle(
color: Colors.white,
fontFamily: 'Gilroy',
fontWeight: CustomColors.regular)),
currentAccountPicture: CircleAvatar(
child: ClipOval(
child: Image.asset('assets/user.jpg'),
),
),
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/wallpaper.jpg'),
fit: BoxFit.cover),
),
),
ListTile(
leading: const Icon(
FontAwesomeIcons.lightbulb,
color: CustomColors.gray,
),
title: const Padding(
padding: EdgeInsets.all(15.0),
child: Text('FAQs',
style: TextStyle(
color: CustomColors.mainText,
fontWeight: CustomColors.semiBold,
fontFamily: 'Gilroy',
)),
),
onTap: () {
ref.read(countProvider.notifier).state = 1;
Navigator.pop(context);
},
),
ListTile(
leading: const Icon(
FontAwesomeIcons.gear,
color: CustomColors.gray,
),
title: const Padding(
padding: EdgeInsets.all(15.0),
child: Text('Settings',
style: TextStyle(
color: CustomColors.mainText,
fontWeight: CustomColors.semiBold,
fontFamily: 'Gilroy',
)),
),
onTap: () {
ref.read(countProvider.notifier).state = 2;
Navigator.pop(context);
},
),
],
),
),
);
}
}
```
provider.dart
```
final countProvider = StateProvider<int>((ref) {
return 0;
});
``` |
Flutter Riverpod StateProvider having slow rebuild of widget when using watch |
|flutter|riverpod| |
null |
|c|linux|xterm| |
In case you are wondering how to have side by side columns in Wordpress gravity forms. |
|php|wordpress|hook|gravity-forms-plugin| |
null |
|reactjs|react-hooks| |
What makes it safe to use a reference? The reference must point to a valid object of the expected type.
When would that cease to be the case? When the lifetime of the referred-to object ends, or when the object is otherwise invalidated (e.g. by being moved from).
In your code none of the two are applicable. `foo` lives in Asio's coro frame, which is stable.
Your capture is **safe**.
## Side-tangent:
It's critical to observe here that `this` refers to the `foo` instance, not the lambda. The lambda instance is likely moved along the async call chain, so can not be considered stable. This might be relevant when you have value-captures and accidentally pass references to them around. Luckily you would probably not have a need for much state in the lambda because the `foo` instance basically
|
Managed to figure this issue out. It's the trigger that needs to be set to "Settings"->"General"->"Split On"->"On". This ensures that multiple items added to the list at once splits the entries into multiple runs instead of just one run. Had to remove the loops which took the output from the "When item is created". Now the connectors are taking trigger output values.
Hope this will help someone save some time. I have struggled for few days trying to understand the settings and behavior of the flow.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/aqpNG.png |
|r|for-loop|dplyr|tidyverse| |
null |
|x11|xterm| |
Train and test split in such a way that each name and proportion of tartget class is present in both train and test |
|python|machine-learning|scikit-learn|train-test-split|imbalanced-data| |
Apple say "When the video zoom factor increases and crosses a camera’s switch-over zoom factor, this camera becomes eligible to set as the activePrimaryConstituentDevice." in this document: [https://developer.apple.com/documentation/avfoundation/avcaptureprimaryconstituentdevicerestrictedswitchingbehaviorconditions][1]
So if you want your app can switch to ultra.wide camera when move iPhone close and switch to Angle Camera when fay away, you need set you device.videoZoomFactor = device.virtualDeviceSwitchOverVideoZoomFactors.first.
For iPhone 14 Pro, the value is 2.
guard let virtualDeviceSwitchOverVideoZoomFactor =
input.device.virtualDeviceSwitchOverVideoZoomFactors.first as? CGFloat else {
return
}
try? input.device.lockForConfiguration()
input.device.videoZoomFactor = virtualDeviceSwitchOverVideoZoomFactor
input.device.unlockForConfiguration()
If you write like this, you can find you App can switch camera like iPhone Native Camera App.
[1]: https://developer.apple.com/documentation/avfoundation/avcaptureprimaryconstituentdevicerestrictedswitchingbehaviorconditions |
I debug the code using `{{ dd($order->id) }}`, I got 100238 order id value. But when I type
<form action="{{ route('admin.pos.update_order', ['id' => $order->id]) }}" method="post">
then its not working. Then I write this `{{ route('admin.pos.update_order', ['id' => 100238]) }}` its works great.
I cannot solve this abnormal behaviour. Can anyone guide me what is the actual issue?
As in debugging it is providing order id then it should work in the action code as `$order->id`
Route is:
Route::group(['middleware' => ['admin']], function () {
Route::group(['prefix' => 'pos', 'as' => 'pos.', 'middleware' => ['module:pos_management']], function () {
Route::post('update_order/{id}', 'POSController@update_order')->name('update_order');
});
});
Controller is:
public function update_order(Request $request, $id): RedirectResponse
{
$order = $this->order->find($order_id);
if (!$order) {
Toastr::error(translate('Order not found'));
return back();
}
$order_type = $order->order_type;
if ($order_type == 'delivery') {
Toastr::error(translate('Cannot update delivery orders'));
return back();
}
$delivery_charge = 0;
if ($order_type == 'home_delivery') {
if (!session()->has('address')) {
Toastr::error(translate('Please select a delivery address'));
return back();
}
$address_data = session()->get('address');
$distance = $address_data['distance'] ?? 0;
$delivery_type = Helpers::get_business_settings('delivery_management');
if ($delivery_type['status'] == 1) {
$delivery_charge = Helpers::get_delivery_charge($distance);
} else {
$delivery_charge = Helpers::get_business_settings('delivery_charge');
}
$address = [
'address_type' => 'Home',
'contact_person_name' => $address_data['contact_person_name'],
'contact_person_number' => $address_data['contact_person_number'],
'address' => $address_data['address'],
'floor' => $address_data['floor'],
'road' => $address_data['road'],
'house' => $address_data['house'],
'longitude' => (string)$address_data['longitude'],
'latitude' => (string)$address_data['latitude'],
'user_id' => $order->user_id,
'is_guest' => 0,
];
$customer_address = CustomerAddress::create($address);
}
// Update order details
$order->coupon_discount_title = $request->coupon_discount_title == 0 ? null : 'coupon_discount_title';
$order->coupon_code = $request->coupon_code ?? null;
$order->payment_method = $request->type;
$order->transaction_reference = $request->transaction_reference ?? null;
$order->delivery_charge = $delivery_charge;
$order->delivery_address_id = $order_type == 'home_delivery' ? $customer_address->id : null;
$order->updated_at = now();
try {
// Save the updated order
$order->save();
// Clear session data if needed
session()->forget('cart');
session(['last_order' => $order->id]);
session()->forget('customer_id');
session()->forget('branch_id');
session()->forget('table_id');
session()->forget('people_number');
session()->forget('address');
session()->forget('order_type');
Toastr::success(translate('Order updated successfully'));
//send notification to kitchen
//if ($order->order_type == 'dine_in') {
$notification = $this->notification;
$notification->title = "You have a new update in order " . $order_id . " from POS - (Order Confirmed). ";
$notification->description = $order->id;
$notification->status = 1;
try {
Helpers::send_push_notif_to_topic($notification, "kitchen-{$order->branch_id}", 'general');
Toastr::success(translate('Notification sent successfully!'));
} catch (\Exception $e) {
Toastr::warning(translate('Push notification failed!'));
}
//}
//send notification to customer for home delivery
if ($order->order_type == 'delivery'){
$value = Helpers::order_status_update_message('confirmed');
$customer = $this->user->find($order->user_id);
$fcm_token = $customer?->fcm_token;
if ($value && isset($fcm_token)) {
$data = [
'title' => translate('Order'),
'description' => $value,
'order_id' => $order_id,
'image' => '',
'type' => 'order_status',
];
Helpers::send_push_notif_to_device($fcm_token, $data);
}
//send email
$emailServices = Helpers::get_business_settings('mail_config');
if (isset($emailServices['status']) && $emailServices['status'] == 1) {
Mail::to($customer->email)->send(new \App\Mail\OrderPlaced($order_id));
}
}
// Redirect back to wherever needed
return redirect()->route('admin.pos.index');
} catch (\Exception $e) {
info($e);
Toastr::warning(translate('Failed to update order'));
return back();
}
}
|
You need to provide a User-Agent HTTP header.
For example:
import requests
import json
url = "https://www.tablebuilder.singstat.gov.sg/api/table/resourceid"
params = {
"isTestApi": "true",
"keyword": "manufacturing",
"searchoption": "all"
}
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3.1 Safari/605.1.15"
}
with requests.get(url, params=params, headers=headers) as response:
response.raise_for_status()
print(json.dumps(response.json(), indent=2)) |
I have tried run pipeline from last one week. But this is not working fine. Is there any issues here? Before last week this pipeline is working perfectly. Now this is stuck with this error.
``` > nx run web:test
> NX Took longer than 3 seconds to hear from heartbeat process
The heartbeat process may have not started properly. This CIPE could have inconsistent status reporting.
> NX Nx Cloud: Workspace is disabled
This Nx Cloud organization has been disabled due to exceeding the FREE plan.
An organization admin can start a free PRO plan trial for up to two months with no billing required at https://cloud.nx.app/orgs/63c038302fe9b1000ec9a7d0/plans
Uploading artifacts for failed job
00:01
Uploading artifacts...
WARNING: /builds/pipeline/qa-alps/coverage/**/**/cobertura-coverage.xml: no matching files. Ensure that the artifact path is relative to the working directory (/builds/pipeline/qa-alps/) ```
[![pipeline-issue][1]][1]
[1]: https://i.stack.imgur.com/Xs9Up.png |
Gitlab pipeline stuck with nx cloud issue |
|unit-testing|build|gitlab-ci|node-modules|nomachine-nx| |
|php|wordpress|woocommerce|custom-fields|meta-boxes| |
null |
|php|wordpress|woocommerce|payment-gateway|cart| |
null |
Rohan Mehta's solution still works!
To make this clear for other novices, this is an example that works:
image_path <- "C:/..." #your path
img<-magick::image_read(image_path)
text <- ocr(img, engine = eng)
Whereas this did not work:
image_path <- "C:/..." #your path
text <- ocr(img_path, engine = eng) |
|php|wordpress|woocommerce|categories|cart| |
null |
In my python application I use child loggers for each module with propagate=False.
(This is because I have a custom Formatter for each child logger objects, and since the the application is expected to write logs to the stdout and since I do not want duplicate logs I set propagate = False. So I explicitly set StreamHanlder to the child loggers and do not set any handler to the root logger.)
The problem I face is while running pytest. Apparently pytest does not capture the logs emitted by child loggers with propagate = False.
What options do I have here if I want the logs emitted by the child loggers to be captured by pytest?
Thanks for the suggestions. |
pytest LogCaptureHandler for child logger object with propagate = False |
|python|logging|pytest| |
|php|magento| |
null |
If you have permissions to use [Jenkins shared libraries][1] you can implement per job named counters slightly abusing [Hidden Parameter](https://plugins.jenkins.io/hidden-parameter/) plugin. Create a global variable named `vars/counter.groovy` in your shared library like the following:
<!-- language: java -->
import hudson.model.*
import com.wangyin.parameter.*;
// Implements per job named counters that
// can be manually controlled. Requires "Hidden Parameter" plugin:
// https://plugins.jenkins.io/hidden-parameter/
/**
* Get current value
*/
int getCurrent(counterName)
{
return getOrCreateParam(counterName).getCurrent();
}
/**
* Get next value (previous value + 1)
* When reset, it's always 0
*/
int getNext(counterName)
{
return getOrCreateParam(counterName).getNext();
}
/**
* Reset the counter (getCurrent() and getNext() will both return 0)
*/
void reset(counterName)
{
getOrCreateParam(counterName).reset();
}
/**
* Get current value and increment
*/
int getCurrentAndIncrement(counterName)
{
def param = getOrCreateParam(counterName);
def current = param.getCurrent();
param.increment();
return current;
}
/**
* Get next value (previous value + 1) and increment
* When reset, it's always 0
*/
int getNextAndIncrement(counterName)
{
def param = getOrCreateParam(counterName);
def next = param.getNext();
param.increment();
return next;
}
private def getOrCreateParam(String counterName)
{
def job = currentBuild.rawBuild.getParent()
def params = job.getProperty(ParametersDefinitionProperty.class)
List<ParameterDefinition> newParams = new ArrayList<>();
if (params != null)
{
for (param in params.parameterDefinitions)
{
if (param.name == counterName)
return new ParamWrapper(param, false);
}
newParams.addAll(params.parameterDefinitions);
}
// "-1" value means that the parameter is initialized/reset
def param = new WHideParameterDefinition(counterName, "-1", "");
newParams.add(param);
if (params != null)
job.removeProperty(params);
job.addProperty(new ParametersDefinitionProperty(newParams));
return new ParamWrapper(param, true);
}
class ParamWrapper
{
private WHideParameterDefinition param;
private int currentValue;
private boolean isReset;
ParamWrapper(WHideParameterDefinition param, boolean isInitialized)
{
this.param = param;
if (isInitialized)
{
currentValue = 0;
this.isReset = true;
}
else
{
currentValue = parseWithDefault(param.defaultValue, 0);
if (currentValue < 0)
{
currentValue = 0;
this.isReset = true;
}
else
{
this.isReset = false;
}
}
}
void reset()
{
param.defaultValue = "-1";
currentValue = 0;
isReset = true;
}
void increment()
{
incrementPrivate();
isReset = false;
}
int getNext()
{
if (isReset)
{
param.defaultValue = "0";
isReset = false;
return 0;
}
incrementPrivate();
return currentValue;
}
int getCurrent()
{
if (isReset)
{
param.defaultValue = "0";
isReset = false;
return 0;
}
return currentValue;
}
private void incrementPrivate()
{
currentValue++;
if (currentValue < 0)
{
param.defaultValue = "0";
currentValue = 0;
}
else
{
param.defaultValue = Integer.toString(currentValue);
}
}
@NonCPS
private static int parseWithDefault(String number, int defaultVal)
{
try
{
return Integer.parseInt(number);
}
catch (NumberFormatException e)
{
return defaultVal;
}
}
}
Then in your pipeline you can use it like the following:
@Library('MySharedLibrary@master') _
pipeline {
agent any
stages {
stage('Example') {
steps {
echo "MyCounter getNext: ${counter.getNext("MyCounter")}"
echo "MyCounter getCurrentAndIncrement: ${counter.getCurrentAndIncrement("MyCounter")}"
echo "MyCounter getCurrent: ${counter.getCurrent("MyCounter")}"
echo "MyCounter getNextAndIncrement: ${counter.getNextAndIncrement("MyCounter")}"
echo "MyCounter getCurrent: ${counter.getCurrent("MyCounter")}"
counter.reset("MyCounter")
echo "MyCounter reset"
echo "MyCounter getCurrent: ${counter.getCurrent("MyCounter")}"
echo "MyCounter getNext: ${counter.getNext("MyCounter")}"
echo "MyCounter getNext: ${counter.getNext("MyCounter")}"
counter.reset("MyCounter")
echo "MyCounter reset"
echo "MyCounter getNextAndIncrement: ${counter.getNextAndIncrement("MyCounter")}"
echo "MyCounter getCurrent: ${counter.getCurrent("MyCounter")}"
}
}
}
}
Which will print:
MyCounter getNext: 2
MyCounter getCurrentAndIncrement: 2
MyCounter getCurrent: 3
MyCounter getNextAndIncrement: 4
MyCounter getCurrent: 5
MyCounter reset
MyCounter getCurrent: 0
MyCounter getNext: 1
MyCounter getNext: 2
MyCounter reset
MyCounter getNextAndIncrement: 0
MyCounter getCurrent: 1
You can conveniently find the counter as a parameter in your pipeline configuration UI, which you can tweak/delete (beware it should be an integer).
[1]: https://www.jenkins.io/doc/book/pipeline/shared-libraries/ |
I am writing a class `stalker<Obj>` that holds inside a variable of type `Obj`. I want `stalker<Obj>` to pretend that it is the same as `Obj` (from the user's perspective). Thus, I expect that `stalker<Obj>` is constructible like `Obj`.
```C++
template <typename Obj>
class stalker {
Obj obj;
// other variables
public:
template <typename... Args>
stalker(Args&&... args) : obj(std::forward<Args>(args)...) {
}
};
```
I implement only copy & move constructors additionally.
`stalker<Obj>` also has other variable(s) which require some specific logiс (independent from `Obj`) when created.
`Obj` can be marked `final`.
However, my approach fails on distinguishing `std::initialiser_list` and curly brackets object. The compiler says: *"No matching constructor for initialization of 'std::vector\<int\>'"*.
```C++
int main() {
stalker<std::vector<int>> v = {1, 2, 3}; // CE
stalker<std::vector<int>> v({1, 2, 3}); // CE
return 0;
}
```
How to reach `stalker<Obj>` maximal imitation of `Obj` in terms of construction?
Creating constructors from `const Obj&` and `Obj&&` fails: sometimes the compiler cannot conclude which of these constructors fits the best and in other cases it does not try to adapt `{...} -> std::init_list -> Obj` at all (just `{...} -> Obj`).
I think of creating constructor(s) from `std::initialiser_list` but what are the pitfalls? And how to do this accurately?
I added these constructors (is `std::is_constructible` enough?):
```C++
template <typename T>
requires (std::is_constructible_v<Obj, const std::initializer_list<T>&>)
stalker(const std::initializer_list<T>& init_list) : obj(init_list) {
}
template <typename T>
requires (std::is_constructible_v<Obj, std::initializer_list<T>&&>)
stalker(std::initializer_list<T>&& init_list) : obj(std::move(init_list)) {
}
```
However, now it compiles with `std::vector` but shows an error (and it does work with the raised error after all!):
```C++
struct A {
int val;
};
int main() {
stalker<A> a = {1};
return 0;
}
```
Also, it does not convert inner `{...}` to `std::initialiser_list`.
```C++
int main() {
stalker<std::vector<std::vector<int>>> v = {{1, 2, 3, 4},
{5, 6, 7},
{8, 9},
{10}};
return 0;
}
``` |
After Debugging in the V8 source code, I really cannot figure out what is the `MarkDependentCodeForDeoptimization();` which is called in function `MarkCompactCollector::ClearNonLiveReferences()` used for?
I find it will clear the references of weak objects embedded in JIT optimized code.
What is a `weak_object` and what dose it mean by `embedded_object` can it be a simple Smi Or String? And the most important thing is, what is the realtionship with deoptimization?
It will be more helpful if you can provided an example of js code with simple string's definition and operation. |
What is 'MarkDependentCodeForDeoptimization()' used for in V8's Mark-Compact phase? |
|garbage-collection|weak-references|embedded-object|deoptimization| |
null |
Your code might compile now, but it will not work as you expect.
`INT_MIN`/`INT_MAX` are the min/max values for an `int`.
It is typically **32 bit** and therefore the values that you used before were probably **–2147483648** and **2147483647** respectively (they could be larger for 64 bit integers).
On the other hand `INT8_MIN`/`INT8_MAX` are min/max values for a **8 bit** signed integer (AKA `int8_t`), which are **-128** and **127** respectively.
In order to get the behavior you had before, you should use `std::numeric_limits<int>::min()` and `std::numeric_limits<int>::max()`, from the [<numeric_limits> header][1].
Finally - you also mentioned `INT16_MIN`/`INT16_MAX` in your title: it is the correlative min/max values for **16 bit** signed integer - i.e. **-32768** and **32767** respectively. The same principle applies to similar constants.
[1]:https://en.cppreference.com/w/cpp/types/numeric_limits
|
This is my DataFrame:
import pandas as pd
df = pd.DataFrame(
{
'a': [10, 14, 20, 10, 12, 5, 3]
}
)
And this is the expected output. I want to create three groups:
a
0 10
1 14
2 20
a
3 10
4 12
a
5 5
From top to bottom, as far as `a` is increasing/equal groups do not change. That is why first three rows are in one group. However, in row `3` `a` has decreased (i.e. 20 > 10). So this is where the second group starts. And the same logic applies for the rest of groups.
This is one my attempts. But I don't know how to continue:
import numpy as np
df['dir'] = np.sign(df.a.shift(-1) - df.a)
|
How can I create groups based on ascending streak of a column? |
|python|pandas|dataframe|group-by| |
I'm learning C# and SQL databases, but mostly C#. I'm working in a project in which we need to write down some data into a SQL Server database.
This is my connection string:
```
<configuration>
<connectionStrings>
<add name="conexionServidorHotel"
connectionString="Data Source=DESKTOP-QG08OQQ\\SQLEXPRESS;Initial Catalog=Script_RESORTSUNED;Integrated Security=True;"/>
</connectionStrings>
</configuration>
```
And this is the code I'm currently using:
```
using Entidades;
using System.Configuration;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Diagnostics;
namespace AccesoDatos
{
public class HotelAD
{
private string cadenaConexion;
public HotelAD()
{
cadenaConexion = ConfigurationManager.ConnectionStrings["conexionServidorHotel"].ConnectionString;
}
public bool RegistrarHotel(Hotel NuevoHotel)
{
bool hotelregistrado = false;
try
{
SqlConnection conexion;
SqlCommand comando = new SqlCommand();
using (conexion = new SqlConnection(cadenaConexion))
{
string instruccion = " Insert Into Hotel (IdHotel, Nombre, Direccion, Estado, Telefono)" +
" Values (@IdHotel, @Nombre, @Direccion, @Estado, @Telefono)";
comando.CommandType = CommandType.Text;
comando.CommandText = instruccion;
comando.Connection = conexion;
comando.Parameters.AddWithValue("@IdHotel", NuevoHotel.IDHotel);
comando.Parameters.AddWithValue("@Nombre", NuevoHotel.NombreHotel);
comando.Parameters.AddWithValue("@Direccion", NuevoHotel.DireccionHotel);
comando.Parameters.AddWithValue("@Estado", NuevoHotel.StatusHotel);
comando.Parameters.AddWithValue("@Telefono", NuevoHotel.TelefonoHotel);
conexion.Open();
Debug.WriteLine("Aqui voy bien 7");
hotelregistrado = comando.ExecuteNonQuery() > 0;
}
}
catch (InvalidOperationException)
{
Debug.WriteLine("No puedo escribir en la base de datos");
}
return hotelregistrado;
}
}
}
```
My project is in Spanish. That is why variable names are in Spanish. When I run my code, and I input the data for the Hotel object, works fine until `conexion.Open()`.
Something tells me there's something wrong with that command but not sure what. Is throwing me the message from the title of my question.
I reviewed the connection string and it looks good to me. The SQL Server file I have is not in the same directory as the C# solution but one directory before. I'm not sure if using `Microsoft.Data.SqlClient` could be affecting too. |
|php|wordpress| |
null |
I want my `__new__` method to behave differently in some cases and wanted to split it into overloaded functions with `singledispatchmethod`.
However this does not work, the overloading functions are never called. Why is that?
```
from functools import singledispatchmethod
class Foo:
@singledispatchmethod
def __new__(cls, arg1, **kwargs):
return "default call"
@__new__.register(int)
def _(cls, arg1, **kwargs):
return "called with int " + str(arg1)
print(Foo("hi"))
# default call
print(Foo(1))
# default call
|
Why does overloading __new__ with singledispatchmethod not work? |
|python|initialization|functools|single-dispatch| |
First check the image format. I was trying with .png format. Then suddenly I realised my images are in .jpg format.
Also you can try below code if it's not working:
```
blob = bucket.get_blob(f'Images/{id}.png')
if blob is not None:
array = np.frombuffer(blob.download_as_string(), np.uint8)
imgStudent = cv2.imdecode(array, cv2.COLOR_BGRA2BGR)
else:
print(f"Blob 'Images/{id}.png' not found.")
```
|
```
class RagQAInput(TypedDict):
question: str
category: str
language: Optional[str]
docs_vectorstore = OpenSearchVectorSearch(
opensearch_url=get_opensearch_url(),
index_name="docs",
embedding_function=embeddings_function,
# vector_field="invoice_desc_vec",
# text_field="invoice_desc",
http_compress=True,
use_ssl=False,
verify_certs=False, # DONT USE IN PRODUCTION
ssl_assert_hostname=False,
ssl_show_warn=False,
bulk_size=2000, # default is 500
)
class RagQAInput(TypedDict):
question: str
category: str
language: Optional[str]
# selected_docs: list[str]
docs_chain = (
RunnableParallel(
context=(
itemgetter("question")
| docs_vectorstore.as_retriever(
search_kwargs={
"filter": [
{
"term": {
"metadata.category": {
"value": f"{itemgetter('category')}",
"case_insensitive": True,
}
},
},
],
}
)
),
question=itemgetter("question"),
language=itemgetter("language"),
)
| RunnableParallel(
answer=(ANSWER_PROMPT | llm_for_qa_client), docs=itemgetter("context")
)
).with_types(input_type=RagQAInput)
```
This is resulting in error:
```
opensearchpy.exceptions.SerializationError: ({'size': 4, 'query': {'bool': {'filter': [{'term': {'metadata.category': {'value': operator.itemgetter('category'), 'case_insensitive': True}
```
```
class RagQAInput(TypedDict):
question: str
category: str
language: Optional[str]
docs_vectorstore = OpenSearchVectorSearch(
opensearch_url=get_opensearch_url(),
index_name="docs",
embedding_function=embeddings_function,
# vector_field="invoice_desc_vec",
# text_field="invoice_desc",
http_compress=True,
use_ssl=False,
verify_certs=False, # DONT USE IN PRODUCTION
ssl_assert_hostname=False,
ssl_show_warn=False,
bulk_size=2000, # default is 500
)
class RagQAInput(TypedDict):
question: str
category: str
language: Optional[str]
# selected_docs: list[str]
docs_chain = (
RunnableParallel(
context=(
itemgetter("question")
| docs_vectorstore.as_retriever(
search_kwargs={
"filter": [
{
"term": {
"metadata.category": {
"value": f"{itemgetter('category')}",
"case_insensitive": True,
}
},
},
],
}
)
),
question=itemgetter("question"),
language=itemgetter("language"),
)
| RunnableParallel(
answer=(ANSWER_PROMPT | llm_for_qa_client), docs=itemgetter("context")
)
).with_types(input_type=RagQAInput)
```
This is resulting in error:
```
opensearchpy.exceptions.SerializationError: ({'size': 4, 'query': {'bool': {'filter': [{'term': {'metadata.category': {'value': operator.itemgetter('category'), 'case_insensitive': True}
``` |
{"OriginalQuestionIds":[35003008],"Voters":[{"Id":487892,"DisplayName":"drescherjm"},{"Id":12002570,"DisplayName":"user12002570","BindingReason":{"GoldTagBadge":"c++"}}]} |
Is there a method in Java to ensure that when a user inputs a value, the subsequent output appears on the same line, directly adjacent to the input prompt, without moving to a new line? In other words, can we achieve a setup where the input and output are displayed on the same line?
Expectations:
Factorial of 5: 120
Reality:
Factorial of 5
: 120
Here's the code for reference
:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int total = 1;
int i;
System.out.print("Factorial of ");
int input = s.nextInt();
for(i = 1; i <= input; i++){
total *= i;
}
System.out.print(": " + total);
}
} |
Input and output the same line in java |
|java| |
null |
```
if ear < EYE_AR_THRESH:
COUNTER += 1
if COUNTER >= EYE_AR_CONSEC_FRAMES:
alarm_sound.play()
else:
COUNTER = 0
if distance > MAR:
current_time = time.time()
if current_time - start_time <= 20:
yawn_counter += 1
cv2.putText(frame, f"Yawn count: {yawn_counter:.2f}", (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
else:
if yawn_counter >= YAWN_COUNTER_THRESHOLD:
alarm_sound.play()
cv2.putText(frame, "YAWN ALERT!", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
yawn_counter = 0
start_time = time.time()
```
This is my code I want to implement gaze tracking but can't do the code.
I could not figure out how to implement the code and as well as the code. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.