instruction
stringlengths 0
30k
⌀ |
---|
How to implement gaze tracking in drowsiness detection system |
|python|opencv|tracking|dlib|imutils| |
null |
I had a similar issue. However, the error SIGSEGV used to happen only once per worker, per task. so if I had 3 tasks, and 2 workers GREEN & BLUE. Each first task run of the 2 tasks on GREEN used to fail, and also on BLUE.
I tried:
- There is NO need to create a retry handler for `WorkerLostError`
- Importing inside functions didn't help
What worked:
- while launching Celery worker using the option `-p` ([Docs Link][1])
- I recommend to use `gevent`
[1]: https://docs.celeryq.dev/en/latest/userguide/concurrency/index.html#overview-of-concurrency-options |
{"Voters":[{"Id":5625547,"DisplayName":"0stone0"},{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]} |
I am using Vue 2 with Vuex. The received object is first sorted into separate sub-objects based on classCategory value.
Does it not work because the v-model value in draggable is a key from parent tag object?
```
<div class="class-draggable__group" v-for="group in groupedClasses" :key="group.categoryLocalised">
<label class="class-draggable__label__category">{{ group.categoryLocalised }}</label>
<draggable v-model="group.classes"
:options="{ group: 'classes', dragClass: 'drag', ghostClass: 'ghost' }">
<div v-for="classItem in group.classes" :key="classItem.class" class="class-draggable__draggable__item">
<div class="d-flex align-items-center">
<svg-icon name="drag" class="mr-8 move item"></svg-icon>
<div>{{ classItem.classLocalised }}</div>
</div>
<div class="class-info d-flex align-items-center">
<checkbox class="class-draggable__draggable__item__checkbox" :view="1"
v-model="classItem.enabled" @select="toggleClassEnabledValue(classItem.class, $event)" />
<div class="icon-wrapper">
<svg-icon v-if="classItem.boolVal1Enabled" name="boolVal1Icon"></svg-icon>
</div>
<div class="icon-wrapper">
<svg-icon v-if="classItem.boolVal2Enabled" name="boolVal2Icon"></svg-icon>
</div>
<btn :content="{ icon: 'edit' }" class="class-draggable__draggable__item__button mr-8"
round="circle" @click="editClassHandler(classItem.class)" />
</div>
</div>
</draggable>
</div>
```
```
groupedClasses() {
const groups = {};
this.zoneInfoClasses.forEach(classItem => {
if (!groups[classItem.categoryLocalised]) {
groups[classItem.categoryLocalised] = [];
}
groups[classItem.categoryLocalised].push(classItem);
});
return Object.keys(groups).map(categoryLocalised => ({
categoryLocalised,
classes: groups[categoryLocalised],
}));
},
```
here's the zoneInfoClasses object:
```
[
{
class: "delivery"
classLocalised: "classA"
categoryLocalised: "category1"
enabled: true
boolVal1Enabled: false
boolVal2Enabled: false
}
{
class: "comfort"
classLocalised: "classB"
categoryLocalised: "category2"
enabled: false
boolVal1Enabled: false
boolVal2Enabled: false
}
{
class: "cargo"
classLocalised: "classC"
categoryLocalised: "category1"
enabled: false
boolVal1Enabled: false
boolVal2Enabled: false
}
{
class: "business"
classLocalised: "classD"
categoryLocalised: "category2"
enabled: false
boolVal1Enabled: false
boolVal2Enabled: false
}
]
```
Dragging functionality is working fully visually only. When I release the dragged item all items are reset to their starting position. |
How to pass dynamic filter to the vector retriever of the chain from the input (request body) in langchain? |
|langchain|opensearch| |
I am trying to run django celery and celery beat
after i start celery and celery beat
this process is running every second is this normal
```
celery-1 | [2024-03-10 16:08:11,479: INFO/MainProcess] Running job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" (scheduled at 2024-03-10 16:08:11.478374+05:30)
celery-1 | [2024-03-10 16:08:11,479: INFO/MainProcess] Job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" executed successfully
celery-beat-1 | [2024-03-10 16:08:11,767: INFO/MainProcess] Running job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" (scheduled at 2024-03-10 16:08:11.766830+05:30)
celery-beat-1 | [2024-03-10 16:08:11,767: INFO/MainProcess] Job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" executed successfully
```
I tried clearing redis db
also tried uninstalling and installing redis,celery
|
Celery and Celery beat wit django after running in docker container running some job |
|django|django-celery|django-celery-beat| |
null |
|php|wordpress|woocommerce|hook-woocommerce|cart| |
null |
I would like your assistance of a dax measure where I need to condition the filtering count of status. The problem here is it only filtered the latest date and when I filter the previous month it shows (Blank). I also don't want to sum the count if all months are selected. Here's my current measure. Thank you
Measure: OnTarget = COUNTROWS( FILTER( 'fact_objectives', 'fact_objectives'[MeasureStatus] = "On Target" && YEAR('fact_objectives'[Date]) = YEAR(TODAY()) && MONTH('fact_objectives'[Date]) = MONTH(TODAY()) ) ) |
Dax Measures Filter by Month |
|powerbi|dax| |
I have researched back and forth on this issue and so far nothing has worked. I'm unable to open sublime while using git using a command such as sublime. or sub.
I have used another command on git but it shows in config --list but it is not opening. |
null |
I am trying to reuse some code within my python project, within an Azure Function, it is structured as follows:
myproject/
| - a_app/
| - b_app/
| - c_lib/
| - requirements.txt
Up until now I have been conveniently avoiding sharing code between my 2 separate modules a_app and b_app. But I now want to create some classes that I can share and place it within c_lib.
I have an Azure function here:
myproject/
| - a_app/FunctionA/init.py
It is referencing the library c_lib by importing using the following statement:
from c_lib.foundation_utility.jwt_enforced_permissions import JWTEnforcedPermissions
All the tests pass locally and the reference is imported successfully but when I deploy to my Azure Function it simply can't find the library (an example class I'm trying to share):
File "/home/site/wwwroot/FunctionA/init.py", line 10, in from c_lib.foundation_utility.jwt_enforced_permissions import JWTEnforcedPermissions File "/home/site/wwwroot/c_lib/foundation_utility/jwt_enforced_permissions.py", line 4, in from foundation_utility.i_token_permissions import ITokenPermissions
For the life of me I can't figure out why it can't find the library. I am trying to browser the Azure Function folder structure so that I can figure out where the file is actually located to reconcile why it's not working.
Given that I have been able to reference various classes within my a_app and b_app respectfully, but not referencing one another, I know how to successfully call the right namespace. I therefore thought about copying the c_lib into the folders of a_app/ and b_app/ respectfully as part of a github build action:
```
- name: Copy c_lib into Function App Directory
run: |
cp -r c_lib a_app/
```
However despite doing this and trying to reference c_lib from within a_app it still not working.
I also considered creating this library as a pip module, but that's not what I'm looking for as I want to deploy the library as the same version as a_app and b_app. I don't want version invariance.
Something about the Azure Function means that it can't access code beyond its own package. |
```
ALTER PROCEDURE [dbo].[identify]
AS
BEGIN
SET NOCOUNT ON;
MERGE INTO [dbo].[warehouse] AS dim
USING [dbo].[staging] AS stg
ON dim.[first_name] = stg.first_name
WHEN MATCHED THEN
UPDATE SET
dim.[first_name] = stg.first_name,
dim.last_name = stg.last_name,
dim.created_date = stg.created_date,
dim.modified_date = stg.modified_date,
dim.gender = stg.gender
WHEN NOT MATCHED THEN
INSERT(first_name, last_name, created_date, modified_date, gender)
VALUES(stg.first_name, stg.last_name, stg.created_date, stg.modified_date, stg.gender)
OUTPUT Inserted.first_name AS first_name, IsNull(Deleted.last_name,Inserted.last_name) AS old_last_name
INTO test;
END
``` |
I need a Regex to match all unicode emojis.
I need this to check if a discord message has a Unicode Emoji in it.
// Here is a example of matching one Unicode Emoji
message.content.match(//g)
// or two
message.content.match(/|/g)
// and three
message.content.match(/||/g)
// then so on.
I have gotten up to like the last 300 or so emojis with this method then it stops working, sending all kinds of errors and stuff.
Is there a better way to do this? and if there is then can you give me an example in the comments. Im new to coding and don't really understand regex and some other stuff so having an example would help a lot. Also I code in JavaScript with node.js on Visual Studio Code.
UPDATE: there is a way that does work and i'm so grateful to Lioness100 for telling about it. There is a npm package called Emoji-Regex. Very useful! |
{"Voters":[{"Id":446594,"DisplayName":"DarkBee"},{"Id":7508700,"DisplayName":"David Buck"},{"Id":839601,"DisplayName":"gnat"}]} |
```python
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import norm
def cosine_similarity(arr1:np.ndarray, arr2:np.ndarray)->float:
dot_product = np.dot(arr1, arr2)
magnitude = norm(arr1) * norm(arr2)
similarity = dot_product / magnitude
return similarity
def euclidean_distance(arr1:np.ndarray, arr2:np.ndarray)->float:
return 1 / (1 + np.linalg.norm(arr1 - arr2))
black = np.array([0.93036434, 0.80134155, 0.82428051, 0.88877041, 0.90235719,
0.86631497, 0.82428051, 0.84878065, 0.99113482, 0.81413637,
0.82428051, 0.80268685, 0.76705671, 0.76605398, 0.82428051,
0.81137288, 0.83886563, 0.80749507, 0.82428051])
blue = np.array([1., 0.75256457, 0.78572852, 0.84459419, 0.88112504,
0.82160288, 0.78572852, 0.8022456 , 0.9949841 , 0.78979966,
0.78572852, 0.76791598, 0.70410357, 0.72986952, 0.78572852,
0.76683488, 0.78731431, 0.77301876, 0.78572852])
green = np.array([1., 0.62172262, 0.60678783, 0.57714708, 0.73848085,
0.69695676, 0.60678783, 0.58584646, 0.60622072, 0.6202182 ,
0.60678783, 0.57949767, 0.52131047, 0.5814518 , 0.60678783,
0.5958478 , 0.62959938, 0.60829778, 0.60678783])
fig = plt.figure(figsize=(8, 4), dpi=80)
gs = fig.add_gridspec(1, hspace=0)
axs = gs.subplots()
print("cosine_similarity = ", cosine_similarity(black, blue))
print("cosine_similarity = ", cosine_similarity(black, green))
print("euclidean_distance = ", euclidean_distance(black, blue))
print("euclidean_distance = ", euclidean_distance(black, green))
axs.plot(black, color='black')
axs.plot(blue, color='blue')
axs.plot(green, color='green')
fig.tight_layout()
plt.show()
```
[![angular similarity][1]][1]
I'm trying to create a similarity factor between two numpy arrays based on shape rather than distance. Even though the shapes (blue and green) are visually different the code prints almost the same factor.
```
cosine_similarity = 0.9993680126707705
cosine_similarity = 0.9914859250612972
```
[1]: https://i.stack.imgur.com/RQ1JS.jpg |
Sharing package within a Python project with Azure Functions |
|python|azure-functions| |
null |
|c++|qt|xterm| |
I'm currently working on a school project where I need to apply multiple border images to an element using border-image-source. However, I'm encountering issues where only one of the border images is displayed, while the other is not being applied. It would show up as a grey border instead if both of the borders are applied, as shown below (left). When I alternate between both borders, it appears as shown in the middle and right images. However, when I try to enable both in the inspect element, it doesn't work (right). [helpme](https://i.stack.imgur.com/rYcE7.png)
Here's the full class code
``` CSS
// CSS
.calendar {
height: 300px;
width: 400px;
margin: 0 auto;
margin-top: 50px;
background-image: url(calendarbg.png);
background-size: auto;
background-position: center;
/* ^^ not relevant, i guess ^^ */
border-style: solid;
border-image-source: url(border1.png);
/* border-image-source: url(border.png); */
border-image-slice: 30 fill;
border-width: 20px;
}
// HTML
<table class="calendar">
<thead>
<tr>
<th colspan="7" class="mHeader"> January </th>
</tr>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
</tr>
<tr>
<td>14</td>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
</tr>
<tr>
<td>28</td>
<td>29</td>
<td>30</td>
<td>31</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
````
I tried simplifying the code, tried different images, issue still persists. I can't seem to have both two image sources running for some reason... |
|php|wordpress|woocommerce|user-roles|badge| |
null |
set `db_table = 'custom_user'` and again run migration. Try this method. |
My iPad app has a View that uses a Metal shader as described [here][1].
#include <metal_stdlib>
using namespace metal;
[[ stitchable ]] half4 borderField(float2 position, half4 currentColor, float2 size, half4 newColor) {
assert(size.x >= 0 && position.x <= size.x);
assert(size.y >= 0 && position.y <= size.y);
// Compute distance to border
float dt = size.y - position.y; // Distance to top
float db = position.y; // Distance to bottom
float dl = position.x; // Distance to left
float dr = size.x - position.x; // Distance to right
float minDistance = min(min(dt, db), min(dl, dr));
float r = minDistance + 1.0;
float strength = 1.0 / sqrt(r);
return half4(newColor.rgb, strength);
}
It is applied to my View using the following modifier:
.colorEffect(ShaderLibrary.fields(.floatArray(viewModel.floatArray)))
The app can use any device orientation.
If I launch it in portrait orientation, the View is displayed correctly:
[![enter image description here][2]][2]
If I turn the simulator left and launch the app in landscape orientation, the following error is logged:
RBLayer: unable to create texture: BGRA8Unorm, [8.196, 5.200]
and the View is not colored:
[![enter image description here][3]][3]
If I turn the simulator back to portrait mode while the app is running, the View is again colored correctly.
However, if I turn it left again while the app is running, I get once more the same error, but the View looks now differently:
[![enter image description here][4]][4]
I don't have experience in Metal programming, and I have no idea what is wrong.
There are 2 posts that report a similar error, but apparently they do not apply to my case: [This one][5], and [this one][6].
Any suggestions?
[1]: https://stackoverflow.com/a/77515224/1987726
[2]: https://i.stack.imgur.com/4XTvi.jpg
[3]: https://i.stack.imgur.com/UFlYa.jpg
[4]: https://i.stack.imgur.com/SoKZG.jpg
[5]: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=2ahUKEwi4z92ov-mEAxXOhP0HHUzCBXQQFnoECBIQAQ&url=https%3A%2F%2Fforums.developer.apple.com%2Fforums%2Fthread%2F723146&usg=AOvVaw2kFuzlY9TIGkDUrZbkQFst&opi=89978449
[6]: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=2ahUKEwi4z92ov-mEAxXOhP0HHUzCBXQQFnoECA0QAQ&url=https%3A%2F%2Fforums.developer.apple.com%2Fforums%2Ftags%2Fswift-charts%2F%3FsortBy%3Doldest&usg=AOvVaw2omr51cHoKVv8iPHIMwxB2&opi=89978449 |
similarity between two numpy arrays based on shape but not distance |
|python|similarity| |
To get ID token along with access token, you need to pass **`openid`** as the scope.
Grant **`openid`** permission to the Microsoft Entra application:

**To get ID token along with access token,** modify your code by passing scope as **`openid`**
```js
scope: 'api://<<<client_id>>>/app openid',
```
For ***sample***, I tried to generate tokens via Postman:
```json
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
scope:api://xxx/api.access openid
grant_type:authorization_code
code:code
redirect_uri:https://jwt.ms
client_secretClientSecret
```

**Reference:**
[Securing Angular and Spring Boot applications with Azure AD - Jeroen Meys — Ordina JWorks Tech Blog (ordina-jworks.io)](https://blog.ordina-jworks.io/security/2020/08/18/Securing-Applications-Azure-AD.html) by *Jeroen Meys* |
I am able to log the Information and Error messages with the same [code](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0#azure-app-service) which you have shared.
- Instead of `(ex.Message,"Text")` , set the Error message as `(ex,"Text")`.
- You can remove `builder.Logging.AddApplicationInsights();
` line of code if you don't want to check the logs in Application Insights.
***My `Controller.cs`:***
```csharp
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
try
{
_logger.LogInformation("Log Information from API");
throw new Exception();
}
catch (Exception ex)
{
_logger.LogError(ex.Message, "Errorrrrrrrrrrrr");
_logger.LogError(ex.StackTrace);
_logger.LogError("DEBUG: A NEW EXCEPTION without Ex");
_logger.LogError(ex, "DEBUG ERROR: Error EXCEPTION with ex");
}
-----
}
```
***My `appsettings.json` file:***
```csharp
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
```
- After deploying the App to Azure App Service, In `App Service logs` enable the `Application logging`,`Web server logging`,`Detailed error messages` and `Failed request tracing` as shown below.

- Execute the request from the Controller.
- Now check for the logs and traces in LogStream.

>Kudu view for the file under home>Logfiles>Application
- Log file with name `Diagnostics-Logs`(which I have set in `Program.cs` file) will be created under `C:\home\LogFiles\Application` folder.

- The logs which you have seen in `LogStream` can be seen here as well.
 |
null |
So I have a string with double letters, 'commenntt', how do I get a list of all double/single letter word combinations?
The list should look like { "commenntt","commennt","commentt","comenntt","commentt","commennt","coment", and whatever else I missed };
It may seem like a "let's assess the issue and solve it a different way" scenario, but this function is what I need.
I've tried to figure it out for awhile but can't and the stuff I have tried is too convoluted and unreasonable to show.
Thanks for your time :] |
Device orientation dependent SwiftUI Metal problem: RBLayer: unable to create texture: BGRA8Unorm |
|ios|swiftui|metal| |
I cannot use Dropdown/Modal from Semantic UI in Next.js. The code below can't work properly (no response when clicking the button)
```
'use client';
import Image from "next/image";
import * as React from "react";
import { Button, Header, Modal, Icon } from "semantic-ui-react";
export default function Home() {
const [open, setOpen] = React.useState(false);
return (
<div className="centered">
<Icon size="massive" name="world" />
<div className="separator" />
<Modal
onClose={() => setOpen(false)}
onOpen={() => setOpen(true)}
open={open}
trigger={<Button>Show Modal</Button>}
>
<Modal.Header>Select a Photo</Modal.Header>
<Modal.Content image>
<span style={{ marginRight: 21 }}>
<Image src="/image.png" width={400} height={266} />
</span>
<Modal.Description>
<Header>Default Profile Image</Header>
<p>
We've found the following gravatar image associated with your
e-mail address.
</p>
<p>Is it okay to use this photo?</p>
</Modal.Description>
</Modal.Content>
<Modal.Actions>
<Button color="black" onClick={() => setOpen(false)}>
Nope
</Button>
<Button
content="Yep, that's me"
labelPosition="right"
icon="checkmark"
onClick={() => setOpen(false)}
positive
/>
</Modal.Actions>
</Modal>
</div>
);
}
```
I've googled a lot, but cannot find any examples with Semantic UI with the APP router. Please help. |
Cannot use Dropdown/Modal from Semantic UI in Next.js |
|next.js|dropdown|semantic-ui| |
null |
{"Voters":[{"Id":14098260,"DisplayName":"Alexander Nenashev"}],"DeleteType":1} |
|php|wordpress|woocommerce| |
null |
|javascript|vue.js|xtermjs| |
I have to use Johnson distribution to see how different means are when modifying the skewness value (.3 in the code below):
```
library(moments)
library(SuppDists)
k <- 500
parms <-JohnsonFit(c(0, 1, .3, 6))
sJohnson(parms)
poblacion <- rJohnson(1000, parms)
mu.pob <- mean(poblacion)
sd.pob <- sd(poblacion)
p <- vector(length=k)
for (i in p){
muestra <- poblacion[rJohnson(1000, parms)]
p[i] <- t.test(muestra, mu = mu.pob)$p.value
}
a_teo = 0.05
a_emp = length(p[p<a_teo])/k
sprintf("alpha_teo = %.3f <-> alpha_emp = %.3f", a_teo, a_emp)
```
If I change the .3 for 1, I got different values for mean and standard deviation, but I got exactly the same empirical value for alpha: 1.000. What is wrong with my code? |
Mean comparison using Johnson distribution in Rstudio |
|r|rstudio|mean| |
(C#) How do I get all double letter combinations from a string? |
|c#| |
null |
{"Voters":[{"Id":14853083,"DisplayName":"Tangentially Perpendicular"},{"Id":11107541,"DisplayName":"starball"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]} |
The solution that is working for me is:
In template, include your question (HumanPrompt) as {question}
For example:
template = """ you are an information extractor. Answer the question.
Context: {context}
Question: {question}
Answer:"""
Then in the qa, put your question as value of key "query"
For example
result = qa({"query": "Tell me about water sector?"})
I believe this is due to the fact that the variable names are hard-coded inside RetrievalQA source code
class BaseRetrievalQA(Chain):
"""Base class for question-answering chains."""
combine_documents_chain: BaseCombineDocumentsChain
"""Chain to use to combine the documents."""
input_key: str = "query" #: :meta private:
output_key: str = "result" #: :meta private:
=> input_key = "query" seems to be the default key.
I haven't found how the code seems to be able to connect my {question} var and {query} var yet, but the above code generates correct result
|
I am using Vue 2 with Vuex. The received object is first sorted into separate sub-objects based on classCategory value.
Does it not work because the v-model value in draggable is a key from parent tag object?
```
<div class="class-draggable__group" v-for="group in groupedClasses" :key="group.categoryLocalised">
<label class="class-draggable__label__category">{{ group.categoryLocalised }}</label>
<draggable v-model="group.classes"
:options="{ group: 'classes', dragClass: 'drag', ghostClass: 'ghost' }">
<div v-for="classItem in group.classes" :key="classItem.class" class="class-draggable__draggable__item">
<div class="d-flex align-items-center">
<svg-icon name="drag" class="mr-8 move item"></svg-icon>
<div>{{ classItem.classLocalised }}</div>
</div>
<div class="class-info d-flex align-items-center">
<checkbox class="class-draggable__draggable__item__checkbox" :view="1"
v-model="classItem.enabled" @select="toggleClassEnabledValue(classItem.class, $event)" />
<div class="icon-wrapper">
<svg-icon v-if="classItem.boolVal1Enabled" name="boolVal1Icon"></svg-icon>
</div>
<div class="icon-wrapper">
<svg-icon v-if="classItem.boolVal2Enabled" name="boolVal2Icon"></svg-icon>
</div>
<btn :content="{ icon: 'edit' }" class="class-draggable__draggable__item__button mr-8"
round="circle" @click="editClassHandler(classItem.class)" />
</div>
</div>
</draggable>
</div>
```
```
groupedClasses() {
const groups = {};
this.zoneInfoClasses.forEach(classItem => {
if (!groups[classItem.categoryLocalised]) {
groups[classItem.categoryLocalised] = [];
}
groups[classItem.categoryLocalised].push(classItem);
});
return Object.keys(groups).map(categoryLocalised => ({
categoryLocalised,
classes: groups[categoryLocalised],
}));
},
```
here's the zoneInfoClasses object:
```
[
{
class: "classa"
classLocalised: "classA"
categoryLocalised: "category1"
enabled: true
boolVal1Enabled: false
boolVal2Enabled: false
}
{
class: "classb"
classLocalised: "classB"
categoryLocalised: "category2"
enabled: false
boolVal1Enabled: false
boolVal2Enabled: false
}
{
class: "classc"
classLocalised: "classC"
categoryLocalised: "category1"
enabled: false
boolVal1Enabled: false
boolVal2Enabled: false
}
{
class: "classd"
classLocalised: "classD"
categoryLocalised: "category2"
enabled: false
boolVal1Enabled: false
boolVal2Enabled: false
}
]
```
Dragging functionality is working fully visually only. When I release the dragged item all items are reset to their starting position. |
As Olakunle indicated, you must include the IAM role that the state machine is using. Some services send directly to SNS, but Step functions is not one of them (See [https://docs.aws.amazon.com/sns/latest/dg/sns-key-management.html][1])
But a few points:
- If you directly give permissions to an IAM role in the KMS key policy, you do not need to give permissions in the IAM policy. This is effectively the same as in any other resource policy, except that with KMS, you must give permissions in the Key Policy, it cannot only be done in the IAM Policy.
- IF you give permissions to root, `arn:aws:iam::ACCOUNT:root`, you are not granting all roles permission, but you are delegating access to the key to IAM, which means then you give access by adding permissions in the IAM role policy (but only to the permissions you permit in the key policy).
- In this case you do not grant permissions to the Service. The IAM Role is the principal that needs permissions. If you want to restrict access to it being used with a specific service, then you need a condition to ensure that it is done VIA the service, and within that region. For example, here is how you would do it in JSON. I included both the section for granting the role access, and if one of the services that send directly to SNS (per the link above) was to be given access.
{
"Sid": "AllowAccountPoliciesToUseKey",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::190565753270:role/YourStateMachineRoleName"
},
"Action": [
"kms:CreateGrant",
"kms:Encrypt",
"kms:Decrypt",
"kms:GenerateDataKey*",
"kms:ReEncrypt*"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"kms:ViaService": [
"sns.REGION.amazonaws.com",
"states.REGION.amazonaws.com"
]
}
}
},
{
"Sid": "Permit Local Account Services to Utilize the Key",
"Effect": "Allow",
"Principal": {
"Service": [
"events.amazonaws.com",
"cloudwatch.amazonaws.com",
"s3.amazonaws.com"
]
},
"Action": [
"kms:Decrypt",
"kms:GenerateDataKey*"
],
"Resource": "*"
},
[1]: https://docs.aws.amazon.com/sns/latest/dg/sns-key-management.html |
null |
|php|wordpress|custom-post-type| |
null |
I'm trying to setup bumblebee (bumblebee-hotword-node) within a server that will listen to a discord server for the 'bumblebee' hotword derived from https://github.com/SteTR/Emost-Bot/tree/master
So far I have got the tool integrated and emitting 'data', but it never fires the 'hotspot' callback when i say "bumblebee".
I am not sure whether I have the wrong format for the stream perhaps that is going into it, or doing something else wrong.
converter.js - Where we convert the discord stream into the appropriate format
```
const ffmpegPath = require("@ffmpeg-installer/ffmpeg").path;
const ffmpeg = require("fluent-ffmpeg");
ffmpeg.setFfmpegPath(ffmpegPath);
/**
* Creates a audio stream convert to convert one audio stream's format to another.
* E.g. 48000 Hz 2 channel to 16000 Hz 1 channel
* @param stream input audio stream
* @param inputArray array of flags for ffmpeg to describe input format
* @param outputArray array of flags for ffmpeg to describe output format
* @param formatType REQUIRED. the format of the output (e.g. s16le)
* @returns {stream.Writable|{end: boolean}|*} a new stream that has converted the input audio stream into the format requested
*/
function createConverter(
stream,
inputArray = ["-f s16le", "-ac 2", "-ar 44100"],
outputArray = ["-ac 1", "-ar 16000"],
formatType = "s16le"
) {
return new ffmpeg()
.input(stream)
.inputOptions(inputArray)
.outputOptions(outputArray)
.format(formatType)
.pipe({ end: false });
}
module.exports = { createConverter };
```
Connect.js - Where stream is converted and then fed to Voice
```
const listenStream = await connection.receiver
.subscribe(member.user.id, {
end: {
behavior: EndBehaviorType.Manual,
},
})
.on("error", (error) => {
console.log("audioReceiveStream error: ", error);
});
// // // Make voice streams for voice commands
const voiceRecorderStream = createConverter(listenStream);
voiceRecorderStream.on('data',(data)=>{
console.log(data)
})
const vr = new VoiceRecognitionService(
hotword,
connection,
voiceRecorderStream
);
```
I have tried to alter the conversion and I have been scanning the logs to see if this is working - I am getting data back through the converted stream with .on('data') - But Bumblebee will not trigger for the hotword I have set (bumblebee).
I have also printed within the bumblebee-hotword-node packages and it appears it is processing the audio just fine and porcupine just isn't flagging when I speak the hotword.
Any help or suggestions are appreciated! |
{"Voters":[{"Id":446594,"DisplayName":"DarkBee"},{"Id":5349916,"DisplayName":"MisterMiyagi"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]} |
How do I get all double letter combinations from a string? |
The accepted answer is good. But...
I didn't see cancel() method implementation
So my implementation with possibility to cancel the running task (simulating cancellation) is below.
Cancel is needed to not run postExecute() method in case of task interruption.
public abstract class AsyncTaskExecutor<Params> {
public static final String TAG = "AsyncTaskRunner";
private static final Executor THREAD_POOL_EXECUTOR =
new ThreadPoolExecutor(20, 128, 1,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
private final Handler mHandler = new Handler(Looper.getMainLooper());
private final AtomicBoolean mIsInterrupted = new AtomicBoolean(false);
protected void onPreExecute(){}
protected abstract Void doInBackground(Params... params) throws InterruptedException;
protected void onPostExecute(){}
protected void onCancelled(){}
@SafeVarargs
public final void executeAsync(Params... params) {
THREAD_POOL_EXECUTOR.execute(() -> {
try {
checkInterrupted();
mHandler.post(this::onPreExecute);
checkInterrupted();
doInBackground(params);
checkInterrupted();
mHandler.post(this::onPostExecute);
} catch (InterruptedException ex) {
mHandler.post(this::onCancelled);
} catch (Exception ex) {
Log.e(TAG, "executeAsync: " + ex.getMessage() + "\n" + Debug.getStackTrace(ex));
}
});
}
public void cancel(boolean mayInterruptIfRunning){
setInterrupted(mayInterruptIfRunning);
}
public boolean isCancelled(){
return isInterrupted();
}
protected void checkInterrupted() throws InterruptedException {
if (isInterrupted()){
throw new InterruptedException();
}
}
protected boolean isInterrupted() {
return mIsInterrupted.get();
}
protected void setInterrupted(boolean interrupted) {
mIsInterrupted.set(interrupted);
}
}
Example of using this class:
public class MySearchTask extends AsyncTaskExecutor<String> {
public MySearchTask(){
}
@Override
protected Void doInBackground(String... params) {
// Your long running task
return null;
}
@Override
protected void onPostExecute() {
// update UI on task completed
}
@Override
protected void onCancelled() {
// update UI on task cancelled
}
}
MySearchTask searchTask = new MySearchTask();
searchTask.executeAsync("Test"); |
So I have a string with double letters, `commenntt`, how do I get a list of all double/single letter word combinations?
The list should look like
```
{ "commenntt","commennt","commentt","comenntt","commentt","commennt","coment", and whatever else I missed };
```
It may seem like a "let's assess the issue and solve it a different way" scenario, but this function is what I need.
I've tried to figure it out for awhile but can't and the stuff I have tried is too convoluted and unreasonable to show. |
From the publication:
"*Since the solar activity cycle is 27 days, this paper uses 27 days as the sliding window
to detect the ionospheric TEC perturbation condition before the volcanic eruption. The
upper bound of TEC anomaly is represented as
UB =Q2+
1.5
IQR
and the lower bound
as LB =Q2−1.5IQR*"
Implementing this in pandas:
# no seed for random, to try it many times
dataLength = 1000 # datalength
data = np.random.randint(1, 100, dataLength) # generate random data
outlierPercentage = 1 # controls amount of outliers in the data
outlierCount = int(dataLength/100 * outlierPercentage) # count of outliers
outlierIdx = np.random.choice(dataLength, outlierCount, replace=False) # choose randomly between the index of the outlier
data[outlierIdx] = np.random.randint(-300, 300, outlierCount) # choose a random int between -300 and 300
df = pd.DataFrame({'Data': data}) # generate the datafrane
winSize = 5 # define size of window
# the statistics calculations...
Mean = df["Data"].rolling(window=winSize).mean()
Q1 = df["Data"].rolling(window=winSize).quantile(0.25)
Q3 = df["Data"].rolling(window=winSize).quantile(0.75)
IQR = Q3 - Q1
# assigning the upper limit and lower limit
df["UL"] = Mean + 1.5 * IQR
df["LL"] = Mean - 1.5 * IQR
# detect the outliers
outliersAboveUL = df[(df['Data'] > df['UL'])].index
outliersBelowLL = df[(df['Data'] < df['LL'])].index
Plotting gives you this:
[![plot][1]][1]
Imported packages:
import pandas as pd
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
As you can see, this is a very basic example. I mainly added the correct calculation of the IQR. If you want a more detailed answer, I would need a sample of your data...
[1]: https://i.stack.imgur.com/61D8k.png |
|php|wordpress|woocommerce|user-roles| |
null |
I tried sending email works perfectly fine, but the link that i've received is local server link and not my domain link.
I'm using gmail for sending emails, do i have create /verify file for html ??
```
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { UserModel, MyModel, TrackedAwbModel } = require('./modules/schema');
const bcrypt = require('bcrypt');
const nodemailer = require('nodemailer');
const mongoose = require('mongoose');
require('dotenv/config')
const app = express()
app.use(cors())
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
});
response.end('Hello World\n');
}).listen(400);
app.use(express.json())
mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch(err => {
console.error('Error connecting to MongoDB', err);
});
app.get('/data', async (req, res) => {
try {
const data = await MyModel.find();
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false,
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD
}
})
app.post('/users', async (req, res) => {
const { email, username, password } = req.body;
try {
const existingUser = await UserModel.findOne({ $or: [{ email }, { username }] });
if (existingUser) {
return res.status(400).json({ error: "Email or username already exists" });
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = await UserModel.create({ email, username, password: hashedPassword });
const verificationLink = `https://${process.env.BASE_URL}/verify/${newUser._id}`;
await transporter.sendMail({
from: process.env.EMAIL_USERNAME,
to: email,
subject: 'Verify Your Email',
html: `<p>Please click <a href="${verificationLink}">here</a> to verify your email address.</p>`
});
res.json({ message: "User created successfully", userId: newUser._id });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/verify/:userId', async (req, res) => {
try {
const userId = req.params.userId;
await UserModel.findByIdAndUpdate(userId, { isEmailVerified: true });
res.send('Email verified successfully. You can now log in. ');
} catch (error) {
console.error(error);
res.status(500).send('Internal server error');
}
});
const port = process.env.PORT || 4000
const server = app.listen(port, () => {
console.log(`Server running on port ${port}`)
})
```
[Image of that local url when i click on the link sent to email](https://i.stack.imgur.com/JcJng.png)
I want this link to be sent to emails and not the local ones
this the domain url that i want to send to registered email users for verification
``
https://${process.env.BASE_URL}/verify/${newUser._id}
`` |
**Code**
maybe there are 4 groups
dfs = [d for _, d in df.groupby(df['a'].diff().lt(0).cumsum())]
dfs
[ a
0 10
1 14
2 20,
a
3 10
4 12,
a
5 5,
a
6 3] |
We are trying to use Apache spark in our existing application. Spark is using `Antlr4` version `4.9`.
While Hibernate is using `Antlr4` version `4.10`.
Antlr has made changes between 4.9 version and 4.10 version which is causing below issue.
Caused by: java.lang.UnsupportedOperationException: java.io.InvalidClassException: org.antlr.v4.runtime.atn.ATN; Could not deserialize ATN with version 3 (expected 4).
We are using below dependencies in our application which is running with **Spring Boot 3.2.3** and **Java 17**. Below are the maven dependencies we are using.
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.12</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.12</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.1.Final</version>
<exclusions>
<exclusion>
<artifactId>dom4j</artifactId>
<groupId>org.dom4j</groupId>
</exclusion>
</exclusions>
</dependency>
Thanks in advance. |
Incompatibility between Hibernate 6 and Apache Spark latest version |
|spring-boot|hibernate|apache-spark|hibernate-6.x| |
I'm porting a Windows C code written for MSVC to be compatible with gcc and clang. I have this snippet of code to declare a variable in a shared segment:
> #pragma comment(linker, "/SECTION:.shr,RWS")
> #pragma data_seg(".shr")
> volatile int g_global = 0;
> #pragma data_seg()
>
I know that the gcc equivalent in Windows is:
> volatile int g_global __attribute__((section("shr"), shared)) = 0;
>
What is the working equivalent for the clang compiler in Windows?
|
Windows shared segment in clang |
|c|windows|clang| |
null |
{"Voters":[{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":9568358,"DisplayName":"Wimanicesir"},{"Id":839601,"DisplayName":"gnat"}]} |
{"Voters":[{"Id":2055998,"DisplayName":"PM 77-1"},{"Id":4850040,"DisplayName":"Toby Speight"},{"Id":839601,"DisplayName":"gnat"}]} |
It seems you haven't installed [coastStat library](https://github.com/kvos/CoastSat).
Using above link you should download the repository.
On your Anaconda environment cd into the folder where You have downloaded coastStat library.
Run below code:
```bash
conda create -n coastsat
conda activate coastsat
conda install -c conda-forge geopandas -y
conda install -c conda-forge earthengine-api scikit-image matplotlib astropy notebook -y
pip install pyqt5 imageio-ffmpeg
conda activate coastsat
```
[More info](https://github.com/kvos/CoastSat?tab=readme-ov-file#installation) regarding Installation. |
Nodemailer email verification errror |
|node.js|mongodb|nodemailer| |
null |
|gdb|mpi|xterm| |
My POST request isn't working and it's not updating? the error is: TypeError: Cannot read properties of undefined (reading 'username')
app.post('/create-user', function(req, resp) { const client = new MongoClient(uri);
const dbo = client.db("eggyDB"); // Get the database object
const collName = dbo.collection("users"); // Get the collection
const info = {
username: req.body.username,
password: req.body.password
};
collName.insertOne(info)
.then(function() {
console.log('User created');
resp.render("main", {
layout: "homepage",
title: "My Home page"
});
})
.catch(function(err) {
console.error('Error creating user:', err);
resp.status(500).send('Internal Server Error');
})
});
this is my html code (in the partials folder):
```
<form
name="signup"
action="/create-user"
method="POST"
class="popup-signup-content"
onsubmit="return verifyPassword()"
>
<h1 onclick="closeSignup()" id="close-login" type="submit">x</h1>
<img src="/images/LOGO-YL.png" alt="None" />
<input
id="username-signup"
name="username"
type="text"
placeholder="Enter Username/Email"
required
/>
<input
id="password-signup"
type="password"
placeholder="Enter Password"
required
/>
<input
id="verify-password-signup"
name="password"
type="password"
placeholder="Re-Enter Password"
required
/>
<button class="login-button bold" type="submit" onclick="console.log('Form Submitted')">Register</button>
</form>
```
it won't add a new user to the database but it connects to the database. it also won't show the onclick function when Register is pressed. what should i do?
```
```
i tried asking chatgpt but i think it was slowly drifting me away from the solution. what do you think should i do here? |
Why won't my POST request work? i'm using handlebars, express, and mongodb. i'm new to this |
|javascript|html|express|handlebars.js| |
null |
|php|laravel| |
null |
|audio|discord|discord.js|audio-streaming|voice-recognition| |
You have intercepted a poorly evolved terrorist cell that uses Caesar's method as a cipher. Messages are always in English. What they do is replace each letter with another letter by moving the alphabet K positions. So, for example, if we move the alphabet two positions forward, we would get the following correspondence:
**A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
CDEFGHIJKLMNOPQRSTUVWXYZAB
**
Of course this method has a very simple attack:
Try all possible substitutions;
Calculate for each possible substitution the next measure between the expected relative frequency of each letter **Ei**, and the obtained **Oi **using the formula: **(Ei-Oi)^2 / Ei**
Your program should read a line of text with at most 10^4 characters.
Your program should print the required offset and the deciphered text. Your program should only handle letters (upper or lower case).
Write a program that reads a line of text and decrypts it. Use the table below for the value Ei (third column) of each letter:
E 11.1607% 56.88 M 3.0129% 15.36
A 8.4966% 43.31 H 3.0034% 15.31
R 7.5809% 38.64 G 2.4705% 12.59
I 7.5448% 38.45 B 2.0720% 10.56
O 7.1635% 36.51 F 1.8121% 9.24
T 6.9509% 35.43 Y 1.7779% 9.06
N 6.6544% 33.92 W 1.2899% 6.57
S 5.7351% 29.23 K 1.1016% 5.61
L 5.4893% 27.98 V 1.0074% 5.13
C 4.5388% 23.13 X 0.2902% 1.48
U 3.6308% 18.51 Z 0.2722% 1.39
D 3.3844% 17.25 J 0.1965% 1.00
P 3.1671% 16.14 Q 0.1962% 1.00
Examples:
**
Input 1**
GXOXKFHKX
**Output 1**
7 NEVERMORE
**Input 2**
Oj wz, jm ijo oj wz, ocvo dn ocz lpznodji: Rczoczm 'odn ijwgzm di ocz hdiy oj npaazm.
**Output 2**
5 To be, or not to be, that is the question: Whether 'tis nobler in the mind to suffer.
```
#include <stdio.h>
#include <string.h>
double tab[26] = {43.31, 10.56, 23.13, 17.25, 56.88, 9.24,
12.59, 15.31, 38.45, 1.00, 5.61, 27.98,
15.36, 33.92, 36.51, 16.14, 1.00, 38.64,
29.23, 35.43, 18.51, 5.13, 6.57, 1.48,
9.06, 1.39};
void calcularfrequencias(const char texto[], double frequencias[])
{
int letras = 0;
for (int i = 0; texto[i] != '\0'; i++)
{
char c = texto[i];
if (c >= 'A' && c <= 'Z')
{
frequencias[c - 'A']++;
letras++;
}
else if (c >= 'a' && c <= 'z')
{
frequencias[c - 'a']++;
letras++;
}
}
for (int i = 0; i < 26; i++)
{
frequencias[i] /= letras;
}
}
int encontrardeslocamento(double frequencias[])
{
int deslocamento = 0;
double menor = 1e9;
for (int i = 0; i < 26; i++)
{
double diferenca = 0.0;
for (int j = 0; j < 26; j++)
{
int x = (j + i) % 26;
diferenca += (frequencias[j] - tab[x]) * (frequencias[j] - tab[x]);
}
if (diferenca < menor)
{
menor = diferenca;
deslocamento = i;
}
}
return deslocamento;
}
void decifrar(char texto[], int deslocamento)
{
for (int i = 0; texto[i] != '\0'; i++)
{
char c = texto[i];
if (c >= 'A' && c <= 'Z')
{
printf("%c", ((c - 'A' + deslocamento) % 26) + 'A');
}
else if (c >= 'a' && c <= 'z')
{
printf("%c", ((c - 'a' + deslocamento) % 26) + 'a');
}
else
{
printf("%c", c);
}
}
}
int main()
{
char texto_cifrado[10000];
if (fgets(texto_cifrado, sizeof(texto_cifrado), stdin) != NULL)
{
double frequencias[26];
calcularfrequencias(texto_cifrado, frequencias);
int deslocamento = encontrardeslocamento(frequencias);
printf("%d ", deslocamento);
decifrar(texto_cifrado, deslocamento);
}
return 0;
}
```
I tried this but when I try it it doesnt works in one input:
**Gx ‘Fwnwj—fwnwjegjw’.”**
the output should be: **8 Of ‘Never—nevermore’.”**
but in this code the output is **21 Bs ‘Arire—arirezber’.”** and I can't figure it out.
Thank you for your help.
|
Cryptography in C |
|c| |
null |
I am trying to convert my discord image into Base 64 from a link so it can be used in Googles [Gemini Pro Vision Model](https://ai.google.dev/tutorials/node_quickstart#generate-text-from-text-and-image-input). However I am encountering an error every time. I believe it occurs when the axios function is run, but I am not 100% sure.
#### Code:
```javascript
async function run(message) {
const model = genAI.getGenerativeModel({ model: "gemini-pro-vision" });
console.log("Pass 1")
const imageAttachmentUrls = message.attachments
.filter(attachIsImage)
.map((attachment) => attachment.url)
.filter((url) => !!url);
console.log("Pass 2")
if (imageAttachmentUrls.length === 0) {
console.log("No valid image attachments found in the message.");
return;
}
console.log("Pass 3")
function getBase64(url) {
console.log("Pass 5")
return axios
.get(url, {
responseType: 'arraybuffer'
})
.then(response => Buffer.from(response.data, 'binary').toString('base64'))
}
console.log("Pass 4")
console.log(imageAttachmentUrls[0]);
const image = {
inlineData: {
data: await getBase64(imageAttachmentUrls[0]),
mimeType: "image/png",
},
};
console.log("Pass 6")
const prompt = "What's this picture?";
const result = await model.generateContent([prompt, image]);
console.log(result);
}
run(message);
}
```
### Console:
```console
Pass 1
Pass 2
Pass 3
Pass 4
https://cdn.discordapp.com/attachments/1213885940909744139/1216332602538065940/image.png?ex=66000102&is=65ed8c02&hm=a3901233e34d1b1239928d97dfbe882553212cde5d841560d252be3d768acc8b&
Pass 5
Pass 6
Critical Error detected:
{} unhandledRejection
```
Expected the Model to return a result and log it in the console successfully. |
The UTF-8 string in example seems to be coded with **too many bytes**!
---
The input string: "TESTTEST"
- “” (U+1F449): A hand pointing right
- “T”, “E”, “S”, “T”: Basic Latin letters
- “” (U+1F4CD): A round pushpin
- “T”, “E”, “S”, “T”: Basic Latin letters
This string is stored in a UTF-8 encoded file, when I use a hexadecimal editor I see the **16 bytes below** as expected. When I copy the strings into [Online tools][1], I find the same 16 bytes.
```
f0 9f 91 89 54 45 53 54 f0 9f 93 8d 54 45 53 54
\_______/ \_______/ \_______/ \_______/
U+1F449 T E S T U+1F4CD T E S T
“” “”
```
---
However, the results of the function [babel:string-to-octets][2] are different, I get **20 bytes**:
```
(let ((string "TESTTEST"))
(format t "TEST STRING [~A]~%" string)
(print-hex (babel:string-to-octets string))
(print-hex (babel:string-to-octets string :encoding :UTF-8)))
TEST STRING [TESTTEST]
ED A0 BD ED B1 89 54 45 53 54 ED A0 BD ED B3 8D 54 45 53 54 (20 bytes)
ED A0 BD ED B1 89 54 45 53 54 ED A0 BD ED B3 8D 54 45 53 54 (20 bytes)
```
If we analyze this further:
```
ED A0 BD ED B1 89 54 45 53 54 ED A0 BD ED B3 8D 54 45 53 54
\_____________/ \_______/ \_____________/ \_______/
??? T E S T ??? T E S T
```
**How do I get the 16 bytes from the input string?**
[1]: https://onlinetools.com/utf8/convert-utf8-to-bytes
[2]: https://quickref.common-lisp.net/babel.html#index-string_002dto_002doctets |
UTF-8 string has too many bytes using SBCL and babel on Windows 64 bits |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.