2023-01-31

why smote raise "Found input variables with inconsistent numbers of samples"?

I try to classify emotion from tweet with dataset of 4401 tweet, when i use smaller sample of data (around 15 tweet) everything just work fine, but when i use the full dataset it raise the error of

Found input variables with inconsistent numbers of samples: [7, 3520]

the error happen when i try to oversampling the data using smote after transforming the data using countvectorizer.

This is the code where the error raise

# N-gram Feature and Term Frequency
vectorizer = CountVectorizer(ngram_range=(1,3))
x_train_tf = vectorizer.fit_transform(str(x_train).split('\n')).toarray()
x_test_tf = vectorizer.transform(str(x_test).split('\n')).toarray()
df_output = pd.DataFrame(data =x_train_tf, columns = vectorizer.get_feature_names_out())
display(df_output)
# the print shape is (7 rows × 250 columns)

smote = SMOTE(random_state=42, k_neighbors=5)
x_smote, y_smote = smote.fit_resample(x_train_tf, y_train)
print("Total Train Data SMOTE : ",x_smote.shape), print("Total Train Label SMOTE : ",y_smote)

i did not understand why this is happening so some explanation could really help. i already tried to solve it using answers from other similiar question but nothing have worked.

This is the full code

import nltk
import re
#nltk.download()
import string
import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt
from nltk import everygrams
from collections import Counter
from sklearn import preprocessing
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from imblearn.over_sampling import SMOTE
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score, confusion_matrix

dataset = pd.read_csv("G:/TA/Program/dataset/Twitter_Emotion_Dataset.csv", encoding='latin-1')
# Preprocessing
dataset['case_folding_tweet'] = dataset['tweet'].str.casefold()
dataset['only_alphabet_tweet'] = [re.sub('[^a-zA-Z]+\s*', ' ', s) for s in dataset['case_folding_tweet']]
dataset['data_cleaning_tweet'] = dataset['only_alphabet_tweet'].str.replace(r'\b\w{1}\b','').str.replace(r'\s+', ' ')

slangword_dictionary = ("G:/TA/Program/dataset/kamus_singkatan.csv")

deslang = {}
list_slangword = open(slangword_dictionary).readlines()
for line in list_slangword:
    slang, unslang = line.strip().split(';')
    deslang[slang] = unslang
deslang[slang] = {r"\b{}\b".format(k): v for k, v in deslang.items()}

dataset['data_cleaning_tweet'] = dataset['data_cleaning_tweet'].replace(deslang[slang], regex=True)
dataset['convert_slang_tweet'] = dataset['data_cleaning_tweet']

replace_dictionary = {'tidak ': 'tidak', 'bukan ': 'bukan', 'jangan ': 'jangan', 'belum ': 'belum'}
dataset['convert_negation_tweet'] = dataset['convert_slang_tweet'].replace(replace_dictionary, regex=True)
dataset['tokenization_tweet'] = dataset['convert_negation_tweet'].apply(word_tokenize) 
list_stopwords = set(stopwords.words("indonesian"))
list_stopwords.add('username')
list_stopwords.add('url')
dataset['stopword_removal_tweet'] = dataset['tokenization_tweet'].apply(lambda x: [item for item in x if item not in list_stopwords])

factory = StemmerFactory()
stemmer = factory.create_stemmer()
dataset['stemmed_tweet'] = dataset['stopword_removal_tweet'].apply(lambda x: [stemmer.stem(y) for y in x]) 

# Split data
x = dataset["stemmed_tweet"].values
y = dataset["label"].values
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, random_state= 42)

# Get N-gram and TF
vectorizer = CountVectorizer(ngram_range=(1,3))
x_train_tf = vectorizer.fit_transform(str(x_train).split('\n')).toarray()
x_test_tf = vectorizer.transform(str(x_test).split('\n')).toarray()

# Oversampling
smote = SMOTE(random_state=42, k_neighbors=5)
x_smote, y_smote = smote.fit_resample(x_train_tf, y_train)

print("Total Train Data SMOTE : ",x_smote.shape), print("Total Train Label SMOTE : ",y_smote)

gnb_classifier = GaussianNB()
gnb_classifier.fit(x_smote, y_smote)
print(gnb_classifier)
y_pred = gnb_classifier.predict(x_test_tf)
print("Emotion Predicted :", y_pred)

Link to the dataset



How to move a device in AD to a different OU in a GUI

We have all of our Autopilot deployed devices in 1 OU and the techs have to move them to their own site's OU I have written a GUI to do this. they enter the device name and the location name. The location name is tha final ou the device will reside in. My GUI gets the OUs for the site and lists them in a Out-Gridview you click on the ou you want and click ok. it sends that to a textbox. then you click move. thats where I ger the error that the device cannot be found. I am sure I have some silly syntax wrong. Thanks in advance.

Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);'

[Console.Window]::ShowWindow([Console.Window]::GetConsoleWindow(), 0)
<# 
.NAME
    AP Device Move
#>

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = New-Object System.Drawing.Point(400,400)
$Form.text                       = "Form"
$Form.TopMost                    = $false

$LBL_APDEVICE                    = New-Object system.Windows.Forms.Label
$LBL_APDEVICE.text               = "Computer Name"
$LBL_APDEVICE.AutoSize           = $true
$LBL_APDEVICE.width              = 25
$LBL_APDEVICE.height             = 10
$LBL_APDEVICE.location           = New-Object System.Drawing.Point(0,2)
$LBL_APDEVICE.Font               = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$TBX_APDEVICE                    = New-Object system.Windows.Forms.TextBox
$TBX_APDEVICE.Text               = ""
$TBX_APDEVICE.multiline          = $false
$TBX_APDEVICE.width              = 100
$TBX_APDEVICE.height             = 20
$TBX_APDEVICE.location           = New-Object System.Drawing.Point(6,37)
$TBX_APDEVICE.Font               = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$LBL_SITE                        = New-Object system.Windows.Forms.Label
$LBL_SITE.text                   = "Site Name"
$LBL_SITE.AutoSize               = $true
$LBL_SITE.width                  = 25
$LBL_SITE.height                 = 10
$LBL_SITE.location               = New-Object System.Drawing.Point(4,71)
$LBL_SITE.Font                   = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$LOCATION                        = New-Object system.Windows.Forms.TextBox
$LOCATION.multiline              = $false
$LOCATION.width                  = 100
$LOCATION.height                 = 20
$LOCATION.location               = New-Object System.Drawing.Point(3,101)
$LOCATION.Font                   = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$DESTINATION_OU                  = New-Object system.Windows.Forms.TextBox
$DESTINATION_OU.text             = ""
$DESTINATION_OU.multiline        = $false
$DESTINATION_OU.width            = 100
$DESTINATION_OU.height           = 20
$DESTINATION_OU.location         = New-Object System.Drawing.Point(14,194)
$DESTINATION_OU.Font             = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$TARGET_OU                       = New-Object system.Windows.Forms.Label
$TARGET_OU.text                  = "Target OU"
$TARGET_OU.AutoSize              = $true
$TARGET_OU.width                 = 25
$TARGET_OU.height                = 10
$TARGET_OU.location              = New-Object System.Drawing.Point(12,139)
$TARGET_OU.Font                  = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$Get_OU                          = New-Object system.Windows.Forms.Button
$Get_OU.text                     = "Get OUs for Site"
$Get_OU.width                    = 104
$Get_OU.height                   = 30
$Get_OU.location                 = New-Object System.Drawing.Point(133,54)
$Get_OU.Font                     = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$BTN_MOVE                        = New-Object system.Windows.Forms.Button
$BTN_MOVE.text                   = "Move Device"
$BTN_MOVE.width                  = 91
$BTN_MOVE.height                 = 30
$BTN_MOVE.location               = New-Object System.Drawing.Point(34,246)
$BTN_MOVE.Font                   = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$Form.controls.AddRange(@($LBL_APDEVICE,$TBX_APDEVICE,$LBL_SITE,$LOCATION,$DESTINATION_OU,$TARGET_OU,$Get_OU,$BTN_MOVE))

$Get_OU.Add_Click({ GetSiteOUs })
$BTN_MOVE.Add_Click({ doit })

#region Logic 
function GetSiteOUs  {
  $DESTINATION_OU.Text = Get-ADOrganizationalUnit -Filter "Name -Like '*$($LOCATION.Text.Trim())*'" |
        Select-Object -ExpandProperty 'Distinguishedname' |
        Out-GridView -PassThru -Title "Select the OU"
        
         }
         

function doit{
$DEVICE = $TBX_APDEVICE.TEXT
$DestOU = "OU=$DESTINATION_OU.text,OU=Computers,OU=World,OU=Disney,OU=Goofy,OU=Duck,OU=Donald,DC=Mickey,DC=Mouse,"

Move-ADObject –Identity "CN=$Device,OU=Autopilot,OU=Lucy,OU=linus,OU=Brown,OU=charlie,DC=Mickey,DC=Mouse," -TargetPath $DestOU
}
#endregion

[void]$Form.ShowDialog()


How do I send a task log within a release from an azure devops deployment pipeline to a Microsoft teams channel?

A MS teams channel has been configured to notify us after the last stage (prod deployment) in an azure devops pipeline has completed. However, there is a need to include SQL execution statistics like rows affected, duration etc. which I'm capturing in the logs in the release pipeline. Is there way to extract that single task log within a stage in the pipeline and post it to the teams channel?

Currently I'm offering stakeholders the ability to click on the link that takes them to the release within ADO and view the log that way. But I would like to just offer the log on the teams channel and save people time and confusion. I'm including a couple links as reference as to what I have been looking at, the official MS documentation and another is a stack overflow thread with a similar question, but for slack.

If it is done with this api, how would I capture the taskId? I'm not fully understanding how to do this:

GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/{releaseId}/environments/{environmentId}/deployPhases/{releaseDeployPhaseId}/tasks/{taskId}/logs?api-version=5.0-preview.2


jq to report rolling differences between array element values

I have an input like below which just has stageIds, along with their submit and completion time in unix time seconds

[
  {
    "stageId": 1,
    "submitTime_epoch_secs": 5,
    "completionTime_epoch_secs": 10
  },
  {
    "stageId": 2,
    "submitTime_epoch_secs": 15,
    "completionTime_epoch_secs": 17
  },
  {
    "stageId": 3,
    "submitTime_epoch_secs": 29,
    "completionTime_epoch_secs": 30
  }
]

desired output is below, where each stageId, submit, and completion times are compared with previous and next and the delay is added as another key/val per element.

[
  {
    "stageId": 1,
    "submitTime_epoch_secs": 5,
    "completionTime_epoch_secs": 10,
    "delayTillNextStageSubmit",5
    "delayFromPrevStageComplete",null
  },
  {
    "stageId": 2,
    "submitTime_epoch_secs": 15,
    "completionTime_epoch_secs": 17,
    "delayTillNextStageSubmit",12
    "delayFromPrevStageComplete",5
  },
  {
    "stageId": 3,
    "submitTime_epoch_secs": 29,
    "completionTime_epoch_secs": 30,
    "delayTillNextStageSubmit",null
    "delayFromPrevStageComplete",12
  }
]

here the stageId 1 delayTillNextStageSubmit is difference between stageId 2 submitTime and stageId 1 completion time, 15 - 10 = 5.

is this possible with jq?

I am new to jq, so don't know how to solve this



how can i hash a specific tag from XML file in a correct way?

we are working on e-invoicing and to send the invoice to the government.

and they gave us what they want from us to do like signing some tags and hashing another.

my problem now is in hashing, when i hash the specific tag after doing every thing right and after that send it i get errors about hashing only.

and they gave us some samples, i took the sample and i took the tag that i face an error whan i hash it and try to hash it and compare it with its hash in the same file and i get different one , not the same.

i called them about this problem they said > you when you take the tag you are taking it in a wrong way.

the hash is : sha256

this is the invoice as XML:

<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"><ext:UBLExtensions>
    <ext:UBLExtension>
        <ext:ExtensionURI>urn:oasis:names:specification:ubl:dsig:enveloped:xades</ext:ExtensionURI>
        <ext:ExtensionContent>
            <!-- Please note that the signature values are sample values only -->
            <sig:UBLDocumentSignatures xmlns:sig="urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2" xmlns:sac="urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2" xmlns:sbc="urn:oasis:names:specification:ubl:schema:xsd:SignatureBasicComponents-2">
                <sac:SignatureInformation>
                    <cbc:ID>urn:oasis:names:specification:ubl:signature:1</cbc:ID>
                    <sbc:ReferencedSignatureID>urn:oasis:names:specification:ubl:signature:Invoice</sbc:ReferencedSignatureID>
                    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="signature">
                        <ds:SignedInfo>
                            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2006/12/xml-c14n11"/>
                            <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"/>
                            <ds:Reference Id="invoiceSignedData" URI="">
                                <ds:Transforms>
                                    <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
                                        <ds:XPath>not(//ancestor-or-self::ext:UBLExtensions)</ds:XPath>
                                    </ds:Transform>
                                    <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
                                        <ds:XPath>not(//ancestor-or-self::cac:Signature)</ds:XPath>
                                    </ds:Transform>
                                    <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
                                        <ds:XPath>not(//ancestor-or-self::cac:AdditionalDocumentReference[cbc:ID='QR'])</ds:XPath>
                                    </ds:Transform>
                                    <ds:Transform Algorithm="http://www.w3.org/2006/12/xml-c14n11"/>
                                </ds:Transforms>
                                <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                                <ds:DigestValue>RvCSpMYz8009KbJ3ku72oaCFWpzEfQNcpc+5bulh3Jk=</ds:DigestValue>
                            </ds:Reference>
                            <ds:Reference Type="http://www.w3.org/2000/09/xmldsig#SignatureProperties" URI="#xadesSignedProperties">
                                <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                                <ds:DigestValue>OGU1M2Q3NGFkOTdkYTRiNDVhOGZmYmU2ZjE0YzI3ZDhhNjlmM2EzZmQ4MTU5NTBhZjBjNDU2MWZlNjU3MWU0ZQ==</ds:DigestValue>
                            </ds:Reference>
                        </ds:SignedInfo>
                        <ds:SignatureValue>MEYCIQDYsDnviJYPgYjyCIYAyzETeYthIoJaQhChblP4eAAPPAIhAJl6zfHgiKmWTtsfUz8YBZ8QkQ9rBL4Uy7mK0cxvWooH</ds:SignatureValue>
                        <ds:KeyInfo>
                            <ds:X509Data>
                                <ds:X509Certificate>MIID6TCCA5CgAwIBAgITbwAAf8tem6jngr16DwABAAB/yzAKBggqhkjOPQQDAjBjMRUwEwYKCZImiZPyLGQBGRYFbG9jYWwxEzARBgoJkiaJk/IsZAEZFgNnb3YxFzAVBgoJkiaJk/IsZAEZFgdleHRnYXp0MRwwGgYDVQQDExNUU1pFSU5WT0lDRS1TdWJDQS0xMB4XDTIyMDkxNDEzMjYwNFoXDTI0MDkxMzEzMjYwNFowTjELMAkGA1UEBhMCU0ExEzARBgNVBAoTCjMxMTExMTExMTExDDAKBgNVBAsTA1RTVDEcMBoGA1UEAxMTVFNULTMxMTExMTExMTEwMTExMzBWMBAGByqGSM49AgEGBSuBBAAKA0IABGGDDKDmhWAITDv7LXqLX2cmr6+qddUkpcLCvWs5rC2O29W/hS4ajAK4Qdnahym6MaijX75Cg3j4aao7ouYXJ9GjggI5MIICNTCBmgYDVR0RBIGSMIGPpIGMMIGJMTswOQYDVQQEDDIxLVRTVHwyLVRTVHwzLWE4NjZiMTQyLWFjOWMtNDI0MS1iZjhlLTdmNzg3YTI2MmNlMjEfMB0GCgmSJomT8ixkAQEMDzMxMTExMTExMTEwMTExMzENMAsGA1UEDAwEMTEwMDEMMAoGA1UEGgwDVFNUMQwwCgYDVQQPDANUU1QwHQYDVR0OBBYEFDuWYlOzWpFN3no1WtyNktQdrA8JMB8GA1UdIwQYMBaAFHZgjPsGoKxnVzWdz5qspyuZNbUvME4GA1UdHwRHMEUwQ6BBoD+GPWh0dHA6Ly90c3RjcmwuemF0Y2EuZ292LnNhL0NlcnRFbnJvbGwvVFNaRUlOVk9JQ0UtU3ViQ0EtMS5jcmwwga0GCCsGAQUFBwEBBIGgMIGdMG4GCCsGAQUFBzABhmJodHRwOi8vdHN0Y3JsLnphdGNhLmdvdi5zYS9DZXJ0RW5yb2xsL1RTWkVpbnZvaWNlU0NBMS5leHRnYXp0Lmdvdi5sb2NhbF9UU1pFSU5WT0lDRS1TdWJDQS0xKDEpLmNydDArBggrBgEFBQcwAYYfaHR0cDovL3RzdGNybC56YXRjYS5nb3Yuc2Evb2NzcDAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMDMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwIwCgYIKwYBBQUHAwMwCgYIKoZIzj0EAwIDRwAwRAIgOgjNPJW017lsIijmVQVkP7GzFO2KQKd9GHaukLgIWFsCIFJF9uwKhTMxDjWbN+1awsnFI7RLBRxA/6hZ+F1wtaqU</ds:X509Certificate>
                            </ds:X509Data>
                        </ds:KeyInfo>
                        <ds:Object>
                            <xades:QualifyingProperties xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" Target="signature">
                                <xades:SignedProperties Id="xadesSignedProperties">
                                    <xades:SignedSignatureProperties>
                                        <xades:SigningTime>2022-09-15T00:41:21Z</xades:SigningTime>
                                        <xades:SigningCertificate>
                                            <xades:Cert>
                                                <xades:CertDigest>
                                                    <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                                                    <ds:DigestValue>YTJkM2JhYTcwZTBhZTAxOGYwODMyNzY3NTdkZDM3YzhjY2IxOTIyZDZhM2RlZGJiMGY0NDUzZWJhYWI4MDhmYg==</ds:DigestValue>
                                                </xades:CertDigest>
                                                <xades:IssuerSerial>
                                                    <ds:X509IssuerName>CN=TSZEINVOICE-SubCA-1, DC=extgazt, DC=gov, DC=local</ds:X509IssuerName>
                                                    <ds:X509SerialNumber>2475382886904809774818644480820936050208702411</ds:X509SerialNumber>
                                                </xades:IssuerSerial>
                                            </xades:Cert>
                                        </xades:SigningCertificate>
                                    </xades:SignedSignatureProperties>
                                </xades:SignedProperties>
                            </xades:QualifyingProperties>
                        </ds:Object>
                    </ds:Signature>
                </sac:SignatureInformation>
            </sig:UBLDocumentSignatures>
        </ext:ExtensionContent>
    </ext:UBLExtension>
</ext:UBLExtensions>
    
    <cbc:ProfileID>reporting:1.0</cbc:ProfileID>
    <cbc:ID>SME00010</cbc:ID>
    <cbc:UUID>8e6000cf-1a98-4174-b3e7-b5d5954bc10d</cbc:UUID>
    <cbc:IssueDate>2022-08-17</cbc:IssueDate>
    <cbc:IssueTime>17:41:08</cbc:IssueTime>
    <cbc:InvoiceTypeCode name="0200000">388</cbc:InvoiceTypeCode>
    <cbc:Note languageID="ar">ABC</cbc:Note>
    <cbc:DocumentCurrencyCode>SAR</cbc:DocumentCurrencyCode>
    <cbc:TaxCurrencyCode>SAR</cbc:TaxCurrencyCode>
    <cac:AdditionalDocumentReference>
        <cbc:ID>ICV</cbc:ID>
        <cbc:UUID>10</cbc:UUID>
    </cac:AdditionalDocumentReference>
    <cac:AdditionalDocumentReference>
        <cbc:ID>PIH</cbc:ID>
        <cac:Attachment>
            <cbc:EmbeddedDocumentBinaryObject mimeCode="text/plain">NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==</cbc:EmbeddedDocumentBinaryObject>
        </cac:Attachment>
    </cac:AdditionalDocumentReference>
    
    
    <cac:AdditionalDocumentReference>
        <cbc:ID>QR</cbc:ID>
        <cac:Attachment>
            <cbc:EmbeddedDocumentBinaryObject mimeCode="text/plain">ARNBY21lIFdpZGdldOKAmXMgTFREAg8zMTExMTExMTExMDExMTMDFDIwMjItMDgtMTdUMTc6NDE6MDhaBAYyMzEuMTUFBTMwLjE1BixSdkNTcE1ZejgwMDlLYkoza3U3Mm9hQ0ZXcHpFZlFOY3BjKzVidWxoM0prPQdgTUVZQ0lRRFlzRG52aUpZUGdZanlDSVlBeXpFVGVZdGhJb0phUWhDaGJsUDRlQUFQUEFJaEFKbDZ6ZkhnaUttV1R0c2ZVejhZQlo4UWtROXJCTDRVeTdtSzBjeHZXb29ICFgwVjAQBgcqhkjOPQIBBgUrgQQACgNCAARhgwyg5oVgCEw7+y16i19nJq+vqnXVJKXCwr1rOawtjtvVv4UuGowCuEHZ2ocpujGoo1++QoN4+GmqO6LmFyfRCUYwRAIgOgjNPJW017lsIijmVQVkP7GzFO2KQKd9GHaukLgIWFsCIFJF9uwKhTMxDjWbN+1awsnFI7RLBRxA/6hZ+F1wtaqU</cbc:EmbeddedDocumentBinaryObject>
        </cac:Attachment>
</cac:AdditionalDocumentReference><cac:Signature>
      <cbc:ID>urn:oasis:names:specification:ubl:signature:Invoice</cbc:ID>
      <cbc:SignatureMethod>urn:oasis:names:specification:ubl:dsig:enveloped:xades</cbc:SignatureMethod>
</cac:Signature><cac:AccountingSupplierParty>
        <cac:Party>
            <cac:PartyIdentification>
                <cbc:ID schemeID="CRN">324223432432432</cbc:ID>
            </cac:PartyIdentification>
            <cac:PostalAddress>
                <cbc:StreetName>الامير سلطان</cbc:StreetName>
                <cbc:BuildingNumber>3242</cbc:BuildingNumber>
                <cbc:PlotIdentification>4323</cbc:PlotIdentification>
                <cbc:CitySubdivisionName>32423423</cbc:CitySubdivisionName>
                <cbc:CityName>الرياض | Riyadh</cbc:CityName>
                <cbc:PostalZone>32432</cbc:PostalZone>
                <cac:Country>
                    <cbc:IdentificationCode>SA</cbc:IdentificationCode>
                </cac:Country>
            </cac:PostalAddress>
            <cac:PartyTaxScheme>
                    <cbc:CompanyID>311111111101113</cbc:CompanyID>
                <cac:TaxScheme>
                    <cbc:ID>VAT</cbc:ID>
                </cac:TaxScheme>
            </cac:PartyTaxScheme>
            <cac:PartyLegalEntity>
                <cbc:RegistrationName>Acme Widget’s LTD</cbc:RegistrationName>
            </cac:PartyLegalEntity>
        </cac:Party>
    </cac:AccountingSupplierParty>
    <cac:AccountingCustomerParty>
        <cac:Party>
            <cac:PostalAddress>
                <cbc:StreetName/>
                <cbc:CitySubdivisionName>32423423</cbc:CitySubdivisionName>
                <cac:Country>
                    <cbc:IdentificationCode>SA</cbc:IdentificationCode>
                </cac:Country>
            </cac:PostalAddress>
            <cac:PartyTaxScheme>
                <cac:TaxScheme>
                    <cbc:ID>VAT</cbc:ID>
                </cac:TaxScheme>
            </cac:PartyTaxScheme>
            <cac:PartyLegalEntity>
                <cbc:RegistrationName/>
            </cac:PartyLegalEntity>
        </cac:Party>
    </cac:AccountingCustomerParty>
    <cac:PaymentMeans>
        <cbc:PaymentMeansCode>10</cbc:PaymentMeansCode>
    </cac:PaymentMeans>
    <cac:AllowanceCharge>
        <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
        <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason>
        <cbc:Amount currencyID="SAR">0.00</cbc:Amount>
        <cac:TaxCategory>
            <cbc:ID schemeID="UN/ECE 5305" schemeAgencyID="6">S</cbc:ID>
            <cbc:Percent>15</cbc:Percent>
            <cac:TaxScheme>
                <cbc:ID schemeID="UN/ECE 5153" schemeAgencyID="6">VAT</cbc:ID>
            </cac:TaxScheme>
        </cac:TaxCategory>
        <cac:TaxCategory>
            <cbc:ID schemeID="UN/ECE 5305" schemeAgencyID="6">S</cbc:ID>
            <cbc:Percent>15</cbc:Percent>
            <cac:TaxScheme>
                <cbc:ID schemeID="UN/ECE 5153" schemeAgencyID="6">VAT</cbc:ID>
            </cac:TaxScheme>
        </cac:TaxCategory>
    </cac:AllowanceCharge>
    <cac:TaxTotal>
        <cbc:TaxAmount currencyID="SAR">30.15</cbc:TaxAmount>
    </cac:TaxTotal>
    <cac:TaxTotal>
        <cbc:TaxAmount currencyID="SAR">30.15</cbc:TaxAmount>
        <cac:TaxSubtotal>
            <cbc:TaxableAmount currencyID="SAR">201.00</cbc:TaxableAmount>
            <cbc:TaxAmount currencyID="SAR">30.15</cbc:TaxAmount>
             <cac:TaxCategory>
                 <cbc:ID schemeID="UN/ECE 5305" schemeAgencyID="6">S</cbc:ID>
                 <cbc:Percent>15.00</cbc:Percent>
                <cac:TaxScheme>
                   <cbc:ID schemeID="UN/ECE 5153" schemeAgencyID="6">VAT</cbc:ID>
                </cac:TaxScheme>
             </cac:TaxCategory>
        </cac:TaxSubtotal>
    </cac:TaxTotal>
    <cac:LegalMonetaryTotal>
        <cbc:LineExtensionAmount currencyID="SAR">201.00</cbc:LineExtensionAmount>
        <cbc:TaxExclusiveAmount currencyID="SAR">201.00</cbc:TaxExclusiveAmount>
        <cbc:TaxInclusiveAmount currencyID="SAR">231.15</cbc:TaxInclusiveAmount>
        <cbc:AllowanceTotalAmount currencyID="SAR">0.00</cbc:AllowanceTotalAmount>
        <cbc:PrepaidAmount currencyID="SAR">0.00</cbc:PrepaidAmount>
        <cbc:PayableAmount currencyID="SAR">231.15</cbc:PayableAmount>
    </cac:LegalMonetaryTotal>
    <cac:InvoiceLine>
        <cbc:ID>1</cbc:ID>
        <cbc:InvoicedQuantity unitCode="PCE">33.000000</cbc:InvoicedQuantity>
        <cbc:LineExtensionAmount currencyID="SAR">99.00</cbc:LineExtensionAmount>
        <cac:TaxTotal>
             <cbc:TaxAmount currencyID="SAR">14.85</cbc:TaxAmount>
             <cbc:RoundingAmount currencyID="SAR">113.85</cbc:RoundingAmount>
        </cac:TaxTotal>
        <cac:Item>
            <cbc:Name>كتاب</cbc:Name>
            <cac:ClassifiedTaxCategory>
                <cbc:ID>S</cbc:ID>
                <cbc:Percent>15.00</cbc:Percent>
                <cac:TaxScheme>
                    <cbc:ID>VAT</cbc:ID>
                </cac:TaxScheme>
            </cac:ClassifiedTaxCategory>
        </cac:Item>
        <cac:Price>
            <cbc:PriceAmount currencyID="SAR">3.00</cbc:PriceAmount>
            <cac:AllowanceCharge>
               <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
               <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason>
               <cbc:Amount currencyID="SAR">0.00</cbc:Amount>
            </cac:AllowanceCharge>
        </cac:Price>
    </cac:InvoiceLine>
    <cac:InvoiceLine>
        <cbc:ID>2</cbc:ID>
        <cbc:InvoicedQuantity unitCode="PCE">3.000000</cbc:InvoicedQuantity>
        <cbc:LineExtensionAmount currencyID="SAR">102.00</cbc:LineExtensionAmount>
        <cac:TaxTotal>
             <cbc:TaxAmount currencyID="SAR">15.30</cbc:TaxAmount>
             <cbc:RoundingAmount currencyID="SAR">117.30</cbc:RoundingAmount>
        </cac:TaxTotal>
        <cac:Item>
            <cbc:Name>قلم</cbc:Name>
            <cac:ClassifiedTaxCategory>
                <cbc:ID>S</cbc:ID>
                <cbc:Percent>15.00</cbc:Percent>
                <cac:TaxScheme>
                    <cbc:ID>VAT</cbc:ID>
                </cac:TaxScheme>
            </cac:ClassifiedTaxCategory>
        </cac:Item>
        <cac:Price>
            <cbc:PriceAmount currencyID="SAR">34.00</cbc:PriceAmount>
            <cac:AllowanceCharge>
               <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
               <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason>
               <cbc:Amount currencyID="SAR">0.00</cbc:Amount>
            </cac:AllowanceCharge>
        </cac:Price>
    </cac:InvoiceLine>
</Invoice>

and the specific tag that i need to take it in a correct way and hash it it is :

xades:SignedProperties this is its ID: Id="xadesSignedProperties"

when i hash the tag and encode it into base64 it needs to be same like this result:

OGU1M2Q3NGFkOTdkYTRiNDVhOGZmYmU2ZjE0YzI3ZDhhNjlmM2EzZmQ4MTU5NTBhZjBjNDU2MWZlNjU3MWU0ZQ==

because it is the result in the sample.


what i have tried is:

i did a cancocalization on the XML file using Python Code after that i had taken the tag and took the hash of it and encode it into base64 and this is my Code:

import lxml.etree as ET
import hashlib
import base64


et = ET.parse("sample_Invoice.xml")

et.write_c14n("my_xml_file.xml")


my_xml = open("my_xml_file.xml","rb")
my_xml_result = my_xml.read().decode()

# i will split the tag that is before <xades:SignedProperties Id="xadesSignedProperties">
# to get the <xades:SignedProperties Id="xadesSignedProperties"> and the rest
SignedProperties_1 = my_xml_result.split('<xades:QualifyingProperties xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" Target="signature">')[-1]

# i will split the tag that is after <xades:SignedProperties Id="xadesSignedProperties">
# to get the specific tag that i want only
SignedProperties_final = SignedProperties_1.split("</xades:QualifyingProperties>")[0]


# i will take the hash as hex
hashed_tag = hashlib.sha256(SignedProperties_final.encode()).hexdigest()

print(hashed_tag)

# i will encode the hex code into base64
print(base64.b64encode(hashed_tag.encode()))

this is my result:

ZjcyZjUyNmFmYmY0ZGRmYWM2NDBlNzljYWVlZWNjOTM5ZjU4ZTY4ZTA3Y2JjM2Q0NzA4MzgwY2ZmOWM2ZTAzMw==

they are not the same at all.

i do not know what is the wrong.



2023-01-30

How to delete object from array when removed from DOM/HTML

I'm creating a library Web application that allows you to click a button that brings up a form to add a book via title, author, pages, and if you've read it or not. Each form input gets added to a "card" in the document via createElement/appendChild and also gets added to the myLibrary array via a constructor function. Here's my script:

const modal = document.getElementById("myModal");
const btn = document.getElementById("newBook");
const modalBtn = document.getElementById("modal-btn");
const title = document.getElementById("title");
const author = document.getElementById("author");
const pages = document.getElementById("pages");
const haveRead = document.getElementById("have-read");
const span = document.getElementsByClassName("close");
const cards = document.getElementById("cards");

let myLibrary = [];

// Book Constructor
function Book(title, author, pages, haveRead) {
  (this.title = title),
    (this.author = author),
    (this.pages = pages),
    (this.haveRead = haveRead);

  if (alreadyInLibrary(title)) {
    return alert("Sorry, it looks like this book is already in your library");
  }
  addBooKToLibrary(this);
}

// Adds book to array
const addBooKToLibrary = function (book) {
  myLibrary.push(book);
};

const book1 = new Book("Harry Potter", "J.K. Rowling", 123, "Unread");
const book2 = new Book("LotR", "J.R.R. Tolkien", 4214, "Read");
const book3 = new Book("No Country for Old Men", "Cormac McCarthy", 575, "Unread");

// Creates books for each card in the DOM
createCard = function () {
  cards.innerHTML = "";
  myLibrary.forEach((book) => {
    let html = `<div class="card"><p>${book.title}</p><p>${book.author}</p><p>${book.pages}</p><p>${book.haveRead}</p><button class="remove-btn" onclick="deleteBook(this)">Delete</div>`;
    cards.innerHTML += html;
  });
};

// Checks the array for already registered books
function alreadyInLibrary(title) {
  return myLibrary.some(function (el) {
    return el.title === title;
  });
}

modalBtn.addEventListener("click", function (event) {
  event.preventDefault();
  const book = new Book(title.value, author.value, pages.value, haveRead.value);
  modal.style.display = "none";
  createCard();
});

I've added a "Delete" button to each book's card that calls a function to remove itself from the document:

function deleteBook(el) {
  const element = el;
  element.parentNode.remove();
}

However, the book stays in the array even after the card is deleted, and I can't figure out how to implement a function that deletes the object from the array if it's not found in the document.

I've tried adding a unique ID to each book object in the myLibrary array to target the object with to delete it from the array, but couldn't get that to work. I've tried looping through the array and using an if statement to see if myLibrary.title === book.title, else remove it from the array, but that's not working either.



How to disable `Back` gesture in `NavigationView`?

I need to disallow the Back swipe gesture in a view that has been "pushed" in a SwiftUI NavigationView.

I am using the navigationBarBackButtonHidden(true) view modifier from the "pushed" view, which obviously hides the standard Back button, and partially solves for the requirement.

But users cans still swipe from left to right (going back), which I don't want to allow.

I have tried using interactiveDismissDisabled, but this only disables swiping down to dismiss, not "back".

Any suggestions welcome.

[UPDATE] I tried creating a new app with Xcode 14.2, and the navigationBarBackButtonHidden(true) worked as expected:

  1. No back button
  2. Back swipe gesture disabled

But when I modified the main class of my existing app, it still allowed the back swipe gesture. Here's the code:

import SwiftUI

@main
struct MyApp: App {
    
    var body: some Scene {
        WindowGroup {
            MyView()
        }
    }
}

struct MyView: View {
    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink("Next page") {
                    Text("Page 2")
                        .navigationBarBackButtonHidden(true)
                }
            }
        }
    }
}

At this point, I'm fairly confused. Recreating my existing project, that was created with Xcode 13 will be a substantial task, so I'm trying to figure out what's different. I'm assuming that there is some build setting or configuration option that is somehow influencing this behavior.

Again, any suggestions welcome



Docker Compose: omitting directory /config/certs.yml, ERROR: no configuration file found

I am trying to use Docker Desktop to run this tutorial to install wazuh in a docker container (single-node deployment). I make a new container in the docker desktop and then try to run the docker compose command in vscode but get the error mentioned in the title. I have tried to change the project directory but it always points to the root directory by /config/certs.yml. my command is

docker-compose --project-directory /com.docker.devenvironments.code/single-node --file /com.docker.devenvironments.code/single-node/generate-indexer-certs.yml run --rm generator

my directory structure is as follows:

enter image description here

where certs.yml is in the config folder, but upon running this command the error always points to the root folder, which is not my project folder. The only folder i want to run this from is the com.docker.devenvironments.code folder, or somehow change where the command finds the certs.yml file. I have also tried cd into different folders and trying to run the command, but get the same error.

Thank you very much in advance for your help!



How it works when I use Play Asset Delivery without any settings?

I'm using Unity 2021.3.14 to create an Android mobile game. I looked up this document on Play Asset Delivery because the game is over 150mb.

There was a sentence like this.

Generated asset packs

Asset packs have download size limits. 
To account for this, Unity changes how it generates asset packs depending on the size of your additional assets:

If the additional assets take less than 1GB of storage,
Unity packs everything into a single asset pack with the install-time delivery mode.
If you do not create any custom asset packs,
this means that the device downloads the asset pack as part of the application installation and,
when the user first launches the application,
all assets are available.

Could you check if the following is correct based on what I understood?

  1. If an app of less than 1GB and build with Play Asset Delivery without configuration, it operates in install-time mode and is downloaded together when the user first runs the application.
  2. After the installation is completed in the above manner, can I use them without additional code that connects resources inside the game?

The above question may be awkward because I am not familiar with English. I apologize in advance for that. Thank you for reading the question and have a nice day.



Highlight borders of the nation

When I search for a country I would like the borders to be highlighted on the map.

I don't know how to do with openstreetmap , leaflet and react

Demo: Countries App



2023-01-29

Docker with Redis via Procfile.dev in iTerm2 output is unreadable

This is a bit of a strange one and I can't find answers anywhere else... if I have a Procfile.dev file with a basic Redis command in it such as redis: docker run --rm -it -p 6379:6379 redis:latest and run it via bin/dev the output from the Redis ascii art makes the logs unreable. If I remove the Redis command from the Procfile.dev it goes back to being neat and readable, below is an example of the messed up output:

Docker running via bin/dev via a Procfile.dev

Does anyone know how to make this look nice? I'm having to run docker outside the procfile atm because of this.

This is a Ruby on Rails 7 app running via bin/dev, if that is relevant.



Having multiple fetching strategies (LAZY, EAGER) by custom condition

I have one entity class, which consists of multiple foreign key constraints, which are handled by ManyToMany etc.

public class MyExampleClazz {
.......

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "secondClazzEntities", joinColumns = @JoinColumn(name = "id"),
        inverseJoinColumns = @JoinColumn(name = "id"))
List<MySecondClazz> secondClazz;
  
.....
}

For some cases, I would like to change the fetching strategy from e.g. from EAGER to LAZY and vice versa, because for some read operations, I don't need EAGER fetching (imagine a RESTful service , which offers only some small portion of data and not everything) but in most cases I need EAGER instead. One option could be introduce an entity (for same table) but different annotation, but it would duplicate code and effort in regards of maintenance.

Are there other ways present, to achive the same result by doing less?



Adjusted mean and mean test for multiple regression in R

I formed a multiple linear regression model:

corona_soz <- lm(LZ~age  + belastet_SZ + belastet_SNZ + guteSeiten_SZ + guteSeiten_SNZ + Zufriedenh_EW + Zufriedenh_BZ + SES_3, data = MF, subset = (sex == 1))
summary(corona_soz)

For this model, I would like to calculate the adjusted mean. For this I have already used the package emmeans. I would like to calculate the adjusted mean for the respective sex (men: sex == 1, women: sex == 2). For this, I also formed an extra regression model again, since sex is already included in the subset in the model above.

mean_MF <- lm(LZ~age  + belastet_SZ + belastet_SNZ + guteSeiten_SZ + guteSeiten_SNZ + Zufriedenh_EW + Zufriedenh_BZ + SES_3, data = MF)
summary(mean_MF)

Then I wanted to calculate the mean value:

emmeans(mean_MF, ~ sex)

And received the following message:

> emmeans(mean_MF, ~ sex)
Error in emmeans(mean_MF, ~sex) : 
  No variable named sex in the reference grid

Is there any other way or simple solution for this? I have also tried various other ways, but unfortunately do not understand where the problem lies.

In addition, I would like to perform a mean test to determine significant differences in the mean values (mean and adjusted mean) and unfortunately I can't find anything suitable.

! How do I handle it if I want to get the emmeans from 3 expressions instead of 2 as in the example above (sex: males == 1, females ==2)? So f.e. the number of children coded as follows (Kinder_A):

  • 1child: 1
  • 2 children: 2
  • ≥3 children: 3
> F_AKind_scor <- lm(LZ~age + belastet_SZ + belastet_SNZ + guteSeiten_SZ + guteSeiten_SNZ + Zufriedenh_EW + Zufriedenh_BZ + SES_3 + Kinder_A, data = Frauen)

Because when I run the code, I only get one EEM instead of 3 EEM's for my 3 expressions (1,2,3).

> emmeans(F_AKind_scor, ~ Kinder_A)
 Kinder_A emmean     SE    df lower.CL upper.CL
      1.2   6.96 0.0223 11415     6.92        7

In addition, I would like to perform a mean test to determine significant differences in the mean values (mean and adjusted mean) and unfortunately I can't find anything suitable.



gdalcubes create_image_collection() results in R session Abort after interrupting it

I want to use gdalcubes in order to create a datacube structure in R from locally safe remote sensing data time series. I have tried it on a big data set (~5GB) and the create_image_collection function started, but the process was very slow (11% after three hours) and I couldn't barely use my computer while it was runinng. Therefore, I interrupted the process in a very brutal way (holding power button).
This seems to have been a big mistake, because now the function always result in a 'R Session Abort', even when calling it on a much smaller dataset. I unistalled gdalcubes and reinstalled it, but nothing has changed. Are there any files I could delete or directories to reset in order to make it work again? I fear there are some files left anywhere in the directory structure that may cause this, but I really don't have no idea of these structures. Thanks for any help, I really need this package! See question on GitHub: https://github.com/appelmar/gdalcubes_R/issues/78

> sessionInfo()
R version 4.2.2 (2022-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)

Matrix products: default

locale:
[1] LC_COLLATE=German_Germany.utf8  LC_CTYPE=German_Germany.utf8    LC_MONETARY=German_Germany.utf8 LC_NUMERIC=C                    LC_TIME=German_Germany.utf8    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] RPostgres_1.4.4

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.9       rstudioapi_0.14  raster_3.6-14    knitr_1.41       hms_1.1.2        rappdirs_0.3.3   bit_4.0.5        here_1.0.1       lattice_0.20-45  rlang_1.0.6     
[11] fastmap_1.1.0    blob_1.2.3       tools_4.2.2      grid_4.2.2       xfun_0.36        png_0.1-8        terra_1.6-53     cli_3.4.1        DBI_1.1.3        htmltools_0.5.4 
[21] ellipsis_0.3.2   yaml_2.3.6       digest_0.6.31    bit64_4.0.5      rprojroot_2.0.3  lifecycle_1.0.3  Matrix_1.5-1     codetools_0.2-18 vctrs_0.5.1      evaluate_0.20   
[31] rmarkdown_2.20   sp_1.5-1         compiler_4.2.2   reticulate_1.26  jsonlite_1.8.4   pkgconfig_2.0.3 


How to copy a method from an existing assembly to a dynamic assembly in .NET Core?

I want to somehow add a method from an on disk assembly to an assembly I am generating, I am creating the assembly via the System.Reflection.Emit and saving it to a file using the Lokad.ILPack nuget package and loading it with AssemblyLoadContext since this is .NET 7 Core, the on disk assembly is also generated.

I would like to avoid using externals libraries, but I understand that it may not be plausible using the standard library, and I can't use something like Pinvoke because the assembly might not even exist when the method call is needed, also if the answer requires copying the type containing the method then that's fine.

Example of how I am creating the assembly:

public static void CreateMethod(string destDllPath)
{
    AssemblyName asmName = new AssemblyName("CAssembly");

    AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);
    //Its RunAndCollect because if the AssemblyLoadContext fails to unload it will do so automatically

    ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("CModule");

    TypeBuilder typeBuilder = modBuilder.DefineType("CType", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed);
    //Abstract | Sealed means that the class is static

    MethodBuilder methodBuilder = typeBuilder.DefineMethod("CMethod",
        MethodAttributes.Static | MethodAttributes.Public,
        CallingConventions.Standard,
        typeof(bool),
        new[] { typeof(bool) });


    ILGenerator ILG = methodBuilder.GetILGenerator();

    ILG.Emit(OpCodes.Ldarg_0);
    //Push the first argument onto the evaluation stack
    ILG.Emit(OpCodes.Ret);
    //Return the first element from the evaluation stack

    _ = typeBuilder.CreateType();

    AssemblyGenerator asmGenerator = new AssemblyGenerator();
    asmGenerator.GenerateAssembly(asmBuilder, destDllPath);
}

Then using the method generated above

public static void CopyMethod(AssemblyBuilder toAssembly, string fromDllPath)
{
    string typeName = "CType";
    string methodName = "CMethod";

    Assembly fromAssembly = Assembly.LoadFile(fromDllPath);
    //note that the assembly at fromDllPath is created via MethodBuilder ILGenerator and Lokad.ILPack

    Type type = fromAssembly.GetType(typeName)!;

    MethodInfo method = type.GetMethod(methodName)!;

    //to test that the generated assembly is valid
    //bool testTesult = (bool)method.Invoke(null, new object[] { true });

    //somehow add method to toAssembly?
}

This is where I run into the problem of not knowing how to add the method to the assembly

I have spend a solid few days trying the find a solution to this problem, but there doesn't seem to be al ot of information on dynamic assembly creation in .NET Core 5 through 7.



2023-01-28

How to change the style of a Lit Element when a certain event is triggered?

(New to the Lit element environment, so apologies for the naive question)

Code Summary

The code below is a File Uploader web component made using Lit Element. When the File is selected, the _inputHandler function validates the file, and if valid, enables/triggers the upload functionality to the server side.

Question

How to set the #cancel-btn css styling to visibility:visible when the input file is selected?

(By default/when page loaded) As long as no file is selectedthe cancel button remains hidden.

The moment a valid file is selected, the Cancel button should Appear(visibility: visible or something)

The complete code for Uploader.ts :


import { html, LitElement, css } from "lit";
import { customElement, property, query } from "lit/decorators.js";

import { styles } from "./Style.Uploader.js";

@customElement("file-uploader")
export class Uploader extends LitElement {
  // CSS Styling
  static get styles() {
    return styles;
  }

  // Properties
  @property()
  fileName = `Accepted File Types : ${getValidFileTypes().toString()}`;

  @property() fileType = "";

  @property() fileSizeInKB: Number = 0;

  private files: FileList | null = null;

  // Actual html elements Rendered

  render() {
    return html`
      <section>
        <form action="" autocomplete="off" enctype="multipart/form-data">
          <h3>Upload your File</h3>
          <div class="box" id="box">
            <input
              type="file"
              name="uploadedFile"
              id="input-box"
              class="input-box"
              style="display: none"
              @change="${this._inputHandler}"
            />
            <label for="input-box" class="input-label" id="input-label">
              ${this.fileName}
            </label>
          </div>

          <div class="buttons">
            <button
              class="upload-btn"
              id="upload-btn"
              @click="${this._uploadHandler}"
            >
              <span class="upload-btn-span" id="upload-btn-span">
                &#8682; Upload
              </span>
              <span class="uploading-span" id="uploading-span">
                Uploading...
              </span>
            </button>

            <button
              class="cancel-btn"
              id="cancel-btn"
              @click="${this._cancelHandler}"
            >
              Cancel
            </button>
          </div>

        </form>
      </section>
    `;
  }

  @query("upload-btn") uploadButton!: HTMLButtonElement;

  get cancelButton() {
    return this.querySelector("#cancel-btn"); // ?? null
  }

  // @query("cancel-btn") cancelButton!: HTMLButtonElement;

  private async _inputHandler(e: Event) {
    const input = e.target as HTMLInputElement;

    // array of files selected to upload
    this.files = input.files;

    if (!(this.files && this.files[0])) {
      return;
    } else {
      const uploadedFileSize = this.files[0]?.size;
      const uploadedFileName = this.files[0]?.name;

      const uploadedFileType =
        FileExtensionService.getFileExtension(uploadedFileName);


      // Trying to Change the visibility of the Cancel button to visible
      this.cancelButton!.style.visibility = "visible";

      // Validating file size and file type
      const validFileSize = await validateFileSize(uploadedFileSize);
      const validFileType = await validateFileType(uploadedFileType);
      if (!validFileSize.isValid) {
          ...
      }
    }
  }

  /**
   *
   * @returns
   */
  private _cancelHandler(e: Event) {
    e.preventDefault();
    this.files = null;
    this.fileName = "";
    this.fileType = "";
    this.fileSizeInKB = 0;
    this.requestUpdate();
  }
}

I am trying to change the style of the button(Which i suppose i can grab with a getter or through @query) but getting an Error: Property 'style' does not exist on type 'Element'.ts(2339) for: this.cancelButton!.**style**.visibility = "visible";



how to apply colors to 1d array

I have a numpy array size of 20 and I want to give each element a color when plotting point cloud

data = np.array([1,2,3,4,5,6,7,8,9,10,20, 19, 18, 17, 16, 15, 14, 13,12,11])


colors # different colors 
colors[data]

I'd like to create colors so that every element of the array represent a color of the unspecified size of an array



React Native—react-native-dotenv error: api.addExternalDependency is not a function

I am using Expo (version: ~47.0.12) with React Native (version: 0.70.5), and I am unable to use the react-native-dotenv npm package. I have followed many tutorials, and they all result in this same error message:

./node_modules/expo/AppEntry.js
TypeError: [BABEL] /Users/jessicagallagher/projects/sfl/sfl-mobile/node_modules/expo/AppEntry.js: api.addExternalDependency is not a function (While processing: "/Users/jessicagallagher/projects/sfl/sfl-mobile/node_modules/react-native-dotenv/index.js")

The tutorials that I have used are basically blogs stating the same information from the docs.

This is my babel.config.js file:

module.exports = function(api) {
  api.cache(false);
  return {
    presets: ['babel-preset-expo'],
    plugins: ['module:react-native-dotenv'],
  };
};

I have also tried this in my babel.config.js file:

"plugins": [
    ["module:react-native-dotenv", {
      "moduleName": "@env",
      "path": ".env",
      "blocklist": null,
      "allowlist": null,
      "safe": false,
      "allowUndefined": true,
    }]
  ]

My .env file is the standard .env:

API_KEY='12345'

Here is my import statement to access the variable:

import { API_KEY } from '@env';

Normally in VS Code, when I start typing import { Something } from ', I will normally get suggestions from packages I have installed. That does not happen here when using @env—the suggestion does, however, show up when I import from 'react-native-dotenv', but I still get that same error message.

I've read a ton of GitHub issues and am just spinning my wheels at this point.



Invalid option in build() call: "watch"

I am following the example as it is described here:

https://bilalbudhani.com/chokidar-esbuild/

When I do:

node esbuild.config.js --watch

I get the message:

[ERROR] Invalid option in build() call: "watch"

I have no idea why this is happening.

Is "watch" not longer a parameter?

I also did this example:

const path = require('path')

require("esbuild").build({
  entryPoints: ["application.js", "client.js"],
  bundle: true,
  sourcemap: true,
  outdir: path.join(process.cwd(), "app/assets/builds"),
  absWorkingDir: path.join(process.cwd(), "app/javascript"),
  minify: true,
  watch: true,
})
.then(() => console.log("⚡Done"))
.catch(() => process.exit(1));

If i remove the line "watch:true", it compiles ok. But if I leave it, I get the same error:

Invalid option in build() call: "watch"

when I do: node esbuild.config.js

Thank you in advance



How to solve ArgumentException : The parameter is not valid for drawing Arcs

I'm making a custom winforms button in VB.Net with rounded edges and other features. I create a path using various inputs defined by the user and draw and fill it using pens and brushes.

When I call e.Graphics.FillEllipse(Brush1, Rect1) and e.Graphics.DrawEllips(Pen1, Rect1) it just works fine without any problems, but when I try e.Graphics.FillPath(Brush1, OuterPath) and e.Graphics.DrawPath(Pen1, OuterPath) it doesn't work at all. I get this error:

ArgumentException: The parameter is not valid

I tried giving the right types of each variable used in the process and not letting the compiler decide, creating more variables to calculate and manage the inputs individually to not make all the calculations in the inputs of each function, which makes my work easier honestly, and even using the CType function in the inputs of each function to make sure that the function understands what I want as inputs. But everything failed and I don't know what to do next to fix the issue.

Here is the code:

Private Sub MetaniumButton_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    Dim PathWidth As Integer = Width - BorderSize / 2
    Dim PathHeight As Integer = Height - BorderSize / 2

    _Roundnes = RoundnesMemory

    If PathHeight < Roundenes.Height Then
        _Roundnes.Height = PathHeight - 1
    End If

    If PathWidth < Roundenes.Width Then
        _Roundnes.Width = PathWidth - 1
    End If

    e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias

    Dim OuterPath As New GraphicsPath

    Dim Rec1 As Rectangle = New Rectangle(CType(BorderSize / 2, Int32), CType(BorderSize / 2, Int32), CType(_Roundnes.Width, Int32), CType(_Roundnes.Height, Int32))
    Dim Rec2 As Rectangle = New Rectangle(PathWidth - _Roundnes.Width, BorderSize / 2, _Roundnes.Width, _Roundnes.Height)
    Dim Rec3 As Rectangle = New Rectangle(PathWidth - _Roundnes.Width, PathHeight - _Roundnes.Height, _Roundnes.Width, _Roundnes.Height)
    Dim Rec4 As Rectangle = New Rectangle(BorderSize / 2, PathHeight - _Roundnes.Height, _Roundnes.Width, _Roundnes.Height)

    OuterPath.StartFigure()

    OuterPath.AddLine(CInt(_Roundnes.Width / 2 + BorderSize / 2), CInt(BorderSize / 2), CInt(PathWidth - _Roundnes.Width / 2), CInt(BorderSize / 2))
    OuterPath.AddArc(Rec1, 180.0, 90.0) ' Here is the problem and it could probably in any AddArc Function i used

    OuterPath.AddLine(PathWidth, CInt(_Roundnes.Height / 2 + BorderSize / 2), PathWidth, CInt(PathHeight - _Roundnes.Height / 2))
    OuterPath.AddArc(Rec2, -90, 90)

    OuterPath.AddLine(CInt(_Roundnes.Width / 2 + BorderSize / 2), PathHeight, CInt(PathWidth - _Roundnes.Width / 2), PathHeight)
    OuterPath.AddArc(Rec3, 0, 90)

    OuterPath.AddLine(CInt(BorderSize / 2), CInt(_Roundnes.Height / 2), CInt(BorderSize / 2), CInt(PathHeight - _Roundnes.Height / 2))
    OuterPath.AddArc(Rec4, 90, 90)

    OuterPath.CloseFigure()

    e.Graphics.FillPath(Brush1, OuterPath)
    e.Graphics.DrawPath(Pen1, OuterPath)

    Dim LabelCount As Integer = 0
    For Each l As Label In Controls
        LabelCount += 1
    Next
    Dim TextPlace As New Label With {.Name = "TextLabel",
                                     .Text = Text,
                                     .AutoEllipsis = True,
                                     .Size = New Size(Width -
 Margin.Left + Margin.Right + 2 * _Roundnes.Width) / 2, Height - (Margin.Top + Margin.Bottom + 2 * _Roundnes.Height) / 2),
                                     .TextAlign = _TextAlign,
                                     .ForeColor = _FontColor,
                                     .BackColor = _MetaniumBackColor,
                                     .Location = New Point((Width - .Width) / 2, (Height - .Height) / 2)}

    AddHandler TextPlace.TextChanged, AddressOf MetaniumButton_TextChanged
    AddHandler Me.TextChanged, AddressOf MetaniumButton_TextChanged
    Controls.Add(TextPlace)
    T += 1
    If LabelCount <= 0 Then
0:      For Each l As Label In Controls
            If l.Name = "TextLabel" Then
                l.Text = Text
                l.AutoEllipsis = True
                l.Size = New Size(Width - (Margin.Left + Margin.Right + 2 * _Roundnes.Width) / 2, Height - (Margin.Top + Margin.Bottom + 2 * _Roundnes.Height) / 2)
                l.TextAlign = _TextAlign
                l.ForeColor = _FontColor
                l.BackColor = _MetaniumBackColor
                l.Location = New Point((Width - l.Width) / 2, (Height - l.Height) / 2)
            End If
        Next
    ElseIf LabelCount = 1 Then
        For Each l As Label In Controls
            If l.Name <> "TextLabel" Then
                Controls.Remove(l)
            Else
                GoTo 1
            End If
1:          GoTo 0
        Next
    Else
    End If
End Sub

When I track down the bug it seems the problem is in the AddArc() function, and I really don't know why it doesn't work. Any help appreciated.

BTW, I use VB.Net Express 2010 with .Net Framework 4.8.

PS: you can post an answer using either VB.Net or C# I can translate the code from both of them.



2023-01-27

How to write Junit5 test cases in Springboot for apache camel Producer Template sendBodyAndHeader() to publish a json event to kafka

Need a help to write junit5 test case in springboot for a post api where it uses apache camel producer template to send message to kafka. Please find the controller class details for which junit test cases are required. Note-I don't have any service/repository layer for this.This is standalone controller which is responsible to publish message to kafka by using camel producer template.Thanks is advance.

Controller Class-->

`
`import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rms.inventory.savr.audit.model.AuditInfo;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MockKafkaProducerController {
  @Autowired ProducerTemplate producerTemplate;
  @Value("${audit.inbound.endpoint.kafka.uri:audit-json-topic}")
  private String auditTopicKafka;
  @Value("${camel.component.kafka.consumer.supply}")
  private String supplyLineUpdateKafkaTopic;
  @Value("${camel.component.kafka.consumer.demand}")
  private String demandLineUpdateKafkaTopic;
  @Value("${camel.component.kafka.consumer.supply-bucket}")
  private String supplybucketTopicKafka;
  @Value("${camel.component.kafka.consumer.demand-bucket}")
  private String demandbucketTopicKafka;
  @Value("${camel.component.kafka.consumer.availability}")
  private String availabilityTopicKafka;
  private Map<String, String> dataTypeTopicMap;
  @PostConstruct
  void init() {
    dataTypeTopicMap =
        Map.of(
            "SUPPLY_LINE",
            supplyLineUpdateKafkaTopic,
            "SUPPLY_BUCKET",
            supplybucketTopicKafka,
            "DEMAND_LINE",
            demandLineUpdateKafkaTopic,
            "DEMAND_BUCKET",
            demandbucketTopicKafka,
            "AVAILABILITY",
            availabilityTopicKafka);
  }
  @PostMapping("/api/mock/producer")
  public ResponseEntity<Boolean> saveAuditInfo(@RequestBody AuditInfo auditInfo)
  public ResponseEntity<Boolean> saveAuditInfo(
      @RequestBody AuditInfo auditInfo, @RequestHeader("AUDIT_TYPE") String auditType)
      throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    if (auditType == null || auditType.isEmpty()) {
      auditType = "SUPPLY_LINE";
    }
    String topicName = dataTypeTopicMap.get(auditType);
    //  producerTemplate.
    producerTemplate.sendBodyAndHeader(
        auditTopicKafka, objectMapper.writeValueAsString(auditInfo), "messageFormat", "CANONICAL");
        topicName, objectMapper.writeValueAsString(auditInfo), "messageFormat", "CANONICAL");
    return ResponseEntity.ok(Boolean.TRUE);
  }
  @PostMapping("/api/inventory/audit/mock/producer")
  public ResponseEntity<Boolean> publishInventoryAudit(@RequestBody String auditInfo)
  public ResponseEntity<Boolean> publishInventoryAudit(
      @RequestBody String auditInfo, @RequestHeader("AUDIT_TYPE") String auditType)
      throws JsonProcessingException {
    producerTemplate.sendBody(auditTopicKafka, auditInfo);
    if (auditType == null || auditType.isEmpty()) {
      auditType = "SUPPLY_LINE";
    }
    String topicName = dataTypeTopicMap.get(auditType);
    producerTemplate.sendBody(topicName, auditInfo);
    return ResponseEntity.ok(Boolean.TRUE);
  }
}`

`

I tried to mock producer template but not able to fix.



Can volatile variables be read multiple times between sequences points?

I'm making my own C compiler to try to learn as much details as possible about C. I'm now trying to understand exactly how volatile objects work.

What is confusing is that, every read access in the code must strictly be executed (C11, 6.7.3p7):

An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Therefore any expression referring to such an object shall be evaluated strictly according to the rules of the abstract machine, as described in 5.1.2.3. Furthermore, at every sequence point the value last stored in the object shall agree with that prescribed by the abstract machine, except as modified by the unknown factors mentioned previously.134) What constitutes an access to an object that has volatile-qualified type is implementation-defined.

Example : in a = volatile_var - volatile_var;, the volatile variable must be read twice and thus the compiler can't optimise to a = 0;

At the same time, the order of evaluation between sequence point is undetermined (C11, 6.5p3):

The grouping of operators and operands is indicated by the syntax. Except as specified later, side effects and value computations of subexpressions are unsequenced.

Example : in b = (c + d) - (e + f) the order in which the additions are evaluated is unspecified as they are unsequenced.

But evaluations of unsequenced objects where this evaluation creates a side effect (with volatile for instance), the behaviour is undefined (C11, 6.5p2):

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.

Does this mean the expressions like x = volatile_var - (volatile_var + volatile_var) is undefined ? Should my compiler throw an warning if this occurs ?

I've tried to see what CLANG and GCC do. Neither thow an error nor a warning. The outputed asm shows that the variables are NOT read in the execution order, but left to right instead as show in the asm risc-v asm below :

const int volatile thingy = 0;
int main()
{
    int new_thing = thingy - (thingy + thingy);
    return new_thing;
}
main:
        lui     a4,%hi(thingy)
        lw      a0,%lo(thingy)(a4)
        lw      a5,%lo(thingy)(a4)
        lw      a4,%lo(thingy)(a4)
        add     a5,a5,a4
        sub     a0,a0,a5
        ret

Edit: I am not asking "Why do compilers accept it", I am asking "Is it undefined behavior if we strictly follow the C11 standard". The standard seems to state that it is undefined behaviour, but I need more precision about it to correctly interpret that



Not able to run backpack on react by skyscanner

Getting the following error, the react app is not compiling at first I was facing and old SSL security error on nodeJS, thanks to stackoverflow I was able to fix that, but now I am facing this.

Failed to compile.

./node_modules/@skyscanner/backpack-web/bpk-component-button/src/BpkButton.js
SyntaxError: C:\Users\prantik\Desktop\SkyScanner Internship\my-app\node_modules\@skyscanner\backpack-web\bpk-component-button\src\BpkButton.js: Missing semicolon. (45:4)

Failed to compile.

./node_modules/@skyscanner/backpack-web/bpk-component-button/src/BpkButton.js
SyntaxError: C:\Users\prantik\Desktop\SkyScanner Internship\my-app\node_modules\@skyscanner\backpack-web\bpk-component-button\src\BpkButton.js: Unexpected token, expected "," (40:7)

  38 |
  39 | import {
> 40 |   type Props as CommonProps,
     |        ^
  41 |   propTypes,
  42 |   defaultProps,
  43 | } from '@skyscanner/backpack-web/bpk-component-button/src/common-types';   
    at parser.next (<anonymous>)
    at normalizeFile.next (<anonymous>)
    at run.next (<anonymous>)
    at transform.next (<anonymous>)

The BpkButton.js has the following code

import React from 'react';
import { BpkCode } from '@skyscanner/backpack-web/bpk-component-code';
import BpkButton from '@skyscanner/backpack-web/bpk-component-button';
import BpkText from '@skyscanner/backpack-web/bpk-component-text';

import { cssModules } from '@skyscanner/backpack-web/bpk-react-utils';

import STYLES from './App.scss';

const getClassName = cssModules(STYLES);

const App = () => (
  <div className={getClassName('App')}>
    <header className={getClassName('App__header')}>
      <div className={getClassName('App__header-inner')}>
        <BpkText tagName="h1" textStyle="xxl" className={getClassName('App__heading')}>Flight Schedule</BpkText>
      </div>
    </header>
    <main className={getClassName('App__main')}>
      <BpkText tagName="p" className={getClassName('App__text')}>
        To get started, edit <BpkCode>src/App.jsx</BpkCode> and save to reload.
      </BpkText>
      <BpkButton onClick={() => alert('It works!')}>Click me</BpkButton>
    </main>
  </div>
);

export default App;

I tried installing typescript, but dont know how to fix this.



All my TRPC queries fail with a 500. What is wrong with my setup?

I am new to TRPC and have set up a custom hook in my NextJS app to make queries. This hook is sending out a query to generateRandomWorker but the response always returns a generic 500 error. I am completely stuck until I can figure out this issue.

The hook:

// filepath: src\utilities\hooks\useCreateRandomWorker.ts

type ReturnType = {
    createWorker: () => Promise<Worker>,
    isCreating: boolean,
}

const useCreateRandomWorker = (): ReturnType => {

    const [isCreating, setIsCreating] = useState(false);

    const createWorker = async (): Promise<Worker> => {

        setIsCreating(true);

        const randomWorker: CreateWorker = await client.generateRandomWorker.query(null);

        const createdWorker: Worker = await client.createWorker.mutate(randomWorker);

        setIsCreating(false);

        return createdWorker;
    }

    return { createWorker, isCreating };

Here is the router. I know the WorkerService calls work because they are returning the proper values when passed into getServerSideProps which directly calls them. WorkerService.generateRandomWorker is synchronous, the others are async.

// filepath: src\server\routers\WorkerAPI.ts

export const WorkerRouter = router({
  generateRandomWorker: procedure
        .input(z.null()) // <---- I have tried completely omitting `.input` and with a `null` property
        .output(PrismaWorkerCreateInputSchema)
        .query(() => WorkerService.generateRandomWorker()),
  getAllWorkers: procedure
        .input(z.null())
        .output(z.array(WorkerSchema))
        .query(async () => await WorkerService.getAllWorkers()),
  createWorker: procedure
        .input(PrismaWorkerCreateInputSchema)
        .output(WorkerSchema)
        .mutation(async ({ input }) => await WorkerService.createWorker(input)),
});

The Next API listener is at filepath: src\pages\api\trpc\[trpc].ts

When the .input is omitted the request URL is /api/trpc/generateRandomWorker?batch=1&input={"0":{"json":null,"meta":{"values":["undefined"]}}} and returns a 500.

When the .input is z.null() the request URL is /api/trpc/generateRandomWorker?batch=1&input={"0":{"json":null}} and returns a 500.

Can anyone help on what I might be missing?

Additional Info

The client declaration.

// filepath: src\utilities\trpc.ts

export const client = createTRPCProxyClient<AppRouter>({
    links: [
        httpBatchLink({
            url: `${getBaseUrl() + trpcUrl}`, // "http://localhost:3000/api/trpc"
            fetch: async (input, init?) => {
                const fetch = getFetch();
                return fetch(input, {
                    ...init,
                    credentials: "include",
                })
            }
        }),
    ],
    transformer: SuperJSON,
});

The init:

// filepath: src\server\trpc.ts

import SuperJSON from "superjson";
import { initTRPC } from "@trpc/server";

export const t = initTRPC.create({
    transformer: SuperJSON,
});

export const { router, middleware, procedure, mergeRouters } = t;


Add text label with semi transparent background to an image using Magick.NET

I have some C# code that adds a simple text overlay with a border and semi-transparent background to an image. It works great, but I'm trying to get an equivalent result using Magick.NET. (The straight C# code drops the XMP tags from the original image, and I haven't found a way to deal with that.) Magick.NET handles the XMP tags well, but I'm having trouble replicating the original output.

Original code follows:

using (Image i = Image.FromStream(stream))
{
  int width = i.Width;
  int height = i.Height;

  using (Graphics graphics =  Graphics.FromImage(i))
  {
    string measureString = "my string";
    Size stringSize = graphics.MeasureString(measureString, stringFont).ToSize();
      
    Point drawLocation = new Point(width - stringSize.Width - 15, height - stringSize.Height - 15);
    Rectangle rect = new Rectangle(drawLocation.X, drawLocation.Y, stringSize.Width, stringSize.Height);
      
    graphics.DrawRectangle(blackPen, rect);
    graphics.FillRectangle(fillBrush, rect);
    graphics.DrawString(measureString, stringFont, Brushes.Yellow, drawLocation);
  }
  i.Save(outputFolder + Path.GetFileName(imgFileName));
}

I cobbled this together based on the Magick.NET examples. This get close to what I'm looking for, but adding the border removes the transparency value, and I'm left with a dark gray background, instead of the transparency.

 var settings = new MagickReadSettings{
                Font = "Calibri",
                FillColor=MagickColors.Yellow,
                StrokeColor=MagickColors.Black,
                TextGravity = Gravity.Center,
                BackgroundColor = new MagickColor("#66666699"),
                BorderColor = MagickColors.Black,
                Height = 250, // height of text box
                Width = 680 // width of text box
            };

using (var image = new MagickImage(inputFile))
{
  using (var caption = new MagickImage($"caption:{myString}", settings))
  {
    //adding this border removes transparency
    // caption.BorderColor = MagickColors.Black;
    // caption.Border(1);

    image.Composite(caption, Gravity.Southeast, CompositeOperator.Over);
    image.Write(outputFile);
  }
}


2023-01-26

Java streams perform different operations by multiple filters

I want to return different error messages minimum and maximum constraints on the values in a given list. I was hoping to use Java streams but i am having to filter the same list twice. Whereas using a for loop i would only have to go over the list once. Is there a better way to achieve this via streams?

My code looks something like this:

list.stream().filter(i -> i < 0).findAny().ifPresent(i -> System.out.println("below min"));

list.stream().filter(i -> i > 100).findAny().ifPresent(i -> System.out.println("above max"));

Using a for loop i can place two if conditions while traversing over the list once,

In actual implementation there are other constraints as well and I'm adding an error to a list, if it not already exists, depending on each violation.

Will i have to filter the list each time for each violation? Help would be appreciated!



Azure DevOps disable 'delete branch' after merge permanent on release branch (Folder: release/*)

I want to permanent disable 'delete Branch' on a specific branch after merging.

Is there a way to avoid this permanently. That all cases for deletion are not possible. Since this is a release branch and must remain after the merge. Unfortunately, it has already happened that the 'delete branch' hack was not removed and the release branch was therefore deleted.

1

The marked checkbox should be permanent grey or not there. Is it possible to do this?

The marked checkbox should be permanent grey or not there. Is it possible to do this?



Too many composite(multi column )indexing is ok?

Consider we have A,B,C,D,E,F,G,H columns in my table and if I make composite indexing on column ABCDE because these column are coming in where clause and then I want composite indexing on ABCEF then I create new composite indexing on ABCEF in same table but in a different query, we want indexing on column ABCGH for that i make another composite indexing in same table,

So my question is can we make too many composite indexes as per our requirements because sometimes our column in where clause gets change and we have to increase its performance so tell me is there any other way to optimise the query or we can make multiple composite indexes as per the requirements.

I tried multiple composite indexing and it did not give me any problem till now but still i want to know from all of you that will it give me any problem in future or is it ok to use only composite indexes and not single index.

Your answers will help me alot waiting for your replies. Thanks in advance.



Facing issue integrating the ACSUICalling library to my project

i am trying to integrate ACS to my app and facing this issue

Failed to build module 'AzureCommunicationCalling'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 5.6 (swiftlang-5.6.0.323.62 clang-1316.0.20.8)', while this compiler is 'Apple Swift version 5.7.1 (swiftlang-5.7.1.135.3 clang-1400.0.29.51)'). Please select a toolchain which matches the SDK.

it is working fine with another project

i tried adding 'AzureCommunicationUICalling', '1.1.0' to my xcode project with minimum deployment target 14.0 and expected to use it



Does devise controller doesn't have access to database?

I'm trying to implement coupon/token functionality. In registration_controller.rb I'm trying to find token/coupon by its code and assign referred user to another user's referrer, but it (coupon) returns me nil.

However if I insert byebug and copy paste code in console, it works perfectly. Any ideas why this is happening?

Also controller assign different user than it should (for example: New user should be assigned to user ID 3, but it assigns it to user ID 15)

def create
  unless params[:user][:referrer_code].empty?
      # This returns nil
      coupon = Coupon.find_by(code: params[:user][:referrer_code])
      params[:user][:referrer_id] = coupon.referrer_id if coupon&.referrer && coupon&.multiple?
  end
  super
end


2023-01-25

Populating columns with days based on a selection

I am trying to build a sleep tracker in Google Sheets (link). The idea is to select a year and a month from a drop-down list in cells A1 and A2, which would then populate columns based on the number of days in that month. I have tried different formulas that I found on stack overflow and elsewhere, but could not get them to work.

In short:

  1. I am looking for a formula that will populate the columns with days of that month and a name of the day in a row bellow.
  2. Looking for a way to summarize the time of sleep at the end of the each day, based on a ticked checkbox.
  3. I am not sure how the year and month selectors should be formatted (as plain number or a date).
  4. Is there a way to automatically insert check-boxes to the days of the month?

This is the formula that I have tried to adjust: =INDEX({TEXT(SEQUENCE(1; DAY(EOMONTH(A2&"/"&A1;0)); A2&"/"&A1; 1); {"d"; "ddd"}); {"Total"; ""}})

But it returns with "Error In ARRAY_LITERAL, an Array Literal was missing values for one or more rows."

Please note that ";" is used as an argument separator instead of "," (regional settings).

Thank you in advance!



How to return object with scala slick after insert

I'm trying to use generic insert function that would return object when inserting data using Slick. I've tried with following code

        // This works without any issues but limited to specific entity and table
    def insertEmployee(employee: Employee): IO[Employee] = DB.run(db, {
        def returnObj = (EmployeeTable.instance returning EmployeeTable.instance.map(_.id)).into((obj, id) => obj.copy(id = id))
        returnObj += employee
    })
    
    // This doesn't work and returns error on "copy". Error: Cannot resolve symbol copy
    def withReturningObj[E <: BaseEntity, T <: BaseTable[E]](query: TableQuery[T]) =
        (query returning query.map(_.id)).into((obj, id) => obj.copy(id = id))

Anyone who could suggest a possible solution?



ASP.NET Misconfiguration Improper Model Validation (CWE ID 1174)

I am creating an ASP.NET MVC application.

I have a model with data annotations like this:

public class SearchModel  
{
    [MaxLength(11)]
    public string? SSN { get; set; } = string.Empty;
}

And I have a controller method that receives an object of this type as parameter:

public async Task<IActionResult> Search([Bind(include: "SSN")] SearchModel searchModel)
{
    // do something
}

I get a Veracode error

ASP.NET misconfiguration : improper model validation (CWE ID 1174)

on the definition of the method...

Testing.. If I replace SearchModel with String, it works. So the problem is the model definition, but I added the data annotations to the property.

What else can I check?

Thanks



WEB3.PHP Contract Call

I am using this PHP library https://github.com/web3p/web3.php to make the requests to smart contracts on BSC.

$web3 = new Web3('https://bsc-dataseed.binance.org');
$contract = new Contract($web3->provider, $abi);

$contract->at('0x10ED43C718714eb63d5aA57B78B54704E256024E')->call('WETH', function($err, $result) {
    print_r($result);
});

Works perfectly but the problem is when I try to call a function that has parameters both uint256 and address[] . For example

enter image description here

And here's the code:

$contract->at('0x10ED43C718714eb63d5aA57B78B54704E256024E')->call('quote', [
    '25000000000000000000',
    '[0x8C851d1a123Ff703BD1f9dabe631b69902Df5f97, 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56]',
], function($err, $result) {
    print_r($result);
});

I get the following error. Tried to send the parameters as dictionary with param name. Couldn't figure out how should be done.

InvalidArgumentException
Please make sure you have put all function params and callback.



Most optimal way to remove an index from an vector-like data structure without copying data in C++

The problem:

I need to create a simple vector or vector-like data structure that has indexable access, for example:

arr[0] = 'a';
arr[1] = 'b';
//...
arr[25] = 'z';

From this structure, I would like to remove some index, for example index [5] The actual value at the index does not need to be erased from memory, and the values should not be copied anywhere, I just need the indexes of the data structure to re-arrange afterward, so that:

arr[0] = 'a';
//...
arr[4] = 'e';
arr[5] = 'g';
//...
arr[24] = 'z';

Is std::vector the best data structure to use in this case, and how should I properly remove the index without copying data? Please provide code.

Or is there a more optimal data structure that I can use for this?

Note, I am not intending on accessing the data in any other way except through the index, and I do not need it to be contiguously stored in memory at any time.



How to create object of a response service class in spring framework

How to use this method in another class? I have to make its object as I have to use this API while creating otherAPI so how can I create its object and use this in another class in same project.


    @POST
    @Path(PathConstants.UPDATE_EPM_DETAILS)
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateEpmDetails(InputStream incomingData, @Context HttpHeaders headers) {
        logger.info();
        mapper = getObjectMapper();
        epmHelper = getEpmHelper();
        ElementUpdateEpmRequest[] updateEpmRequestArray = null;
        String jsonInString = "{}";
        UpdateEpmDetailsResponse updateEpmDetailsResponse = new UpdateEpmDetailsResponse();
        int responseStatus = Response.Status.OK.getStatusCode();
        try {
            updateEpmRequestArray = mapper.readValue(incomingData, ElementUpdateEpmRequest[].class);
            List<ElementUpdateEpmRequest> updateEpmRequestList = new ArrayList<>(Arrays.asList(updateEpmRequestArray));
            updateEpmDetailsResponse = epmHelper.updateEpmDetails(updateEpmRequestList);
            jsonInString = mapper.writeValueAsString(updateEpmDetailsResponse);
            logger.infoEndOfMethod();
            return Response.status(responseStatus).entity(jsonInString).build();
        } catch (Exception e) {
            return DataUtils.prepareServerErrorWithMessage(e, e.getMessage());
        }
    }



2023-01-24

How to solve the captcha enterprise?

I need to pass the captcha in steam, captcha kind Recaptcha v2 Enterprise, used the service 2recaptcha.com to pass the captcha, displays an error ERROR_CAPTCHA_UNSOLVABLE, the site itself is written that may require additional parameters such as the parameter s. I will show my code as an example:

def solve_recaptcha(data, url):
    solver = TwoCaptcha(api_2captcha)
    try:
        result = solver.recaptcha(sitekey=data["sitekey"], url=url, enterprise=1, datas=data["datas"])
    except Exception as ex:
        print(f"Error during captcha solution: {ex}")
    else:
        return result

At first I made a mistake and didn't notice that captcha enterprise, captcha was solved but steam gave me an error, now when I started solving captcha like enterprise captcha, 2recaptcha site gives me an error. What is my error and how can I solve it? If I'm not using the right tools, which ones should I use?



How to change a boolean value in FARM

I am having an issue creating a router that updates a boolean false value to true in my mongodb. All of this is activated by a button on my front end.

    @router.post("/started", response_description="start fight")
    async def update_started(request: Request, started: bool):
        start = await request.app.mongodb["matches"].update_one({"$set": {"started": True}})
        return start

    
    #@router.put("/update", response_description="start fight")
    #async def update_started(started: bool, request: Request):
     #   if started == False:
       #     started = request.app.database["matches"].update_one(
         #       {"started": False}, {"$set": True}
        #    )

I've tried many variations of this and am getting a 500 http error



Need advice with Error Handling for Invalid Path

I could use some advice on how to handle a strange issue that happens to my users.

Issue: All of my users are on laptops that use VPN to connect to our network. When they disconnect from the VPN and reconnect the network drive also disconnects till they open the drive or folder through file explorer. When this happens and they don't re-establish the connection to the network drive they end up with 3304 error.

Error Handling? What I'd like to do is setup some sort of error handler to tell them thats what happened with a potential link they could click on to re establish the connection. OR even better just have the VBA code identify that error 3304 has occurred and re-establish the connection automatically for them and no pop up error happen at all.

Has anyone done this? I've done some research but nothing I've found quite fits the criteria for this issue. Looking for any advice or push in the right direction.

I was thinking of something like this where either they get a pop up with a link or skip the pop up all together and find a way to re-connect the drive in the background.

On Error GoTo ErrHandler

'Error Handler
ErrHandler:
If Err.Number = 3304 Then

MsgBox "Error Number:" & Err.Number & vbCrLf & _
    "Error Description: " & Err.Description & vbCrLf & _
    "This error is due to your VPN being disconnected and reconnected"
Else
End If 


how to extract the apk of my app in delphi 10.3?

I need to extract the APK of my application when it is installed, I know there is an application called APK EXTRACTOR which performs this task, but in my case I want to extract the apk myself from delphi code.

So far I have only been able to find the APKs of pre-installed applications on the phone in the path "/system/app" and "system/priv-app" but internally I cannot find the apk of my app. Inside each folder is its apk Inside each folder is its apk



Populating the SQLDatasource SelectCommand

How do I take this string and drop it into the select command?

    String SqlC = "select * from dbo.FindIt where " + SqlStr;

The object is to populate the SelectCommand:

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:M3ConnectionString %>" 
     SelectCommand = SqlC >
</asp:SqlDataSource>


2023-01-23

How to solve Authorization header using Bearer Angular x OpenAI

I have this error which appear and disappear time to time, but those days that's every day :
You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://beta.openai.com.

And so my Angular application doesn't work properly anymore.
Here is my call to the API :

  try {
    const body = {
      "model": "text-davinci-003",
      "prompt": ask,
      "temperature": 0.7,
      "max_tokens": 10000,
      "top_p": 1,
      "frequency_penalty": 0.0,
      "presence_penalty": 0.0
    }
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${environment.OPENAI_SECRET_KEY}`
    });
    const completion: any = await this.http.post("https://api.openai.com/v1/completions", body, { headers }).toPromise();
    this.response = completion.choices[0].text as string;
    this.articleService.updateArticle(this.createdArticleId, this.generateText(this.response));
    console.log(completion);
    console.log(completion.choices[0].text);
  } catch (error: any) {
    if (error.response) {
      console.log(error.response.status);
      console.log(error.response.data);
    } else {
      console.log(error.message);
    }
    this.connectToAPI(ask, true);
  }

Before I was using the properly method with npm install of openai packages, but today I changed for this way to have the APIKEY in the header, but that didn't help...

If someone have an idea, I would be very great full, because I already watch many link on Google, but nothing did !



React hook form pass an array of values to child - some Regster and some not

I want to pass an array of strings to my Child Component which creates an input field managed by React Hook Form.

Sometimes, I want the React Hook Form to NOT register some fields in the array passed as the input fields are optional to the user. For example, address_line2 in the inputForm array is not always required to be completed on the form.

I use this Child Component in a number of places, so if I change it, is it possible to make the change or component optional or use an if statement? So, that i can continue to use the child component as is.

Here is the parent component:

const StopForm: React.FC<IProps> = ({ id, index, stop }) => {
  const Router = useRouter();

  const {
    register,
    handleSubmit,
    unregister,
    formState: { errors },
  } = useForm<Stop>({
    defaultValues: sampleStopData,
  });

  const inputFields = [
    "address_line1",
    "address_line2",
  ];
return (
<>
  {inputFields.map((field, index) => (
          <InputField
            key={index}
            val={field}
            register={register}
            defaultValue={
              typeof stop === "object" &&
              typeof stop[field as keyof Stop] !== "undefined"
                ? // ? stop[field as keyof Stop].toString()
                  String(stop[field as keyof Stop])
                : ""
            }
            errors={errors}
            classes="px-3 py-1.5 rounded placeholder:text-gray-800 lg:w-[25rem] lg:mx-auto bg-transparent border outline-none"
          />
        ))}
</>);

My Child Component that manages the react hook form part is this:

interface IProps {
  val: string;
  type?: string;
  defaultValue: string;
  register: UseFormRegister<any>;
  errors: any;
  classes: string;
}

const InputField: React.FC<IProps> = ({
  defaultValue,
  register,
  errors,
  val,
  classes,
  type = "text",
}) => {
  return (
    <>
      <input
        id={val}
        type={type}
        placeholder={val}
        className={`${classes} ${
          errors?.val ? "border-red-900" : "border-gray-400"
        }`}
        defaultValue={defaultValue}
        {...register(val, {
          required: { value: true, message: `${val} is required` },
        })}
      />
      {errors[val] && (
        <small className="text-red-700">{errors[val].message}</small>
      )}
    </>
  );
};

export default InputField;

Can the input fields also pass a value or somehow let the child component know to 'skip' that value and not register it?

Any assistance on how to do this - I have been going round and round on this one, wouuld be graciously received!

Thank you! Karen



PostgreSQLClientKit querying database

Is there a short way to prepare the statements and execute them, if you are trying to run multiple queries and you are not concerned with the results that are generated by those statements.

Forexample I want to execute these two statements, is there any short way to write these two statements and execute them.

do{
        let load_age_statement = try connection.prepareStatement(text: "Load 'age';")
        let set_path_statement = try connection.prepareStatement(text: "SET search_path = ag_catalog, '$user', public;")
    
        var cursor = try load_age_statement.execute()
        load_age_statement.close()
        cursor  = try set_path_statement.execute()
        
}catch{
        print(error)
}


How to display/put/use LDA model in my dash app

I would like to display/use/put my LDA model in my dash app. Here's the code for the LDA model which works and that I've saved in html on my computer :

# Libraries
import spacy
from gensim.corpora import Dictionary
from gensim.models import LdaModel
import pyLDAvis.gensim_models
import pandas as pd 

nlp_teletravail = spacy.load("fr_core_news_sm")

# Create df for the example
data = [['tweet content in french'], ['tweet 2 content in french'], ['tweet 3 content in french']] # lots of tweets and other columns but not useful for the example
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Preprocessed_tweets'])

spacy_docs_teletravail = list(nlp_teletravail.pipe(df["Preprocessed_tweets"]))

# Create empty list called docs_teletravail
docs_teletravail = []

# Pre processing
# For each document in spacy_docs_teletravail
for doc in spacy_docs_teletravail:
    # We create empty list called tokens_teletravail
    tokens_teletravail = []
    # for each token in each document of spacy_docs_teletravail
    for token in doc:
        # pre processing 1 and 2
        if len(token.orth_) > 2 and not token.is_stop:     
            # pre processing 3 and 4
            tokens_teletravail.append( token.lemma_.lower() ) 
            # append results of tokens_teletravail in docs_teletravail
    docs_teletravail.append( tokens_teletravail )

dictionary_teletravail = Dictionary(docs_teletravail)
corpus_teletravail = [ dictionary_teletravail.doc2bow(doc) for doc in docs_teletravail]

model_teletravail_passes_5 = LdaModel(corpus=corpus_teletravail,
                             id2word=dictionary_teletravail,
                             num_topics=10,
                             chunksize=1000,
                             passes=5,
                             random_state=1) 


vis_data_teletravail = pyLDAvis.gensim_models.prepare(model_teletravail_passes_5, corpus_teletravail, dictionary_teletravail, sort_topics=False)

# Export the graph and store it where we want in our computer
pyLDAvis.save_html(vis_data_teletravail, 'C:/Users/mario/Downloads/lda_model_passes_5.html')

Maybe you can add content for the tweets (random sentences that you can find on the internet). I think I can't load my html file on the post but don't hesitate to tell me if it's possible and I'll do it so that you don't have to run the first part. And here's the code of my dash app where I have multiple tabs and subtabs but I don't put their content here because it's useless, you just have the code with the tabs (empty). I would like to put the LDA model in tab 3 (Latent Dirichlet Allocation Model) subtab 10 (LDA Model 10 topics). I left most of my attempts in comments to return the LDA model in subtab10 but nothing is happening (no errors, nothing appearing on the dash app). Thank you for your help !

# Needed libraries
#import pandas as pd
import dash 
import dash_bootstrap_components as dbc
#import plotly.express as px
#import numpy as np
from dash import dcc, html
from dash.dependencies import Input, Output
from dash_bootstrap_templates import ThemeSwitchAIO, template_from_url

# Two different templates stored in variables for the dash app
template_theme1 = "cyborg"
template_theme2 = "lumen"
url_theme1 = dbc.themes.CYBORG
url_theme2 = dbc.themes.LUMEN

# Link which gives access to the templates
dbc_css = (
    "https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@V1.0.1/dbc.min.css"
)

# Create the app and define the main theme in external_stylesheets
app = dash.Dash(__name__, external_stylesheets=[url_theme1, dbc_css])


# Define a sentence that appears on the top left of the app in order to choose between the two proposed themes
header = html.P("Click if you want to change theme of graphics",style={'textAlign': 'left','font-size':'300','font-family':'helvetica'})



# Create the layout of the app 
app.layout = html.Div([ # html Div to use html components (style, text, tabs, subtabs etc)
                       
                       html.H1('Health consequences during covid-19 pandemic dashboard', style={'textAlign': 'center','font-size':'300','font-family':'helvetica'}),
                       
                       dbc.Container( # dbc container and row to use dbc Col to define the different themes to choose
                           dbc.Row(
                               [
                                   dbc.Col( # Define the two possible themes to choose
                                       [
                                           header, # header is the sentence that we've dehttps://stackoverflow.com/questions/64736956/how-to-use-iframe-in-dash-plotly-python-htmlfined earlier in header variable
                                           ThemeSwitchAIO( # switch with icons
                                               aio_id="theme", # id of the switch
                                               themes=[url_theme1,url_theme2], # proposed themes that we've defined earlier
                                               ),
                                           ])])),
                       
                       dcc.Tabs(id='tabs', value='Tab1', style={'background-color': 'black'}, children=[
                           # Create tabs and their sub tabs
                                                                   
                                                                   
                           dcc.Tab(label='Data information', id='tab1', value='Tab1', style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'},children =[ # First tab 
                               dcc.Tabs(id="subtabs1", value='Subtab1',children=[ # Create sub tabs in the first tab 
                                   dcc.Tab(label='Basic information about the dashboard', id='subtab1', value='Subtab1',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 1
                                   dcc.Tab(label='Number of collected tweets', id='subtab2', value='Subtab2',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 1
                                   dcc.Tab(label='Number of collected tweets per month each year', id='subtab3', value='Subtab3',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Third sub tab of tab 1
                                   dcc.Tab(label='Wordcloud', id='subtab4', value='Subtab4',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Fourth sub tab of tab 1
                                   
                                   ]),
                               
                           dcc.Tab(label='Sentiment Analysis', id='tab2', value='Tab2',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the Second tab 
                                dcc.Tabs(id="subtabs2", value='Subtab2', children=[ # Create sub tabs for the second tab
                                    dcc.Tab(label='Number or percentage of tweets according to sentiments', id='subtab5', value='Subtab5', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 2
                                    dcc.Tab(label='Percentage of tweets according to sentiments and time slots', id='subtab6', value='Subtab6', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 2
                                    dcc.Tab(label='Number or percentage of tweets according to sentiments and time slots', id='subtab7', value='Subtab7', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Third sub tab of tab 2
                                    dcc.Tab(label='Number or percentage of tweets according to sentiments each year', id='subtab8', value='Subtab8', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Fourth sub tab of tab 2
                                    
                                    ]), 
                                
                           dcc.Tab(label='Latent Dirichlet Allocation Model', id='tab3', value='Tab3',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the Third tab 
                                dcc.Tabs(id="subtabs3", value='Subtab3', children=[
                                    dcc.Tab(label='LDA Model interpretation', id='subtab9', value='Subtab9', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 3
                                    dcc.Tab(label='LDA Model 10 topics', id='subtab10', value='Subtab10', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 3
                                    dcc.Tab(label='LDA Model 5 topics', id='subtab11', value='Subtab11', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Third sub tab of tab 3
                                    
                                    ]), 
                                
                                
                           dcc.Tab(label='Network Graph', id='tab4', value='Tab4',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the fourth tab 
                                dcc.Tabs(id="subtabs4", value='Subtab4', children=[
                                    dcc.Tab(label='To determine', id='subtab13', value='Subtab13', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 4
                                    dcc.Tab(label='To determine', id='subtab14', value='Subtab14', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 4
                                    dcc.Tab(label='To determine', id='subtab15', value='Subtab15', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Third sub tab of tab 4    
                                    
                                    ])
                           
                           ])
                       ])
                                                     



############################################ Tab 3 LDA MODEL 
############### Sub tab 10 LDA Model 10 topics


# Callback for Tab 3 and subtab 10 LDA Model 10 topics
@app.callback(Output('subtab10', 'children'), # Output 
              [Input('subtabs3', 'value'), # Input 
              Input(ThemeSwitchAIO.ids.switch("theme"),"value")]) # Another input is the selected theme/template

# Create function to display lda model
def display_lda_subtab10(value,toggle): # 2 parameters value for which subtab and toggle for theme/template
    
    if value == 'Subtab10':# If we are in subtab2 in tab 1 we return a graph

        template = template_theme1 if toggle else template_theme2 # We define the theme selected

        #lda_10_topics = html.Iframe(src='C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
        
        #return html.Div([dcc.Graph(figure=lda_10_topics)])
        
        
        # https://stackoverflow.com/questions/64736956/how-to-use-iframe-in-dash-plotly-python-html
        #return html.Div([dcc.Graph(id='example'),
         #                html.Iframe(src='C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
          #               ])
        
        
        
        
        #return html.Div([dcc.Graph(id='example'),
         #                html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
          #               ])
        
        
        
        
        #https://stackoverflow.com/questions/68269257/local-html-file-wont-load-properly-into-dash-application
        #return html.Div([html.Iframe(src="assets/lda_model_topics_10.html")])
        
        
        
        
        # https://stackoverflow.com/questions/74534261/dash-include-custom-html-object
        #lda_10_topics = html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
        #with open("C:/Users/mario/Downloads/lda_model_passes_5_json.json",'r') as f:
        
        #with open(lda_passes_5_json,'r') as f:
            
         #   return html.Div([dcc.Graph(figure=json.load(f))])
            #return json.load(f)

    #html.Iframe(src=r'static/lda_model_topics_10.html')
    #html.Div([html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')])




# Run the dash app
if __name__ =='__main__':   
    app.run_server(debug=False)