Posts

Showing posts from January, 2023

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("T...

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]::EnableVisual...

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}/_...

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"...

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:CommonBasicCo...

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)...

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: No back button 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 { v...

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

Image
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: 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 e...

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? 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. After the installation ...

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

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

Image
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: 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 als...

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 ...

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...

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; } // ...

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", "pat...

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 is...

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; impo...

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 ti...

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...

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 th...

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.FillRectan...

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/*)

Image
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. 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

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: 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. Looking for a way to summarize the time of sleep at the end of the each day, based on a ticked checkbox. I am not sure how the year and month selectors should be formatted (as plain number or a date). 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 ...

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

Image
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 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...

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<>(...

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 ge...

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

Image
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.

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>

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.OP...

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) => ( ...

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 to...