instruction
stringlengths
0
30k
So I have a navbar, and in this navbar I have the logo, the options and then the button. Whenever I apply padding to the button it pushes everything else to the left? Any advice cause I have never had this happen before. This happens with other stuff as well, so if I give the logo any padding it also pushes the items around. Why is this happening because I watched some tutorials just to be sure and I have no clue what I am doing wrong. ``` <div class="container"> <section class=section1> <div class="navbar"> <label class="logo">appy</label> <ul class="nav-buttons"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Pricing</a></li> <li><a href="#">Features</a></li> <li><a href="#">FAQ</a></li> </ul> <a href="#" class="sign-up">SIGN UP</a> </div> CSS: *{ margin: 0; padding: 0; box-sizing: border-box; } html{ font-size: 10px; } .container{ height: auto; width: 100%; /* overflow: hidden; */ } .section1{ background: rgb(180,135,238); background: linear-gradient(90deg, rgba(180,135,238,1) 0%, rgba(148,187,233,1) 100%); } .logo{ font-size: 4rem; font-family: "Protest Revolution", sans-serif; font-weight: 400; font-style: normal; color: white; margin-bottom: 10px; margin-left: -10px; } .navbar{ width: 100%; font-family: 'Montserrat', sans-serif; background: rgb(180,135,238); background: linear-gradient(90deg, rgba(180,135,238,1) 0%, rgba(148,187,233,1) 100%); display: flex; justify-content: space-between; align-items: center; padding: 25px 40px; position: sticky; top: 0; z-index: 99999; } .nav-buttons li{ font-weight: 500; font-size: 1.7rem; display: inline-block; padding: 20px; list-style: none; } .nav-buttons li a{ color: white; text-decoration: none; } .navbar .sign-up{ color: white; font-size: 1.5rem; text-decoration: none; border: 2px solid white; border-radius: 5px; padding: 8px 50px 8px 50px; }
SQL Query to Track Production Operations Outcome Progression with Conditional NULLs
|sql|sql-server|
Found a number of issues here: First, range in line 25 is calling a sheet, not a range of cells. I have changed it to `e.range` to call on the event object. Also, I believe you have to use an installable onEdit trigger to utilize the mail service. I changed the name of your function from `onEdit` to `onMyEdit` and set up an onEdit trigger. [![Screenshot1][1]][1] [![Screenshot2][2]][2] [![Screenshot3][3]][3] Second there are some misspellings: First, `senEmail()` in line 4 and line 23. Doesn't matter if you don't call that function but you do in the last line of your code. Second, `getRagne()` in line 37 and line 38. Additionally, I got the following error after these corrections had been made: > Exception: The parameters (String,String,String,String,String) don't > match the method signature for MailApp.sendEmail. I combined messageBody, messageBody2, and respondent to bring it in line with the method signature. Finally, you have name and email calling on the same cell. I changed the name to Column 3, but if this assumption is incorrect it can easily be modified. These changes are reflected in the code below: function onMyEdit(e) { addTimeStamp(e); sendEmail(e); } function addTimeStamp(e){ var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet5") ; var range = e.range; var row = range.getRow(); var col = range.getColumn(); var cellValue = range.getValue(); if (col == 9 && cellValue === true){ sheet.getRange(row,10).setValue(new Date()); } } function sendEmail(e){ var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet5") ; var range = e.range; var row = range.getRow(); var col = range.getColumn(); let cellValue = range.getValue(); // The value of the edited cell // Check if the edit occurred in column 5 and the value is true if (col == 9 && cellValue === true) { let email = sheet.getRange(row, 2).getValue(); let name = sheet.getRange(row, 3).getValue(); let orderID = sheet.getRange(row, 5).getValue(); let orderDate =sheet.getRange(row, 1).getValue(); let methodOfPayment = sheet.getRange(row, 4).getValue(); let numberOfTickets = sheet.getRange(row, 6).getValue(); let payableTotal = sheet.getRange(row, 7).getValue(); let html_link ="https://checkout.payableplugins.com/order/"+orderID; const subject = "PHLL Raffle Fundraiser Follow-Up on Order ID #" + orderID ; const messageBody = 'Dear ' + name + ',' + "\n\n" + 'We hope this message finds you well. We wanted to remind you that we have received your order information for the raffle ticket. According to our records, you have selected the cash method for payment, but we have not yet received the payment.' + "\n\n" + 'If you have already provided the payment to the player, please let us know as soon as possible. This will allow us to coordinate with them to ensure that your payment is collected and your raffle ticket is processed accordingly.' + "\n\n" + 'However, if you have not yet provided the payment to the player, we kindly ask you to do so at your earliest convenience. Once the payment is received, we will promptly send you your raffle ticket.' + "\n\n" + 'Please note that if payment is not received within the specified timeframe, we will have to remove your name from the drawing.' + "\n\n" + 'If you wish to change your method of payment, you may do so by following this link: empty. Should you have any further questions or concerns, please do not hesitate to reach out to us. We are here to assist you in any way we can.' + "\n\n" + 'Best of luck in the raffle drawing!' + "\n\n" + 'Warm regards,' + "\n\n" + 'Treasurer' + "\n\n" + 'EmailAddress' + "\n\n" + 'Paradise Hills Little League' + "\n\n" + 'ORDER DETAILS:' + "\n\n" + 'ORDER DATE:' + orderDate +"\n\n" + 'ORDER ID #' + orderID +"\n\n" + 'METHOD OF PAYMENT:' + methodOfPayment + "\n\n" + 'NUMBER OF TICKETS:' + numberOfTickets +"\n\n" +'PAYABLE TOTAL:' + payableTotal; MailApp.sendEmail(email,subject,messageBody); console.log(sendEmail) } } Note: you cannot run this code from the script editor. There needs to be an event object for the script to run. You will need to test it from the spreadsheet itself. If this is not working for you, let me know. [1]: https://i.stack.imgur.com/uv2Fy.png [2]: https://i.stack.imgur.com/F9oaO.png [3]: https://i.stack.imgur.com/eP4uh.png
|spring-boot|openapi-generator|springdoc|
{"OriginalQuestionIds":[30088983],"Voters":[{"Id":12002570,"DisplayName":"user12002570","BindingReason":{"GoldTagBadge":"c++"}}]}
The program was written using version Qt 6.4.3 **CMakeLists.txt** file: ``` cmake_minimum_required(VERSION 3.16) project(youtube_video VERSION 0.1 LANGUAGES CXX) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(Qt6 6.4 REQUIRED COMPONENTS Quick WebEngineQuick) qt_standard_project_setup() qt_add_executable(appyoutube_video main.cpp ) qt_add_qml_module(appyoutube_video URI youtube_video VERSION 1.0 QML_FILES Main.qml ) # Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1. # If you are developing for iOS or macOS you should consider setting an # explicit, fixed bundle identifier manually though. set_target_properties(appyoutube_video PROPERTIES # MACOSX_BUNDLE_GUI_IDENTIFIER com.example.appyoutube_video MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} MACOSX_BUNDLE TRUE WIN32_EXECUTABLE TRUE ) target_link_libraries(appyoutube_video PRIVATE Qt6::Quick Qt6::WebEngineQuick ) include(GNUInstallDirs) install(TARGETS appyoutube_video BUNDLE DESTINATION . LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) ``` **main.cpp** file: ``` #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QtWebEngineQuick/qtwebenginequickglobal.h> int main(int argc, char *argv[]) { QtWebEngineQuick::initialize(); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; const QUrl url(u"qrc:/youtube_video/Main.qml"_qs); QObject::connect( &engine, &QQmlApplicationEngine::objectCreationFailed, &app, []() { QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); } ``` **Main.qml** file: ``` import QtQuick import QtQuick.Controls import QtQuick.Window import QtWebEngine Window { width: 640 height: 480 visible: true title: qsTr("Hello World") WebEngineView { anchors.fill: parent url: "https://www.youtube.com/embed/cabBXCq7_P8" } } ``` Shows a preview after launch: [after launch](https://i.stack.imgur.com/rsuHE.png) But trying to play the video results in an error: [error message](https://i.stack.imgur.com/RB2eI.png) Can anyone tell me what the error is and how to fix it? As a result, the video is expected to play
I suppose for the right `div` (not for `.right`), you can set the height as the height of the viewport. Make it `flex` to allow `.right` to use all the empty space until the bottom. Smth like: ```css div { height: 100vh; display: flex; flex-direction: column; } .right { ... flex: 1; } ``` [Example][1] [1]: https://jsfiddle.net/wbt1an70/1/
I've set up a server with the help of NiceGUI and Nginx on a VPS. The requests are coming through a subdomain and routed correctly: The server receives the request and prints the html elements. However, upon making use of the websockets, I can see the following error on my server's out: ```ERROR:engineio.server:Invalid websocket upgrade (further occurrences of this error will be logged with level INFO)```. Conversely, my browser shows ```manager.js:108 WebSocket connection to 'wss://{I-hid-this}/_nicegui_ws/socket.io/?client_id=ce259c07-9781-4739-9faa-051f24e911bd&EIO=4&transport=websocket' failed```. The same setup, running it `on_air` **works perfectly**. Here's my nginx config for my subdomain: ``` server { listen 80; server_name {I-hid-this}; location / { proxy_pass http://127.0.0.1:8080; # Assuming your Uvicorn app is running on port 8030 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } server{ # SSL configuration listen 443 ssl; server_name {I-hid-this}; ssl_certificate /etc/nginx/ssl/{I-hid-this}_ssl_certificate.cer; ssl_certificate_key /etc/nginx/ssl/_.{I-hid-this}_private_key.key; location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` I tried adding sockets on extra ports, but it made no difference. The main problem I have with this is that I can't find any specific documentation on the posted error.
This is another answer for [Kotlin build scripts][1] (build.gradle.**kts**). It tries to read from *local.properties* file, falling back to the OS environment variables. It can be especially useful in CIs like GitHub Actions (you can create environment secrets in your repository settings). Note that I'm using Kotlin 1.6.10 and Gradle 7.4.2 and Android Gradle Plugin (AGP) 7.0.4. ```kotlin import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties // ... val environment = System.getenv() fun getLocalProperty(key: String) = gradleLocalProperties(rootDir).getProperty(key) fun String.toFile() = File(this) android { signingConfigs { create("MySigningConfig") { keyAlias = getLocalProperty("signing.keyAlias") ?: environment["SIGNING_KEY_ALIAS"] ?: error("Error!") storeFile = (getLocalProperty("signing.storeFile") ?: environment["SIGNING_STORE_FILE"] ?: error("Error!")).toFile() keyPassword = getLocalProperty("signing.keyPassword") ?: environment["SIGNING_KEY_PASSWORD"] ?: error("Error!") storePassword = getLocalProperty("signing.storePassword") ?: environment["SIGNING_STORE_PASSWORD"] ?: error("Error!") enableV1Signing = true enableV2Signing = true } } buildTypes { release { signingConfig = signingConfigs["MySigningConfig"] isMinifyEnabled = true proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } } } ``` As said, you can either have a *local.properties* file at the root of your project with values for the properties: ```properties signing.keyAlias=My key signing.keyPassword=zyxwvuts signing.storePassword=abcdefgh signing.storeFile=C\:\\Users\\Mahozad\\keystore.jks ``` ... or you can set/create environment variables on your OS; for example to create an environment variable called `SIGNING_KEY_ALIAS` run: - Windows Command Prompt: `setx SIGNING_KEY_ALIAS "My key"` - Linux Terminal: `export SIGNING_KEY_ALIAS="My key"` **NOTE**: As mentioned by other answers, do NOT add your *local.properties* file to your version control system (like Git), as it exposes your secret information like passwords etc. to the public (if it's a public repository). ### Generate your APK with either of the 3 ways that [this answer](https://stackoverflow.com/a/20927125/8583692) mentioned. [1]: https://docs.gradle.org/current/userguide/kotlin_dsl.html
I have used recast for my code generation with babel as i have checked it is compatible with babel but recast is removing all my comments Here is my recast code const generatedAst = recast.print(ast, { tabWidth: 2, quote: 'single', }); I am passing AST generated from babel parse and directly if i use babel generate to generate my code then parenthesis are removed Can anyone help me with this Thank you in advance I don't know any other package that is compatible with babel i used recast because i have checked this [text](https://github.com/babel/babel/issues/8974) and in this it is mentioned that babel removes parenthesis This is the AST that is generated using babel parse Node { type: 'File', start: 0, end: 1046, loc: SourceLocation { start: Position { line: 1, column: 0, index: 0 }, end: Position { line: 45, column: 0, index: 1046 }, filename: undefined, identifierName: undefined }, errors: [], program: Node { type: 'Program', start: 0, end: 1046, loc: SourceLocation { start: [Position], end: [Position], filename: undefined, identifierName: undefined }, sourceType: 'module', interpreter: null, body: [ [Node], [Node], [Node], [Node], [Node] ], directives: [] }, comments: [ { type: 'CommentLine', value: ' eslint-disable-next-line react/no-array-index-key', start: 191, end: 243, loc: [SourceLocation] } ] } and using babel-generate the parenthesis are being removed
null
The comment by @Christian Stieber identifies the immediate problem: > When you do the recursive call to `count_end`, you wanted to assign the return value to `ctr`. ```lang-cpp //start = count_end(a, start + 1, ctr); // Wrong! ctr = count_end(a, start + 1, ctr); // Right. ``` With this fix, the two `cout` expressions display the same value. For the trial run below, I entered a famous quotation by Mahatma Gandhi. ```lang-none An ounce of patience is worth more than a tonne of preaching. 12 is count12 ``` You can clean up the output by by removing `cout` from function `count_end`, and rewording the message. ```lang-none WORD COUNTER Enter some text: An ounce of patience is worth more than a tonne of preaching. Word count: 12 ``` This works fine, so long as the user does not forget to enter a period. Without one, however, function `count_end` will overrun the buffer, while it searches for a period. Rather than stopping when a period is encountered, you should stop when the terminating null character (`'\0'`) of the C-string is found. Here is the complete program: ```lang-cpp // main.cpp #include <iostream> using std::cin; using std::cout; int count_end(char* a, int start, int ctr) { if (a[start] == '\0') { // Stop when '\0' is found //cout << ctr << "\n"; // Delete this return ctr; } else if (a[start] == ' ' && a[start - 1] != ' ') { ctr++; } //start = count_end(a, start + 1, ctr); // Wrong! ctr = count_end(a, start + 1, ctr); // Right. return ctr; } int main() { char sentence[1000]; cout << "WORD COUNTER\n\n" << "Enter some text: "; cin.getline(sentence, 1000); cout << '\n'; int x; x = count_end(sentence, 1, 1); cout << "Word count: " << x << "\n\n"; return 0; } // end file: main.cpp ``` #### A C++ Solution When a student posts a question about a "C++" program that use more `C` than `C++`, the explanation is usually that he is in a course that teaches both languages at the same time. If that is the case here, my advice is to write two solutions to each homework assignment, one using `C`, and the other, `C++`. The program in the previous section patches up the `C` program from the OP. This section shows an approach that could be used in a `C++` program. It uses a simple `Lexer` class that stores a string, and doles out words one at a time. ```lang-cpp std::string s{ "An ounce of patience is worth more than a tonne of preaching." }; Lexer lexer{ s }; // constructor takes a string, and saves a copy. ``` Member function `get_word` is the only public member function in a `Lexer`. It returns the next word from string `s`. When there are no more words remaining, function `get_word` returns an empty string. ```lang-cpp std::string word = lexer.get_word(); ``` To count words, you can test whether the value returned by `get_word` is empty. The while-loop below says, in effect, loop while "the string returned by `lexer.get_word()` is not empty." ```lang-cpp int main() { std::string s{ "An ounce of patience is worth more than a tonne of preaching." }; Lexer lexer{ s }; int count{}; while (!lexer.get_word().empty()) ++count; std::cout << "There are " << count << " words in the string: \n\n" << std::quoted(s) << "\n\n"; return 0; } ``` #### Output ```lang-none There are 12 words in the string: "An ounce of patience is worth more than a tonne of preaching." ``` #### Class `Lexer` The implementation below defines a word to be any sequence of non-whitespace characters. So letters, digits, and punctuation marks are all considered to be characters belonging to a word. Member variable `next_char` is a subscript into string `s`. It is the index of the next character to be extracted from string `s`. It starts out at zero, and is incremented as words are extracted from string s. When `next_char == s.size()`, there are no words remaining in `s`. After skipping over whitespace characters, function `get_word` marks the start of a word by saving the value of `next_char`: ```lang-cpp auto const start{ next_char }; ``` Function `get_word` then runs a loop, searching for either the end of string `s`, or the whitespace character that marks the end of the word, whichever comes first. After the loop, `next_char` is an index to the (possibly nonexistent) character that follows the final character of the word. The value returned from function `get_word` is a substring formed from variables `s`, `start`, and `next_char`. The size of the substring is `next_char - start`. Here is the complete function. The loop says, in effect, "While characters remain, and the next character is not whitepace, keep looping." ```lang-cpp std::string get_word() noexcept { skip_whitespace(); auto const start{ next_char }; while (next_char != s.size() && !is_space(s[next_char])) ++next_char; return s.substr(start, next_char - start); } ``` This is the complete program: ```lang-cpp // main.cpp #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <utility> class Lexer { std::string s; std::string::size_type next_char{}; public: Lexer (std::string s) noexcept : s{ std::move(s) } {} std::string get_word() noexcept { skip_whitespace(); auto const start{ next_char }; while (next_char != s.size() && !is_space(s[next_char])) ++next_char; return s.substr(start, next_char - start); } private: static bool is_space(unsigned char const c) noexcept { return std::isspace(c); } void skip_whitespace() noexcept { while (next_char != s.size() && is_space(s[next_char])) ++next_char; } }; int main() { std::string s{ "An ounce of patience is worth more than a tonne of preaching." }; Lexer lexer{ s }; int count{}; while (!lexer.get_word().empty()) ++count; std::cout << "There are " << count << " words in the string: \n\n" << std::quoted(s) << "\n\n"; return 0; } // end file: main.cpp ```
I'm trying to write zipstream compression tool, like getting data from 3rd party service, transform it, compress it and then add those bytes to zip archive byte stream and send to another service. Crc32 is recalculating after every chunk. Made 3rd party service emulation - reading file by chunk. This version works, but after extracting i get empty file. But it is not empty - i see data in hex editor. I think there is something with crc32. But if i compressing the whole file at once, it works just fine. Here is my question. Is it possible to compress big amount of data by chunks with deflatestream? I need to extract this data later with regular zip tools. public async Task<byte[]> Compress(string fileName, IAsyncEnumerable<byte[]> data) { var crc32Helper = new System.IO.Hashing.Crc32(); var lfh = ZipTools.GetLocalFileHeaderEntry(fileName); testResult.AddRange(lfh); var bytearray = new List<byte>(); await foreach (var chunk in data) { _originalSize += (ulong) chunk.Length; var compressedData = Compress(chunk); _compressedSize += (ulong) compressedData.Length; crc32Helper.Append(chunk); testResult.AddRange(compressedData); } _originalSize += (ulong) bytearray.Count; _crc32 = crc32Helper.GetCurrentHashAsUInt32(); var cd = ZipTools.GetCentralDirectoryEntry( fileName, _crc32, (ulong) lfh.Length + _compressedSize, _compressedSize, _originalSize); testResult.AddRange(cd); return testResult.ToArray(); } public byte[] Compress(byte[] data) { using var input = new MemoryStream(data); using var resultStream = new MemoryStream(); using (DeflateStream compressionStream = new DeflateStream(resultStream, CompressionMode.Compress)) { input.CopyTo(compressionStream); } return resultStream.ToArray(); }
Big file compression using DeflateStream
|c#|zip|
I have a question. First of all, I am using ngx translate, but I don't read from the.json file. I get the Locaization from the database.. Now what I want is that in my router, I create a title for the route.  I want to translate it based on the current language. I have read some articles, and they used resolver. Is this the best or is there another way? or there is something better ?
Angular title routing translation
|angular|routes|angular-ui-router|
I subscribe to several nodes at the same time, so that I receive a notification only when the values change. I have to save the data to a csv file and I write rows with the timestamp + all the values of the nodes. I implemented asyncio.Queue to handle the simultaneous writing but still if I receive more than one notification at the same time, the file gets updated with the first notification but not the other ones which are lost. Here the output: ``` sv_writer_task started Queue list: <Queue maxsize=0> Datachange notification received. 29032024 14:10:16Data change notification was received and queued: ns=2;s=Unit_SB.UC3.TEMP.TEMP_v 19.731399536132812 Datachange notification received. 29032024 14:10:16Data change notification was received and queued: ns=2;s=Unit_SB.UC3.HUMI.HUMI_v 36.523399353027344 Dequeue value: 19.731399536132812 val name: TEMP Prefix UC1 is no match for node: Unit_SB.UC3.TEMP.TEMP_v. Skipping. Prefix UC2 is no match for node: Unit_SB.UC3.TEMP.TEMP_v. Skipping. csv file: UC3.csv Appending new row Data written to file UC3.csv succesfully Dequeue value: 36.523399353027344 val name: HUMI Prefix UC1 is no match for node: Unit_SB.UC3.HUMI.HUMI_v. Skipping. Prefix UC2 is no match for node: Unit_SB.UC3.HUMI.HUMI_v. Skipping. csv file: UC3.csv Updating existing row Data written to file UC3.csv succesfully ``` In the csv file one can see in last line that only the TEMP value, which arrived first, was changed, but not the HUMI one: ``` Timestamp,OUT_G,OUT_U,HUMI,TEMP 29032024 14:08:42,True,True,47.38769912719727,15.043899536132812 29032024 14:10:16,True,True,47.38769912719727,19.731399536132812 ``` here the code so far. Since I'm subscribing to several subsystem and each of them has it's own data file, I'm checking to which file to write: ``` # this is the consumer which consumes items from the queue async def csv_writer_task(queue): print("csv_writer_task started") print('Queue list: ') print(queue) print('') while True: try: dte, node, val = await queue.get() print('Dequeue value: ', val) except Exception as e: print(f"Error in csv_writer_task while retrieving value fromt he queue: {e}") node_id_str = str(node.nodeid.Identifier) node_parts = node_id_str[len("Unit_SB."):].split('.') val_name = node_parts[-1].replace('_v', '') print('val name: ', val_name) for key, header_row in prefix_mapping.items(): if f"Unit_SB.WAGO.{key}" in node_id_str: csv_file = f"{key}.csv" print('csv file: ', csv_file) break else: print(f"Prefix {key} is no match for node: {node_id_str}. Skipping.") df = pd.read_csv(csv_file) last_row = df.iloc[-1].copy() if last_row['Timestamp'] == dte: print("Updating existing row") last_row[val_name] = val else: print("Appending new row") new_row = last_row.copy() new_row['Timestamp'] = dte new_row[val_name] = val df = pd.concat([df, new_row.to_frame().T], ignore_index=True) df.to_csv(csv_file, index=False) print(f'Data written to file {csv_file} succesfully') queue.task_done() class SubscriptionHandler(object): def __init__(self, wsconn): self.wsconn = wsconn self.q = asyncio.Queue() self.queuwriter = asyncio.create_task(csv_writer_task(self.q)) # this is the producer which produces items and puts them into a queue async def datachange_notification(self, node, val, data): print("Datachange notification received.") dte = data.monitored_item.Value.ServerTimestamp.strftime("%d%m%Y %H:%M:%S") await self.q.put((dte, node, val)) print(dte + "Data change notification was received and queued: ", node, val) class SBConnection(): def __init__(self): self.listOfWSNode = [] self.dpsList = ... async def connectAndSubscribeToServer(self): self.csv_file = '' async with Client(url=self.url) as self.client: for element in self.dpsList: node = "ns=" + element["NS"] + ";s=" + element["Name"] var = self.client.get_node(node) self.listOfWSNode.append(var) print("Subscribe to ", self.listOfWSNode) handler = SubscriptionHandler(self) sub = await self.client.create_subscription(period=10, handler=handler) await sub.subscribe_data_change(self.listOfWSNode) print('subscription created') # create infinite loop while True: await asyncio.sleep(0.1) async def main(): uc = SBConnection() await uc.connectAndSubscribeToServer() if __name__ == '__main__': asyncio.run(main()) ``` Anyone can help me in finding the problem? Thanks
save to csv simultaneously opcua datachange notification
|python|asynchronous|python-asyncio|subscription|opc-ua|
null
I am trying to access a webpage using `Selenium` for `C#` and I am struggling to make some elements accessible. Some elements seem to be readily available whilst other do not. An excerpt of the structure of the page is as follows: <header class="l-quotepage__header"> <div class="c-faceplate c-faceplate--bond is-positive /*debug*/" data-faceplate="" data-faceplate-symbol="1rPFR0010870956" data-ist="1rPFR0010870956" data-ist-init="{&#34;symbol&#34;:&#34;1rPFR0010870956&#34;,&#34;high&#34;:0,&#34;low&#34;:0,&#34;previousClose&#34;:114.45,&#34;totalVolume&#34;:0,&#34;tradeDate&#34;:&#34;2024-03-27 09:34:21&#34;,&#34;variation&#34;:0,&#34;last&#34;:114.45,&#34;exchangeCode&#34;:&#34;PAR&#34;,&#34;category&#34;:&#34;BND&#34;,&#34;decimals&#34;:2}" data-ist-variation-indicator=""> <input class="c-faceplate__accordion-toggle" id="faceplate-1492129610" type="checkbox"/> <div class="c-faceplate__body"> <div class="c-faceplate__company">[...]</div> <div class="c-faceplate__data" data-faceplate-target=""> <ul class="c-list-info__list c-list-info__list--split-half"> <li class="c-list-info__item"> <p class="c-list-info__heading u-color-neutral">open</p> <p class="c-list-info__value u-color-big-stone"> <span class="c-instrument c-instrument--open" data-ist-open="">0.00</span> </p> </li> <li class="c-list-info__item"> <p class="c-list-info__heading u-color-neutral">previous close</p> <p class="c-list-info__value u-color-big-stone"> <span class="c-instrument c-instrument--previousclose" data-ist-previousclose="">114.45</span> </p> </li> <li class="c-list-info__item"> <p class="c-list-info__heading u-color-neutral">high</p> <p class="c-list-info__value u-color-big-stone"> <span class="c-instrument c-instrument--high" data-ist-high="">0.00</span> </p> </li> <li class="c-list-info__item"> <p class="c-list-info__heading u-color-neutral">low</p> <p class="c-list-info__value u-color-big-stone"> <span class="c-instrument c-instrument--low" data-ist-low="">0.00</span> </p> </li> </ul> <ul class="c-list-info__list c-list-info__list--split-half"> <li class="c-list-info__item"> <p class="c-list-info__heading u-color-neutral">volume</p> <p class="c-list-info__value u-color-big-stone"> <span class="c-instrument c-instrument--totalvolume" data-ist-totalvolume="">0</span> </p> </li> <li class="c-list-info__item"> <p class="c-list-info__heading u-color-neutral">last trading time</p> <p class="c-list-info__value u-color-big-stone"> <span class="c-instrument c-instrument--tradedate" data-ist-tradedate="">27.03.24 / 09:34:21</span> </p> </li> </ul> <ul class="c-list-info__list c-list-info__list--split-half@sm-max c-list-info__list--nowrap@md-min"> <li class="c-list-info__item c-list-info__item--has-picto c-list-info__item--fixed-width"> <p class="c-list-info__heading u-color-neutral">low threshold</p> <p class="c-list-info__value u-color-big-stone">114.94</p> </li> <li class="c-list-info__item c-list-info__item--has-picto c-list-info__item--fixed-width"> <p class="c-list-info__heading u-color-neutral">high threshold</p> <p class="c-list-info__value u-color-big-stone">116.94</p> </li> </ul> </div> </div> <label class="c-faceplate__accordion-button" for="faceplate-1492129610"/> </div> </header> Whilst I can access anything located within <div class="c-faceplate__company">[...]</div> I cannot access any of the data located within <div class="c-faceplate__data" data-faceplate-target=""> I can locate the parent `IWebElement element` (here in `C#`) defined for the `XPath` //*div[@class="c-faceplate__data"] but, even after creating a `WebBrowserWait wait` to wait for it to be in `element.Displayed` or `element.Enabled` mode, makes it time out unsuccessfully (for long time spans such as up to 60s). The data under this section are displayed on the UI side by toggling the button <input class="c-faceplate__accordion-toggle" id="faceplate-1492129610" type="checkbox"/> that comes with its label <label class="c-faceplate__accordion-button" for="faceplate-1492129610"/> although, on a full screen, the data under <div class="c-faceplate__data" data-faceplate-target=""> are visible by default, only when one uses a reduced-sized screen does it disapppear and can only be made visible again by pressing the button. Other than this, the cross reference between the "input" 'id' and the "label" 'for', here "faceplate-1492129610", is random. The "faceplate-#" changes at each page call or refresh. I am wondering to what extent does this button control the access to the div section too, how can I see if it is the case and how I can manage the `Selenium` browser to by-pass this hurdle.
I believe there was an internal mix related to the paths of the two versions. I finally uninstalled version 9 completely. Then, as I was one version late for Jupyter lab, I decided to upgrade Jupyter right after. All went nicely and everything is working fine with the new versions. Finally, the approach I feared the most was the easiest and most straightforward. All the scripts I wrote using former versions of python, pandas, sk-learn work nicely.
|python|gekko|
Im trying to check if URL contains upper case character. here is the code. public class Test { public static boolean validate(String str) { for (char c : str.toCharArray()) { // check if the character is not a lowercase letter if (!(c >= 'a' && c <= 'z')) { return false; } } // all characters are lowercase letters return true; } public static void main(String args[]) { // test cases String example1 = "alCDev-112.am.dev.oneenterprise.com"; String example2 = "ABC123abc"; // check if each example contains only lowercase letters System.out.println("Example 1 contains only lowercase letters: " + validate(example1)); System.out.println("Example 2 contains only lowercase letters: " + validate(example2)); } } however, it is returning false only in both the cases. please suggest , how can we use reg ex to check URL should not contain upper case character in java
How to use regex to check if URL contains upper case character in java
|java|
On old Kafka 2.0.0.3.1.0.0-78 (HDP) we're facing an interesting issue with ISR. So, actually we don't have ISR accordingly to replication factor for certain paritions. For instance: ``` Topic:yb_test3 PartitionCount:3 ReplicationFactor:3 Topic: yb_test3 Partition: 0 Leader: 1002 Replicas: 1002,1005,1008 Isr: 1002,1008,1005 Topic: yb_test3 Partition: 1 Leader: 1005 Replicas: 1005 Isr: 1005 Topic: yb_test3 Partition: 2 Leader: 1010 Replicas: 1010,1005,1008 Isr: 1010,1005,1008 ``` We've tried to play with partition reassignment as well as preferred replica election but without success. The most interesting behaviour observed during troubleshooting (and playing with partition reassignment) was the following. The attempt was to make partition 1 (on broker 1002) in ISR list. So, initially we have: ``` Topic:yb_test3 PartitionCount:3 ReplicationFactor:3 Topic: yb_test3 Partition: 0 Leader: 1002 Replicas: 1002,1005,1008 Isr: 1002,1008,1005 Topic: yb_test3 Partition: 1 Leader: 1005 Replicas: 1005 Isr: 1005 Topic: yb_test3 Partition: 2 Leader: 1010 Replicas: 1010,1005,1008 Isr: 1010,1005,1008 ``` And in Zookeeper: ``` [zk: prod-nn-0006.pv.mts.ru:2181(CONNECTED) 0] get /brokers/topics/yb_test3/partitions/1/state {"controller_epoch":163,"leader":1005,"version":1,"leader_epoch":90,"isr":[1005]} cZxid = 0x1a054a0c57 ctime = Thu Feb 16 11:06:41 MSK 2023 mZxid = 0x1a0d0b6c0e mtime = Thu Mar 28 13:24:09 MSK 2024 pZxid = 0x1a054a0c57 cversion = 0 dataVersion = 262 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 81 numChildren = 0 ``` We see leader_epoch = 90. Now let's do reassign partitions to (1005,1002,1008) via triggering kafka-reassign-partitions.sh tool. As a result: ``` Topic:yb_test3 PartitionCount:3 ReplicationFactor:3 Topic: yb_test3 Partition: 0 Leader: 1002 Replicas: 1002,1005,1008 Isr: 1002,1008,1005 Topic: yb_test3 Partition: 1 Leader: 1005 Replicas: 1005,1002,1008 Isr: 1005 Topic: yb_test3 Partition: 2 Leader: 1010 Replicas: 1010,1005,1008 Isr: 1010,1005,1008 ``` So, 1002 and 1008 are not in ISR. Checking trace logs reveals the following procedure. In /var/log/kafka/state-change.log on 1002 (where broker and conrollers are currently) we see: ``` [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sending become-leader LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=91, isr=1005, zkVersion=263, replicas=1005,1002,1008, isNew=false) to broker 1005 for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sending become-follower LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=91, isr=1005, zkVersion=263, replicas=1005,1002,1008, isNew=false) to broker 1008 for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sending become-follower LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=91, isr=1005, zkVersion=263, replicas=1005,1002,1008, isNew=false) to broker 1002 for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sending UpdateMetadata request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=[1005], zkVersion=262, replicas=[1005, 1002, 1008], offlineReplicas=[]) to brokers Set(1002, 1008, 1005, 1010) for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sent LeaderAndIsr request (Leader:1005,ISR:1005,LeaderEpoch:91,ControllerEpoch:163) with new assigned replica list 1005,1002,1008 to leader 1005 for partition being reassigned yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Changed state of replica 1002 for partition yb_test3-1 from NonExistentReplica to NewReplica (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sending become-follower LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=1005, zkVersion=262, replicas=1005,1002,1008, isNew=true) to broker 1002 for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sending UpdateMetadata request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=[1005], zkVersion=262, replicas=[1005, 1002, 1008], offlineReplicas=[]) to brokers Set(1002, 1008, 1005, 1010) for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Changed state of replica 1008 for partition yb_test3-1 from NonExistentReplica to NewReplica (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sending become-follower LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=1005, zkVersion=262, replicas=1005,1002,1008, isNew=true) to broker 1008 for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Controller id=1002 epoch=163] Sending UpdateMetadata request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=[1005], zkVersion=262, replicas=[1005, 1002, 1008], offlineReplicas=[]) to brokers Set(1002, 1008, 1005, 1010) for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,783] TRACE [Broker id=1002] Received LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=91, isr=1005, zkVersion=263, replicas=1005,1002,1008, isNew=false) correlation id 2184 from controller 1002 epoch 163 for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,784] TRACE [Broker id=1002] Handling LeaderAndIsr request correlationId 2184 from controller 1002 epoch 163 starting the become-follower transition for partition yb_test3-1 with leader 1005 (state.change.logger) [2024-03-28 13:28:10,790] TRACE [Broker id=1002] Stopped fetchers as part of become-follower request from controller 1002 epoch 163 with correlation id 2184 for partition yb_test3-1 with leader 1005 (state.change.logger) [2024-03-28 13:28:10,790] TRACE [Broker id=1002] Truncated logs and checkpointed recovery boundaries for partition yb_test3-1 as part of become-follower request with correlation id 2184 from controller 1002 epoch 163 with leader 1005 (state.change.logger) [2024-03-28 13:28:10,792] TRACE [Broker id=1002] Started fetcher to new leader as part of become-follower request from controller 1002 epoch 163 with correlation id 2184 for partition yb_test3-1 with leader 1005 (state.change.logger) [2024-03-28 13:28:10,792] TRACE [Broker id=1002] Completed LeaderAndIsr request correlationId 2184 from controller 1002 epoch 163 for the become-follower transition for partition yb_test3-1 with leader 1005 (state.change.logger) [2024-03-28 13:28:10,792] TRACE [Broker id=1002] Cached leader info PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=[1005], zkVersion=262, replicas=[1005, 1002, 1008], offlineReplicas=[]) for partition yb_test3-1 in response to UpdateMetadata request sent by controller 1002 epoch 163 with correlation id 2185 (state.change.logger) [2024-03-28 13:28:10,792] TRACE [Broker id=1002] Received LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=1005, zkVersion=262, replicas=1005,1002,1008, isNew=true) correlation id 2186 from controller 1002 epoch 163 for partition yb_test3-1 (state.change.logger) [2024-03-28 13:28:10,792] WARN [Broker id=1002] Ignoring LeaderAndIsr request from controller 1002 with correlation id 2186 epoch 163 for partition yb_test3-1 since its associated leader epoch 90 is not higher than the current leader epoch 91 (state.change.logger) [2024-03-28 13:28:10,801] TRACE [Broker id=1002] Cached leader info PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=[1005], zkVersion=262, replicas=[1005, 1002, 1008], offlineReplicas=[]) for partition yb_test3-1 in response to UpdateMetadata request sent by controller 1002 epoch 163 with correlation id 2187 (state.change.logger) [2024-03-28 13:28:10,802] TRACE [Broker id=1002] Cached leader info PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=[1005], zkVersion=262, replicas=[1005, 1002, 1008], offlineReplicas=[]) for partition yb_test3-1 in response to UpdateMetadata request sent by controller 1002 epoch 163 with correlation id 2188 (state.change.logger) ``` So, what is interesting here and what we actually can't understand - the WARN message that LeaderAndIsr was ignored because its associated leader epoch 90 is not higher than the current leader epoch 91. Indeed, leader_epoch was incremented (and in Zookeeper it is 91 now). But why controller sent twice: \[2024-03-28 13:28:10,783\] TRACE \[Controller id=1002 epoch=163\] Sending become-follower LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=91, isr=1005, zkVersion=263, replicas=1005,1002,1008, isNew=false) to broker 1002 for partition yb_test3-1 (state.change.logger) \[2024-03-28 13:28:10,783\] TRACE \[Controller id=1002 epoch=163\] Sending become-follower LeaderAndIsr request PartitionState(controllerEpoch=163, leader=1005, leaderEpoch=90, isr=1005, zkVersion=262, replicas=1005,1002,1008, isNew=true) to broker 1002 for partition yb_test3-1 (state.change.logger) And more specifically, why on the 2nd request the old leader_epoch was sent? And the main question: how to deal with such a problem and make ISR correct? We tried to trigger controller change via Zookeeper but without any success. We have only one idea - use unclean.leader.election.enable=true and reboot broker 1005 (and probably 1002 will be used in such scenario) - but honestly we want to understand the root cause. We tried partition reassignment, preferred replica election, switching to different controllers.
Can't put replica to ISR in Kafka 2.0
|apache-kafka|
null
I am testing the m.if3 function in gekko by using conditional statements of if-else but I get two different outputs. The optimal sites i get from below code is 10. I plug that in the next code with if-else statement to ensure that the cost matches up but it does not. Am I using if3/if2 incorrectly? The enroll_rate is 0.1 for the first 5 months and it switches to 0.3 for the remaining 45 months. ``` m = GEKKO(remote=False) # parameters sitecost = 9 # Cost per site patcost = 12 # Cost per patient num_pat = 50 # Required number of patients recruit_duration = 50 # Duration of recruitment # Define a piecewise function for the enrollment rate enroll_rate = m.if3(recruit_duration - 5, 0.3, 0.1) x = m.Var(integer=True, lb=1) # Number of sites cost = m.if3(recruit_duration - 5, (0.3 * patcost * recruit_duration + sitecost) * x, (0.1 * patcost * recruit_duration + sitecost) * x) pat_count = m.if3(recruit_duration - 5, (0.3 * recruit_duration * x), (0.1 * recruit_duration * x)) m.Minimize(cost) m.Equation(pat_count >= num_pat) m.solve(disp=False) num_sites = int(x.value[0]) print(f'num_sites = {num_sites}') print(cost.value[0]) print(pat_count.value[0]) ``` ``` # Parameters sitecost = 9 # Cost per site patcost = 12 # Cost per patient num_pat = 50 # Required number of patients recruit_duration = 50 # Duration of recruitment # Define an enrollment rate based on recruit_duration if recruit_duration > 5: enroll_rate = 0.1 else: enroll_rate = 0.3 # GEKKO Variables x = 10 # Number of sites # Calculate cost based on enrollment rate and site cost cost1 = (0.1 * patcost * 45 + sitecost) * 12 cost2 = (0.3 * patcost * 5 + sitecost) * 12 cost = cost1 + cost2 # Calculate total patient count pat_count1 = 0.1 * 5 * 12 pat_count2 = 0.3 * 45 * 12 pat_count = pat_count1 + pat_count2 print(pat_count) print(cost) ``` I get different outputs even though I am doing the same thing in both of them. I tried everything from using if-else statements to using if2 statements.
The [handle class](https://www.mathworks.com/help/matlab/handle-classes.html) and its copy-by-reference behavior is the natural way to implement linkage in Matlab. It is, however, possible to implement a linked list in Matlab without OOP. And an abstract list which does *not* splice an existing array in the middle to insert a new element -- as complained in [this comment](https://stackoverflow.com/questions/1413860/matlab-linked-list#comment23877880_1422443). (Although I do have to use a Matlab data type somehow, and adding new element to an existing Matlab array requires memory allocation somewhere.) The reason of this availability is that we can model linkage in ways other than pointer/reference. The reason is *not* [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)) with [nested functions](https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html). I will nevertheless use closure to encapsulate a few *persistent* variables. At the end, I will include an example to show that closure alone confers no linkage. And so [this answer](https://stackoverflow.com/a/1421186/3181104) as written is incorrect. At the end of the day, linked list in Matlab is only an academic exercise. Matlab, aside from aforementioned handler class and classes inheriting from it (called subclasses in Matlab), is purely copy-by-value. Matlab will optimize and automate how copying works under the hood. It will avoid deep copy whenever it can. That is probably the better take-away for OP's question. The absence of reference in its core functionality is also why linked list is not obvious to make in Matlab. ------------- ##### Example Matlab linked list: ```lang-matlab function headNode = makeLinkedList(value) % value is the value of the initial node % for simplicity, we will require initial node; and won't implement insert before head node % for the purpose of this example, we accommodate only double as value % we will also limit max list size to 2^31-1 as opposed to the usual 2^48 in Matlab vectors m_id2ind=containers.Map('KeyType','int32','ValueType','int32'); % pre R2022b, faster to split than to array value m_idNext=containers.Map('KeyType','int32','ValueType','int32'); %if exist('value','var') && ~isempty(value) m_data=value; % stores value for all nodes m_id2ind(1)=1; m_idNext(1)=0; % 0 denotes no next node m_id=1; % id of head node m_endId=1; %else % m_data=double.empty; % % not implemented %end headNode = struct('value',value,... % note: this field is for convenince; but is access only 'get',@getValue,... 'set',@set,... 'next',@next,... 'head',struct.empty,... 'push_back',@addEnd,... 'addAfter',@addAfter,... 'deleteAt',@deleteAt,... 'nodeById',@makeNode,... 'id',m_id); function value=getValue(node) if isempty(node) warning("Node is empty.") value=double.empty; else value=id2val(node(id)); end end function set(node,val) if isempty(node) warning("Node is empty.") else m_data(m_id2ind(node.id))=val; end end function nextNode=next(node) if m_idNext(node.id)==0 warning('There is no next node.') nextNode=struct.empty; else nextNode=makeNode(m_idNext(node.id)); end end function node=makeNode(id) if isKey(m_id2ind,id) node=struct('value',id2val(id),... % note: this field is for convenince; but is access only 'get',@getValue,... 'set',@set,... 'next',@next,... 'head',headNode,... 'push_back',@addEnd,... 'addAfter',@addAfter,... 'deleteAt',@deleteAt,... 'nodeById',@makeNode,... 'id',id); else warning('No such node!') node=struct.empty; end end function temp=id2val(id) temp=m_data(m_id2ind(id)); end function addEnd(value) addAfter(value,m_endId); end function addAfter(value,id) m_data(end+1)=value; temp=numel(m_data);% new id will be new list length if (id==m_endId) m_idNext(temp)=0; else m_idNext(temp)=temp+1; end m_id2ind(temp)=temp; m_idNext(id)=temp; m_endId=temp; end function deleteAt(id) %delete to free memory does not make sense with the chosen data type. But can work if m_data had been acell array by setting a particular element empty end end ``` With the above .m file, the following runs: ```lang-matlab >> clear all % remember to clear all before making new lists >> headNode = makeLinkedList(1); >> node2=headNode.next(headNode); Warning: There is no next node. > In makeLinkedList/next (line 33) >> headNode.push_back(2); >> headNode.push_back(3); >> node2=headNode.next(headNode); >> node3=node2.next(node2); >> node3=node3.next(node3); Warning: There is no next node. > In makeLinkedList/next (line 33) >> node0=node2.head; >> node2=node0.next(node0); >> node2.value ans = 2 >> node3=node2.next(node2); >> node3.value ans = 3 >> node2.set(node2,222); >> nodeNot4=headNode.next(headNode); >> nodeNot4.value ans = 222 ``` `.next()`, `.get()`, `.set()` etc in the above can take any valid node `struct` as input -- not limited to itself. Similarly, `.push_back()` etc can be done from any node. But what relative node to get next node or value from etc needs to be passed manually in because a non-OOP [`struct`](https://www.mathworks.com/help/matlab/ref/struct.html) in Matlab cannot reference itself implicitly and automatically. It does not have a `this` pointer or `self` reference. In the above example, nodes are given unique IDs, a dictionary is used to map ID to data (index) and to map ID to next ID. (With pre-R2022 `containers.Map()`, it's more efficient to have 2 dictionaries even though we have the same key and same value type across the two.) So when inserting new node, we simply need to update the relevant next ID. (Double) array was chosen to store the node values (which are doubles) and that is the data type Matlab is designed to work with and be efficient at. As long as no new allocation is required to append an element, insertion is constant time. Matlab automates the management of memory allocation. Since we are not doing array operations on the underlying array, Matlab is unlikely to take extra step to make copies of new contiguous arrays every time there is a resize. [Cell array](https://www.mathworks.com/help/matlab/ref/cell.html) may incur less re-allocation but with some trade-offs. Since [dictionary](https://www.mathworks.com/help/matlab/ref/dictionary.html) is used, I am not sure if this solution qualifies as purely [functional](https://en.wikipedia.org/wiki/Functional_programming). ------------ ##### re: closure vs linkage In short, closure does not confer linkage. Matlab's nested functions have access to variables in parent functions directly -- as long as they are not shadowed by local variables of the same names. But there is no variable passing. And thus there is no pass-by-reference. And thus we can't model linkage with this non-existent referencing. I did take advantage of closure above to make a few variables persistent and shared, since scope (called [workspace](https://www.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html) in Matlab) being referred to means all variables in the scope will persist. That said, Matlab also has a [persistent](https://www.mathworks.com/help/matlab/ref/persistent.html) specifier. Closure is not the only way. To showcase this distinction, the example below will not work because every time there is passing of `previousNode`, `nextNode`, they are passed-by-value. There is no way to access the original `struct` across function boundaries. And thus, even with nested function and closure, there is no linkage! ```lang-matlab function newNode = SOtest01(value,previousNode,nextNode) if ~exist('previousNode','var') || isempty(previousNode) i_prev=m_prev(); else i_prev=previousNode; end if ~exist('nextNode','var') || isempty(nextNode) i_next=m_next(); else i_next=nextNode; end newNode=struct('value',m_value(),... 'prev',i_prev,... 'next',i_next); function out=m_value out=value; end function out=m_prev out=previousNode; end function out=m_next out=nextNode; end end ``` ```lang-matlab >> newNode=SOtest01(1,[],[]); >> newNode2=SOtest01(2,newNode,[]); >> newNode2.prev.value=2; >> newNode.value ans = 1 ``` But we tried to set prev node of node 2 to be have value 2!
Please make sure first that the API is not the bottlenck here. You can send a request to your API using [PostMan][1] or the [Thunderclient][2] Visual Studio Code Plugin. With these tools, you can check whether the API itself needs that much time to return the response. Once you sorted this out as a possible cause, I would suggest that you attach a [debugger][3] and set a breakpoint to the code within the `LaunchedEffect`. I see no obvious error in your code, but some smells: **1.)** `LaunchedEffect` or `viewModelScope` is redundant You are using both a `viewModelScope` and a `LaunchedEffect` combined for calling the `getTodayMatches` function. If you use a `LaunchedEffect`, you can directly call a suspend function without the need for a `viewModelScope`. So you could update your ViewModel function like this: suspend fun getTodayMatches(date: String, season: Int) { _todayMatchesState.value = TodayMatchesState.Loading try { val todayMatchesResponse = matchesRepository.getTodayMatches(date, season) _todayMatchesState.value = TodayMatchesState.Success(todayMatchesResponse) } catch (exception: HttpException) { _todayMatchesState.value = TodayMatchesState.Error("Something went wrong") } catch (exception: IOException) { _todayMatchesState.value = TodayMatchesState.Error("No internet connection") } } **2.)** Callback Handling seems odd Once the DatePicker is confirmed, you set the `isClicked` variable in the ViewModel to true. Then you use a side effect on another place to execute code when the variable becomes true. Instead of this approach, I would suggest that you directly call the ViewModel function when the selected date changes. var selectedDate by rememberSaveable { mutableStateOf<LocalDate?>(LocalDate.now()) } val datePickerState = rememberDatePickerState() var sheetState by remember{ mutableStateOf(false) } // Whenever selected date changes, call getTodayMatches LaunchedEffect(datePickerState.selectedDateMillis) { if (datePickerState.selectedDateMillis != null) { // update state variable selectedDate = Instant.ofEpochMilli(datePickerState.selectedDateMillis ?: 0) .atZone(ZoneId.systemDefault()) .toLocalDate() viewModel.getTodayMatches(selectedDate.toString(), 2023) } } if (sheetState) BottomSheetDatePicker( // ... ) // ... } **3.)** LazyColumn seems odd It seems like you are mixing two overloads of the [`items`][4] function. You probably wanted to do LazyColumn { items(matchesList) { matchItem -> TodayMatchItem(matchItem) } } **4.)** Single Source of Truth It seems like you are having a lot of duplication in your Composable and ViewModel. Either store the date in your ViewModel, or store it in the Composable. But now, you have a `selectedDate` variable in your Composable, and also at the same time you have a `dialogueDate` in your ViewModel. And you need a lot of code to keep these two synchronized. In my suggestion above, I store the date in the Composable. [1]: https://www.postman.com/downloads/ [2]: https://www.thunderclient.com/ [3]: https://developer.android.com/studio/debug [4]: https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyListScope#items(kotlin.Int,kotlin.Function1,kotlin.Function1,kotlin.Function2)
Invalid websocket upgrade
|python|websocket|web-frameworks|nicegui|
On jackhenry.dev it has the Banno EES Event 110010 listed as supporting "[Device Registered](https://jackhenry.dev/open-enterprise-api-docs/enterprise-event-system/event-publishers/banno/110010-banno-event/developer-resource/)" that happens when a user logs in from a new device. It has a change.affectedPerson.personip listed. However, personip is returning blank. It also seems to be triggering even when a new device is not registered. How do we get the IP when a new device is registered? I setup an EES event: ``` Event Number: 110010 Rules: name = DeviceRegistered ``` And was expecting it to return like on the documentation page when a new device is registered: ``` { "eventId": "a9eef6eb-f717-414c-9145-eb894ac1d00d", "date": "1979-09-30T21:08:48.426Z", "institutionId": "edf692e7-fe0b-40de-ba39-e040cc318b4c", "change": { "application": "devices", "name": "DeviceRegistered", "affectedPerson": { "personId": "b6e1b00c-b86d-4630-a06e-456a3cae7ec1", "fullName": "Benjamin Garcia", "personIp": "116.123.1.255" }, "deviceId": "1852a68b-1815-4150-917f-80d0d43ccdf7" } } ``` But it seems to launch anytime anyone logs in and personIp is null.
Banno EES Event 110010 "Device Registered" not returning an IP
|banno-digital-toolkit|jackhenry-jxchange|
null
class ItemGetter extends EventEmitter { constructor () { super(); this.on('item', item => this.handleItem(item)); } handleItem (item) { console.log('Receiving Data: ' + item); } getAllItems () { for (let i = 0; i < 15; i++) { this .getItem(i) .then(item => this.emit('item', item)) .catch(console.error); } console.log('=== Loop ended ===') } async getItem (item = '') { console.log('Getting data:', item); return new Promise((resolve, reject) => { exec('echo', [item], (error, stdout, stderr) => { if (error) { throw error; } resolve(item); }); }); } } (new ItemGetter()).getAllItems() You logic, for first, run loop with calling all GetItem, then output '=== Loop ended ===', and only after that run all promices resolution, so, if you want get result of each getItem execution independently of eachother, just don't abuse asynchronous logic, frequently right solution much simpliest, than it seems ;) Note: in this solution, you will get the same output, because loop with getItem calling, runnung faster, then promises with exec, but in this case, each item will be handled exactly after appropriate promise will be resolved, except of awaiting of all promises resolution
Web application is loaded only in the form address `ip:8080`. I've a web application that is configured as `Wildfly` server and `Nginx` reverse proxy, I am trying to load this application in the browser without success because the application load only with ip address information. This is my first time that I use `Wildfly` server and `Nginx` then I don't have experience, but I've reading high. My application is a `Maven` project in `Java`, all in the project is working fine. Below is my configurations. My `standalone.xml`: ``` <subsystem xmlns="urn:jboss:domain:deployment-scanner:2.0"> 161 <deployment-scanner name="itcmedbr.war" path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000" auto-deploy-exploded="true" runtime-failure-causes-rollback="${jboss.deployment.scanner.rollback.on.failure:false}"/> 162 </subsystem> ``` My `nginx` conf: ``` 1 server { 2 listen 80; 3 listen [::]:80; 4 server_name itcmedbr.com www.itcmedbr.com; 5 6 # Load configuration files for the default server block. 7 8 location / { 9 root /opt/wildfly/standalone/data/content/39/c296b5d6d608465514ecce78b062f85b5f9001/content; 10 proxy_set_header X-Forwarded-For $remote_addr; 11 proxy_set_header Host $server_name:$server_port; 12 proxy_set_header Origin http://myipaddress; 13 proxy_set_header Upgrade $http_upgrade; 14 15 proxy_pass http://127.0.0.1:8080; 16 } 17 18 error_page 404 /404.html; 19 location = /40x.html { 20 } 21 22 error_page 500 502 503 504 /50x.html; 23 location = /50x.html { 24 } 25 } ``` In my mind I understanding that when is made a deploy a file is created so I looked in the `wildfly` folders and found this file that I specified in the root parameter of my `nginx.conf`, but the problem still the same, i.e `domain.com` and load the page. What I must to do to solve this problem? Thanks and best regards. 1 - deploy the war file ``` ls /opt/wildfly/standalone/deployments/ itcmedbr.war itcmedbr.war.deployed README.txt ``` 2 - configuration of `nginx`: ``` # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. # include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } # Settings for a `TLS` enabled server. # # server { # listen 443 ssl http2 default_server; # listen [::]:443 ssl http2 default_server; # server_name _; # root /usr/share/nginx/html; # # ssl_certificate "/etc/pki/nginx/server.crt"; # ssl_certificate_key "/etc/pki/nginx/private/server.key"; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 10m; # ssl_ciphers PROFILE=SYSTEM; # ssl_prefer_server_ciphers on; # # # Load configuration files for the default server block. # include /etc/nginx/default.d/*.conf; # # location / { # } # # error_page 404 /404.html; # location = /40x.html { # } # # error_page 500 502 503 504 /50x.html; # location = /50x.html { # } # } } ``` 2.1 - configuration of `itcmedbr.com.conf` in `/etc/nginx/conf.d`: ``` server { listen 80; listen [::]:80; server_name itcmedbr.com www.itcmedbr.com; listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; # Redirect all port 80 (HTTP) requests to port 443 (HTTPS). return 301 https://itcmedbr.com$request_uri; # Load configuration files for the default server block. location / { proxy_set_header Origin http://ipaddress; proxy_pass http://127.0.0.1:8080; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } ``` 3 - status `nginx`: ``` Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since Sun 2024-03-03 18:36:43 -03; 41s ago ``` 4 - status `wildfly.service`: ``` Loaded: loaded (/etc/systemd/system/wildfly.service; enabled; vendor preset: disabled) Active: active (running) since Sun 2024-03-03 18:25:40 -03; 41s ago ``` 5 - `firewall` ports: ``` firewall-cmd --list-all public (active) target: default icmp-block-inversion: no interfaces: eth0 sources: services: http https ssh ports: 8080/tcp 9990/tcp 3306/tcp 80/tcp 443/tcp protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: ss -tunelp | grep 80 tcp LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=159107,fd=6),("nginx",pid=159105,fd=6)) ino:2538418 sk:4b <-> tcp LISTEN 0 2048 xxx.xxx.xx.xxx:8080 0.0.0.0:* users:(("java",pid=158828,fd=494)) uid:990 ino:2536856 sk:4c <-> tcp LISTEN 0 511 [::]:80 [::]:* users:(("nginx",pid=159107,fd=7),("nginx",pid=159105,fd=7)) ino:2538419 sk:4f v6only:1 <-> ss -tunelp | grep 443 tcp LISTEN 0 511 0.0.0.0:443 0.0.0.0:* users:(("nginx",pid=159107,fd=8),("nginx",pid=159105,fd=8)) ino:2538420 sk:4d <-> tcp LISTEN 0 2048 xxx.xxx.xx.xxx:8443 0.0.0.0:* users:(("java",pid=158828,fd=495)) uid:990 ino:2536857 sk:4e <-> tcp LISTEN 0 511 [::]:443 [::]:* users:(("nginx",pid=159107,fd=9),("nginx",pid=159105,fd=9)) ino:2538421 sk:50 v6only:1 <-> ``` Now when I typing `itcmedbr.com` I receiving " This site can't be reached The connection was reset." and if I typing in the browser `ip:8080` the "`Welcome to Wildfly`" page is loaded. Trying to solve the problem I did the following steps: 1 - uninstall and remove `Nginx` 2 - install `nginx` with `certbot` ``` yum install nginx certbot python3-certbot-nginx ``` 3 - create my `server conf` ``` vi /etc/nginx/conf.d/itcmedbr.conf server { server_name itcmedbr.com; } ``` 4 - configure `certbot` ``` certbot --nginx define email define domain ``` 5 - `reload`, `restart`, `nginx` and `wildfly` 6 - when test `nginx` result is: ``` nginx -t nginx: [warn] conflicting server name "itcmedbr.com" on 0.0.0.0:80, ignored <==(I don't know why this occur and how to solve this) nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful ``` 7 - result of `nginx.conf` ``` # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } # Settings for a TLS enabled server. server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name _; root /usr/share/nginx/html; ssl_certificate "/etc/ssl/certs/nginx-selfsigned.crt"; ssl_certificate_key "/etc/ssl/private/nginx-selfsigned.key"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_ciphers PROFILE=SYSTEM; ssl_prefer_server_ciphers on; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } server { server_name itcmedbr.com; # managed by Certbot root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/itcmedbr.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/itcmedbr.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = itcmedbr.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80 ; listen [::]:80 ; server_name itcmedbr.com; return 404; # managed by Certbot }} ``` How we can see `nginx.conf` was updated by `certbot` and is managed by `certbot` too. After all of this now I've a new problem that when I typing my `ipaddress:9990` in the browser to open `wildfly` console I receive the same message "This site can't be reached."
## Editing and saving a network connection Copy a reference of the row item model so that it doesn't update the row item model until the Save button is clicked. Set this reference to the copied row item model on the component instance. Then set the `v-model` attribute for input fields to field values in the reference. Implement the `saveNetwork` method for clicks to the `Save` button and copy field values from the reference to the row item model. ### Deleting a network connection Assuming that the SSID is unique for the connections in `wifiNetworks`, update `wifiNetworks` to the list of networks with the network with the SSID in the copied reference excluded. ```jsx <template> <div class="pa-4 text-center"> <v-dialog v-model="showEditDialog" max-width="600"> <v-card prepend-icon="mdi-account" title="Edit Wifi settings"> <v-card-text> <v-row dense> <v-col cols="12" md="4" sm="6"> <v-text-field hint="Enter the Wifi password of your router." label="Wifi Password *" type="text" required="true" v-model="itemRef.value.SSID" ></v-text-field> </v-col> <v-col cols="12" sm="6"> <v-checkbox v-model="itemRef.value.autoConnect" label="Auto-Connect" > </v-checkbox> </v-col> </v-row> <small class="text-caption text-medium-emphasis" >* indicates a required field</small > </v-card-text> <v-divider></v-divider> <v-card-actions> <v-spacer></v-spacer> <v-btn text="Close" variant="plain" @click="showEditDialog = false" ></v-btn> <v-btn color="primary" text="Save" variant="tonal" @click="saveNetwork()" ></v-btn> </v-card-actions> </v-card> </v-dialog> <v-dialog v-model="showDeleteDialog" max-width="500"> <v-card title="Delete Wifi"> <v-card-text> Are you sure you want to remove {{ itemRef.value.SSID }} from the list of known Wifis? </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn text="Cancel" variant="plain" @click="hideDeleteWifiDialog()" ></v-btn> <v-btn color="red" text="Delete Wifi" variant="tonal" prepend-icon="$vuetify" @click="deleteWifi()" ></v-btn> </v-card-actions> </v-card> </v-dialog> </div> <v-data-table :headers="headers" :items="wifiNetworks" :items-per-page="20" :items-per-page-options="[ { value: 20, title: '20' }, { value: -1, title: 'All' }, ]" > <template v-slot:item.autoConnect="{ item }"> <v-chip :color="item.autoConnect ? 'green' : 'black'" :text="item.autoConnect ? 'Yes' : 'No'" :variant="item.autoConnect ? 'tonal' : 'text'" size="small" label > </v-chip> </template> <template v-slot:item.isConnected="{ item }"> <div class="text-end"> <v-chip :color="item.isConnected ? 'green' : 'black'" :text="item.isConnected ? 'Connected' : 'Connect'" :variant="item.isConnected ? 'tonal' : 'outlined'" @click="item.isConnected ? {} : { click: connect(item) }" size="small" label > </v-chip> </div> </template> <template v-slot:item.action="{ item }"> <v-icon class="me-2" size="small" @click="editItem(item)"> mdi-pencil </v-icon> <v-icon size="small" @click="showDeleteWifiDialog(item)" :disabled="false" > mdi-delete </v-icon> </template> </v-data-table> </template> <script> import { ref } from 'vue'; export default { data: () => ({ showEditDialog: false, showDeleteDialog: false, headers: [ { title: 'Network Name (SSID)', key: 'SSID' }, { title: 'Security Type', key: 'security' }, { title: 'Auto Connect', key: 'autoConnect' }, { title: 'Action', key: 'action' }, { title: 'Connection', key: 'isConnected' }, ], wifiNetworks: [ { SSID: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', security: 'WEP', isConnected: false, autoConnect: true, action: 'connect', }, { SSID: 'XYZ', security: 'WPA2', isConnected: true, autoConnect: true, action: 'connect', }, { SSID: '0x1234', security: 'None', isConnected: false, autoConnect: false, action: 'connect', }, { SSID: 'BGT', security: 'WPA', isConnected: false, autoConnect: false, action: 'connect', }, ], }), methods: { editItem(item) { this.item = item; this.itemRef = ref({ ...item }); this.showEditDialog = true; }, showDeleteWifiDialog(item) { this.item = item; this.itemRef = ref({ ...item }); this.showDeleteDialog = true; }, saveNetwork() { this.showEditDialog = false; this.item.SSID = this.itemRef.value.SSID; this.item.autoConnect = this.itemRef.value.autoConnect; }, hideDeleteWifiDialog() { this.showDeleteDialog = false; }, deleteWifi(item) { this.showDeleteDialog = false; this.wifiNetworks = this.wifiNetworks.filter( (w) => w.SSID !== this.itemRef.value.SSID ); }, }, }; </script> ``` [Stackblitz](https://stackblitz.com/edit/vitejs-vite-xmjkvp?file=src%2Fcomponents%2FSO.vue)
You might also use a regular expression to manually parse your digits and sort by treating those digits as numbers. This can be passed as a `key` function if you specify a level in `DataFrame.sort_index` ```python import pandas as pd from re import match df1 = pd.DataFrame({ ('y1', '0'): [1, 2, 3], ('y2', '0'): [4, 5, 6], ('y11', '0'): [7, 8, 9], }) df2 = pd.DataFrame({ ('y1', '1'): [1.5, 2.5, 3.5], ('y2', '1'): [4.5, 5.5, 6.5], ('y11', '1'): [7.5, 8.5, 9.5], }) df = ( pd.concat((df1, df2), axis="columns") .sort_index( axis='columns', level=0, key=lambda idx: idx.str.extract(r'(\w)(\d+)').astype({1: int}) ) ) print(df) # y1 y2 y11 # 0 1 0 1 0 1 # 0 1 1.5 4 4.5 7 7.5 # 1 2 2.5 5 5.5 8 8.5 # 2 3 3.5 6 6.5 9 9.5 ```
Why does it provide two different outputs with if2/if3?
|python|gekko|
In school I made a game with C++ graphic libs and all in Turbo C++. Horrible dev experience but made me addicted because of the freedom to do anything you want. Still in love with it because I love solving problems and learning new stuff.
null
I am using the laravel 7 and implement rate limit in kernel file ` protected $routeMiddleware = [ 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ]` i have 3 route file admin, home and user i put in all file group middleware like `Route::middleware(['throttle:10,1'])->group(function () { .... }` but it's take randomly like 8, 9,12,13 like not accurate. Any other things affected the rate limiter? i made also change in server config file like ` # Rate Limiting Configuration <Location var/www/html/abcd> SetOutputFilter RATE_LIMIT SetEnv rate-limit 5 SetEnv rate-limit-burst 5 </Location>` but not taking, why? please help me...
`(a == b) & (c == d)` will return true if all of the conditions are true. Another way to express this is with [`pl.all_horizontal()`](https://docs.pola.rs/docs/python/dev/reference/expressions/api/polars.all_horizontal.html#polars.all_horizontal) ```python pl.all_horizontal(a == b, c == d) ``` - [`pl.any_horizontal()`](https://docs.pola.rs/docs/python/dev/reference/expressions/api/polars.any_horizontal.html#polars.any_horizontal) can be used for "logical OR" To which you can pass your comprehension directly: ```python expr = pl.all_horizontal( pl.col(k) == v for k, v in row_index.items() ) df.row(by_predicate=expr) ```
What I would do is just put the dispose on the complete handler of the subscribe. ```kotlin package example import reactor.core.publisher.Flux import reactor.core.scheduler.Schedulers import reactor.util.Loggers import java.util.* object Parallel private val log = Loggers.getLogger(Parallel::class.java.name) private val COLORS = listOf("red", "white", "blue") fun main() { val flux = Flux.fromIterable(COLORS) val subScheduler = Schedulers.newParallel("sub") val pubScheduler = Schedulers.newParallel("pub", 1) flux .log() .map { obj: String -> obj.uppercase( Locale.getDefault() ) } .subscribeOn(subScheduler) .publishOn(pubScheduler) .subscribe( { value -> log.info("==============Consumed: $value") }, { err -> log.error("{}", err.message) }, { subScheduler.dispose() pubScheduler.dispose() } ) } ```
You can use [`str.split`](https://docs.python.org/3/library/stdtypes.html#str.split), [`itertools.pairwise`](https://docs.python.org/3/library/itertools.html#itertools.pairwise), [`map`](https://docs.python.org/3/library/functions.html#map) and [`str.join`](https://docs.python.org/3/library/stdtypes.html#str.join): ``` from itertools import pairwise s = 'A->B->C->D->E->F' out = ','.join(map('->'.join, pairwise(s.split('->')))) ``` Output: ``` 'A->B,B->C,C->D,D->E,E->F' ``` Similar logic if you have a Series/DataFrame: ``` from itertools import pairwise df = pd.DataFrame({'Input': ['A->B->C->D', 'X->Y->Z', 'A->B->Z->D->Y', 'X->Y->A->E->F']}) out = df.join(pd.DataFrame([['->'.join(x) for x in pairwise(s.split('->'))] for s in df['Input']]) .rename(columns=lambda x: f'split {x+1}')) Input split 1 split 2 split 3 split 4 0 A->B->C->D A->B B->C C->D NaN 1 X->Y->Z X->Y Y->Z NaN NaN 2 A->B->Z->D->Y A->B B->Z Z->D D->Y 3 X->Y->A->E->F X->Y Y->A A->E E->F ```
Postgresql doesn't respond, select * from claims where case_number='22222' but responds select * from claims
According to metaplex docs here : https://developers.metaplex.com/token-metadata/delegates, I first use the approve function to select a delegated authority. The function works as expected and here I can see that https://explorer.solana.com/tx/2rc14gbRE11jT6uJrpf6SzL2wBcFaaaetjXEJPQMMZLJB6dWqkoXYMAbrp5sh3KKkYRqKu1Gcr7ET67yG1o1SSUz?cluster=devnet, delegate authority is now of my choice account with publickey : 5nsp1dfFFxoneGKEhSgaUvFiHDFtTqSBc3bUBqTedh8r When I connect to my d'app using the delegated authority wallet(5nsp1dfFFxoneGKEhSgaUvFiHDFtTqSBc3bUBqTedh8r) and try to execute the lock function, I get an incorrect account error. But as I mentioned above I can see that the delegated authority is correct in Solana Explorer. What am I missing here ? Any answer would be very appreciated, thanks!
Can't Lock NFT after Delegating using Metaplex
|blockchain|web3js|solana|metaplex|
This best earlier answer does not work anymore in JDK 21.0.2, it was working in JDK 21, something has changed internally. I suspect that tryTransfer() does not work in this case. It seems that Doug Lea broke LinkedTransferQueue: https://github.com/openjdk/jdk/commit/8d1ab57065c7ebcc650b5fb4ae098f8b0a35f112 ``` BlockingQueue<Runnable> queue = new LinkedTransferQueue<Runnable>() { @Override public boolean offer(Runnable e) { return tryTransfer(e); } }; ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 50, 60, TimeUnit.SECONDS, queue); threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { executor.getQueue().put(r); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); ``` My workaround is to use normal LinkedBlockingQueue<Runnable> but the following: ``` @Override public void execute(Runnable command) { super.execute(command); // workaround problem with JDK 21.0.2 if (!getQueue().isEmpty()) { // if there are items in queue int poolSize = getPoolSize(); if (poolSize < getMaximumPoolSize()) { // if we can add more threads int activeCount = getActiveCount(); if (activeCount >= poolSize) { // if all current threads are active (not idle) synchronized (this) { setCorePoolSize(poolSize + 1); // add new thread setCorePoolSize(poolSize); // this does not remove threads until timeout } } } } } ``` This creates minimum new threads, only if there are items in queue and all current threads are active (not idle).
I'm trying to convert a column having values like May 24, 1960, Mar. 1, 1990, Aug. 22, 1981 and May 1, 1953 into Date (MM:DD:YYYY). Notice some have '.' between month and date and some don't. df['Customer DOB'] = pd.to_datetime(df['Customer DOB'], format='%b.%d,%Y').dt.strftime('%m:%d:%Y') Im getting error "time data "May 24, 1960" doesn't match format "%b. %d, %Y"," which makes sense as the code only handles cases with '.'.How do I account for both these cases?
Currently, I've a .img file (Kernel source file) with a capacity of 3.7GB. Could you Please suggest Linux terminal commands for extracting this .img file into a normal kernel source file? Thanks & Regards Ravikumar
How to extract the .img file into normal kernel source file in the linux?
In my work I use both STATA and R. Currently I want to perform a dose-response meta-analysis and use the "dosresmeta" package in R. The following syntax is used: ``` DRMeta <- dosresmeta( formula = logRR ~ dose, type = type, cases = n_cases, n = n, lb = RR_lo, ub = RR_hi, id = ID, data = DRMetaAnalysis ) ``` When executing this syntax, however, I encounter a problem. The error message appears: ``` Error in if (delta \< tol) break : missing value where TRUE/FALSE needed. ``` The reason for this error message is that I am missing some values for the variables "n_cases" and "n", which the authors have not provided. Interestingly, STATA does not require this information for the calculation of the dose-response meta-analysis. Is there a way to perform the analysis in R without requiring the values for "n_cases" and "n"? What can I do if I have not given these values? I have already asked the authors for the missing values, unfortunately without success. However, I need these studies for the dose-response meta-analysis, so it is not an option to exclude them.
null
For those stumbling upon this looking for a solution, the comment from @FedeH did it for me: > You can select your app as a debugging app under the developer options. This may help to reduce the unwanted system alerts.
I think you need to modify your `formSchema` as per bellow: ```javascript const formSchema = z.object({ // name: z.string().min(1), -- in prisma schema we have label and imageUrl, not a name. name: z.string().min(1), images: z.object({ url: z.string() }).array(), price: z.coerce.number().min(1), categoryId: z.string().min(1), colorId: z.string().min(1), sizeId: z.string().min(1), isFeatured: z.boolean().default(false).optional(), isArchived: z.boolean().default(false).optional(), }); ``` Changes: - Replaced `image` with `images`
I tried to load saved model by `Loaded_model = tf.keras.models.load_model('model.keras')` But occurs following error. Tensorflow version is Version: 2.16.1 Python version is Python 3.12.2 I ran the same code on Google Colab, where it successfully saved and loaded the model. However, when attempting to load a locally trained model, Colab failed to do so. I tried both .h5 and .keras file formats for saving the model. While both formats were successfully saved, neither could be loaded. ``` AttributeError Traceback (most recent call last) Cell In[9], line 3 1 import tensorflow as tf 2 from keras.models import load_model ----> 3 Loaded_model = tf.keras.models.load_model( 4 # 'model.keras') 5 'models\dress_classifier_transferlearn.h5') . . . AttributeError: Exception encountered when calling Flatten.call(). 'list' object has no attribute 'shape' Arguments received by Flatten.call(): • args=(['<KerasTensor shape=(None, 7, 7, 512), dtype=float32, sparse=False, name=keras_tensor_178>'],) • kwargs=<class 'inspect._empty'> ```
1. \[enter image description here\](https://i.stack.imgur.com/JYxhM.png) ``` * type here * xmkosjpscndowdv dwnmo ``` i am try to learn but i have no idea about because i disturb my mind tell me about it any one have idea about it can any person know about i am try to learn but i have no idea about because i disturb my mind tell me about it any one have idea about it can any person know about
Why is this program unable to execute? I aim to utilize this code to detect left and right mouse clicks, and terminate the program upon detecting scroll wheel movement. ``` from pymouse import PyMouseEvent def fibo(): a = 0 yield a b = 1 yield b while True: a, b = b, a + b yield b class Clickonacci(PyMouseEvent): def __init__(self): PyMouseEvent.__init__(self) self.fibo = fibo() def click(self, x, y, button, press): if press: if button == 1: print("left QAQp") elif button == 2: print("right ouob") def scroll(self, x, y, vertical, horizontal): print("Mouse scrolled") self.stop() C = Clickonacci() C.run() ```
Troubleshooting: Detecting Mouse Clicks and Terminating Program on Scroll Wheel Movement
|python|linux|ubuntu|unix|mouseevent|
I've implemented the SoftDeletes trait in my models, and I want to retrieve soft-deleted records when hitting API endpoints specifically from the admin panel. However, I don't want these records to be visible to other roles/users. I've tried using the withTrashed() method in my Eloquent queries, but it's not feasible to write this method in every query. I'm using the laravel 10. I'm expecting the global level solution for that.
How can I return the soft deleted records in the admin API's
|laravel|eloquent|laravel-10|soft-delete|
null
For me it still was using Bourne shell even though I selected /bin/zsh in the prefernces window. What helped was to execute ```sh chsh -s /bin/zsh ``` After restarting intelij terminal, zsh was properly started
I find myself in the position of needing to really use intrinsics for the first time as optimization for image conversion. I found this project here: [https://github.com/jabernet/YCbCr2RGB/blob/master/conversion.cpp ](https://github.com/jabernet/YCbCr2RGB/blob/master/conversion.cpp) and it almost works, but my output target needs to be in r8g8b8a8 while this is outputting in r8g8b8. I tried modifiying this bit here: const __m128 rgb1_1 = _mm_shuffle_ps( _mm_shuffle_ps(b1, g1, _MM_SHUFFLE(0, 0, 0, 0)), _mm_shuffle_ps(r1, b1, _MM_SHUFFLE(1, 1, 0, 0)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb1_2 = _mm_shuffle_ps( _mm_shuffle_ps(g1, r1, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b1, g1, _MM_SHUFFLE(2, 2, 2, 2)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb1_3 = _mm_shuffle_ps( _mm_shuffle_ps(r1, b1, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_ps(g1, r1, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb2_1 = _mm_shuffle_ps( _mm_shuffle_ps(b2, g2, _MM_SHUFFLE(0, 0, 0, 0)), _mm_shuffle_ps(r2, b2, _MM_SHUFFLE(1, 1, 0, 0)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb2_2 = _mm_shuffle_ps( _mm_shuffle_ps(g2, r2, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b2, g2, _MM_SHUFFLE(2, 2, 2, 2)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb2_3 = _mm_shuffle_ps( _mm_shuffle_ps(r2, b2, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_ps(g2, r2, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb3_1 = _mm_shuffle_ps( _mm_shuffle_ps(b3, g3, _MM_SHUFFLE(0, 0, 0, 0)), _mm_shuffle_ps(r3, b3, _MM_SHUFFLE(1, 1, 0, 0)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb3_2 = _mm_shuffle_ps( _mm_shuffle_ps(g3, r3, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b3, g3, _MM_SHUFFLE(2, 2, 2, 2)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb3_3 = _mm_shuffle_ps( _mm_shuffle_ps(r3, b3, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_ps(g3, r3, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb4_1 = _mm_shuffle_ps( _mm_shuffle_ps(b4, g4, _MM_SHUFFLE(0, 0, 0, 0)), _mm_shuffle_ps(r4, b4, _MM_SHUFFLE(1, 1, 0, 0)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb4_2 = _mm_shuffle_ps( _mm_shuffle_ps(g4, r4, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b4, g4, _MM_SHUFFLE(2, 2, 2, 2)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb4_3 = _mm_shuffle_ps( _mm_shuffle_ps(r4, b4, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_ps(g4, r4, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128i pack1l = _mm_packs_epi32(_mm_cvtps_epi32(rgb1_1), _mm_cvtps_epi32(rgb1_2)); const __m128i pack1h = _mm_packs_epi32(_mm_cvtps_epi32(rgb1_3), _mm_cvtps_epi32(rgb2_1)); const __m128i pack1 = _mm_packus_epi16(pack1l, pack1h); const __m128i pack2l = _mm_packs_epi32(_mm_cvtps_epi32(rgb2_2), _mm_cvtps_epi32(rgb2_3)); const __m128i pack2h = _mm_packs_epi32(_mm_cvtps_epi32(rgb3_1), _mm_cvtps_epi32(rgb3_2)); const __m128i pack2 = _mm_packus_epi16(pack2l, pack2h); const __m128i pack3l = _mm_packs_epi32(_mm_cvtps_epi32(rgb3_3), _mm_cvtps_epi32(rgb4_1)); const __m128i pack3h = _mm_packs_epi32(_mm_cvtps_epi32(rgb4_2), _mm_cvtps_epi32(rgb4_3)); const __m128i pack3 = _mm_packus_epi16(pack3l, pack3h); const __m128i packAlpha = { 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF }; // and finally store in output _mm_storeu_si128((__m128i*)(pixels + ((wh - width) * 4) - h * width * 4 + w * 4 + 0 * 16), pack1); _mm_storeu_si128((__m128i*)(pixels + ((wh - width) * 4) - h * width * 4 + w * 4 + 1 * 16), pack2); _mm_storeu_si128((__m128i*)(pixels + ((wh - width) * 4) - h * width * 4 + w * 4 + 2 * 16), pack3); _mm_storeu_si128((__m128i*)(pixels + ((wh - width) * 4) - h * width * 4 + w * 4 + 3 * 16), packAlpha); with the packAlpha lines added by me. I thought it would line things up properly, but what I ended up with was grayscale and had vertical while lines throughout. It's also flipped on both axes, but that was true before my changes, and can be solved by rotating the texture that pixels is given too later. Edit: appended the calculation for the rgbX_Y variables to the top of the code block, per comment request. Also edited the numbers in the storing functions to reflect that I did in fact change those 3s to 4s
|excel|vba|french|
{"OriginalQuestionIds":[13966186],"Voters":[{"Id":1541563,"DisplayName":"Patrick Roberts","BindingReason":{"GoldTagBadge":"javascript"}}]}
The business has BPC 11.1 version and using analysis for Office Excel AFO, but they are facing one issue that is when business users are trying to execute the macro, their system is not able to read that macro. It is because their system Office language is French or maybe Spanish or Italian, but our The macro written in English should work for French users like it worked for Japan users. In the system of French people, the system is not able to read macro logic in English. But when it was in Japan, the system was able to read the same macro in english. The logic is not readable for French users : ``` Result = Application.Run("SAPGetProperty", "IsConnected", "DS_1") ```
Handling multiple formats: Convert to datetime (MM:DD:YYYY)
|python|python-3.x|pandas|date|datetime|
i don't understand were i was doing wrong i'm getting this again and again i'm getting error like this Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in sitaram.urls, Django tried these URL patterns, in this order: members/ [name='members'] admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. wanted to know were i'm i doing wrong
django framework 404 error page not found
|django|http-status-code-404|
null
I am trying to convert the IP subnet 192.168.224.0/22 into Regular Expression. The valid IP range is 192.168.224.1 to 192.16.227.254 I can use this in Sentinel KQL query. Is the below correct one? 192\.168\.(22[4-7]|23[0-6])\.(25[0-4]|2[0-4][0-9]|[01]?[0-9][0-9]?) I can use this in Sentinel KQL query. Is the below correct one? 192\.168\.(22[4-7]|23[0-6])\.(25[0-4]|2[0-4][0-9]|[01]?[0-9][0-9]?)
Convert into Regular Expression
|regex|kql|
null
It's an old question but I've got an answer. I'm not sure if it's the right answer for you. I had the same issue and Signalling didn't work. So I used the following ```xml <action class="org.alfresco.repo.workflow.jbpm.AlfrescoJavaScript"> <script> <variable name="wf_ended" access="read,write" /> <expression>wf_ended = true;</expression> </script> </action> <script> executionContext.getTaskMgmtInstance().endAll(); </script> ```
null
With this modification, the referralUsers function will stop recursive calls once it reaches the third level of referrals, effectively limiting the query to 3 levels. public function referralUsers($id, $currentLevel = 1) { // Check if the current level exceeds 3 if ($currentLevel > 3) { return $this->allusers; // Return the collected users } $users = $this->getUsers($id); if ($users['status']) { $this->allusers[$currentLevel] = $users['user']; $currentLevel++; $this->referralUsers($users['ids'], $currentLevel); } return $this->allusers; }
The straight solution would be to go to: workspace settings->general->general settings->execution mode->custom->local(select this) explanation: if your modules are locally stored how would terraform know or access them so upon setting local mode, your plans and applies occur on machines you control. Terraform Cloud is only used to store and synchronize state.
I am trying to run a python worksheet in Snowflake with some external packages. I installed them from the dropdown inside the same python worksheet but when I try to import a certain function, I receive an error message saying this: "100357 (P0000): Cannot create a Python function with the specified packages. Please check your packages specification and try again." Although pandas is inside the list of installed packages I've looked up the versions for the packages to check compatibility and I think the problem does not come from here. Also, the package or the function I try to import is slashed-underlined, and when I place mi cursor over it it says "couldn't access to <package or function>".
The asynchronous nature of state updates in React seems to be causing this. When you call setBar() to update r2, the state update isn't immediate, and r2 doesn't reflect the new value of "bar" immediately after setBar() is called. So, when you immediately call setValue("result2", r2), r2 still holding its previous value ("foo") imo. you can try to use useEffect to update the value of "result2" after r2 has been updated. Try something like this, ```js useEffect(() => { setValue("result2", r2) // update result2 when r2 changes }, [r2, setValue]) const showResults = () => { setValue("result1", "bar") setBar() } ```
There were several issues with the Gitlab server: 1. It didn't support ed25519, it supported only rsa 2. It refused git as a user, it expected some service account name instead ``` git clone svcaccnt@gitlab.xxx:path/to/repo.git --config core.sshCommand="ssh -i /path/to/private_key" ```
We could add a temporary column `".rm"` (for remove), created from unlisting the `"id"` column and scanning it for `duplicated`. This gives a vector that can be `split`ted along `rep`eated consecutive integers each `nrow` times for each sub-list and added to the sub-lists using `` `[<-`() ``. Finally we `subset` for not `TRUE`s in `".rm"` and remove that temporary column. > fn <- \(x, idcol) { + Map(`[<-`, x, '.rm', value= + lapply(x, `[`, idcol) |> + unlist() |> + duplicated() |> + split(sapply(x, nrow) |> { + \(.) mapply(rep.int, seq_along(.), .) + }())) |> + lapply(subset, !.rm, select=-.rm) + } > > fn(my_list, 'id') [[1]] id country 1 xxxyz USA 3 zzuio Canada [[2]] id country 2 ppuip Canada This removes "zzuio" in second sub-list instead of the first, but that actually makes more sense to me.
I have a list of comment boxes and buttons that go with each box. When the user clicks edit I only want that particular textbox to be enabled. When the click save or cancel I want the text box to be hidden and the "<p></p>" to be visible. Here is my ng-template where I am trying to track by index <ng-template #item let-item let-i="index"> <textarea [disabled]="IsDisabled(i)" [(ngModel)]="item.commentText" nz-input rows="4"></textarea> <nz-form-item> <button nz-button nzType="primary" [nzLoading]="submitting" (click)="openEdit(i)">Edit Comment</button> <button (click)=updateCommentsById(item, index)> Save Comment</button> </nz-form-item> </nz-form-item> </ng-template> async updateCommentsById(item, index) { console.log(item, index); } openEdit(index){ //Open this list item for edit } As you see in this list each row has a textarea. When the user clicks on the Edit button I want the textbox to be enabled for that row only. When the user clicks cancel or Save I want the corresponding actions to be attached for that row only. How can I use the index to edit and save each row