instruction
stringlengths
0
30k
JSON Parsing Error in Java Spring Function
null
There is a difference in SwiftUI between a `View` instance being created and that counting as the view "appearing". Creation of the tree of view structs happens all the time, and then SwiftUI's diffing mechanism compares the new tree with the current tree to decide what has appeared or disappeared and what just needs a `body` re-evaluation. This is a fundamental difference to UIKit, where you create an instance of a view and that instance is the one that is then drawn on your screen, and the instance is persistent. A single `View` could be instantiated hundreds of times in response to events elsewhere in the app, but that doesn't mean it will have `onAppear` executed hundreds of times. Your code doesn't look like idiomatic SwiftUI and you will probably end up hitting more issues with this pattern, because you're fighting the framework. In particular, any time you are storing a reference to a `View` instance, you are almost definitely doing it wrong (for the reasons outlined above). You can get the effect you're after by adding `.id(str)` to your `SubView`: ```swift SubView(businessLogic: BusinessLogic(str: str)).id(str) ``` This forces SwiftUI to treat the view as "new" compared to the previous instance, because it has a different identity, but the sheer ugliness of the code should tell you it's the wrong thing to do. `BusinessLogic` should probably be `Observable`, and expose variables that can be used as bindings or just observed by subviews. Try to keep actual business logic out of your view structs, you will be much happier.
Xampp not connecting to DBForge what to do? [xampp] (https://i.stack.imgur.com/xycb6.png) [dbforge] (https://i.stack.imgur.com/aCrDu.png) I clicked on xampp mysql start and opened dbforge then i clicked to new connection in dbforge but the user and root did not popped up only that window what i attached here as a dbforge picture. I use win 10 OS, vscode, vuejs3, laravel10, git etc etc, just reinstalled OS and reinstalled all the programs and extensions, that took a while believe me, everything worked now i'm stuck here. What i only tried was to refresh, delete localhosts..... then went to search to google. Thanks in advance:)
Before committing a record to the database, I want to do a sanity check on a certain field. More precisely, it is an ArrayField and I want to remove any NaN/None values and replace them by zero. However, there are many ways to create said record. A user might `MyObject().save()`, or `MyObject.objects.create()`, or `MyObject.objects.bulk_create()`, and even `MyObject.objects.bulk_update(field=my_field)`. I believe there are also ways in that Django Rest Framework might use. How can I be sure that NaN/None is always replaced by zero before committing to the database? Should I overwrite all the above methods? Should I create a custom field that inherits from `ArrayField` but does all the data munging? What is the best practice?
Strange behavior with FileReader()
|jquery|filereader|
null
I have this problem, y really don´t understand how can i fix it. Please i need help with this. The label's for attribute doesn't match any element id. This might prevent the browser from correctly autofilling the form and accessibility tools from working correctly. To fix this issue, make sure the label's for attribute references the correct id of a form field. This is my code ``` <label for="billing_country" class="">País / Región&nbsp;<abbr class="required" title="obligatorio">*</abbr></label> ``` Please i need help with this.
Incorrect use of <label for=FORM_ELEMENT>
|html|
null
{"Voters":[{"Id":537064,"DisplayName":"Null Pointers etc."}]}
I'm creating a [DTD][1] for an xml document. I have an [Enumerated attribute][2] for an xml element. My question is: Can the attribute **Type** have spaces? eg: <!ELEMENT Link (#PCDATA)> <!ATTLIST Link Type (Amendment|Reference|Superseded|Modified| Corrigendum|Corresponds|Endorsement|Equivalent|Identical|Modified| Not Equivalent|Note taken of|Related|Similar) "Reference"> So what I would like is: <Link Type="Not Equivalent" \> But that seems to barf. When I say barf, I mean that when I try to validate the document (Eg Open it in a web browser) I get an error message: > Invalid character found in ATTLIST enumeration. Error processing > resource 'file:///C:/myxmldocument.xml'. ... Is there some magic voodoo I need to do for spaces? Or is it just tough luck? I looked in a [few][3] [spots][4] but couldn't see any reference [1]: http://www.xmlfiles.com/dtd/ [2]: http://www.xmlfiles.com/dtd/dtd_attributes.asp [3]: http://www.w3schools.com/XML/xml_attributes.asp [4]: http://www.javacommerce.com/displaypage.jsp?name=attribut.sql&id=18238
There Some doubts about used RDBMS. I will offer a solution without using regexp. ``` select id,words ,string_agg(w,'-' order by rn) newWords from( select * ,row_number()over(partition by id order by (select null)) rn ,count(*)over(partition by id order by (select null)) cnt from(select *,string_to_table(words,'-') w from test )t )t2 where rn>3 and rn<=(cnt-2) group by id,words ``` Output is |id| words| newwords| |-:|:-----------------|:-----------| |1| GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET-ABORT| Azerbaijan-country| |2| GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET| Azerbaijan| from test data |id| words| |-:|:---------| |1| GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET-ABORT| |2| GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET| |3| GLOBE-WORLD-AIRPORT-Azerbaijan-country| |4| GLOBE-WORLD-AIRPORT-Azerbaijan| |5| GLOBE-WORLD-AIRPORT| |6| GLOBE-WORLD|
I have successfully implemented SMS based MFA on a Laravel project following the guide here: [https://www.nicesnippets.com/blog/laravel-10-two-factor-authentication-with-sms-example](https://www.nicesnippets.com/blog/laravel-10-two-factor-authentication-with-sms-example) and AWS for SMS messaging. This works really well but unfortunately I cannot work out how to use cookies allow a user to 'trust' a device and avoid the need for MFA on every login. The tutorial relies on the following Middleware added to the project: ``` class TwoFactorAuth { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next){ Log::info('TwoFactorAuth middleware triggered'); if (!Session::has('user_2fa')) { return redirect()->route('2fa.index'); } return $next($request); } } ``` And the following simple model: ``` class UserCode extends Model{ use HasFactory; public $table = "user_codes"; protected $fillable = [ 'user_id', 'code', ]; } ``` The app/Http/Kernel.php is updated to activate the middleware: ``` class Kernel extends HttpKernel { protected $routeMiddleware = [ .... '2fa' => \App\Http\Middleware\TwoFactorAuth::class, ]; } ``` I have tried using a cookie called 'trust-device' which gets created when the user logs in (if they have checked the "Trust Device" box on the login page. The cookie gets created but now I don't know where to implement the code to look for that and circumvent the MFA requirement. I tried adding the following to the authenticated function within the standard Laravel LoginController.php page: ``` protected function authenticated(\Illuminate\Http\Request $request, $user){ Log::info('Login controller "authenticated" triggered'); if(request()->cookie('trust_device')=='true') { Log::info('Found trust_device cookie so creating user_2fa and tfa session'); \Session::put('user_2fa', auth()->user()->id); \Session::put('tfa', auth()->user()->id); } ``` But the user is still prompted for MFA everytime.
I have a dataset from flights. The airplane communicates with a ground station and through GPS I have the distance between the current airplane location and the ground station location, alongside with the respective longitude, latitude and altitude. What I need to do now is convert the long, lat, alt position data into a x,y,z coordinate system. Since the ground station is at a static position I want to have it in the origin (0,0,0) of the coordinate system. I'm in search of a python module that can handle this transformation. As an example I provide the actual data from the ground station alongside 1 position of the airplane which needs to be converted: Ground Station [should be (0, 0, 0)] Latitude: 41.947.694 Longitude: 3.209.083 Altitude(m): 379.41 Airplane Position: Lat.: 419.763.015.750 Long.: 34.890.851.772 Alt.[m]: 971.32 Moving the ground station to the origin I would have to subtract its position from the airplane position if I understand correctly which would mean: Ground Station: Latitude: 0 Longitude: 0 Altitude(m): 0 Airplane Position: Lat.: 419.721.068.056 Long.: 34.887.642.689 Alt.[m]: 591.91 Since I'm new to working with such data and tried some simple solutions and did not find anything that was converting this data I hope you can help me find a solution. I need the converted data to simulate ellipsoids in 3D to find possible intersections. This could also be done with a different approach than python. So matlab would be fine too eve if I have never worked with that.
I have developed a scientific application to measure the area of shapes drawn on a scanned paper using canvg (version 3. something). The application works mostly fine (in Chrome), but gets really slow after a lot of small areas are selected. var s = canvg('canvas', inp_xmls, {ignoreMouse: true, ignoreAnimation: true}); Each click inside an area performs a bucket fill using the canvg bucket-fill: var bucket = Bucket(canvas, cfg, event, color); Subsequently, the image is updated to view the new filled area: var lowerimg = svg.image(can.toDataURL()); console.log(lowerimg) lowerimg.node.onload = function () { drawDown(); ... function drawDown() { inp_xmls = XMLS.serializeToString(svg.node); s.loadXml(ctx, inp_xmls); s.stop(); } function undo() { var last = svg.last(); if(svg.index(last) > 1) { last.remove(); drawDown(); s.draw(); } undoAddArea(); } Using the memory snapshots I can see 'strings' are increasing in size significantly (and image + #document). And it looks like for each stroke a new 'src' object is added: [![screenshot][1]][1] The application is available online here: https://limo.mni.thm.de/ Clicking on "Beispiel" on the right open an example slide in the drawing board. My questions: - How can I reduce memory usage of the filling/ drawing on the canvas? Is there a function in canvg to 'clear' older layers? - I need the possibility to 'undo' clicks, so I need to store some of them. How do I access the old images like in the 'undo' function to remove everything older than 5 edits for example? [1]: https://i.stack.imgur.com/K6nLu.png
I have one View that allows the user to select exercises from a list (NewRoutine), assign them to a day of the week, and then save them. Then I have another view that displays the exercises that the user selected, organized by day of the week (YourRoutines). However, in testing when I select multiple exercises and assign them to one day, they're not displayed properly in the other view. Only the first exercise that I selected is displayed. This the code for the view that should display the exercises selected: ``` import SwiftUI import SQLite3 struct YourRoutines: View { @State private var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] @ObservedObject var routinedatabase: RoutineDatabase var body: some View { ZStack { ScrollView { ForEach($days, id: \.self) { day in VStack { Text(day.wrappedValue) .font(.title.bold()) .padding(.bottom, 5) .foregroundColor(.white) .multilineTextAlignment(.leading) ForEach(routinedatabase.routineList) { routine in if day.wrappedValue == routine.Day { Text(routine.Exercise) .foregroundColor(.white) .multilineTextAlignment(.leading) } } } } } } } } ``` This is the code for my database: ``` import SQLite3 struct Routines : Identifiable { var id = UUID() var dbID : Int var routineID : Int var Exercise: String var Day: String } class RoutineDatabase : ObservableObject { @Published var routineList = [Routines]() @Published var routineIDMax = 0 @Published var dbIDMax = 0 init() { var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter } var stmt : OpaquePointer? let dbURL: URL = { let fileName: String = "ShapeShiftDB.db" let fileManager:FileManager = FileManager.default let directory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! let documentUrl = directory.appendingPathComponent(fileName) let bundleUrl = Bundle.main.resourceURL?.appendingPathComponent(fileName) // here check if file already exists on simulator if fileManager.fileExists(atPath: (documentUrl.path)) { print("document file exists!") return documentUrl } else if fileManager.fileExists(atPath: (bundleUrl?.path)!) { print("document file does not exist, copy from bundle!") do { print(bundleUrl!.path) try fileManager.copyItem(at:bundleUrl!, to:documentUrl) } catch { print("Unable to copy item: \(error)") } } return documentUrl }() if sqlite3_open_v2(String(dbURL.path), &db, SQLITE_OPEN_READWRITE, nil) != SQLITE_OK { print(dbURL.path) print("Error66:" + String(cString: sqlite3_errmsg(db))) sqlite3_close(db) //Else if database opens successfully... } else { let routineTable = "SELECT * FROM Routines;" if sqlite3_prepare_v2(db, routineTable, -1, &stmt, nil) == SQLITE_OK { while sqlite3_step(stmt) == SQLITE_ROW { let dbID = Int(sqlite3_column_int(stmt, 0)) let routineID = Int(sqlite3_column_int(stmt, 1)) let name = String(cString: sqlite3_column_text(stmt, 2)) let day = String(cString: sqlite3_column_text(stmt, 3)) if routineID > routineIDMax {routineIDMax = routineID} if dbID > dbIDMax {dbIDMax = dbID} routineList.append(Routines(dbID: dbID, routineID: routineID, Exercise: name, Day: day)) } } else { print(dbURL.path) print("Error92:" + String(cString: sqlite3_errmsg(db))) sqlite3_close(db) } } } } ``` I had this problem before and I fixed it because I'd forgotten to keep incrementing dbIDMax in one of the loops. That fixed it and it worked fine, but after checking back on it after a while it stopped working. I don't get any errors so I don't know what's wrong. I have one View that allows the user to select exercises from a list (NewRoutine), assign them to a day of the week, and then save them. Then I have another view that displays the exercises that the user selected, organized by day of the week (YourRoutines). However, in testing when I select multiple exercises and assign them to one day, they're not displayed properly in the other view. Only the first exercise that I selected is displayed. This the code for the view that should display the exercises selected: ``` import SwiftUI import SQLite3 struct YourRoutines: View { @State private var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] @ObservedObject var routinedatabase: RoutineDatabase var body: some View { ZStack { ScrollView { ForEach($days, id: \.self) { day in VStack { Text(day.wrappedValue) .font(.title.bold()) .padding(.bottom, 5) .foregroundColor(.white) .multilineTextAlignment(.leading) ForEach(routinedatabase.routineList) { routine in if day.wrappedValue == routine.Day { Text(routine.Exercise) .foregroundColor(.white) .multilineTextAlignment(.leading) } } } } } } } } ``` This is the code for my database: ``` import SQLite3 struct Routines : Identifiable { var id = UUID() var dbID : Int var routineID : Int var Exercise: String var Day: String } class RoutineDatabase : ObservableObject { @Published var routineList = [Routines]() @Published var routineIDMax = 0 @Published var dbIDMax = 0 init() { var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter } var stmt : OpaquePointer? let dbURL: URL = { let fileName: String = "ShapeShiftDB.db" let fileManager:FileManager = FileManager.default let directory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! let documentUrl = directory.appendingPathComponent(fileName) let bundleUrl = Bundle.main.resourceURL?.appendingPathComponent(fileName) // here check if file already exists on simulator if fileManager.fileExists(atPath: (documentUrl.path)) { print("document file exists!") return documentUrl } else if fileManager.fileExists(atPath: (bundleUrl?.path)!) { print("document file does not exist, copy from bundle!") do { print(bundleUrl!.path) try fileManager.copyItem(at:bundleUrl!, to:documentUrl) } catch { print("Unable to copy item: \(error)") } } return documentUrl }() if sqlite3_open_v2(String(dbURL.path), &db, SQLITE_OPEN_READWRITE, nil) != SQLITE_OK { print(dbURL.path) print("Error66:" + String(cString: sqlite3_errmsg(db))) sqlite3_close(db) //Else if database opens successfully... } else { let routineTable = "SELECT * FROM Routines;" if sqlite3_prepare_v2(db, routineTable, -1, &stmt, nil) == SQLITE_OK { while sqlite3_step(stmt) == SQLITE_ROW { let dbID = Int(sqlite3_column_int(stmt, 0)) let routineID = Int(sqlite3_column_int(stmt, 1)) let name = String(cString: sqlite3_column_text(stmt, 2)) let day = String(cString: sqlite3_column_text(stmt, 3)) if routineID > routineIDMax {routineIDMax = routineID} if dbID > dbIDMax {dbIDMax = dbID} routineList.append(Routines(dbID: dbID, routineID: routineID, Exercise: name, Day: day)) } } else { print(dbURL.path) print("Error92:" + String(cString: sqlite3_errmsg(db))) sqlite3_close(db) } } } } ``` I had this problem before and I fixed it because I'd forgotten to keep incrementing dbIDMax in one of the loops. That fixed it and it worked fine, but after checking back on it after a while it stopped working. I don't get any errors so I don't know what's wrong.
ModuleNotFoundError on .ipynb
|python|pandas|jupyter-notebook|modulenotfounderror|
null
{"Voters":[{"Id":354577,"DisplayName":"Chris"},{"Id":522444,"DisplayName":"Hovercraft Full Of Eels"},{"Id":546871,"DisplayName":"AdrianHHH"}],"SiteSpecificCloseReasonIds":[18]}
|python|pip|pycharm|
In such cases `for` loops can be much faster. > for (s in seq_along(my_list)) { + x <- my_list[[s]] + if ('col3' %in% names(x)) { + x$col3[is.na(x$col3) & x$col1 %in% c('v2', 'v3')] <- 'VAL' + my_list[[s]] <- x + } + } > my_list [[1]] col1 col2 col3 col4 1 v1 wood cup <NA> 2 v2 <NA> VAL pear 3 v3 water fork banana 4 v2 <NA> VAL <NA> 5 v1 water <NA> apple [[2]] col1 col2 col4 1 v1 wood <NA> 2 v2 <NA> pear [[3]] col1 col3 col4 1 v1 cup <NA> 2 v2 VAL pear 3 v3 VAL banana 4 v3 VAL <NA> ## Benchmark Runs 80% faster, which is quite significant. Demonstrated on a list with just 1,000 elements. $ Rscript --vanilla foo.R Unit: milliseconds expr min lq mean median uq max neval cld floop 18.84617 19.95898 22.17803 22.08178 24.21662 27.02679 100 a lapply 100.05645 106.24458 111.66269 111.17931 116.06089 150.08886 100 b *Benchmark code* set.seed(42) big_list <- my_list[sample(1:3, 1e3, replace=TRUE)] microbenchmark::microbenchmark( floop={ for (s in seq_along(big_list)) { x <- big_list[[s]] if ('col3' %in% names(x)) { x$col3[is.na(x$col3) & x$col1 %in% c('v2', 'v3')] <- 'VAL' big_list[[s]] <- x } } big_list }, lapply=lapply( big_list, \(x) if ('col3' %in% names(x)) { transform(x, col3=replace(col3, is.na(col3) & col1 %in% c('v2', 'v3'), 'VAL')) } else { x }), check='identical') ## Edit Add a `"col3"` that is filled with `"VAL"` if none exists yet: > for (s in seq_along(my_list)) { + x <- my_list[[s]] + if ('col3' %in% names(x)) { + x$col3[is.na(x$col3) & x$col1 %in% c('v2', 'v3')] <- 'VAL' + } else { + x$col3 <- 'VAL' + } + my_list[[s]] <- x + } > my_list [[1]] col1 col2 col3 col4 1 v1 wood cup <NA> 2 v2 <NA> VAL pear 3 v3 water fork banana 4 v2 <NA> VAL <NA> 5 v1 water <NA> apple [[2]] col1 col2 col4 col3 1 v1 wood <NA> VAL 2 v2 <NA> pear VAL [[3]] col1 col3 col4 1 v1 cup <NA> 2 v2 VAL pear 3 v3 VAL banana 4 v3 VAL <NA> ---- *Data:* > dput(my_list) list(structure(list(col1 = c("v1", "v2", "v3", "v2", "v1"), col2 = c("wood", NA, "water", NA, "water"), col3 = c("cup", NA, "fork", NA, NA ), col4 = c(NA, "pear", "banana", NA, "apple")), class = "data.frame", row.names = c(NA, -5L)), structure(list(col1 = c("v1", "v2"), col2 = c("wood", NA), col4 = c(NA, "pear")), class = "data.frame", row.names = c(NA, -2L)), structure(list(col1 = c("v1", "v2", "v3", "v3"), col3 = c("cup", NA, NA, NA), col4 = c(NA, "pear", "banana", NA)), class = "data.frame", row.names = c(NA, -4L)))
Django: changing contents on a field on every save-like action
|django|
If I understand correctly, you have a bunch of pins in your data source, the map only displays what's in view, and you want to list only the pins in view. Unfortunately, this is a bit more complicated than I'd like due to the map supporting rotating and pitching (a bounding box won't property represent the map viewable area). There is a code sample for this scenario here: https://samples.azuremaps.com/?sample=get-points-in-current-map-view It does the following: 1. Monitors the maps `moveend` event to trigger an update to the list. 2. Calculates the rotated/pitches polygon area for the map view based on the pixel coordinates of the map container. 3. Loops through all points in the data source and finds which shapes intersect with the polygon. Here is the main code blocks: ```javascript //Monitor for when the map is done moving. map.events.add('moveend', mapChangedView); function mapChangedView() { //Calculate a polygon for the map view. var viewPolygon = getMapViewPolygon(map); //Get all shapes in the datasource. var shapes = datasource.getShapes(); var pointsInView = []; //Do something with the points in view. //For demo purposes, we will simply output the name of each pin. var html = []; //Search for all point shapes that intersect the polygon. for (var i = 0; i < pins.length; i++) { if (shapes[i].getType() === 'Point' && isPointInPolygon(shapes[i].getCoordinates(), viewPolygon)) { pointsInView.push(shapes[i]); html.push(shapes[i].getProperties().name, '<br/>'); } } document.getElementById('output').innerHTML = pointsInView.length + ' pins in view:<br/><br/>' + html.join(''); } /** * Generates an array of polygons to create a polygon that represents the map view. * Coordinates are converted into mercator piels so we can do pixel accurate calculations. * @param map The map to calculate the view polygon for. */ function getMapViewPolygon(map) { //Simply using the bounding box of the map will not generate a polygon that represents the map area when it is rotated and pitched. //Instead we need to calculate the coordinates of the corners of the map. var mapRect = map.getCanvasContainer().getBoundingClientRect(); var width = mapRect.width; var height = mapRect.height; //Calculate positions from the corners of the map. var pos = map.pixelsToPositions([ //Top Left corner [0, 0], //Top right corner. [width, 0], //Bottom Right corner. [width, height], //Bottom left corner. [0, height] ]); //Convert the positions to mercator pixels at zoom level 22. return atlas.math.mercatorPositionsToPixels(pos, 22); } /** * Checks to see if a position is within a mercator polygon. * @param position A position point to determine if it is in a polygon. * @param mercatorPolygon Array of Mercator coordinates that form a polygon. */ function isPointInPolygon(position, mercatorPolygon) { //Convert point into a mercator pixel at zoom level 22 for pixel accurate calculations. var p = atlas.math.mercatorPositionsToPixels([position], 22)[0]; var x = p[0]; var y = p[1]; var inside = false; for (var i = 0, j = mercatorPolygon.length - 1; i < mercatorPolygon.length; j = i++) { var xi = mercatorPolygon[i][0], yi = mercatorPolygon[i][1]; var xj = mercatorPolygon[j][0], yj = mercatorPolygon[j][1]; if (((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) { inside = !inside; } } return inside; } ``` As an optimization, the code uses Mercator pixel coordinates at zoom level 22 (3cm/1" accuracy) so that it can use a basic geometry point in polygon algorithm rather than a more complex spatial algorithm using latitude/longitude which would require taking into consideration the curvature of the earth.
SwiftUI View not displaying data properly
|arrays|swift|database|view|foreach|
Using GNU awk for arrays of arrays and length(array): $ cat ./tst.sh #!/usr/bin/env bash arr=(test,meta my,amazon test,amazon this,meta test,google my,google hello,microsoft) printf '%s\n' "${arr[@]}" | awk -F',' ' { vals_locs[$1][$2] } END { for ( val in vals_locs ) { out = length(vals_locs[val]) " " val ": " sep = "" for ( loc in vals_locs[val] ) { out = out sep loc sep = ", " } print out } } ' <p> $ ./tst.sh 1 hello: microsoft 1 this: meta 2 my: google, amazon 3 test: google, amazon, meta
How to create data file path if not exists in postgres server using userchangelog.xml file changeset id i tried following ways but getting many errors. can any one suggest how can we create data file path from the application if it doesn't exist at the location while creating database using changesets ` DO $$ DECLARE BEGIN PERFORM pg_catalog.pg_stat_file('${DATAFILEPATHNAME}', false); EXCEPTION WHEN undefined_file THEN EXECUTE format('mkdir -p %s', '${DATAFILEPATHNAME}'); END; $$ LANGUAGE plpgsql; `
postgresql create data file path from application using userchangelog.xml file a
|java|postgresql|liquibase-sql|
null
One of the methods of my Entity class had a subclass type constraint with more than one target class, e.g. `protected virtual SomeMethod<T>(T arg): where T: Foo, Bar`. Not the comma-separated list after the `:`. NHibernate chokes on that, because of this code in the proxy generation code (GenerateMethodSignature() in ProxyBuilderHelper.cs): var typeConstraints = typeArg.GetGenericParameterConstraints() Select(x => ResolveTypeConstraint(method, x)); var baseTypeConstraint = typeConstraints.SingleOrDefault(x => x.IsClass); There is more than one type constraint with IsClass == true, so SingleOrDefault throws. In this case, I was able to remove the second type constraint and the problem was fixed.
Removing ```jaxws-rt``` dependency resolved the issue.
null
The apk needs to be zipaligned with parameter '4' for this specific purpose. If an external apk is used, then zipalign must be done manually or else the .so file inside the apk will refuse to load because of the wrong alignment. Even though you might think that the gradle build of your app already did a zipalign, that zipalign might not be aligned to the offsets required. If zipalign does not solve the issue, then check Android source code: bionic/linker/linker.cpp, function open_library_in_zipfile() which might give you more clues why the library is not loaded.
OS: vxWorks<br> I'm using `select()` system call to enforce timeout on serial port read functionality.<br> I am working on an IMU with data rate of 1000 Hz (IMU sends data every 1 ms).<br> The baud rate is 921600.<br> Every packet transfer is 36 bytes long. I calculate data transmission of 388-400 us per data transfer.<br> I calculated if no new bytes are received for 400 us then the packet is said to have been transferred.<br> The problem is as stated in the title select() always returns 0 and no data being read.<br> I've to use `select()` system call as in vxWorks `epoll()` is only supported for file descriptors of INET type. Code : int return_value; fd_set select_fd; struct timeval tv; //Run continuously till reader thread is to be executed this->data.clear(); while (not this->exitReaderThread.load()) { try { this->readBuffer.fill(0); FD_ZERO(&select_fd); FD_SET(this->fd, &select_fd); tv.tv_sec = 0; tv.tv_usec = 400; return_value = select(this->fd+1, &select_fd, nullptr, nullptr, &tv); std::cerr << "Select Return Value : " << return_value << std::endl; if(return_value == -1) //Error { perror("SerialPort select()"); //TODO Log Error continue; } else if(return_value > 0) //Data Available { if(FD_ISSET(this->fd, &select_fd) == true) { ssize_t returnValue = ::read(this->fd, this->readBuffer.data(), this->readBuffer.size()); if(returnValue == -1) { //TODO Log Error std::cout << "Error sending data on serial port " << this->portNumber <<". Error : " << errorToString(errno) << std::endl; continue; } this->data.append((char *)this->readBuffer.data(), returnValue); std::cerr << "Data Receive in progress\n"; } } else if(return_value == 0) //No Data Available { if(this->data.empty()) { continue; } std::cerr << "Data Receive Complete\n"; this->push_receive_data_in_queue("", this->portNumber, this->data); this->mCallbackSerialPort(this->portNumber, this->data); this->data.clear(); } } } ---------- Code to open and configure serial port this->fd = ::open("/usb2ttyS/0", O_RDWR); if(this->fd == -1) { std::cout << "Error open serial port. Error : " << errorToString(errno) << std::endl; return false; } struct termios tty; returnValue = tcgetattr(this->fd, &tty); tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF); tty.c_oflag &= ~OPOST; tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); tty.c_cflag &= ~(CSIZE | PARENB); switch(this->dataBits) { case 5: tty.c_cflag |= CS5; break; case 6: tty.c_cflag |= CS6; break; case 7: tty.c_cflag |= CS7; break; case 8 : default: tty.c_cflag |= CS8; break; } switch(this->stopBits) { case 2: tty.c_cflag |= CSTOPB; break; case 1: default: tty.c_cflag &= ~CSTOPB; break; } switch(this->parity) { case 'o': tty.c_cflag |= PARENB; //enable parity break; case 'e': tty.c_cflag |= PARENB; //enable parity tty.c_cflag &= ~PARODD; //disable odd parity, therefore-> even parity break; case 'n': default: tty.c_cflag &= ~PARENB; // No-Parity break; } returnValue = cfsetispeed(&tty, 921600); returnValue = cfsetospeed(&tty, 921600); returnValue = tcsetattr(this->fd, TCSANOW, &tty);
I am creating a secured back-end for a new app with Keycloak and NestJS. I imported my realm with clients and user in it and I am trying to get the token and access protected data through Insomnia. Trying to reach endpoint ```{{ _.baseUrl }}/protocol/openid-connect/auth``` with a ```POST``` request passing data through JSON is returning ``` keycloak-1 | 2024-03-11 16:01:56,436 WARN [org.keycloak.protocol.oidc.endpoints.request.AuthorizationEndpointRequestParserProcessor] (executor-thread-131) Parameter 'client_id' not present or present multiple times in the HTTP request parameters keycloak-1 | 2024-03-11 16:01:56,437 WARN [org.keycloak.events] (executor-thread-131) type="LOGIN_ERROR", realmId="55542514-fc71-4e4e-be3e-42af869de2a7", clientId="null", userId="null", ipAddress="172.18.0.1", error="invalid_request" ``` in my Docker Keycloak logs and a ```400 Bad request error``` in Insomnia response preview window. At first I was only passing my credentials and the error made me rethink the whole thing and pass client_id and client_secret as well i the JSON data yet error i still the same. I was following [this tutorial][1] but it does not seem suitable for a Keycloak environment How to reach to my Keycloak endpoints via Insomnia and furthermore how to get more verbose logs in the future ? [1]: https://www.ankursheel.com/blog/automatically-set-access-token-authenticated-requests-insomnia
HTTP request to keycloak with insommia
|oauth-2.0|keycloak|insomnia|
|sql|ms-access|
I have the exact same issue as the person who asked this question: https://stackoverflow.com/questions/74039512/fatal-unable-to-access-https-gitlab-xxxx-send-failure-connection-was-rese. They got it working again by disabling their antivirus. When I attempt to execute `git push -u origin main` or `git fetch`, I encounter the following error: > fatal: unable to access 'https://github.com/...': Send failure: Connection was reset. I've attempted the following troubleshooting steps: - disable everything in Kaspersky Total Security (all the "Essential Threat Protection", "Advanced Threat Protection", "Security Controls", and "Data Protection") - reset my network and tried two different ones as well - turn off IPv6 (restarted my computer as well) - re-install Git - create a new repository on GitHub - use Bitbucket instead of GitHub - uninstall Kaspersky VPN Additionally, I executed the following commands sequentially: ```bash git config --global http.sslVerify false git config --global --unset http.proxy git config --global --unset https.proxy git config http.postBuffer 524288000 ``` However, none of these solutions have worked for me. I would greatly appreciate any further suggestions. (Note: I refrained from commenting on the original question or providing an answer due to my insufficient reputation, as Stack Overflow advises against asking questions within answer sections.)
I need to color a table column background using Bootstrap. It was working before as follows: ```html <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" integrity="sha256-PI8n5gCcz9cQqQXm3PEtDuPG8qx9oFsFctPg0S5zb8g=" crossorigin="anonymous"> </head> <body> <div class="table-responsive mt-2"> <table class="table table-bordered table-striped mb-0"> <colgroup> <col> <col class="table-info"> <col> </colgroup> <thead class="text-center"> <th scope="col">Blah</th> <th scope="col">Blah</th> <th scope="col">Blah</th> </thead> <tr> <th scope="row" class="text-center">Blah</th> <td>Blah</td> <td>Blah</td> </tr> <tr class="table-info"> <th scope="row" class="text-center">Blah</th> <td>Blah</td> <td>Blah</td> </tr> <tr> <th scope="row" class="text-center">Blah</th> <td>Blah</td> <td>Blah</td> </tr> </table> </div> <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> </body> </html> ``` The website was working before updating to Bootstrap 5.3.3. I am using Bootstrap as: ```html <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" integrity="sha256-PI8n5gCcz9cQqQXm3PEtDuPG8qx9oFsFctPg0S5zb8g=" crossorigin="anonymous"> (...) <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> ``` Here is the fiddle: https://jsfiddle.net/vwkozhba/ **Edit**: The computed CSS shows the color: [![enter image description here][1]][1] **Edit 2**: Included minimal reproducible example and the fiddle. [1]: https://i.stack.imgur.com/SKoAV.png
I don't know when this was added, but it is present in Safari on El Capitan (Safari 9.0). It works the same as in Chrome (right click in the console window and select "Keep Log on Navigation"). **Update:** As per [Daniel Compton's answer](https://stackoverflow.com/a/46508266/792525), in Safari 11+ this is now under the settings icon as 'Console: Clear when page navigates'. **Update:** The setting is now back to "Preserve log" in the Network tab in the developer console in Safari 14+ **Update:** At least in Safari 17 (not sure about 15-16), there are separate "Preserve Log" options for the Network tab and the Console. It's under the menu icon that looks like a circle with three horizontal lines of descending lengths and appears in the top bar of each tab.
I am working in a CMS (Modern Campus) that is XML-based. XSLT is still a thing i'm attempting to learn on the fly, so I am not well-versed in this area yet. Our CMS is building a blog feed (which we use for news) using the following code: <items> <!--Internal News Articles--> <xsl:for-each select="$internal-doc/items/item"> <xsl:sort select="concat(substring(pubDate,7,4), substring(pubDate,1,2),substring(pubDate,4,2))" order="descending"/> <xsl:if test="not(articlePreview) or articlePreview != 'true'"> <item> <xsl:apply-templates select="attribute()|node()" /> <searchtags>{string-join(tags/tag, ',')}</searchtags> </item> </xsl:if> </xsl:for-each> <!--External News Articles--> <xsl:if test="$include-broadcast='true'"> <!--Check to see if broadcast option is on, if so, get external news articles--> <xsl:for-each select="$array"> <xsl:variable name="external-doc" select="(.)" /> <!--Get current array item--> <xsl:variable name="base-url" select="tokenize($external-doc, '/_resources')[1]" /> <!--Get website URL, need to use it for link to news and images--> <xsl:for-each select="$external-doc/document(.)/items/item"> <xsl:sort select="concat(substring(pubDate,7,4), substring(pubDate,1,2),substring(pubDate,4,2))" order="descending"/> <xsl:if test="contains(broadcast,$broadcast-unit)"> <item> <xsl:attribute name="href" select="concat($base-url,@href)"/> <xsl:apply-templates select="attribute()[not(name() = 'href')]|node()[not(name() = 'hero-image') and not(name() = 'image')]" /> <xsl:if test="image"> <image> <xsl:choose> <xsl:when test="not(contains(image/img/@src,'://'))"> <img> <xsl:attribute name="src" select="concat($base-url,image/img/@src)"/> <xsl:apply-templates select="image/img/attribute()[not(name() = 'src')]" /> </img> </xsl:when> <xsl:otherwise><xsl:apply-templates select="image/img" /></xsl:otherwise> </xsl:choose> </image> </xsl:if> <searchtags>{string-join(tags/tag, ',')}</searchtags> </item> </xsl:if> </xsl:for-each> </xsl:for-each> </xsl:if> </items> The code works great - the second half of the code looks at an external blog feed to see if it needs to bring in any items from it. This code works as well. The issue I'm having, or unsure of how to accomplish, is performing a final sort based on the pubDate. As it currently stands, when the feed is built, the internal news articles are sorted, and then when the external news articles are added, they too are sorted, but both are sorted separately. What I want is a final sort so that if an external news article happens to have a newer date than an internal news article, it will appear at the top of the feed, not at the end of the feed, as the code will presently do. How can I accomplish this?
|python|opencv|mss|
null
It's basically a one-liner with the modern APIs (iOS 14+) ``` let limit = 10 //... TextField("", text: $text) .onChange(of: text) { text in self.text = String(text.prefix(limit)) } ```
Yes, vanilla SwaggerUI supports PKCE! I run SwaggerUI with PKCE in docker with the following command: docker run --rm -p 80:8080 \ -v ~/Desktop/SWAGGER_UI:/foo \ -e SWAGGER_JSON=/foo/my-service-openapi.yml \ -e OAUTH_CLIENT_ID=my-service-client-id \ -e OAUTH_SCOPES="openid offline" \ -e OAUTH_USE_PKCE=true \ swaggerapi/swagger-ui (Place your OpenAPI spec in "~/Desktop/SWAGGER_UI/my-service-openapi.yml") You can see the settings [here][1] In the OpenAPI Spec you can define it like described [here][2]! You have to change to "authorizationCode": components: securitySchemes: oAuthSample: type: oauth2 description: This API uses OAuth 2 flows: authorizationCode: authorizationUrl: https://your-host.com/oauth2/auth tokenUrl: https://your-host.com/oauth2/token refreshUrl: https://your-host.com/oauth2/token scopes: openid: openid scope offline: offline scope [1]: https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/ [2]: https://swagger.io/docs/specification/authentication/oauth2/
There is no way that EF Core is bypassing your triggers. There must be a bug in the trigger logic. Your trigger as it stands may or may not be correct, but it uses a huge amount of Bad Stuff: * Cursors, instead of a joined update. * You would need to join `inserted` and `deleted` using a full-join, although in this case, because you want a qiantity difference, it could make more sense to use `UNION ALL` and `GROUP BY`. * Use of three-part column names. * Lack of table aliases to make it more readable. * Checking `TRIGGER_NESTLEVEL` without passing an object ID. * One would hope that `(WarehouseId, ComponentId, ColorId)` is a primary or unique key in both tables, otherwise you may end up updating multiple rows. Your trigger should look like this: ```tsql CREATE OR ALTER TRIGGER dbo.tr_update_stocks ON dbo.WarehouseComponentLoadRows AFTER INSERT, UPDATE, DELETE AS IF @@ROWCOUNT = 0 OR TRIGGER_NESTLEVEL(@@PROCID) > 1 RETURN; SET NOCOUNT ON; UPDATE wc SET StockQuantity += i.DiffQuantity, AvailableQuantity += i.DiffQuantity FROM dbo.WarehouseComponents wc JOIN ( SELECT i.WarehouseId, i.ComponentId, i.ColorId, SUM(i.Quantity) AS DiffQuantity FROM ( SELECT i.WarehouseId, i.ComponentId, i.ColorId, i.Quantity FROM inserted i UNION ALL SELECT d.WarehouseId, d.ComponentId, d.ColorId, -d.Quantity FROM deleted d ) i GROUP BY i.WarehouseId, i.ComponentId, i.ColorId ) i ON i.WarehouseId = wc.WarehouseId AND i.ComponentId = wc.ComponentId AND i.ColorId = wc.ColorId; ``` ____ **To be honest,** if you all you want is the total child quantity then **you should probably just use a view** instead of triggers. ```tsql CREATE VIEW dbo.TotalWarehouseComponentLoadRows WITH SCHEMABINDING AS SELECT wcl.WarehouseId, wcl.ComponentId, wcl.ColorId, SUM(wcl.Quantity) AS Quantity, COUNT_BIG(*) AS Count FROM dbo.WarehouseComponentLoadRows wcl GROUP BY wcl.WarehouseId, wcl.ComponentId, wcl.ColorId; ``` For extra performance, you could make that into an indexed view. ```tsql CREATE UNIQUE CLUSTERED INDEX IX ON WarehouseComponentLoadRows (WarehouseId, ComponentId, ColorId); ```
null
I'm trying to show/hide more info about names on click, but don't know how to make it work of a single click. I'm creating a div with JS like so: const newDiv = document.createElement("div"); newDiv.className = "game-info"; newDiv.innerHTML = ` <p onclick="toggler()";>${game.Name}</p> <div class="info"> <img src="${game.Thumbnail}"> <p>${game.Description}</p> </div> `; document.body.appendChild(newDiv); The toggler function is written like this: function toggler(){ $('div.game-info').click(function(e){ $(this).children('.info').toggle(); }); } It kinda works, but it takes one or more clicks to view the additional info. I know the problem is due to multiple onclick calls, but don't know how to make it with a single click. I tried using jQuery without the toggler function, but then it opens info on all the names and not just the one which was clicked. So if someone could either tell me how to get rid of that secondary onclick or how to properly target the info which I clicked in the innerHTML section that'd be great!
How can I remove one of the clicks from hide/show?
|javascript|jquery|onclick|
null
I ran into the same issue and have found a workaround. In my viewmodel I have an ObservableCollection Projects which is displayed using a CollectionView on my ContentPage. Then I have the following method: public async Task ReloadProjects() { var temp = Projects.ToList(); Projects.Clear(); await Task.Delay(1); foreach (var project in temp) { Projects.Add(project); } } This gets method gets called from the code-behind of my ContentPage each time the page is resized: private async void OnPageSizeChanged(object sender, EventArgs e) { await viewModel.ReloadProjects(); } This asynchronous reloading of my Projects correctly rescales the width of my grid columns. I'm wondering if there's a better fix for this issue though and would love to hear if you found something else.
here is the link to my gist https://gist.github.com/tomleejumah/d11d1996bce8957c140c90e7856e01eb I do have a bug in fetching whereby it doesnt fetch Im requesting help in debugging
How to work with youtube dl android library
|android|rx-java|youtube-dl|
{"OriginalQuestionIds":[7395542],"Voters":[{"Id":523612,"DisplayName":"Karl Knechtel","BindingReason":{"GoldTagBadge":"python"}}]}
It is the `@abstractmethod` decorator that is causing you problems. It's because use of this decorator implies that a method must be overridden, which conflicts with the use of protocols as a mechanism for type checking rather than behavioral enforcement. The point of protocol is to define an interface that other classes can implement, not to enforce implementation of methods through inheritance (see [Protocol docs](https://typing.readthedocs.io/en/latest/spec/protocol.html)). Removing this decorator should solve the problem, however when I checked that with PyCharm Community version, I linter still complained with ``` Type of "get_context_data" is incompatible with "HasViewProtocol" ``` so small refactoring to implementation of `get_context_data()` is additionally needed to make it shut up: ```python def get_context_data(self, **kwargs) -> dict: context = super().get_context_data(**kwargs) context.update({"extra_data": "bla"}) return context ```
Sorting items after building an XML feed?
|xml|xslt|
While this is *legal* in that you can write it and it will execute correctly, it seems very ugly to me; a simple `if`...`else` would appear to be able to express the intent while actually being clearer. I would even go as far as to say that I would expect that to normally be true. ```tcl # Just the bit inside the switch case chan puts stdout opt_2 if { [info exists ui_state] && $ui_state == $valid && [catch { # This is a stand-in for something real, right? Right? throw {Database Error} "Failed to Write" } result] } then { chan puts stdout "${result}. Rolled back" set rv 1 set response "Operation Failed" } else { chan puts stdout "Opt_1 code to run only when\ no valid ui_state or valid state succeeds." set rv 0 set response "Successful write." } ``` Would there be a case where doing this convoluted thing with a run-once `while` is best? I doubt it... but never say never. ---- A run-once `for` would be slightly better, provided you put `break` in the increment clause. Like that, it's clearer at the top what you are doing. Or you could use `try` with an `on break` clause.
I'm making a quick draft for a project I'm doing and I can't seem to get winsound module to work. Well the module would load no yellow error line, and won't tell me that it doesn't exist. It even does the rest of the lines opening up the browser. But the audio doesn't play, ------------------------------------------------------------------------------------ if messagebox.showerror(title="*ANGRY*", message="ALRIGHT THIS IS WHAT YOU GET!!!"): if messagebox.showerror(title="sus", message="MY SUPER LASER PISS!!!!!!!!!!!!!!!!!!!!!!!!"): for i in range(1): winsound.PlaySound('SUPERLASERPISS.mp3', winsound.SND_FILENAME) webbrowser.open("https://www.bing.com/images/search?q=PISS&form=HDRSC3&first=1") ------------------------------------------------------------------------------------------------- I used "SND_FILENAME" instead of 0 to see if that would fix ti but it wouldnt. I expected it to play the sound, end of story. (and also open up 100 tabs of eggman but that's not the point) It won't play.
Winsound not working isn't working at all
|python|audio|
null
Encountering issue regarding 'pip install bytetrack' on my pycharm project
I am working with a school project where I need to obtain the analyst price targets estimates of certain stocks from the Yahoo Finance Website (this is mandatory). When I tried to use it by beatiful soup I couldn't scrape it (I believe JS is adjusting the page as it laods), so I turned to selenium to obtain such data. However when I'm trying to obtain the elements through the XPATH, it returns error as if it doesn't exist. I am using EC in case it needs to load, but its not working. I've tried modifying the wait times up until 2 minutes, so that is not the issue Code below: ```from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument("--headless") chrome_options.add_argument(f'user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36') chrome_options.add_argument("window-size=1920,1080") driver = webdriver.Chrome(options=chrome_options) driver.get("https://finance.yahoo.com/quote/BBAJIOO.MX?.tsrc=fin-srch") driver.delete_all_cookies() WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="Col2-11-QuoteModule-Proxy"]/div/section/div/div[2]/div[1]/span[2]'))) ``` Anyone has an idea as to why this is happening? and how can I obtain such ratings? Image below of desired ratings [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/mBp3Q.png
|excel|vba|solidworks|
I want to generate apk in vs code by command `flutter build apk` but after execute it in vs code terminal, returns this error : > No Android SDK found. Try setting the ANDROID_HOME environment variable. [![enter image description here][1]][1] So i defined `ANDROID_HOME` in environment variable : [![enter image description here][2]][2] These are the contents of Android SDK release 26 : [![enter image description here][3]][3] But problem not solved and occures same error again. there is solution for this problem? [1]: https://i.stack.imgur.com/denno.jpg [2]: https://i.stack.imgur.com/zwPGg.jpg [3]: https://i.stack.imgur.com/3lgFT.jpg
I have logic app that needs to read messages from teams which I want to provision via terraform on portal I can login to teams with my user and connection works. I am not sure how to setup api-connection teams and how to pass my user for login inside Iac? any idea this is my team api-connection? ``` resource "azapi_resource" "teams-connection" { type = "Microsoft.Web/connections@2016-06-01" name = "teams" parent_id = azurerm_resource_group.resource_group_name.id location = var.location body = jsonencode({ properties = { api = { id = data.azurerm_managed_api.teams-api.id, type = "Microsoft.Web/locations/managedApis" } authentication = { type = "ManagedServiceIdentity" } parameterValueSet: { name: "managedIdentityAuth" values: {} } } }) schema_validation_enabled = false }
logiapp teams api connection terraform user sign in
|terraform|microsoft-teams|azure-logic-apps|
I think this could be best achieved by: select my_column, row_number() over (order by my_column) as No from my_table
Log retation setting for ECS
{"Voters":[{"Id":1744164,"DisplayName":"Sir Rufo"},{"Id":1136211,"DisplayName":"Clemens"},{"Id":426185,"DisplayName":"Andy"}],"SiteSpecificCloseReasonIds":[13]}
A minute ago, I wrote a function without return of finding max value in C++, ```cpp #include <iostream> #include <algorithm> using namespace std; int myItem(int x, int y, int z) { int a = std::max(x, y); int b = std::max(a, z); // return b; } int main() { cout << myItem(2, 5, 16); } ``` But, why it returns max value without `return`? On the Windows, g++ (MinGW.org GCC-6.3.0-1) 6.3.0.
Why it returns max anyway?
|c++|return|
null
Since I was not so versed at awk, I tried python for the job. Interestingly I need much more code than in awk. But it delivers the requested output and is readable. Though it still can be improved in style and campactness. Btw it seems you don't need the keyword "pac". public AResponse retrieveA(ARequest req){ String server = "AAA"; String method = "retrieveA()"; log.info(method, server, req); return res; } public BResponse retrieveB(BRequest req){ String method = "retrieveB()"; BBB pac = new BBB(); log.info(method, pac, req); return res; } public CResponse retrieveC(CRequest req) { String server = "CCC"; log.info(server, req); return res; } public DResponse retrieveD(DRequest req) { String method = "retrieveD()"; log.info(method,req); return res; } public EResponse retrieveE(ERequest req){ EEE pac = new EEE(); String method = "retrieveE()"; String server = "EEE"; log.info(method, server, pac, req); return res; }
Dialogflow Webhook response format (Dialogflow messenger)
import pandas as pd import numbers data = {'value':[100, 150, 200, 250], 'coupon':[3,'-',4,5], 'income':[3,'-',8,'-']} df = pd.DataFrame(data) def filler(value, coupon, income): if not isinstance(income, numbers.Number) and isinstance(coupon, numbers.Number): income = (coupon * value) / 100 return income else: return income df['income'] = df.apply(lambda row: filler(row['value'], row['coupon'], row['income']), axis=1) print(df)
Here are three improvements for your post: 1) The logic for your states looks 'pulled out' or extracted from the original state machine process and put into separate processes. I put it back for you so that you no longer have separate processes, which eliminates the possibility of multiple drivers which was pointed out by @Greg in the comments. I put is some comments and block names to make the SM easier to read. ``` module robertson( input clk, input reset, input [15:0] Q, input [15:0] M, output reg [31:0] z ); parameter STATE_IDLE = 2'b00; parameter STATE_PROCESS = 2'b01; parameter STATE_DONE = 2'b10; reg [1:0] state_reg; reg [4:0] counter; reg F; wire overflow; reg [15:0] A_reg; wire [15:0] A_wire; reg [15:0] Q_reg; wire [15:0] Q_wire; wire [15:0] M_neg; wire [31:0] AQ_wire; wire [3:0] moved_time_wire; zero zero_i(.z(moved_time_wire)); noop noop_i(.x(M),.z(M_neg)); shifter shifter_i( .f(F), .x({A_reg,Q_reg}), .y(AQ_wire), .counter(moved_time_wire)); CSkA CSkA_i( .x(AQ_wire[31:16]), .y(M), .c_in(1'b0), .z(A_wire), .c_fin(overflow) ); always @(posedge clk or negedge reset) begin if (~reset) begin state_reg <= STATE_IDLE; counter <= 0; F = 1'b0; Q_reg = Q; A_reg = 16'b0; end else begin case(state_reg) // -------------------------------------- // idle // -------------------------------------- STATE_IDLE: begin state_reg <= STATE_PROCESS; end // -------------------------------------- // process // -------------------------------------- STATE_PROCESS: begin :STATE_PROCESS_BLOCK if (counter == 15) begin state_reg <= STATE_DONE; end //***************************************** // Move code here to avoid multiple drivers //***************************************** if(moved_time_wire != 0) begin counter <= counter + moved_time_wire; end else begin counter <= counter + 1; end A_reg <= A_wire; Q_reg <= AQ_wire[15:0]; end :STATE_PROCESS_BLOCK // -------------------------------------- // done // -------------------------------------- STATE_DONE: begin :STATE_DONE_BLOCK state_reg <= STATE_IDLE; if (state_reg == STATE_DONE) begin if(Q_reg[0] == 1'b1) begin A_reg <= A_reg + M_neg; Q_reg[0] <= 0; z <= {A_reg,Q_reg}; end else begin z <= {A_reg,Q_reg}; end end end :STATE_DONE_BLOCK endcase end end endmodule ``` 2) In this snippet of code ``` if (~reset) begin state_reg <= STATE_IDLE; counter <= 0; F = 1'b0; Q_reg = Q; // this line is bad A_reg = 16'b0; end else begin ``` You don't want to assign one variable to another in the reset part of a synchronous process. In this example you are assigning `Q_reg = Q;` You probably want to assign it elsewhere. The reset is used to initialize to a constant value (0, 1, 3'b111, etc). 3) In the same snippet of code use non-blocking assignments `<=` rather than blocking assignments `=`. Non-blocking is used for modeling synchronous logic, blocking is used for modeling combinational logic. ``` if (~reset) begin state_reg <= STATE_IDLE; counter <= 0; F <= 1'b0; // changed to non-blocking Q_reg <= Q; // changed to non-blocking A_reg <= 16'b0; // changed to non-blocking end else begin ``
I am unable to create a build with this command: `docker build -t feedback-node .` Although docker was working fine previously. I have also tried almost all the available suggestions but found nothing that could resolve it. [![This is the snapshot of it ](https://i.stack.imgur.com/igImj.png)](https://i.stack.imgur.com/igImj.png) I was trying to build an image with the tag feedback-node and was expecting the id of the image after build. This is the Dockerfile ```dockerfile FROM node:14 WORKDIR /app # .represents the current directory COPY package.json . RUN npm install COPY . . EXPOSE 80 CMD ["node", "server.js"] ```
I am working on a Flutter web project with firebase authentication. When I select "All exceptions" in the breakpoints tab in visual studio code I get this exception: > FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app). I have looked all over the place and I understand comments such as "You are probably invoking firebase before the app is initialized. All calls to firebase must come after .initializeApp(); firebase." However if you look at my code I am not calling anything before it, the only thing coming before that is loading my environment files for api keys etc. Here is the culprit: ``` import 'package:appname_web/app.dart'; import 'package:appname_web/bootstrap.dart'; import 'package:appname_web/firebase_options.dart'; import 'package:appname_web/src/_src.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await dotenv.load(fileName: 'dotEnv.dev'); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); await bootstrap(() => const App(AppEnvironment.development)); } ``` The exception does not happen at all if I don't select the "all exceptions" breakpoint I have tried what most people suggest on Stack Overflow, but they are telling me to structure my code the same way its already structured
|flutter|firebase|dart|
null
I have a neo4j graph: (person)-[like]-(fruit). I want to find person of person of person recursively using [like] and (fruit). For example, (John)-[like]->(Apple)<-[like]-(Sam)->[like]-(Banana)<-[like]-(Jack)-[like]->(Grape)<-[like]-(Lisa)... How can I query this relationship using the neo4j?
If I understand your logic correctly, this is easily done using `ave`. > transform(asd1, id=ave(a, x, FUN=\(x) c(x[-1], NA))) x a b id 1 g 1 5 3 2 g 3 6 5 3 g 5 7 NA 4 h 1 8 7 5 h 7 9 8 6 h 8 5 NA > transform(asd2, id=ave(a, x, FUN=\(x) c(x[-1], NA))) x a b id 1 g 1 5 3 2 g 3 6 5 3 g 5 7 NA 4 h 1 8 7 5 h 7 9 8 6 h 8 5 6 7 h 6 4 NA ---- *Data:* > dput(asd1) structure(list(x = c("g", "g", "g", "h", "h", "h"), a = c(1, 3, 5, 1, 7, 8), b = c(5, 6, 7, 8, 9, 5)), class = "data.frame", row.names = c(NA, -6L)) > dput(asd2) structure(list(x = c("g", "g", "g", "h", "h", "h", "h"), a = c(1, 3, 5, 1, 7, 8, 6), b = c(5, 6, 7, 8, 9, 5, 4)), class = "data.frame", row.names = c(NA, -7L))
I'm not sure where to start with this one. I have a list of obsolete items with a new item_code listed somewhere in the description column. Item codes are always between 8 & 12 characters so all other numbers in the description should be ignored. import pandas as pd df1 = pd.DataFrame({'Item_Code': ['00001234', '00012345', '00123456', '01234567'], 'Desc': ['Widget1 - Obsolete Use Alternative 56789100', 'Obsolete Widget 2 - Use Alternative 56789100 - Blah Blah Blah', 'Alternative Use 9999999910 - Blah Blah Blah', 'Obsolete use 99999999911']}, index=[0, 1, 3, 4]) print(df1.head(10)) [![enter image description here][1]][1] So ideally I'm looking to have the alternative codes in a new column. [![enter image description here][2]][2] [1]: https://i.stack.imgur.com/tvW0t.png [2]: https://i.stack.imgur.com/UBBJx.png
Python 3 Data Frame string manipulation to extract numbers between 8 to 12 characters
|python|python-3.x|
I use https://webgpu.github.io/webgpu-samples/ I wanna integrate simple texture to the https://webgpu.github.io/webgpu-samples/?sample=shadowMapping example. loadTex (this.texture0) ```js async loadTex0(texturesPaths, device) { return new Promise(async (resolve) => { const response = await fetch(texturesPaths[0]); const imageBitmap = await createImageBitmap(await response.blob()); this.texture0 = device.createTexture({ size: [imageBitmap.width, imageBitmap.height, 1], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT, }); var texture0 = this.texture0 device.queue.copyExternalImageToTexture( {source: imageBitmap}, {texture: texture0}, [imageBitmap.width, imageBitmap.height] ); resolve() }) } ``` Fow begin i just put ```js this.sceneBindGroupForRender = this.device.createBindGroup({ layout: this.bglForRender, entries: [ { binding: 0, resource: { buffer: this.sceneUniformBuffer, }, }, { binding: 1, resource: this.shadowDepthTextureView, }, { binding: 2, resource: this.device.createSampler({ compare: 'less', }), }, // ADDED HERE { binding: 3, resource: this.texture0.createView(), }, ], }); ``` I need shaders also to be updated... I not sure is it posible some inject intro `texture_depth_2d`: ```WGSL @group(0) @binding(1) var shadowMap: texture_depth_2d; @group(0) @binding(2) var shadowSampler: sampler_comparison; ``` OR i need to add new tec sample and texture and then in main func to call something like `color.rgb += texture` ``` this.sceneBindGroupForRender = this.device.createBindGroup({ layout: this.bglForRender, entries: [ { binding: 0, resource: { buffer: this.sceneUniformBuffer, }, }, { binding: 1, resource: this.shadowDepthTextureView, }, { binding: 2, resource: this.device.createSampler({ compare: 'less', }), }, { binding: 3, resource: this.sampler, }, { binding: 4, resource: texture.createView(), }, ], }); ``` ``` export let fragmentWGSL = `override shadowDepthTextureSize: f32 = 1024.0; struct Scene { lightViewProjMatrix : mat4x4f, cameraViewProjMatrix : mat4x4f, lightPos : vec3f, } @group(0) @binding(0) var<uniform> scene : Scene; @group(0) @binding(1) var shadowMap: texture_depth_2d; @group(0) @binding(2) var shadowSampler: sampler_comparison; @group(0) @binding(3) var meshSampler: sampler; @group(0) @binding(4) var meshTexture: texture_2d<f32>; struct FragmentInput { @location(0) shadowPos : vec3f, @location(1) fragPos : vec3f, @location(2) fragNorm : vec3f, } const albedo = vec3f(0.9); const ambientFactor = 0.2; @fragment fn main(input : FragmentInput) -> @location(0) vec4f { // Percentage-closer filtering. Sample texels in the region // to smooth the result. var visibility = 0.0; let oneOverShadowDepthTextureSize = 1.0 / shadowDepthTextureSize; for (var y = -1; y <= 1; y++) { for (var x = -1; x <= 1; x++) { let offset = vec2f(vec2(x, y)) * oneOverShadowDepthTextureSize; visibility += textureSampleCompare( shadowMap, shadowSampler, input.shadowPos.xy + offset, input.shadowPos.z - 0.007 ); } } visibility /= 9.0; let lambertFactor = max(dot(normalize(scene.lightPos - input.fragPos), normalize(input.fragNorm)), 0.0); let lightingFactor = min(ambientFactor + visibility * lambertFactor, 1.0); let textureColor = textureSample(meshTexture, meshSampler, input.shadowPos.xy); return vec4(textureColor.rgb * lightingFactor * albedo, 1.0); }` ``` LOG : ``` Binding doesn't exist in [BindGroupLayout]. - While validating that the entry-point's declaration for @group(0) @binding(3) matches [BindGroupLayout] - While validating the entry-point's compatibility for group 0 with [BindGroupLayout] - While validating fragment stage ([ShaderModule], entryPoint: ). - While validating fragment state. - While calling [Device].CreateRenderPipeline([RenderPipelineDescriptor]). ``` LAST LOG ``` The sample type in the shader is not compatible with the sample type of the layout. None of the supported sample types (Float|UnfilterableFloat) of [Texture] match the expected sample types (Depth). - While validating entries[3] as a Texture. Expected entry layout: { binding: 3, visibility: ShaderStage::(Vertex|Fragment), texture: { sampleType: TextureSampleType::Depth, viewDimension: TextureViewDimension::e2D, multisampled: 0 } } - While validating [BindGroupDescriptor] against [BindGroupLayout] - While calling [Device].CreateBindGroup([BindGroupDescriptor]). ``` Any suggestion ?
I have 4 LEDs which represent left, right, open and down. I also have a Joystick. My goal is it to light up one LED and move the joystick to this direction. I am almost finished, but I am now realising, that my code only checks the Joystick position when the LED is set On (really short timeframe). How can I let my code check the joystick input during the delay time i have included, to even make this game playable? ``` int r = 10; //right int o = 11; //up int l = 12; //left int u = 13; //down int highscore = 0; boolean checker = true; boolean start = false; char wo; int i = 0; int points = 0; //LCD IC2 libaries #include <Wire.h> // Wire Bibliothek #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x3f, 16, 2); //Joystick #define VRX_PIN A0 // Arduino pin connected to VRX pin #define VRY_PIN A1 // Arduino pin connected to VRY pin #define LEFT_THRESHOLD 400 #define RIGHT_THRESHOLD 800 #define UP_THRESHOLD 400 #define DOWN_THRESHOLD 800 #define COMMAND_NO 0x00 #define COMMAND_LEFT 0x01 #define COMMAND_RIGHT 0x02 #define COMMAND_UP 0x04 #define COMMAND_DOWN 0x08 int xValue = 0 ; // To store value of the X axis int yValue = 0 ; // To store value of the Y axis int command = COMMAND_NO; void setup() { Serial.begin(9600); pinMode(r, OUTPUT); pinMode(o, OUTPUT); pinMode(u, OUTPUT); pinMode(l, OUTPUT); //initialize lcd screen lcd.init(); // turn on the backlight lcd.backlight(); lcd.setCursor(0,0); lcd.print("Bewege den Joy-"); lcd.setCursor(0,1); lcd.print("stick nach unten"); } void loop() { //Joystick part xValue = analogRead(VRX_PIN); yValue = analogRead(VRY_PIN); // converts the analog value to commands // reset commands command = COMMAND_NO; // check left/right commands if (xValue < LEFT_THRESHOLD) command = command | COMMAND_LEFT; else if (xValue > RIGHT_THRESHOLD) command = command | COMMAND_RIGHT; // check up/down commands if (yValue < UP_THRESHOLD) command = command | COMMAND_UP; else if (yValue > DOWN_THRESHOLD) command = command | COMMAND_DOWN; int randomChoice = random(4); // Generiert eine Zufallszahl zwischen 0 und 3 if (start == true && i<10){ switch (randomChoice) { case 0: digitalWrite(r, HIGH); digitalWrite(o, LOW); digitalWrite(u, LOW); digitalWrite(l, LOW); wo = r; i ++; break; case 1: digitalWrite(r, LOW); digitalWrite(o, HIGH); digitalWrite(u, LOW); digitalWrite(l, LOW); wo = o; i ++; break; case 2: digitalWrite(r, LOW); digitalWrite(o, LOW); digitalWrite(u, HIGH); digitalWrite(l, LOW); wo = u; i ++; break; case 3: digitalWrite(r, LOW); digitalWrite(o, LOW); digitalWrite(u, LOW); digitalWrite(l, HIGH); wo = l; i ++; break; default: digitalWrite(r, LOW); digitalWrite(o, LOW); digitalWrite(u, LOW); digitalWrite(l, LOW); break; } delay(200); digitalWrite(r, LOW); digitalWrite(o, LOW); digitalWrite(u, LOW); digitalWrite(l, LOW); lcd.clear(); lcd.setCursor(0,0); lcd.print(i); lcd.print(" von 10"); lcd.setCursor(0,1); lcd.print(points); lcd.print(" Treffer"); delay(random(800, 2500)); // print command to serial and process command if (command & COMMAND_LEFT && wo == l) { Serial.println("COMMAND LEFT"); points ++; } if (command & COMMAND_RIGHT && wo == r) { Serial.println("COMMAND RIGHT"); points ++; } if (command & COMMAND_UP && wo == o) { Serial.println("COMMAND UP"); points ++; } if (command & COMMAND_DOWN && wo == u) { Serial.println("COMMAND DOWN"); points ++; } } if (points>highscore){ highscore = points; } if(i==10){ start = false; delay(50); lcd.setCursor(0,0); lcd.print("Punkte: "); lcd.print(points); lcd.setCursor(0,1); lcd.print("Highscore: "); lcd.print(highscore); if (command & COMMAND_DOWN && checker == false){ start = true; i = 0; points = 0; } } } ```