content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: how does react diff algorithm find out this assumption? I am using react to build my own web app, but I am wondering how does the following assumption make react diff faster. In other words, what does react base this assumption on? Two elements of different types will produce different trees. A: React creates and keeps an exactly same copy of actual DOM which is termed as virtual DOM. This will have everything the actual DOM has like objects and their types and their values. Whenever there is any change in the actual DOM, react takes a snapshot of it right before the update and compares it with the virtual DOM, and based on the differences found it goes and updates the actual DOM. So if you have two elements of different types, there will be a different tree. This is my understanding, let me know if you find something else. A: That assumption enables React to find out minimum number of operations to transform one DOM tree into another one in O(n) time. However, the state of the art algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree. If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. By assuming that elements of different types have different trees, react will save valuable computation time by avoiding too many comparisons to convert one tree into another. So without this if you have the following structure <div> <span> </span> <span> </span> </div> and if your new structure is <span> <span> </span> <div> </div> </span> React will now have to compare whether the first span child was there or not. Then it will have to compare whether second child div is there or not; now it finds that it wasn't there so it will have to only change the second div along with the outer parent tag. (Imagine doing this for 1000 elements) They have also mentioned In practice, these assumptions are valid for almost all practical use cases. And from my experience in almost all cases it is always true. A: Diffing Algorithm Assumptions If two react elements have a different type, the algorithm assumes their content to be different. Note: If two react elements have the same content but different types, the diffing algorithm takes the content differently and unnecessary modification will be done in the real DOM. Try out this by creating two-component, render one of them in the first render and render the other in the future render. If you inspect the element in the developer tool you will see unnecessary modification is made in the real DOM. https://codesandbox.io/s/diffing-algorithm-assumptions-7gsxxw We are providing a key as a prop to every element in case we are rendering a list of items.
how does react diff algorithm find out this assumption?
I am using react to build my own web app, but I am wondering how does the following assumption make react diff faster. In other words, what does react base this assumption on? Two elements of different types will produce different trees.
[ "React creates and keeps an exactly same copy of actual DOM which is termed as virtual DOM. This will have everything the actual DOM has like objects and their types and their values. Whenever there is any change in the actual DOM, react takes a snapshot of it right before the update and compares it with the virtual DOM, and based on the differences found it goes and updates the actual DOM.\nSo if you have two elements of different types, there will be a different tree.\nThis is my understanding, let me know if you find something else.\n", "That assumption enables React to find out minimum number of operations to transform one DOM tree into another one in O(n) time.\n\nHowever, the state of the art algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree. If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive.\n\nBy assuming that elements of different types have different trees, react will save valuable computation time by avoiding too many comparisons to convert one tree into another. So without this if you have the following structure\n<div>\n <span> </span>\n <span> </span>\n</div>\n\nand if your new structure is\n<span>\n <span> </span>\n <div> </div>\n</span>\n\nReact will now have to compare whether the first span child was there or not. Then it will have to compare whether second child div is there or not; now it finds that it wasn't there so it will have to only change the second div along with the outer parent tag. (Imagine doing this for 1000 elements)\nThey have also mentioned\n\nIn practice, these assumptions are valid for almost all practical use cases.\n\nAnd from my experience in almost all cases it is always true.\n", "Diffing Algorithm Assumptions\n\nIf two react elements have a different type, the algorithm assumes their content to be different. \nNote: If two react elements have the same content but different types, the diffing algorithm takes the content differently and unnecessary modification will be done in the real DOM.\n\nTry out this by creating two-component, render one of them in the first render and render the other in the future render. If you inspect the element in the developer tool you will see unnecessary modification is made in the real DOM. \nhttps://codesandbox.io/s/diffing-algorithm-assumptions-7gsxxw\nWe are providing a key as a prop to every element in case we are rendering a list of items.\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "diff", "reactjs", "web" ]
stackoverflow_0054663522_diff_reactjs_web.txt
Q: Making a sliding puzzle game using turtle (not tkinter or pygame) So I'm currently trying to program a slidepuzzle game without importing tkinter or pygame. So far i've generated a board and populated it with working buttons (quit,load,reset) but I'm really lost on how to program the actual slide puzzle game with the images i've been provided. This code generates the screen and buttons that makeup my board. clicking the load button (which i already have setup) allows the user to type in the puzzle they want to load and unscramble. The issue is that I don't know how to get all the images onto the board and Im not sure what direction i should go in to actually program the game elements (it's just a screen and buttons right now). I'm a newbie programmer so any help is really appreciated. screen = turtle.Screen() def generate_screen(): `os.chdir('Resources') # Changes directory to allow access to .gifs in Resources screen.setup(700, 700) screen.title("Sliding Puzzle Game") screen.tracer(0) generate_scoreboard() generate_leaderboard() iconturtle = turtle.Turtle() iconturtle.penup() for file in os.listdir(): screen.register_shape(file) iconturtle.goto(280, -270) iconturtle.shape('quitbutton.gif') iconturtle.stamp() iconturtle.goto(180, -270) iconturtle.shape('loadbutton.gif') iconturtle.stamp() iconturtle.goto(80, -270) iconturtle.shape('resetbutton.gif') iconturtle.stamp()` `def load_yoshi(): os.chdir('Images\\yoshi') screen.tracer(1) screen.register_shape('yoshi_thumbnail.gif') t = turtle.Turtle() t.penup() t.shape('yoshi_thumbnail.gif') t.goto(250,290) t.stamp() screen.update() files = glob.glob('*.gif') # pulling out only .gif images = files print(images) for file in images: screen.register_shape(file)` A: I've only seen turtle used to draw lines, not shapes, much less movable game pieces. I think pygame would definitely be better for this – OneCricketeer Below is an example slide game simplified from an earlier answer I wrote about creating numbered tiles using turtle: from turtle import Screen, Turtle from functools import partial from random import random SIZE = 4 TILE_SIZE = 100 OFFSETS = [(-1, 0), (0, -1), (1, 0), (0, 1)] CURSOR_SIZE = 20 def slide(tile, row, col, x, y): tile.onclick(None) # disable handler inside handler for dy, dx in OFFSETS: try: if row + dy >= 0 <= col + dx and matrix[row + dy][col + dx] is None: matrix[row][col] = None row, col = row + dy, col + dx matrix[row][col] = tile x, y = tile.position() tile.setposition(x + dx * TILE_SIZE, y - dy * TILE_SIZE) break except IndexError: pass tile.onclick(partial(slide, tile, row, col)) screen = Screen() matrix = [[None for _ in range(SIZE)] for _ in range(SIZE)] offset = TILE_SIZE * 1.5 for row in range(SIZE): for col in range(SIZE): if row == SIZE - 1 == col: break tile = Turtle('square', visible=False) tile.shapesize(TILE_SIZE / CURSOR_SIZE) tile.fillcolor(random(), random(), random()) tile.penup() tile.goto(col * TILE_SIZE - offset, offset - row * TILE_SIZE) tile.onclick(partial(slide, tile, row, col)) tile.showturtle() matrix[row][col] = tile screen.mainloop() Click on a tile next to the blank space to have it move into that space:
Making a sliding puzzle game using turtle (not tkinter or pygame)
So I'm currently trying to program a slidepuzzle game without importing tkinter or pygame. So far i've generated a board and populated it with working buttons (quit,load,reset) but I'm really lost on how to program the actual slide puzzle game with the images i've been provided. This code generates the screen and buttons that makeup my board. clicking the load button (which i already have setup) allows the user to type in the puzzle they want to load and unscramble. The issue is that I don't know how to get all the images onto the board and Im not sure what direction i should go in to actually program the game elements (it's just a screen and buttons right now). I'm a newbie programmer so any help is really appreciated. screen = turtle.Screen() def generate_screen(): `os.chdir('Resources') # Changes directory to allow access to .gifs in Resources screen.setup(700, 700) screen.title("Sliding Puzzle Game") screen.tracer(0) generate_scoreboard() generate_leaderboard() iconturtle = turtle.Turtle() iconturtle.penup() for file in os.listdir(): screen.register_shape(file) iconturtle.goto(280, -270) iconturtle.shape('quitbutton.gif') iconturtle.stamp() iconturtle.goto(180, -270) iconturtle.shape('loadbutton.gif') iconturtle.stamp() iconturtle.goto(80, -270) iconturtle.shape('resetbutton.gif') iconturtle.stamp()` `def load_yoshi(): os.chdir('Images\\yoshi') screen.tracer(1) screen.register_shape('yoshi_thumbnail.gif') t = turtle.Turtle() t.penup() t.shape('yoshi_thumbnail.gif') t.goto(250,290) t.stamp() screen.update() files = glob.glob('*.gif') # pulling out only .gif images = files print(images) for file in images: screen.register_shape(file)`
[ "\nI've only seen turtle used to draw lines, not shapes, much less\nmovable game pieces. I think pygame would definitely be better for\nthis – OneCricketeer\n\nBelow is an example slide game simplified from an earlier answer I wrote about creating numbered tiles using turtle:\nfrom turtle import Screen, Turtle\nfrom functools import partial\nfrom random import random\n\nSIZE = 4\nTILE_SIZE = 100\nOFFSETS = [(-1, 0), (0, -1), (1, 0), (0, 1)]\n\nCURSOR_SIZE = 20\n\ndef slide(tile, row, col, x, y):\n tile.onclick(None) # disable handler inside handler\n\n for dy, dx in OFFSETS:\n try:\n if row + dy >= 0 <= col + dx and matrix[row + dy][col + dx] is None:\n matrix[row][col] = None\n row, col = row + dy, col + dx\n matrix[row][col] = tile\n x, y = tile.position()\n tile.setposition(x + dx * TILE_SIZE, y - dy * TILE_SIZE)\n break\n except IndexError:\n pass\n\n tile.onclick(partial(slide, tile, row, col))\n\nscreen = Screen()\n\nmatrix = [[None for _ in range(SIZE)] for _ in range(SIZE)]\n\noffset = TILE_SIZE * 1.5\n\nfor row in range(SIZE):\n for col in range(SIZE):\n if row == SIZE - 1 == col:\n break\n\n tile = Turtle('square', visible=False)\n tile.shapesize(TILE_SIZE / CURSOR_SIZE)\n tile.fillcolor(random(), random(), random())\n tile.penup()\n tile.goto(col * TILE_SIZE - offset, offset - row * TILE_SIZE)\n tile.onclick(partial(slide, tile, row, col))\n tile.showturtle()\n\n matrix[row][col] = tile\n\nscreen.mainloop()\n\nClick on a tile next to the blank space to have it move into that space:\n\n" ]
[ 0 ]
[]
[]
[ "game_development", "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074672476_game_development_python_python_turtle_turtle_graphics.txt
Q: How can I encryption Acii code using a Caesar method I want to use the same program # Caesar Cipher # http://inventwithpython.com/hacking (BSD Licensed) import pyperclip # the string to be encrypted/decrypted message = 'This is my secret message.' # the encryption/decryption key key = 13 # tells the program to encrypt or decrypt mode = 'encrypt' # set to 'encrypt' or 'decrypt' # every possible symbol that can be encrypted LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # stores the encrypted/decrypted form of the message translated = '' # capitalize the string in message message = message.upper() # run the encryption/decryption code on each symbol in the message string for symbol in message: if symbol in LETTERS: # get the encrypted (or decrypted) number for this symbol num = LETTERS.find(symbol) # get the number of the symbol if mode == 'encrypt': num = num + key elif mode == 'decrypt': num = num - key # handle the wrap-around if num is larger than the length of # LETTERS or less than 0 if num >= len(LETTERS): num = num - len(LETTERS) elif num < 0: num = num + len(LETTERS) # add encrypted/decrypted number's symbol at the end of translated translated = translated + LETTERS[num] else: # just add the symbol without encrypting/decrypting translated = translated + symbol # print the encrypted/decrypted string to the screen print(translated) # copy the encrypted/decrypted string to the clipboard pyperclip.copy(translated) Input: (This is my secret message) Output: (GUVF VF ZL FRPERG ZRFFNTR) This program is encrypted in a Caesar method I want this program to encrypt Ascii code using a Caesar method How can i convert it to do that? A: To encrypt the ASCII code of each symbol in the message using a Caesar cipher, you will need to modify the code as follows: Replace the LETTERS string with a string containing all the ASCII characters that you want to encrypt. For example, you could use the string string.printable from the string module, which includes all the ASCII characters that are considered printable, including digits, letters, and punctuation marks. In the for loop that iterates over each symbol in the message, use the ord() function to convert the symbol to its ASCII code, and the chr() function to convert the encrypted or decrypted ASCII code back to a character. Here is an example of how you could modify the code to encrypt the ASCII code of each symbol in the message using a Caesar cipher: import string import pyperclip # the string to be encrypted/decrypted message = 'This is my secret message.' # the encryption/decryption key key = 13 # tells the program to encrypt or decrypt mode = 'encrypt' # set to 'encrypt' or 'decrypt' # every possible ASCII character that can be encrypted LETTERS = string.printable # stores the encrypted/decrypted form of the message translated = '' # run the encryption/decryption code on each symbol in the message string for symbol in message: # get the ASCII code of the symbol ascii_code = ord(symbol) if ascii_code in range(len(LETTERS)): # get the encrypted (or decrypted) ASCII code for this symbol if mode == 'encrypt': ascii_code = ascii_code + key elif mode == 'decrypt': ascii_code = ascii_code - key # handle the wrap-around if the ASCII code is out of range if ascii_code >= len(LETTERS): ascii_code = ascii_code - len(LETTERS) elif ascii_code < 0: ascii_code = ascii_code + len(LETTERS) # add the encrypted/decrypted character to the translated string translated = translated + chr(ascii_code) else: # just add the character without encrypting/decrypting translated = translated + symbol # print the encrypted/decrypted string to the screen print(translated) # copy the encrypted/decrypted string to the clipboard pyperclip.copy(translated) This code should encrypt the ASCII code of each symbol in the message using a Caesar cipher and print the encrypted message to the screen. The encrypted message will also be copied to the clipboard.
How can I encryption Acii code using a Caesar method I want to use the same program
# Caesar Cipher # http://inventwithpython.com/hacking (BSD Licensed) import pyperclip # the string to be encrypted/decrypted message = 'This is my secret message.' # the encryption/decryption key key = 13 # tells the program to encrypt or decrypt mode = 'encrypt' # set to 'encrypt' or 'decrypt' # every possible symbol that can be encrypted LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # stores the encrypted/decrypted form of the message translated = '' # capitalize the string in message message = message.upper() # run the encryption/decryption code on each symbol in the message string for symbol in message: if symbol in LETTERS: # get the encrypted (or decrypted) number for this symbol num = LETTERS.find(symbol) # get the number of the symbol if mode == 'encrypt': num = num + key elif mode == 'decrypt': num = num - key # handle the wrap-around if num is larger than the length of # LETTERS or less than 0 if num >= len(LETTERS): num = num - len(LETTERS) elif num < 0: num = num + len(LETTERS) # add encrypted/decrypted number's symbol at the end of translated translated = translated + LETTERS[num] else: # just add the symbol without encrypting/decrypting translated = translated + symbol # print the encrypted/decrypted string to the screen print(translated) # copy the encrypted/decrypted string to the clipboard pyperclip.copy(translated) Input: (This is my secret message) Output: (GUVF VF ZL FRPERG ZRFFNTR) This program is encrypted in a Caesar method I want this program to encrypt Ascii code using a Caesar method How can i convert it to do that?
[ "To encrypt the ASCII code of each symbol in the message using a Caesar cipher, you will need to modify the code as follows:\nReplace the LETTERS string with a string containing all the ASCII characters that you want to encrypt. For example, you could use the string string.printable from the string module, which includes all the ASCII characters that are considered printable, including digits, letters, and punctuation marks.\nIn the for loop that iterates over each symbol in the message, use the ord() function to convert the symbol to its ASCII code, and the chr() function to convert the encrypted or decrypted ASCII code back to a character.\nHere is an example of how you could modify the code to encrypt the ASCII code of each symbol in the message using a Caesar cipher:\nimport string\nimport pyperclip\n\n# the string to be encrypted/decrypted\nmessage = 'This is my secret message.'\n# the encryption/decryption key\nkey = 13\n\n# tells the program to encrypt or decrypt\nmode = 'encrypt' # set to 'encrypt' or 'decrypt'\n# every possible ASCII character that can be encrypted\nLETTERS = string.printable\n\n# stores the encrypted/decrypted form of the message\ntranslated = ''\n\n# run the encryption/decryption code on each symbol in the message string\nfor symbol in message:\n # get the ASCII code of the symbol\n ascii_code = ord(symbol)\n if ascii_code in range(len(LETTERS)):\n # get the encrypted (or decrypted) ASCII code for this symbol\n if mode == 'encrypt':\n ascii_code = ascii_code + key\n elif mode == 'decrypt':\n ascii_code = ascii_code - key\n\n # handle the wrap-around if the ASCII code is out of range\n if ascii_code >= len(LETTERS):\n ascii_code = ascii_code - len(LETTERS)\n elif ascii_code < 0:\n ascii_code = ascii_code + len(LETTERS)\n\n # add the encrypted/decrypted character to the translated string\n translated = translated + chr(ascii_code)\n\n else:\n # just add the character without encrypting/decrypting\n translated = translated + symbol\n\n# print the encrypted/decrypted string to the screen\nprint(translated)\n\n# copy the encrypted/decrypted string to the clipboard\npyperclip.copy(translated)\n\nThis code should encrypt the ASCII code of each symbol in the message using a Caesar cipher and print the encrypted message to the screen. The encrypted message will also be copied to the clipboard.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074679603_python.txt
Q: Troubleshooting React versions: Is it O.K. to simply change the package.json file? I think that when I upgraded to React 18, React broke a part of my app. I wanted to verify this behavior by simply using my previous package.json file which I saved as package-previous.json. I'm assuming webpack allows one to simply change the package.json file to restore a previous app configuration, but I wanted to make sure there are no caveats. I'm going back from: "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0", "react-redux": "^7.2.6" }, to: "dependencies": { "react": "^17.0.2", "react-dom": "^17.0.2", "react-redux": "^7.2.6" }, A: There's no problem with updating the dependency versions in your package.json; if the dependencies you changed are already installed, you can run npm update to upgrade or downgrade their versions, otherwise, you should run npm install. This will update your node_modules and your package-lock.json files.
Troubleshooting React versions: Is it O.K. to simply change the package.json file?
I think that when I upgraded to React 18, React broke a part of my app. I wanted to verify this behavior by simply using my previous package.json file which I saved as package-previous.json. I'm assuming webpack allows one to simply change the package.json file to restore a previous app configuration, but I wanted to make sure there are no caveats. I'm going back from: "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0", "react-redux": "^7.2.6" }, to: "dependencies": { "react": "^17.0.2", "react-dom": "^17.0.2", "react-redux": "^7.2.6" },
[ "There's no problem with updating the dependency versions in your package.json; if the dependencies you changed are already installed, you can run npm update to upgrade or downgrade their versions, otherwise, you should run npm install.\nThis will update your node_modules and your package-lock.json files.\n" ]
[ 1 ]
[]
[]
[ "npm", "reactjs", "webpack" ]
stackoverflow_0074679446_npm_reactjs_webpack.txt
Q: How do I delete a specific row from sqlite with Android Studio (Kotlin)? I looked through so many tutorials and it's still not working for me. I have a database that looks like this: databaseImage Note that the actual row does not match up with the id. I would like to delete from the actual row rather than using the id. I have the following function: `fun deleteDBData(TABLE_NAME:String, rowID : Int) { val db = this.writableDatabase db.delete(TABLE_NAME, "$ID_COL=$rowID", null) }` This however, deletes using the number in the id column rather than the actual row. So with this function, if I tell it to delete rowID = 4, it will delete row 1 rather than row 4. How do I get sqlite to delete row 4? A: You are telling to delete the row that has the ID_COL = 4 To delete the 4th row you can run a query like delete from tran_log where id in (select id from tran_log limit 1 offset 3); A: You can find the id of the nth row with LIMIT 1 and OFFSET n - 1 after the ORDER BY clause which I assume should use the column id to sort the rows: fun deleteDBData(TABLE_NAME: String, n: Long) { val db = this.writableDatabase db.delete( TABLE_NAME, "$ID_COL = (SELECT $ID_COL FROM $TABLE_NAME ORDER BY $ID_COL LIMIT 1 OFFSET ? - 1)", arrayOf(n.toString()) ) db.close() }
How do I delete a specific row from sqlite with Android Studio (Kotlin)?
I looked through so many tutorials and it's still not working for me. I have a database that looks like this: databaseImage Note that the actual row does not match up with the id. I would like to delete from the actual row rather than using the id. I have the following function: `fun deleteDBData(TABLE_NAME:String, rowID : Int) { val db = this.writableDatabase db.delete(TABLE_NAME, "$ID_COL=$rowID", null) }` This however, deletes using the number in the id column rather than the actual row. So with this function, if I tell it to delete rowID = 4, it will delete row 1 rather than row 4. How do I get sqlite to delete row 4?
[ "You are telling to delete the row that has the ID_COL = 4\nTo delete the 4th row you can run a query like\ndelete from tran_log where id in (select id from tran_log limit 1 offset 3);\n\n", "You can find the id of the nth row with LIMIT 1 and OFFSET n - 1 after the ORDER BY clause which I assume should use the column id to sort the rows:\nfun deleteDBData(TABLE_NAME: String, n: Long) {\n val db = this.writableDatabase\n db.delete(\n TABLE_NAME,\n \"$ID_COL = (SELECT $ID_COL FROM $TABLE_NAME ORDER BY $ID_COL LIMIT 1 OFFSET ? - 1)\",\n arrayOf(n.toString())\n )\n db.close()\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "android", "kotlin", "sqlite" ]
stackoverflow_0074669702_android_kotlin_sqlite.txt
Q: How to implement Idempotent key into an asp.net web api? An app makes an HTTP post with Idempotency Key in the API request header. On the server-side, you want to check if the request with the Idempotent Key has been processed for this client or not. If the request has not been processed than we proceed with the method to CREATE, UPDATE or DELETE. If the Idempotent Key has been used in the previous request, then we response back to the client with an error message. How do we track the API request, the API count, and the Idempotent Key used in request etc? By logging all API request in the database and make a round trip to the database to check this information everytime a new request is made? Or is there a better way? A: You can try to use this open source component on github to solve your problem IdempotentAPI A: What I like doing in a fairly standard setup (database, EF core, web api) is use a middleware to add (Context.Add()) the idempotency key (which in my case is the causation ID (ID of the originating event) + date time of the event) to the database without committing. Later on, in the controller, a service or some sort of handler, I make sure Context.SaveChanges() (or UnitOfWork.Commit()) is called only once (which should normally be the case since you’re supposed to update only 1 aggregate root per transaction). This way you’re sure you’re saving atomically, your idempotency key will only be saved if your insert/update/delete is successful. If the idempotency key already exists in the database your insert/update/delete will fail. Finally, what you can also do is cache your successful responses, so that in case of idempotency exception, you can simply return the cached response.
How to implement Idempotent key into an asp.net web api?
An app makes an HTTP post with Idempotency Key in the API request header. On the server-side, you want to check if the request with the Idempotent Key has been processed for this client or not. If the request has not been processed than we proceed with the method to CREATE, UPDATE or DELETE. If the Idempotent Key has been used in the previous request, then we response back to the client with an error message. How do we track the API request, the API count, and the Idempotent Key used in request etc? By logging all API request in the database and make a round trip to the database to check this information everytime a new request is made? Or is there a better way?
[ "You can try to use this open source component on github to solve your problem IdempotentAPI\n", "What I like doing in a fairly standard setup (database, EF core, web api) is use a middleware to add (Context.Add()) the idempotency key (which in my case is the causation ID (ID of the originating event) + date time of the event) to the database without committing.\nLater on, in the controller, a service or some sort of handler, I make sure Context.SaveChanges() (or UnitOfWork.Commit()) is called only once (which should normally be the case since you’re supposed to update only 1 aggregate root per transaction).\nThis way you’re sure you’re saving atomically, your idempotency key will only be saved if your insert/update/delete is successful. If the idempotency key already exists in the database your insert/update/delete will fail.\nFinally, what you can also do is cache your successful responses, so that in case of idempotency exception, you can simply return the cached response.\n" ]
[ 0, 0 ]
[]
[]
[ "api", "asp.net", "asp.net_core", "asp.net_web_api", "c#" ]
stackoverflow_0053039359_api_asp.net_asp.net_core_asp.net_web_api_c#.txt
Q: flutter_background_service not receiving updates I'm using awesome_notifications and flutter_background_service in conjunction to update some app state when receiving data notifications from FirebaseMessaging. As noted in the awesome_notifications, the background message handler must be a top-level function, so I am using flutter_background_service to pass data to the main isolate and update app state. Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeBackgroundService(); FirebaseMessaging.onBackgroundMessage(_backgroundMessageHandler); _initLocalNotifications(); runApp(MyApp()); } I'm initializing the background service similarly to the example in flutter_background_service: Future<void> initializeBackgroundService() async { final service = FlutterBackgroundService(); await service.configure( androidConfiguration: AndroidConfiguration( onStart: onStart, autoStart: true, isForegroundMode: true, ), iosConfiguration: IosConfiguration( autoStart: true, onForeground: onStart, onBackground: onIosBackground, ), ); await service.startService(); } and invoking update in the _backgroundMessageHandler when a notification is received: Future<void> _backgroundMessageHandler( RemoteMessage message, ) async { final service = FlutterBackgroundService(); ... service.invoke('update', { 'key1': 'val1', 'key2': 'val2', }); } And in the StatefulWidget for my app in the main isolate, I'm listening on the update call to receive the data: void listenForNotificationData() { final backgroundService = FlutterBackgroundService(); backgroundService.on('update').listen((event) async { print('received data message in feed: $event'); }, onError: (e, s) { print('error listening for updates: $e, $s'); }, onDone: () { print('background listen closed'); }); } It's never invoking the listen callback on the 'update' event. I can confirm it's calling the invoke('update') portion and calling on('update').listen, but never receiving the update. It also doesn't seem to be erroring out. Am I missing a step somewhere here? A: I was encountering the same issue on flutter background service. I solved it by removing the async keyword from the callback and creating a separate async function to perform the callback operations. void listenForNotificationData() { final backgroundService = FlutterBackgroundService(); backgroundService.on('update').listen((event) { print('received data message in feed: $event'); }, onError: (e, s) { print('error listening for updates: $e, $s'); }, onDone: () { print('background listen closed'); }); } void action(Map? event) async { print('received data message in feed: $event'); } Hope it helps, forgive me if there are syntax error A: You can try this. main(){ .... } Future<void> readyForShared() async { var sharedPreferences = await SharedPreferences.getInstance(); counterValue = sharedPreferences.getString("yourVariable") ?? "0"; } Future<void> saveData(String value) async { var sharedPreferences = await SharedPreferences.getInstance(); sharedPreferences.setString("yourVariable", value); } @pragma('vm:entry-point') void onStart(ServiceInstance service) async { // Only available for flutter 3.0.0 and later DartPluginRegistrant.ensureInitialized(); // For flutter prior to version 3.0.0 // We have to register the plugin manually SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.setString("hello", "world"); /// OPTIONAL when use custom notification final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((event) { service.setAsForegroundService(); }); service.on('setAsBackground').listen((event) { service.setAsBackgroundService(); }); } service.on('stopService').listen((event) { service.stopSelf(); }); // bring to foreground Timer.periodic(const Duration(seconds: 1), (timer) async { final receivePort = ReceivePort(); // here we are passing method name and sendPort instance from ReceivePort as listener await Isolate.spawn(computationallyExpensiveTask, receivePort.sendPort); if (service is AndroidServiceInstance) { if (await service.isForegroundService()) { //It will listen for isolate function to finish // receivePort.listen((sum) { // flutterLocalNotificationsPlugin.show( // 888, // 'Title', // 'Description ${DateTime.now()}', // const NotificationDetails( // android: AndroidNotificationDetails( // 'my_foreground', // 'MY FOREGROUND SERVICE', // icon: 'ic_bg_service_small', // ongoing: true, // ), // ), // ); // }); var sharedPreferences = await SharedPreferences.getInstance(); await sharedPreferences.reload(); // Its important service.setForegroundNotificationInfo( title: "My App Service", content: "Updated at ${sharedPreferences.getString("yourVariable") ?? 'no data'}", ); } } /// you can see this log in logcat if (kDebugMode) { // print('FLUTTER BACKGROUND SERVICE: ${deee.toString()}'); } // test using external plugin final deviceInfo = DeviceInfoPlugin(); String? device; if (Platform.isAndroid) { final androidInfo = await deviceInfo.androidInfo; device = androidInfo.model; } if (Platform.isIOS) { final iosInfo = await deviceInfo.iosInfo; device = iosInfo.model; } service.invoke( 'update', { "current_date": '400', "device": device, }, ); }); } .... .... .... class _MyAppState extends State<MyApp> { @override void initState() { super.initState(); readyForShared(); // init shared preferences }); } ... ... ... ElevatedButton(onPressed:(){saveData('Your Updated data.');}....
flutter_background_service not receiving updates
I'm using awesome_notifications and flutter_background_service in conjunction to update some app state when receiving data notifications from FirebaseMessaging. As noted in the awesome_notifications, the background message handler must be a top-level function, so I am using flutter_background_service to pass data to the main isolate and update app state. Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeBackgroundService(); FirebaseMessaging.onBackgroundMessage(_backgroundMessageHandler); _initLocalNotifications(); runApp(MyApp()); } I'm initializing the background service similarly to the example in flutter_background_service: Future<void> initializeBackgroundService() async { final service = FlutterBackgroundService(); await service.configure( androidConfiguration: AndroidConfiguration( onStart: onStart, autoStart: true, isForegroundMode: true, ), iosConfiguration: IosConfiguration( autoStart: true, onForeground: onStart, onBackground: onIosBackground, ), ); await service.startService(); } and invoking update in the _backgroundMessageHandler when a notification is received: Future<void> _backgroundMessageHandler( RemoteMessage message, ) async { final service = FlutterBackgroundService(); ... service.invoke('update', { 'key1': 'val1', 'key2': 'val2', }); } And in the StatefulWidget for my app in the main isolate, I'm listening on the update call to receive the data: void listenForNotificationData() { final backgroundService = FlutterBackgroundService(); backgroundService.on('update').listen((event) async { print('received data message in feed: $event'); }, onError: (e, s) { print('error listening for updates: $e, $s'); }, onDone: () { print('background listen closed'); }); } It's never invoking the listen callback on the 'update' event. I can confirm it's calling the invoke('update') portion and calling on('update').listen, but never receiving the update. It also doesn't seem to be erroring out. Am I missing a step somewhere here?
[ "I was encountering the same issue on flutter background service. I solved it by removing the async keyword from the callback and creating a separate async function to perform the callback operations.\n\n\nvoid listenForNotificationData() {\n final backgroundService = FlutterBackgroundService();\n backgroundService.on('update').listen((event) {\n print('received data message in feed: $event');\n }, onError: (e, s) {\n print('error listening for updates: $e, $s');\n }, onDone: () {\n print('background listen closed');\n });\n}\n\nvoid action(Map? event) async {\nprint('received data message in feed: $event');\n}\n\n\n\nHope it helps, forgive me if there are syntax error\n", "You can try this.\nmain(){\n....\n}\nFuture<void> readyForShared() async {\n var sharedPreferences = await SharedPreferences.getInstance();\n counterValue = sharedPreferences.getString(\"yourVariable\") ?? \"0\";\n}\n\nFuture<void> saveData(String value) async {\n var sharedPreferences = await SharedPreferences.getInstance();\n sharedPreferences.setString(\"yourVariable\", value);\n}\n\n@pragma('vm:entry-point')\nvoid onStart(ServiceInstance service) async {\n\n // Only available for flutter 3.0.0 and later\n DartPluginRegistrant.ensureInitialized();\n\n // For flutter prior to version 3.0.0\n // We have to register the plugin manually\n\n SharedPreferences preferences = await SharedPreferences.getInstance();\n await preferences.setString(\"hello\", \"world\");\n\n /// OPTIONAL when use custom notification\n final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();\n\n if (service is AndroidServiceInstance) {\n service.on('setAsForeground').listen((event) {\n service.setAsForegroundService();\n });\n\n service.on('setAsBackground').listen((event) {\n service.setAsBackgroundService();\n });\n }\n\n service.on('stopService').listen((event) {\n service.stopSelf();\n });\n \n // bring to foreground\n Timer.periodic(const Duration(seconds: 1), (timer) async {\n final receivePort = ReceivePort();\n // here we are passing method name and sendPort instance from ReceivePort as listener\n await Isolate.spawn(computationallyExpensiveTask, receivePort.sendPort);\n\n if (service is AndroidServiceInstance) {\n if (await service.isForegroundService()) {\n //It will listen for isolate function to finish\n // receivePort.listen((sum) {\n // flutterLocalNotificationsPlugin.show(\n // 888,\n // 'Title',\n // 'Description ${DateTime.now()}',\n // const NotificationDetails(\n // android: AndroidNotificationDetails(\n // 'my_foreground',\n // 'MY FOREGROUND SERVICE',\n // icon: 'ic_bg_service_small',\n // ongoing: true,\n // ),\n // ),\n // );\n // });\n\n var sharedPreferences = await SharedPreferences.getInstance();\n await sharedPreferences.reload(); // Its important\n service.setForegroundNotificationInfo(\n title: \"My App Service\",\n content: \"Updated at ${sharedPreferences.getString(\"yourVariable\") ?? 'no data'}\",\n );\n }\n }\n\n\n /// you can see this log in logcat\n if (kDebugMode) {\n // print('FLUTTER BACKGROUND SERVICE: ${deee.toString()}');\n }\n\n // test using external plugin\n final deviceInfo = DeviceInfoPlugin();\n String? device;\n if (Platform.isAndroid) {\n final androidInfo = await deviceInfo.androidInfo;\n device = androidInfo.model;\n }\n\n if (Platform.isIOS) {\n final iosInfo = await deviceInfo.iosInfo;\n device = iosInfo.model;\n }\n service.invoke(\n 'update',\n {\n \"current_date\": '400',\n \"device\": device,\n },\n );\n });\n}\n\n\n....\n....\n....\nclass _MyAppState extends State<MyApp> {\n @override\n void initState() {\n super.initState();\n readyForShared(); // init shared preferences\n });\n }\n...\n...\n...\nElevatedButton(onPressed:(){saveData('Your Updated data.');}....\n\n" ]
[ 0, 0 ]
[]
[]
[ "awesome_notifications", "background_process", "dart", "dart_isolates", "flutter" ]
stackoverflow_0071812571_awesome_notifications_background_process_dart_dart_isolates_flutter.txt
Q: The system ui isn't responding in android emulator (Flutter) After starting the avd in android studio, the system ui is not responding message comes in the android emulator. So, how can i fix it ? A: 1.Open AVD Manager. 2.Click to edit button for your device. 3.Select Hardware in the Graphics drop down menu. A: I used to face this problem every time I started my AVD. Also the cold boot option was just a temporary fix for me. I checked the android version that I had installed on my emulator, and noticed the ABI version was x86. To fix that, I made a new android emulator, and in the selecting system image section, I chose the X86_64 version. That fixed the problem for me. A: On OS X, I am able to solved it by steps: Open Android Studio. Navigate to Configure > AVD Manager. Under Actions > dropdown triangle on the right > Cold Boot Now: A: I was constantly annoyed by this and would often click on Wait, then realize after some time the tremendous amount of time wasted. I fixed it by creating a new emulator (ctrl + shirt + a -> "avd", select avd manager): Choose create new device, select Pixel 4 or Pixel 4 XL for example Then instead of selecting recommended system image, selected "API Level S, ABI x86_64 (former device was only x86), Target Android API S (Google Play). Beware it will take 1.3GB and download, although fast will take a little bit -> go grab a cup of coffee. Finish? Click on Next. In advanced settings (show), increase RAM from 512 to 1024. Now I don't have this problem anymore. A: I finally found what causes this in my case. Once I resize, after a couple of minutes I got that error. So: DON'T RESIZE YOUR EMULATOR WINDOW !!!! I still got that message from time to time, but not that often. A: On Windows 10, I just wiped the data from the emulator image and started it again. However, as Aadn commented below, this is only a temporary solution. A: I had the same problem and solved it by navigating to the AVD Manager by Tools > AVD Manager > Right Click the emulator > Wipe all data > Switch on the virtual device. It worked for me just fine, you can also use it when you are troubleshooting the problem with the emulator in android studio. A: If you use the Nexus S image with API 29 the message does not appear. I am using Android Studio 4.1.2. Pixel 4 api 29 - shows the message when first used but if you diable a few apps it works fine. eg Disable Android Auto, Calendar, Camera, Clock, Device Policy, Google, Google, Google Indice Keyboard, Google Korean Input, Pinyin Input, Maps, YouTube. A: Instead of clicking "Stop" just click on "wait" and the Emulator will work fine. And If it is taking too much time in loading make sure you have installed the "HAXM installer" in SDK tools , Also make sure "Hyper V" option is also unchecked in "Turn Windows features on or off" in Control Panel --> Program and features. Only After unchecking this feature you can install the HAXM installer. After doing this the Emulator will not take time to load , but still it can show the error "System UI isn't responding", as I told in starting just click on "wait" and it will run smoothly. A: After installing the latest system images and creating an emulator using that. My problem is gone. A: I tried this and solved my issue. Solution 01 - Change Emulated Performance Solution 02 - Create New Emulator - (Pixel 4 or Pixel 4 XL) Solution 03 - (Temporary) - Wipe Data More Details - https://coderog.com/community/threads/the-system-ui-isn%E2%80%99t-responding-error-in-android-studio-emulator.71/ A: Just follow this instruction hope it will be solved. A: You can download "Google APIs intel x86 atom_64 system image" from your sdk manager of your android version. This technique worked for me!! A: I solved my problem using this solution from https://stackoverflow.com/a/66265270/5128831 It seems even though intel HAXM shows as installed on SDK Tools, it wasnt really installed so i had to go to below location and manually reinstall (intelhaxm-android) file. C:\Users\SUHAIL\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager if the file doesnt exist in that location, that means it wasnt downloaded and you will have to download the file online A: Change RAM of your emulator to bigger value. That's works for me)
The system ui isn't responding in android emulator (Flutter)
After starting the avd in android studio, the system ui is not responding message comes in the android emulator. So, how can i fix it ?
[ "1.Open AVD Manager.\n\n2.Click to edit button for your device.\n\n3.Select Hardware in the Graphics drop down menu.\n\n", "I used to face this problem every time I started my AVD. Also the cold boot option was just a temporary fix for me.\nI checked the android version that I had installed on my emulator, and noticed the ABI version was x86.\nTo fix that, I made a new android emulator, and in the selecting system image section, I chose the X86_64 version.\nThat fixed the problem for me.\n", "On OS X, I am able to solved it by steps:\nOpen Android Studio. Navigate to Configure > AVD Manager.\nUnder Actions > dropdown triangle on the right > Cold Boot Now:\n", "I was constantly annoyed by this and would often click on Wait, then realize after some time the tremendous amount of time wasted.\nI fixed it by creating a new emulator (ctrl + shirt + a -> \"avd\", select avd manager):\n\nChoose create new device, select Pixel 4 or Pixel 4 XL for example\nThen instead of selecting recommended system image, selected \"API Level S, ABI x86_64 (former device was only x86), Target Android API S (Google Play). Beware it will take 1.3GB and download, although fast will take a little bit -> go grab a cup of coffee. Finish? Click on Next.\nIn advanced settings (show), increase RAM from 512 to 1024.\n\nNow I don't have this problem anymore.\n", "I finally found what causes this in my case.\nOnce I resize, after a couple of minutes I got that error. So:\nDON'T RESIZE YOUR EMULATOR WINDOW !!!!\nI still got that message from time to time, but not that often.\n", "On Windows 10, I just wiped the data from the emulator image and started it again. However, as Aadn commented below, this is only a temporary solution.\n", "I had the same problem and solved it by navigating to the AVD Manager by\nTools > AVD Manager > Right Click the emulator > Wipe all data > Switch on the virtual device.\n\nIt worked for me just fine, you can also use it when you are troubleshooting the problem with the emulator in android studio.\n", "If you use the Nexus S image with API 29 the message does not appear. I am using Android Studio 4.1.2.\nPixel 4 api 29 - shows the message when first used but if you diable a few apps it works fine. eg Disable Android Auto, Calendar, Camera, Clock, Device Policy, Google, Google, Google Indice Keyboard, Google Korean Input, Pinyin Input, Maps, YouTube.\n", "Instead of clicking \"Stop\" just click on \"wait\" and the Emulator will work fine.\nAnd If it is taking too much time in loading make sure you have installed the\n\"HAXM installer\" in SDK tools , Also make sure \"Hyper V\" option is also unchecked in\n\"Turn Windows features on or off\" in Control Panel --> Program and features.\nOnly After unchecking this feature you can install the HAXM installer.\nAfter doing this the Emulator will not take time to load , but still it can show the error \"System UI isn't responding\", as I told in starting just click on \"wait\" and it will run smoothly.\n", "After installing the latest system images and creating an emulator using that. My problem is gone.\n\n", "I tried this and solved my issue.\n\nSolution 01 - Change Emulated Performance\nSolution 02 - Create New Emulator - (Pixel 4 or Pixel 4 XL)\nSolution 03 - (Temporary) - Wipe Data\n\nMore Details -\nhttps://coderog.com/community/threads/the-system-ui-isn%E2%80%99t-responding-error-in-android-studio-emulator.71/\n", "\n\nJust follow this instruction hope it will be solved.\n", "You can download \"Google APIs intel x86 atom_64 system image\" from your sdk manager of your android version.\nThis technique worked for me!!\n", "I solved my problem using this solution from https://stackoverflow.com/a/66265270/5128831\n\nIt seems even though intel HAXM shows as installed on SDK Tools, it\nwasnt really installed so i had to go to below location and manually\nreinstall (intelhaxm-android) file.\nC:\\Users\\SUHAIL\\AppData\\Local\\Android\\Sdk\\extras\\intel\\Hardware_Accelerated_Execution_Manager\n\nif the file doesnt exist in that location, that means it wasnt\ndownloaded and you will have to download the file online\n\n", "Change RAM of your emulator to bigger value. That's works for me)\n" ]
[ 91, 53, 31, 26, 7, 5, 3, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "android", "android_emulator", "android_studio", "flutter" ]
stackoverflow_0063371056_android_android_emulator_android_studio_flutter.txt
Q: C language program Can anyone develop this program? Develop a program in c language that collect a positive number from the keyboard repeatedly, if the user inputs a negative number, it should ignore it and continue collecting the number until the user input zero. program then display the list of all even and odd numerous from the collection and the sum of all numbers.? this is the program which i have tried... #include <stdio.h> int main() { int num, even, odd, total_of_num; printf("Enter a Positive Number: "); scanf("%d", &num); for (num; num<=50; num++) { if (num >= 0) { if (num%2==0) { even=num; printf("%d ", even); } else { odd=num; printf("%d", odd); } } else { printf("Sorry! Negative number is not acceptable, Enter a positive Number\n"); } } return 0; }
C language program
Can anyone develop this program? Develop a program in c language that collect a positive number from the keyboard repeatedly, if the user inputs a negative number, it should ignore it and continue collecting the number until the user input zero. program then display the list of all even and odd numerous from the collection and the sum of all numbers.? this is the program which i have tried... #include <stdio.h> int main() { int num, even, odd, total_of_num; printf("Enter a Positive Number: "); scanf("%d", &num); for (num; num<=50; num++) { if (num >= 0) { if (num%2==0) { even=num; printf("%d ", even); } else { odd=num; printf("%d", odd); } } else { printf("Sorry! Negative number is not acceptable, Enter a positive Number\n"); } } return 0; }
[]
[]
[ "Here is one possible implementation of a program in C that collects positive numbers from the keyboard repeatedly, ignores negative numbers, and displays a list of all even and odd numbers collected, as well as the sum of all numbers:\n#include <stdio.h>\n\nint main()\n{\n int num;\n int even_sum = 0;\n int odd_sum = 0;\n int total_sum = 0;\n\n // Collect positive numbers from the keyboard\n printf(\"Enter positive numbers (enter 0 to end):\\n\");\n do\n {\n scanf(\"%d\", &num);\n\n // Ignore negative numbers\n if (num < 0)\n {\n continue;\n }\n\n // Keep track of the sum of all numbers\n total_sum ++;\n\n // Keep track of the sum of even and odd numbers separately\n if (num % 2 == 0)\n {\n even_sum ++;\n }\n else\n {\n odd_sum ++;\n }\n }\n while (num != 0);\n\n // Display the sums of even and odd numbers\n printf(\"Sum of even numbers: %d\\n\", even_sum);\n printf(\"Sum of odd numbers: %d\\n\", odd_sum);\n printf(\"Total sum: %d\\n\", total_sum);\n\n return 0;\n}\n\nThis program uses a do-while loop to repeatedly collect numbers from the keyboard until the user enters 0. Inside the loop, it uses the continue keyword to skip the current iteration of the loop if the user enters a negative number. It also keeps track of the sums of even and odd numbers, as well as the total sum of all numbers. Finally, it displays all of these sums at the end of the program.\nI hope this helps! Let me know if you have any other questions.\n", "#include <stdio.h>\n\nint main()\n{\n // Define variables for storing the input numbers,\n // their sum, and the counts of even and odd numbers.\n int num, sum = 0, even_count = 0, odd_count = 0;\n\n // Read numbers from the keyboard repeatedly until the user inputs 0.\n while (1)\n {\n printf(\"Enter a number: \");\n scanf(\"%d\", &num);\n\n // If the user inputs a negative number, ignore it and continue.\n if (num < 0)\n {\n continue;\n }\n\n // If the user inputs 0, stop reading numbers.\n if (num == 0)\n {\n break;\n }\n\n // If the number is positive, add it to the sum.\n sum += num;\n\n // Check if the number is even or odd and increment the corresponding count.\n if (num % 2 == 0)\n {\n even_count++;\n }\n else\n {\n odd_count++;\n }\n }\n\n // Print the results.\n printf(\"Total number of even numbers: %d\\n\", even_count);\n printf(\"Total number of odd numbers: %d\\n\", odd_count);\n printf(\"Sum of all numbers: %d\\n\", sum);\n\n return 0;\n}\n\n" ]
[ -3, -3 ]
[ "c" ]
stackoverflow_0074679637_c.txt
Q: How to prevent "a program is trying to access data from Outlook..." warning for a trusted program I have a C# WinForms application on a corporate network that should behave as a drag-and-drop target for emails in Outlook, i.e. I want to be able to drag and drop an email to my application. It is using the Office Interop libraries, v14 (for outlook 2010). When dropping, Outlook gives a security warning, and an option to "allow access" for (1 | 5 | 10) minutes. Other applications (e.g. Visual Studio, TRIM (a records management system), etc) allow dragging and dropping without any warning on the same machine. The security settings are managed by an administrator, and I don't have access to change them. How do I prevent this from occuring for users of my application? Is there a certificate I need to sign my app with? Do I need to register my app in some kind of registry? A: You get a standard security prompt in Outlook. "Security" in this context refers to the so-called "object model guard" that triggers security prompts and blocks access to certain features in an effort to prevent malicious programs from harvesting email addresses from Outlook data and using Outlook to propagate viruses and spam. These prompts cannot simply be turned off, except in latest Outlook versions with an anti-virus application running. To avoid such security prompts you can: Use a low-level API on which Outlook is based on instead of OOM. Or just any other third-party wrapper around that API (for example, such as Redemption). Use Outlook Security Manager which allows to supress such warnings programmatically. Just a few lines of code is required. In a corporate environment, the administrator may choose to loosen Outlook security for some or all users. Create an Outlook COM add-in which doesn't trigger security prompts (all COM add-ins are trusted by default). Read more about these ways in the Outlook "Object Model Guard" Security Issues for Developers article. A: This prompt could surface if Outlook does not detect an Antivirus Solution installed on the host machine. In Outlook go to File -> Options -> Trust Center -> Trust Center Settings -> Programmatic Access From here, you can override the recommended setting (not recommended) or Install a known Antivirus Solution. Once a known Antivirus Solution is detected, the security prompt ceases to appear.
How to prevent "a program is trying to access data from Outlook..." warning for a trusted program
I have a C# WinForms application on a corporate network that should behave as a drag-and-drop target for emails in Outlook, i.e. I want to be able to drag and drop an email to my application. It is using the Office Interop libraries, v14 (for outlook 2010). When dropping, Outlook gives a security warning, and an option to "allow access" for (1 | 5 | 10) minutes. Other applications (e.g. Visual Studio, TRIM (a records management system), etc) allow dragging and dropping without any warning on the same machine. The security settings are managed by an administrator, and I don't have access to change them. How do I prevent this from occuring for users of my application? Is there a certificate I need to sign my app with? Do I need to register my app in some kind of registry?
[ "You get a standard security prompt in Outlook. \"Security\" in this context refers to the so-called \"object model guard\" that triggers security prompts and blocks access to certain features in an effort to prevent malicious programs from harvesting email addresses from Outlook data and using Outlook to propagate viruses and spam. These prompts cannot simply be turned off, except in latest Outlook versions with an anti-virus application running. \nTo avoid such security prompts you can:\n\nUse a low-level API on which Outlook is based on instead of OOM. Or just any other third-party wrapper around that API (for example, such as Redemption).\nUse Outlook Security Manager which allows to supress such warnings programmatically. Just a few lines of code is required.\nIn a corporate environment, the administrator may choose to loosen Outlook security for some or all users.\nCreate an Outlook COM add-in which doesn't trigger security prompts (all COM add-ins are trusted by default). \n\nRead more about these ways in the Outlook \"Object Model Guard\" Security Issues for Developers article. \n", "This prompt could surface if Outlook does not detect an Antivirus Solution installed on the host machine. In Outlook go to File -> Options -> Trust Center -> Trust Center Settings -> Programmatic Access\nFrom here, you can override the recommended setting (not recommended) or Install a known Antivirus Solution.\n\nOnce a known Antivirus Solution is detected, the security prompt ceases to appear.\n\n" ]
[ 2, 0 ]
[]
[]
[ "c#", "email", "office_interop", "outlook" ]
stackoverflow_0040777917_c#_email_office_interop_outlook.txt
Q: Outer minimum vectorization in numpy follow up This is a follow-up to my previous question. Given an NxM matrix A, I want to efficiently obtain the NxN matrix whose ith row is the sum along the 2nd axis of the result of applying np.minimum between A and the ith row of A. Using a for loop, > A = np.array([[1, 2], [3, 4], [5,6]]) > output = np.zeros(shape=(A.shape[0], A.shape[0])) > for i in range(A.shape[0]): output[i] = np.sum(np.minimum(A, A[i]), axis=1) > output array([[ 3., 3., 3.], [ 3., 7., 7.], [ 3., 7., 11.]]) Is is possible to optimize this further without the for loop? Edit: I would also like to do it without allocating an MxMxN tensor because of memory constraints. A: instead of a for loop. Using the NumPy minimum and sum functions, you can compute the desired matrix output as follows: output = np.sum(np.minimum(A[:, None], A), axis=2)
Outer minimum vectorization in numpy follow up
This is a follow-up to my previous question. Given an NxM matrix A, I want to efficiently obtain the NxN matrix whose ith row is the sum along the 2nd axis of the result of applying np.minimum between A and the ith row of A. Using a for loop, > A = np.array([[1, 2], [3, 4], [5,6]]) > output = np.zeros(shape=(A.shape[0], A.shape[0])) > for i in range(A.shape[0]): output[i] = np.sum(np.minimum(A, A[i]), axis=1) > output array([[ 3., 3., 3.], [ 3., 7., 7.], [ 3., 7., 11.]]) Is is possible to optimize this further without the for loop? Edit: I would also like to do it without allocating an MxMxN tensor because of memory constraints.
[ "instead of a for loop. Using the NumPy minimum and sum functions, you can compute the desired matrix output as follows:\noutput = np.sum(np.minimum(A[:, None], A), axis=2)\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "vectorization" ]
stackoverflow_0074679407_numpy_python_vectorization.txt
Q: Regular Expression with Python (pattern with character exception) Please I tried to create a pattern that can index some references, but I have a case that is hard for me to separate. line = "thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38)." line = re.sub(r'([^–])(\d+):(\d+)([^\\|–|\}|\d])(\d+)', r'\1\2:\3\4\5\\index[KT]{?@?!0\2|0\3 @\2:\3\4\5}', line) print("12 => ", line) line = re.sub(r'([^–])(\d+):(\d+)(?!\-)', r'\1\2:\3\\index[KT]{?@?!0\2|0\3 @\2:\3}', line) print("13 => ", line) Return 12 => thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}). 13 => thiêu (30:33\index[KT]{?@?!030|033 @30:33}). chương 36-37 ghi lại tất cả những 2:6\index[KT]{?@?!02|06 @2:6} việc này đã thật sự xảyra như thế nào (37:3\index[KT]{?@?!037|03 @37:3}6-38\index[KT]{?@?!037|036 @37:3\index[KT]{?@?!037|03 @37:3}6-38}). I want it to do the indexing like that: 12 => thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}). 13 => thiêu (30:33\index[KT]{?@?!030|033 @30:33}). chương 36-37 ghi lại tất cả những 2:6\index[KT]{?@?!02|06 @2:6} việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}). A: Does this do what you want? It's not clear what the conversion requirements are, but this matches your target strings: import re line = "thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38)." want1 = 'thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}).' want2 = 'thiêu (30:33\index[KT]{?@?!030|033 @30:33}). chương 36-37 ghi lại tất cả những 2:6\index[KT]{?@?!02|06 @2:6} việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}).' line1 = re.sub(r'(\d+):(\d+)-(\d+)', r'\1:\2-\3\\index[KT]{?@?!0\1|0\2 @\1:\2-\3}', line) print(line1) assert line1 == want1 line2 = re.sub(r'(\d+):((\d+)(?:-\d+)?)', r'\1:\2\\index[KT]{?@?!0\1|0\3 @\1:\2}', line) print(line2) assert line2 == want2 Output: thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}). thiêu (30:33\index[KT]{?@?!030|033 @30:33}). chương 36-37 ghi lại tất cả những 2:6\index[KT]{?@?!02|06 @2:6} việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}).
Regular Expression with Python (pattern with character exception)
Please I tried to create a pattern that can index some references, but I have a case that is hard for me to separate. line = "thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38)." line = re.sub(r'([^–])(\d+):(\d+)([^\\|–|\}|\d])(\d+)', r'\1\2:\3\4\5\\index[KT]{?@?!0\2|0\3 @\2:\3\4\5}', line) print("12 => ", line) line = re.sub(r'([^–])(\d+):(\d+)(?!\-)', r'\1\2:\3\\index[KT]{?@?!0\2|0\3 @\2:\3}', line) print("13 => ", line) Return 12 => thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}). 13 => thiêu (30:33\index[KT]{?@?!030|033 @30:33}). chương 36-37 ghi lại tất cả những 2:6\index[KT]{?@?!02|06 @2:6} việc này đã thật sự xảyra như thế nào (37:3\index[KT]{?@?!037|03 @37:3}6-38\index[KT]{?@?!037|036 @37:3\index[KT]{?@?!037|03 @37:3}6-38}). I want it to do the indexing like that: 12 => thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}). 13 => thiêu (30:33\index[KT]{?@?!030|033 @30:33}). chương 36-37 ghi lại tất cả những 2:6\index[KT]{?@?!02|06 @2:6} việc này đã thật sự xảyra như thế nào (37:36-38\index[KT]{?@?!037|036 @37:36-38}).
[ "Does this do what you want? It's not clear what the conversion requirements are, but this matches your target strings:\nimport re\n\nline = \"thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38).\"\nwant1 = 'thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38\\index[KT]{?@?!037|036 @37:36-38}).'\nwant2 = 'thiêu (30:33\\index[KT]{?@?!030|033 @30:33}). chương 36-37 ghi lại tất cả những 2:6\\index[KT]{?@?!02|06 @2:6} việc này đã thật sự xảyra như thế nào (37:36-38\\index[KT]{?@?!037|036 @37:36-38}).'\n\nline1 = re.sub(r'(\\d+):(\\d+)-(\\d+)', r'\\1:\\2-\\3\\\\index[KT]{?@?!0\\1|0\\2 @\\1:\\2-\\3}', line)\nprint(line1)\nassert line1 == want1\nline2 = re.sub(r'(\\d+):((\\d+)(?:-\\d+)?)', r'\\1:\\2\\\\index[KT]{?@?!0\\1|0\\3 @\\1:\\2}', line)\nprint(line2)\nassert line2 == want2\n\nOutput:\nthiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38\\index[KT]{?@?!037|036 @37:36-38}).\nthiêu (30:33\\index[KT]{?@?!030|033 @30:33}). chương 36-37 ghi lại tất cả những 2:6\\index[KT]{?@?!02|06 @2:6} việc này đã thật sự xảyra như thế nào (37:36-38\\index[KT]{?@?!037|036 @37:36-38}).\n\n" ]
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074679413_python_regex.txt
Q: Unsupported URL Type "link:" while using NPM Following some guidance on the net, I edited my package.json to include a link URL: ... "dependencies": { ... "react": "link:../some-other-module/node_modules/react", } But when installing, I get the following error: $ npm install npm ERR! code EUNSUPPORTEDPROTOCOL npm ERR! Unsupported URL Type "link:": link:../some-other-module/node_modules/react A: This is because link has been replaced with file in recent versions of NPM. Simply update your package.json: ... "dependencies": { ... "react": "file:../some-other-module/node_modules/react", }
Unsupported URL Type "link:" while using NPM
Following some guidance on the net, I edited my package.json to include a link URL: ... "dependencies": { ... "react": "link:../some-other-module/node_modules/react", } But when installing, I get the following error: $ npm install npm ERR! code EUNSUPPORTEDPROTOCOL npm ERR! Unsupported URL Type "link:": link:../some-other-module/node_modules/react
[ "This is because link has been replaced with file in recent versions of NPM. Simply update your package.json:\n...\n\"dependencies\": {\n ...\n \"react\": \"file:../some-other-module/node_modules/react\",\n}\n\n" ]
[ 0 ]
[]
[]
[ "npm" ]
stackoverflow_0074679689_npm.txt
Q: How to read only one column from a csv file in c++? Here I have an excel file whose first column has ID's i.e: ID 12 32 45 12 .. There are other columns as well but I only want to read the data present in first column i.e. ID. Here is my code which throws exception. I don't know why? #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include<string> #include<cstdlib> //std::find #include<cstring> using namespace std; int main() { ifstream fin("1.csv"); string line; int rowCount = 0; int rowIdx = 0; //keep track of inserted rows //count the total nb of lines in your file while (getline(fin, line)) { rowCount++; } //this will be your table. A row is represented by data[row_number]. //If you want to access the name of the column #47, you would //cout << data[0][46]. 0 being the first row(assuming headers) //and 46 is the 47 column. //But first you have to input the data. See below. std::vector<std::vector<std::string>> data; fin.clear(); //remove failbit (ie: continue using fin.) fin.seekg(fin.beg); //rewind stream to start while (getline(fin, line)) //for every line in input file { stringstream ss(line); //copy line to stringstream string value; while (getline(ss, value, ',')) { //for every value in that stream (ie: every cell on that row) data[rowIdx].push_back(value);//add that value at the end of the current row in our table } rowIdx++; //increment row number before reading in next line } fin.close(); //Now you can choose to access the data however you like. //If you want to printout only column 47... int colNum; string colName = "ID"; //1.Find the index of column name "computer science" on the first row, using iterator //note: if "it == data[0].end()", it means that that column name was not found vector<string>::iterator it = find(data[0].begin(), data[0].end(), colName); //calulate its index (ie: column number integer) colNum = std::distance(data[0].begin(), it); //2. Print the column with the header "computer science" for (int row = 0; row < rowCount; row++) { cout << data[row][colNum] << "\t"; //print every value in column 47 only } cout << endl; return 0; } Kindly help me to fix the issue. I want to display only first column which contain ID's. A: Here's a simplified version of the above code. It gets rid of the 2D vector, and only reads the first column. std::vector<std::string> data; ifstream fin("1.csv"); string line; while (getline(fin, line)) //for every line in input file { stringstream ss(line); //copy line to stringstream string value; if (getline(ss, value, ',')) { data.push_back(value); } } A: The problem: std::vector<std::vector<std::string>> data; Allocates a vector of vectors. Both dimensions are currently set to 0. data[rowIdx].push_back(value); pushes into and potentially resizes the inner vector, but the outer vector remains size 0. No value of rowIdx is valid. The naive solution is to use rowCount to size the outer vector, but it turns out that's a waste. You can assemble whole rows and then push_back the row into data, but even this is a waste since only one column is needed. One of the beauties of vector is you don't have to know the number of rows. Your make a row vector, push the columns into it, then push the row into data. when you hit the end of he file, you're done reading. No need to read the file twice, but you probably trade off a bit of wasted storage on data's last self-resize. #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> // reduced includes to minimum needed for this example // removed using namespace std; to reduce odds of a naming collision int main() { std::ifstream fin("1.csv"); // Relative path, so watch out for problems // with working directory std::string line; std::vector<std::string> data; // only need one column? Only need one // dimension if (fin.is_open()) { while (std::getline(fin, line)) //for every line in input file { std::stringstream ss(line); std::string value; if (std::getline(ss, value, ',')) { // only take the first column If you need, say, the third // column read and discard the first two columns // and store the third data.push_back(value); // vector sizes itself with push_back, // so there is no need to count the rows } } } else { std::cerr << "Cannot open file\n"; return -1; } // use the column of data here }
How to read only one column from a csv file in c++?
Here I have an excel file whose first column has ID's i.e: ID 12 32 45 12 .. There are other columns as well but I only want to read the data present in first column i.e. ID. Here is my code which throws exception. I don't know why? #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include<string> #include<cstdlib> //std::find #include<cstring> using namespace std; int main() { ifstream fin("1.csv"); string line; int rowCount = 0; int rowIdx = 0; //keep track of inserted rows //count the total nb of lines in your file while (getline(fin, line)) { rowCount++; } //this will be your table. A row is represented by data[row_number]. //If you want to access the name of the column #47, you would //cout << data[0][46]. 0 being the first row(assuming headers) //and 46 is the 47 column. //But first you have to input the data. See below. std::vector<std::vector<std::string>> data; fin.clear(); //remove failbit (ie: continue using fin.) fin.seekg(fin.beg); //rewind stream to start while (getline(fin, line)) //for every line in input file { stringstream ss(line); //copy line to stringstream string value; while (getline(ss, value, ',')) { //for every value in that stream (ie: every cell on that row) data[rowIdx].push_back(value);//add that value at the end of the current row in our table } rowIdx++; //increment row number before reading in next line } fin.close(); //Now you can choose to access the data however you like. //If you want to printout only column 47... int colNum; string colName = "ID"; //1.Find the index of column name "computer science" on the first row, using iterator //note: if "it == data[0].end()", it means that that column name was not found vector<string>::iterator it = find(data[0].begin(), data[0].end(), colName); //calulate its index (ie: column number integer) colNum = std::distance(data[0].begin(), it); //2. Print the column with the header "computer science" for (int row = 0; row < rowCount; row++) { cout << data[row][colNum] << "\t"; //print every value in column 47 only } cout << endl; return 0; } Kindly help me to fix the issue. I want to display only first column which contain ID's.
[ "Here's a simplified version of the above code. It gets rid of the 2D vector, and only reads the first column.\nstd::vector<std::string> data;\nifstream fin(\"1.csv\");\nstring line;\nwhile (getline(fin, line)) //for every line in input file\n{\n stringstream ss(line); //copy line to stringstream\n string value;\n if (getline(ss, value, ',')) {\n data.push_back(value);\n }\n}\n\n", "The problem:\nstd::vector<std::vector<std::string>> data;\n\nAllocates a vector of vectors. Both dimensions are currently set to 0.\ndata[rowIdx].push_back(value);\n\npushes into and potentially resizes the inner vector, but the outer vector remains size 0. No value of rowIdx is valid. The naive solution is to use rowCount to size the outer vector, but it turns out that's a waste. You can assemble whole rows and then push_back the row into data, but even this is a waste since only one column is needed.\nOne of the beauties of vector is you don't have to know the number of rows. Your make a row vector, push the columns into it, then push the row into data. when you hit the end of he file, you're done reading. No need to read the file twice, but you probably trade off a bit of wasted storage on data's last self-resize.\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <vector>\n// reduced includes to minimum needed for this example\n// removed using namespace std; to reduce odds of a naming collision\nint main() {\n\n std::ifstream fin(\"1.csv\"); // Relative path, so watch out for problems \n // with working directory\n std::string line;\n std::vector<std::string> data; // only need one column? Only need one \n // dimension\n if (fin.is_open())\n {\n while (std::getline(fin, line)) //for every line in input file\n {\n std::stringstream ss(line);\n std::string value;\n \n if (std::getline(ss, value, ',')) \n {\n // only take the first column If you need, say, the third \n // column read and discard the first two columns \n // and store the third\n data.push_back(value); // vector sizes itself with push_back, \n // so there is no need to count the rows\n }\n }\n }\n else\n {\n std::cerr << \"Cannot open file\\n\";\n return -1;\n }\n // use the column of data here\n}\n\n" ]
[ 1, 0 ]
[]
[]
[ "c++" ]
stackoverflow_0074679310_c++.txt
Q: colors are wrong numpy array for pillow image when I use txt firstly I am transforming an image into numpy array and writing it to a text file and this part is working the problem is when i copy the txt content and dynamically paste it as vector and display the image. the colors are showing wrong. enter image description here enter image description here ` import cv2 import sys import numpy from PIL import Image numpy.set_printoptions(threshold=sys.maxsize) def img_to_txt_array(img): image = cv2.imread(img) # print(image) f = open("img_array.txt", "w") f.write(str(image)) f.close() meuArquivo = open('img_array.txt', 'r') with open('img_array.txt', 'r') as fd: txt = fd.read() txt = txt.replace(" ", ",") txt = txt.replace('\n',',\n') txt = txt.replace("[,", "[") txt = txt.replace(',[', '[') txt = txt.replace(",,", ",") txt = txt.replace(',[', '[') txt = txt.replace("[,", "[") txt = txt.replace(",,", ",") with open('img_array.txt', 'w') as fd: fd.write(txt) with open('img_array.txt', 'r') as fr: lines = fr.readlines() with open('img_array.txt', 'w') as fw: for line in lines: if line.strip('\n') != ',': fw.write(line) def show_imagem(array): # Create a NumPy array arry = numpy.array(array) # Create a PIL image from the NumPy array image = Image.fromarray(arry.astype('uint8'), 'RGB') # Save the image #image.save('image.jpg') # Show the image image.show(image) array = [] #paste here the txt img_to_txt_array('mickey.png') show_imagem(array) ` I need to get the colors right
colors are wrong numpy array for pillow image when I use txt
firstly I am transforming an image into numpy array and writing it to a text file and this part is working the problem is when i copy the txt content and dynamically paste it as vector and display the image. the colors are showing wrong. enter image description here enter image description here ` import cv2 import sys import numpy from PIL import Image numpy.set_printoptions(threshold=sys.maxsize) def img_to_txt_array(img): image = cv2.imread(img) # print(image) f = open("img_array.txt", "w") f.write(str(image)) f.close() meuArquivo = open('img_array.txt', 'r') with open('img_array.txt', 'r') as fd: txt = fd.read() txt = txt.replace(" ", ",") txt = txt.replace('\n',',\n') txt = txt.replace("[,", "[") txt = txt.replace(',[', '[') txt = txt.replace(",,", ",") txt = txt.replace(',[', '[') txt = txt.replace("[,", "[") txt = txt.replace(",,", ",") with open('img_array.txt', 'w') as fd: fd.write(txt) with open('img_array.txt', 'r') as fr: lines = fr.readlines() with open('img_array.txt', 'w') as fw: for line in lines: if line.strip('\n') != ',': fw.write(line) def show_imagem(array): # Create a NumPy array arry = numpy.array(array) # Create a PIL image from the NumPy array image = Image.fromarray(arry.astype('uint8'), 'RGB') # Save the image #image.save('image.jpg') # Show the image image.show(image) array = [] #paste here the txt img_to_txt_array('mickey.png') show_imagem(array) ` I need to get the colors right
[]
[]
[ "It looks like the problem is that the image array is being saved in a text file as an array of strings rather than an array of integers. When you read the text file and convert it back into an array, the values are being interpreted as strings, resulting in the wrong colors when the image is displayed.\nOne solution to this problem is to save the array in the text file as an array of integers rather than an array of strings. You can do this by using the numpy.savetxt() function, which saves an array to a text file in a specified format. Here is an example of how you could modify your code to save the array as integers in the text file:\nimport cv2\nimport sys\nimport numpy\nfrom PIL import Image\n\nnumpy.set_printoptions(threshold=sys.maxsize)\n\ndef img_to_txt_array(img):\n image = cv2.imread(img)\n # Save the array as integers in the text file\n numpy.savetxt('img_array.txt', image, fmt='%d')\n\ndef show_imagem(array):\n # Create a NumPy array from the text file\n arry = numpy.loadtxt('img_array.txt', dtype=int)\n \n # Create a PIL image from the NumPy array\n image = Image.fromarray(arry.astype('uint8'), 'RGB')\n \n # Save the image\n #image.save('image.jpg')\n \n # Show the image\n image.show(image)\n\narray = [] #paste here the txt\n\nimg_to_txt_array('mickey.png')\nshow_imagem(array)\n\nIn this code, the img_to_txt_array() function saves the image array as integers in the text file using the numpy.savetxt() function. The show_imagem() function reads the array from the text file using the numpy.loadtxt() function, and then creates and displays the image from the array. This should fix the problem of the wrong colors in the image.\n" ]
[ -1 ]
[ "numpy", "python", "python_3.x", "python_imaging_library" ]
stackoverflow_0074679658_numpy_python_python_3.x_python_imaging_library.txt
Q: subprocess.call can't find file/shutil.which failed in pycharm I am trying to transform a mp3 to a wav file in pycharm using subprocess import subprocess subprocess.call(['ffmpeg', '-i','test.mp3','test.wav']) It returns error of not finding file, so I change the 'ffmpeg' to its path on my pc and it work. The problem is that I am making an app and others might install ffpmeg on other's location (since it is download with zip and can be unzip at any place), but I don't know how to get its full path. I tried using os module import os print(os.path('ffmpeg.exe')) but it seems like it is not able to get the path of exe Traceback (most recent call last): File "C:\Users\Percy\PycharmProjects\APP\test3.py", line 8, in <module> print(os.path('ffmpeg.exe')) TypeError: 'module' object is not callable I also tried shutil module import shutil print(shutil.which('ffmpeg')) print(shutil.which('ffmpeg.exe')) but it returns 2 None (prob wrong cause I am 100% sure I have installed ffmpeg) None None I want to ask if there is any way to get the full path of ffmpeg in pycharm or any method that I can make ffmpeg install in designated path with the app when it is downloaded by users A: If you can make "everyone" to install using my ffmpeg-downloader then all of you can install FFmpeg by: pip install ffmpeg-downloader ffdl install Then in Python your package could use import ffmpeg_downloader as ffdl sp.run([ffdl.ffmpeg_path, '-i', 'input.mp4', 'output.mkv']) Alternately, you can use static-ffmpeg to (dynamically) install FFmpeg to Lib/site-package. (See the linked GitHub page for howto.)
subprocess.call can't find file/shutil.which failed in pycharm
I am trying to transform a mp3 to a wav file in pycharm using subprocess import subprocess subprocess.call(['ffmpeg', '-i','test.mp3','test.wav']) It returns error of not finding file, so I change the 'ffmpeg' to its path on my pc and it work. The problem is that I am making an app and others might install ffpmeg on other's location (since it is download with zip and can be unzip at any place), but I don't know how to get its full path. I tried using os module import os print(os.path('ffmpeg.exe')) but it seems like it is not able to get the path of exe Traceback (most recent call last): File "C:\Users\Percy\PycharmProjects\APP\test3.py", line 8, in <module> print(os.path('ffmpeg.exe')) TypeError: 'module' object is not callable I also tried shutil module import shutil print(shutil.which('ffmpeg')) print(shutil.which('ffmpeg.exe')) but it returns 2 None (prob wrong cause I am 100% sure I have installed ffmpeg) None None I want to ask if there is any way to get the full path of ffmpeg in pycharm or any method that I can make ffmpeg install in designated path with the app when it is downloaded by users
[ "If you can make \"everyone\" to install using my ffmpeg-downloader then all of you can install FFmpeg by:\npip install ffmpeg-downloader\nffdl install\n\nThen in Python your package could use\nimport ffmpeg_downloader as ffdl\n\nsp.run([ffdl.ffmpeg_path, '-i', 'input.mp4', 'output.mkv'])\n\nAlternately, you can use static-ffmpeg to (dynamically) install FFmpeg to Lib/site-package. (See the linked GitHub page for howto.)\n" ]
[ 0 ]
[]
[]
[ "ffmpeg", "python", "shutil", "subprocess" ]
stackoverflow_0074678072_ffmpeg_python_shutil_subprocess.txt
Q: plt.legend() when plotting multiple dataframes in a for loop suppose i have three dataframes df1 = pd.DataFrame({"A" : [1,2,3], "B" : [4,5,6]}) df2 = pd.DataFrame({"A" : [2,5,3], "B" : [7,3,1]}) df3 = pd.DataFrame({"A" : [1,2,1], "B" : [5,3,6]}) I put all three dataframes in a list to perform an identical operation on all three dataframes dframes = [df1, df2, df3] for frame in dframes: frame["C"] = frame["A"] + frame["B"] plt.plot(frame["C"]) works like a charm. my problem: when i want to add a legend. plt.legend() throws No artists with labels found to put in legend. plt.legend(frame) uses the names of the columns in the dataframes, i.e., "A", "B" & "C" and not as desired "df1", "df2", "df3" how can i grab the correct line handles ? A: As mentioned in the message you've received after trying plt.legend(), the function is looking for labels. So, let's supply them inside plt.plot by setting the label parameter. We can use enumerate to get index values for the dfs in your list dframes as well, to be used inside the f-strings. dframes = [df1, df2, df3] for i, frame in enumerate(dframes): frame["C"] = frame["A"] + frame["B"] plt.plot(frame["C"], label=f'df{i+1}') # setting the label: `df1`, `df2`, `df3` plt.legend() # or `plt.legend(bbox_to_anchor=[1,1])` to move it outside of the plot plt.show() Result Update. Example using a dict and using the keys for the labels: dframes = {'ll_800': df1, 'll_600wo_200': df2, 'wo_800': df3} for k, v in dframes.items(): v["C"] = v["A"] + v["B"] plt.plot(v["C"], label=k) plt.legend(bbox_to_anchor=[1,1]) plt.show() Result
plt.legend() when plotting multiple dataframes in a for loop
suppose i have three dataframes df1 = pd.DataFrame({"A" : [1,2,3], "B" : [4,5,6]}) df2 = pd.DataFrame({"A" : [2,5,3], "B" : [7,3,1]}) df3 = pd.DataFrame({"A" : [1,2,1], "B" : [5,3,6]}) I put all three dataframes in a list to perform an identical operation on all three dataframes dframes = [df1, df2, df3] for frame in dframes: frame["C"] = frame["A"] + frame["B"] plt.plot(frame["C"]) works like a charm. my problem: when i want to add a legend. plt.legend() throws No artists with labels found to put in legend. plt.legend(frame) uses the names of the columns in the dataframes, i.e., "A", "B" & "C" and not as desired "df1", "df2", "df3" how can i grab the correct line handles ?
[ "As mentioned in the message you've received after trying plt.legend(), the function is looking for labels. So, let's supply them inside plt.plot by setting the label parameter.\nWe can use enumerate to get index values for the dfs in your list dframes as well, to be used inside the f-strings.\ndframes = [df1, df2, df3]\nfor i, frame in enumerate(dframes):\n frame[\"C\"] = frame[\"A\"] + frame[\"B\"]\n plt.plot(frame[\"C\"], label=f'df{i+1}') # setting the label: `df1`, `df2`, `df3`\n \nplt.legend() # or `plt.legend(bbox_to_anchor=[1,1])` to move it outside of the plot\nplt.show()\n\nResult\n\n\nUpdate. Example using a dict and using the keys for the labels:\ndframes = {'ll_800': df1, 'll_600wo_200': df2, 'wo_800': df3}\nfor k, v in dframes.items():\n v[\"C\"] = v[\"A\"] + v[\"B\"]\n plt.plot(v[\"C\"], label=k)\nplt.legend(bbox_to_anchor=[1,1])\nplt.show()\n\nResult\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074679576_dataframe_matplotlib_pandas_python.txt
Q: vs in Generics What is the difference between <out T> and <T>? For example: public interface IExample<out T> { ... } vs. public interface IExample<T> { ... } A: The out keyword in generics is used to denote that the type T in the interface is covariant. See Covariance and contravariance for details. The classic example is IEnumerable<out T>. Since IEnumerable<out T> is covariant, you're allowed to do the following: IEnumerable<string> strings = new List<string>(); IEnumerable<object> objects = strings; The second line above would fail if this wasn't covariant, even though logically it should work, since string derives from object. Before variance in generic interfaces was added to C# and VB.NET (in .NET 4 with VS 2010), this was a compile time error. After .NET 4, IEnumerable<T> was marked covariant, and became IEnumerable<out T>. Since IEnumerable<out T> only uses the elements within it, and never adds/changes them, it's safe for it to treat an enumerable collection of strings as an enumerable collection of objects, which means it's covariant. This wouldn't work with a type like IList<T>, since IList<T> has an Add method. Suppose this would be allowed: IList<string> strings = new List<string>(); IList<object> objects = strings; // NOTE: Fails at compile time You could then call: objects.Add(new Image()); // This should work, since IList<object> should let us add **any** object This would, of course, fail - so IList<T> can't be marked covariant. There is also, btw, an option for in - which is used by things like comparison interfaces. IComparer<in T>, for example, works the opposite way. You can use a concrete IComparer<Foo> directly as an IComparer<Bar> if Bar is a subclass of Foo, because the IComparer<in T> interface is contravariant. A: For remembering easily the usage of in and out keyword (also covariance and contravariance), we can image inheritance as wrapping: String : Object Bar : Foo A: consider, class Fruit {} class Banana : Fruit {} interface ICovariantSkinned<out T> {} interface ISkinned<T> {} and the functions, void Peel(ISkinned<Fruit> skinned) { } void Peel(ICovariantSkinned<Fruit> skinned) { } The function that accepts ICovariantSkinned<Fruit> will be able to accept ICovariantSkinned<Fruit> or ICovariantSkinned<Banana> because ICovariantSkinned<T> is a covariant interface and Banana is a type of Fruit, the function that accepts ISkinned<Fruit> will only be able to accept ISkinned<Fruit>. A: "out T" means that type T is "covariant". That restricts T to appear only as a returned (outbound) value in methods of the generic class, interface or method. The implication is that you can cast the type/interface/method to an equivalent with a super-type of T. E.g. ICovariant<out Dog> can be cast to ICovariant<Animal>. A: From the link you posted.... For generic type parameters, the out keyword specifies that the type parameter is covariant. EDIT: Again, from the link you posted For more information, see Covariance and Contravariance (C# and Visual Basic). http://msdn.microsoft.com/en-us/library/ee207183.aspx A: The simplest explanation I found is in this article stated as interface ISomeName<in T> <– means that T can be only passed as a parameter to a method (it enters inteface’s methods, so it goes inside, maybe that’s why we use here keyword ‘in’… Hmm, no, that’s just a coincidence ?) interface ISomeName<out T> <– means that T can be only returned as method results (it is what we receive from a method so it goes out of it – wow, again sounds legit!)
vs in Generics
What is the difference between <out T> and <T>? For example: public interface IExample<out T> { ... } vs. public interface IExample<T> { ... }
[ "The out keyword in generics is used to denote that the type T in the interface is covariant. See Covariance and contravariance for details.\nThe classic example is IEnumerable<out T>. Since IEnumerable<out T> is covariant, you're allowed to do the following:\nIEnumerable<string> strings = new List<string>();\nIEnumerable<object> objects = strings;\n\nThe second line above would fail if this wasn't covariant, even though logically it should work, since string derives from object. Before variance in generic interfaces was added to C# and VB.NET (in .NET 4 with VS 2010), this was a compile time error.\nAfter .NET 4, IEnumerable<T> was marked covariant, and became IEnumerable<out T>. Since IEnumerable<out T> only uses the elements within it, and never adds/changes them, it's safe for it to treat an enumerable collection of strings as an enumerable collection of objects, which means it's covariant.\nThis wouldn't work with a type like IList<T>, since IList<T> has an Add method. Suppose this would be allowed:\nIList<string> strings = new List<string>();\nIList<object> objects = strings; // NOTE: Fails at compile time\n\nYou could then call:\nobjects.Add(new Image()); // This should work, since IList<object> should let us add **any** object\n\nThis would, of course, fail - so IList<T> can't be marked covariant.\nThere is also, btw, an option for in - which is used by things like comparison interfaces. IComparer<in T>, for example, works the opposite way. You can use a concrete IComparer<Foo> directly as an IComparer<Bar> if Bar is a subclass of Foo, because the IComparer<in T> interface is contravariant.\n", "For remembering easily the usage of in and out keyword (also covariance and contravariance), we can image inheritance as wrapping:\nString : Object\nBar : Foo\n\n\n", "consider,\nclass Fruit {}\n\nclass Banana : Fruit {}\n\ninterface ICovariantSkinned<out T> {}\n\ninterface ISkinned<T> {}\n\nand the functions,\nvoid Peel(ISkinned<Fruit> skinned) { }\n\nvoid Peel(ICovariantSkinned<Fruit> skinned) { }\n\nThe function that accepts ICovariantSkinned<Fruit> will be able to accept ICovariantSkinned<Fruit> or ICovariantSkinned<Banana> because ICovariantSkinned<T> is a covariant interface and Banana is a type of Fruit,\nthe function that accepts ISkinned<Fruit> will only be able to accept ISkinned<Fruit>.\n", "\"out T\" means that type T is \"covariant\". That restricts T to appear only as a returned (outbound) value in methods of the generic class, interface or method. The implication is that you can cast the type/interface/method to an equivalent with a super-type of T.\nE.g. ICovariant<out Dog> can be cast to ICovariant<Animal>.\n", "From the link you posted....\n\nFor generic type parameters, the out keyword specifies that the type\n parameter is covariant.\n\nEDIT: \nAgain, from the link you posted\n\nFor more information, see Covariance and Contravariance (C# and Visual Basic). http://msdn.microsoft.com/en-us/library/ee207183.aspx\n\n", "The simplest explanation I found is in this article stated as\n\ninterface ISomeName<in T> <– means that T can be only passed as a\nparameter to a method (it enters inteface’s methods, so it goes\ninside, maybe that’s why we use here keyword ‘in’… Hmm, no, that’s\njust a coincidence ?)\ninterface ISomeName<out T> <– means that T can be only returned as\nmethod results (it is what we receive from a method so it goes out of\nit – wow, again sounds legit!)\n\n" ]
[ 261, 79, 62, 55, 7, 0 ]
[ "I think this screenshot from VS2022 is pretty descriptive - it says what sort of constraints this put on generics:\n\n" ]
[ -1 ]
[ "c#", "covariance", "generics" ]
stackoverflow_0010956993_c#_covariance_generics.txt
Q: selenium python element select from dropdown menu Trying to select multiple elements from dropdown menu via selenium in python. Website from URL. But Timeoutexception error is occurring. I have tried Inspect menu from GoogleChrome. //label[@for="inputGenre"]/parent::div//select[@placeholder="Choose a Category"] gives exactly the select tag that I need. But unfortunately, with selenium I cannot locate any element within this tag. Any ideas why the error occur? code is below; slect_element = Select(WebDriverWait(driver, 10).until(EC.element_located_to_be_selected((By.XPATH, '//label[@for="inputGenre"]/parent::div//select[@placeholder="Choose a Category"]')))) slect_element.select_by_index(1) slect_element.select_by_value('23') strangeness is it is possible to locate it and get its text values from code below; drp_menu=driver.find_elements(By.XPATH,'//label[@for="inputGenre"]/parent::div//div[@class="dropdown-main"]/ul/li') print(len(drp_menu)) ls_categories=[] for i in drp_menu: ls_categories.append(i.get_attribute('innerText')) print is giving 15 elements, and get_attribute(innerText) gives text of each option element text. Anyway, Thanks a lot @Prophet A: That Select element is hidden and can't be used by Selenium as we use normal Select elements to select drop-down menu items. Here we need to open the drop-down as we open any other elements by clicking them, select the desired options and click the Search button. So, these lines are opening that drop down and selecting 2 options in the drop-down menu: wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='form-group'][contains(.,'Category')]//div[@class='dropdown-display-label']"))).click() wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='form-group'][contains(.,'Category')]//li[@data-value='23']"))).click() wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='form-group'][contains(.,'Category')]//li[@data-value='1']"))).click() The result so far is: And by finally clicking the Search button the result is: The entire code is: from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC options = Options() options.add_argument("start-maximized") webdriver_service = Service('C:\webdrivers\chromedriver.exe') driver = webdriver.Chrome(service=webdriver_service, options=options) wait = WebDriverWait(driver, 20) url = "https://channelcrawler.com/" driver.get(url) wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='form-group'][contains(.,'Category')]//div[@class='dropdown-display-label']"))).click() wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='form-group'][contains(.,'Category')]//li[@data-value='23']"))).click() wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='form-group'][contains(.,'Category')]//li[@data-value='1']"))).click() wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()
selenium python element select from dropdown menu
Trying to select multiple elements from dropdown menu via selenium in python. Website from URL. But Timeoutexception error is occurring. I have tried Inspect menu from GoogleChrome. //label[@for="inputGenre"]/parent::div//select[@placeholder="Choose a Category"] gives exactly the select tag that I need. But unfortunately, with selenium I cannot locate any element within this tag. Any ideas why the error occur? code is below; slect_element = Select(WebDriverWait(driver, 10).until(EC.element_located_to_be_selected((By.XPATH, '//label[@for="inputGenre"]/parent::div//select[@placeholder="Choose a Category"]')))) slect_element.select_by_index(1) slect_element.select_by_value('23') strangeness is it is possible to locate it and get its text values from code below; drp_menu=driver.find_elements(By.XPATH,'//label[@for="inputGenre"]/parent::div//div[@class="dropdown-main"]/ul/li') print(len(drp_menu)) ls_categories=[] for i in drp_menu: ls_categories.append(i.get_attribute('innerText')) print is giving 15 elements, and get_attribute(innerText) gives text of each option element text. Anyway, Thanks a lot @Prophet
[ "That Select element is hidden and can't be used by Selenium as we use normal Select elements to select drop-down menu items.\nHere we need to open the drop-down as we open any other elements by clicking them, select the desired options and click the Search button.\nSo, these lines are opening that drop down and selecting 2 options in the drop-down menu:\nwait.until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='form-group'][contains(.,'Category')]//div[@class='dropdown-display-label']\"))).click()\nwait.until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='form-group'][contains(.,'Category')]//li[@data-value='23']\"))).click()\nwait.until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='form-group'][contains(.,'Category')]//li[@data-value='1']\"))).click()\n\nThe result so far is:\n\nAnd by finally clicking the Search button the result is:\n\nThe entire code is:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\noptions = Options()\noptions.add_argument(\"start-maximized\")\n\nwebdriver_service = Service('C:\\webdrivers\\chromedriver.exe')\ndriver = webdriver.Chrome(service=webdriver_service, options=options)\nwait = WebDriverWait(driver, 20)\n\nurl = \"https://channelcrawler.com/\"\n\ndriver.get(url)\n\nwait.until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='form-group'][contains(.,'Category')]//div[@class='dropdown-display-label']\"))).click()\nwait.until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='form-group'][contains(.,'Category')]//li[@data-value='23']\"))).click()\nwait.until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='form-group'][contains(.,'Category')]//li[@data-value='1']\"))).click()\nwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"button[type='submit']\"))).click()\n\n" ]
[ 2 ]
[]
[]
[ "drop_down_menu", "python", "select", "selenium", "xpath" ]
stackoverflow_0074679519_drop_down_menu_python_select_selenium_xpath.txt
Q: How to set turtle tracer false using tkinter? I have to generate two turtle windows and draw in each one, so I'm using tkinter to create and show the windows. My code currently opens the right screen and draws in it, but the turtle is really slow so I want to set the turtle tracer to false to use the update function, but I can't figure out how to. This is my turtle_interpreter.py file, which has all the functions I use to draw the L-system: import turtle from tkinter import * class Window(Tk): def __init__(self, title, geometry): super().__init__() self.running = True self.geometry(geometry) self.title(title) self.protocol("WM_DELETE_WINDOW", self.destroy_window) self.canvas = Canvas(self) self.canvas.pack(side=LEFT, expand=True, fill=BOTH) self.turtle = turtle.RawTurtle(turtle.TurtleScreen(self.canvas)) def update_window(self): ''' sets window to update ''' if self.running: self.update() def destroy_window(self): ''' sets window to close ''' self.running = False self.destroy() def drawString(turt, dstring, distance, angle): '''Interpret the characters in string dstring as a series of turtle commands. Distance specifies the distance to travel for each forward command. Angle specifies the angle (in degrees) for each right or left command. The list of turtle supported turtle commands is: F : forward - : turn right + : turn left ''' for char in dstring: if char == 'F': turt.forward(distance) elif char == '-': turt.right(angle) elif char == '+': turt.left(angle) def place(turt, xpos, ypos, angle=None): ''' places turtle at given coordinates and angle ''' turt.penup() turt.goto(xpos, ypos) if angle != None: turt.setheading(angle) turt.pendown() def goto(turt, xpos, ypos): ''' moves turtle to given coordinates ''' turt.penup() turt.goto(xpos, ypos) turt.pendown() def setColor(turt, color): ''' sets turtle color ''' turt.color(color) And this is the file where the functions get called. Running it draws the L-system. import turtle_interpreter as turt_int import lsystem_scene_three as lsystem def turtle_scene_two(): ''' generates scene two ''' # create window win_two = turt_int.Window('Turtle Scene 2', '640x480+650+0') # assign turtle turt2 = win_two.turtle # lsystem setup lsystemFile = lsystem.Lsystem('lsystem_scene_two.txt') tstr = lsystemFile.buildString(4) # draw stuff turt_int.setColor(turt2, (0, 0, 0)) turt_int.place(turt2, 0, -200, 90) turt_int.drawString(turt2, tstr, 4, 90) # update window (loop) while win_two.running: win_two.update_window() turtle_scene_two() Hope this makes sense. Let me know if it doesn't. Appreciate your help! Tried a few things but nothing was promising. Calling turtle generates another screen (which I don't want). A: Since you didn't provide all your code, I can't test this, so I'm guessing a good start would be changing this: self.turtle = turtle.RawTurtle(turtle.TurtleScreen(self.canvas)) to something like: screen = turtle.TurtleScreen(self.canvas) screen.tracer(False) self.turtle = turtle.RawTurtle(screen)
How to set turtle tracer false using tkinter?
I have to generate two turtle windows and draw in each one, so I'm using tkinter to create and show the windows. My code currently opens the right screen and draws in it, but the turtle is really slow so I want to set the turtle tracer to false to use the update function, but I can't figure out how to. This is my turtle_interpreter.py file, which has all the functions I use to draw the L-system: import turtle from tkinter import * class Window(Tk): def __init__(self, title, geometry): super().__init__() self.running = True self.geometry(geometry) self.title(title) self.protocol("WM_DELETE_WINDOW", self.destroy_window) self.canvas = Canvas(self) self.canvas.pack(side=LEFT, expand=True, fill=BOTH) self.turtle = turtle.RawTurtle(turtle.TurtleScreen(self.canvas)) def update_window(self): ''' sets window to update ''' if self.running: self.update() def destroy_window(self): ''' sets window to close ''' self.running = False self.destroy() def drawString(turt, dstring, distance, angle): '''Interpret the characters in string dstring as a series of turtle commands. Distance specifies the distance to travel for each forward command. Angle specifies the angle (in degrees) for each right or left command. The list of turtle supported turtle commands is: F : forward - : turn right + : turn left ''' for char in dstring: if char == 'F': turt.forward(distance) elif char == '-': turt.right(angle) elif char == '+': turt.left(angle) def place(turt, xpos, ypos, angle=None): ''' places turtle at given coordinates and angle ''' turt.penup() turt.goto(xpos, ypos) if angle != None: turt.setheading(angle) turt.pendown() def goto(turt, xpos, ypos): ''' moves turtle to given coordinates ''' turt.penup() turt.goto(xpos, ypos) turt.pendown() def setColor(turt, color): ''' sets turtle color ''' turt.color(color) And this is the file where the functions get called. Running it draws the L-system. import turtle_interpreter as turt_int import lsystem_scene_three as lsystem def turtle_scene_two(): ''' generates scene two ''' # create window win_two = turt_int.Window('Turtle Scene 2', '640x480+650+0') # assign turtle turt2 = win_two.turtle # lsystem setup lsystemFile = lsystem.Lsystem('lsystem_scene_two.txt') tstr = lsystemFile.buildString(4) # draw stuff turt_int.setColor(turt2, (0, 0, 0)) turt_int.place(turt2, 0, -200, 90) turt_int.drawString(turt2, tstr, 4, 90) # update window (loop) while win_two.running: win_two.update_window() turtle_scene_two() Hope this makes sense. Let me know if it doesn't. Appreciate your help! Tried a few things but nothing was promising. Calling turtle generates another screen (which I don't want).
[ "Since you didn't provide all your code, I can't test this, so I'm guessing a good start would be changing this:\nself.turtle = turtle.RawTurtle(turtle.TurtleScreen(self.canvas))\n\nto something like:\nscreen = turtle.TurtleScreen(self.canvas)\nscreen.tracer(False)\nself.turtle = turtle.RawTurtle(screen)\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_turtle", "tkinter", "turtle_graphics" ]
stackoverflow_0074670230_python_python_turtle_tkinter_turtle_graphics.txt
Q: Why does my pyrogram bot keep turning off? For some reason my bot always turns off without printing any output to the command line or showing any kind of error. The bot functions properly for a few hours after being turned on. Basic code looks like this: app = Client("my_account", '123456', '123456789abcd') TESTING = "321" USER_ID = "123" chat_mapping = {TESTING: "-10011111111111", USER_ID: "-10011111111111"} @app.on_message() def my_handler(client, message): if str(message.chat.id) not in chat_mapping: return elif str(message.chat.id) == USER_ID: storeMsg(message) else: print(message.text) app.run() Any advice would be greatly appreciated! A: if str(message.chat.id) not in chat_mapping in this lane, your statement will check if message.chat.id is equal one of the keys of dictionary, not values. Means your message.chat.id can't be 123 or 321. USER_ID = some id chat_mapping = [some ids] @app.on_message() def my_handler(client, message): if str(message.chat.id) not in chat_mapping: return elif str(message.chat.id) == USER_ID: storeMsg(message) else: print(message.text) app.run()
Why does my pyrogram bot keep turning off?
For some reason my bot always turns off without printing any output to the command line or showing any kind of error. The bot functions properly for a few hours after being turned on. Basic code looks like this: app = Client("my_account", '123456', '123456789abcd') TESTING = "321" USER_ID = "123" chat_mapping = {TESTING: "-10011111111111", USER_ID: "-10011111111111"} @app.on_message() def my_handler(client, message): if str(message.chat.id) not in chat_mapping: return elif str(message.chat.id) == USER_ID: storeMsg(message) else: print(message.text) app.run() Any advice would be greatly appreciated!
[ "if str(message.chat.id) not in chat_mapping\nin this lane, your statement will check if message.chat.id is equal one of the keys of dictionary, not values.\nMeans your message.chat.id can't be 123 or 321.\nUSER_ID = some id\nchat_mapping = [some ids] \n@app.on_message()\ndef my_handler(client, message):\n if str(message.chat.id) not in chat_mapping:\n return\n elif str(message.chat.id) == USER_ID:\n storeMsg(message)\n else:\n print(message.text)\n\napp.run()\n\n" ]
[ 0 ]
[]
[]
[ "pyrogram", "python" ]
stackoverflow_0071444813_pyrogram_python.txt
Q: Expo eas: Android build fails if I run a prebuild before I use Expo 46. I would like to change some config in my AndroidManifest so I run an npx expo prebuild that generates an android folder without error. But then my eas build is not working anymore (it is if I don't run prebuild). I get this error: Failed to find 'build.gradle' file for project: /home/expo/workingdir/build/android/app. Am I missing something? A: It sounds like running npx expo prebuild is causing some issues with your Expo project. Expo uses the Android Gradle build system to build and run Android projects, so the error you're seeing about the build.gradle file indicates that there may be a problem with the build configuration. One potential cause of this issue could be that the npx expo prebuild command is modifying or deleting the build.gradle file, which would prevent the project from building properly. Another possibility is that the npx expo prebuild command is changing the location of the build.gradle file, so that the Expo build process can't find it. To resolve this issue, you may need to check the output of the npx expo prebuild command to see if it is making any changes to the build.gradle file or its location. You can also try running the npx expo build:android command to rebuild the Android project and see if that fixes the issue. If the problem persists, you may need to consult the Expo documentation or seek help from the Expo community for further assistance. A: Run the npx expo-updates in the root of your project in order to update the build.gradle file with the necessary changes. By the way, as I saw your remarks under the other posts: The expo prebuild command generates an Android project in the android directory, which contains the build.gradle file that is used by the expo build:android command. The eas build command is a shorthand for the expo build:android command, so it expects the Android project to be present in the android directory. If you run expo prebuild and then eas build, the eas build command should be able to find the build.gradle file and build the Android app successfully. A: Try running the expo prebuild command with the --clear flag, which will clear any existing pre-build files before generating the new ones. This should ensure that the generated android folder includes the build.gradle file, and the eas build command should be able to use this file to build the app. npx expo prebuild --clear Alternatively, you can try running the eas build command without running the expo prebuild command first. This will use the original Android project files in your app, which should include the build.gradle file and allow the eas build command to work correctly. How to run the eas build command without running expo prebuild first: npx eas build
Expo eas: Android build fails if I run a prebuild before
I use Expo 46. I would like to change some config in my AndroidManifest so I run an npx expo prebuild that generates an android folder without error. But then my eas build is not working anymore (it is if I don't run prebuild). I get this error: Failed to find 'build.gradle' file for project: /home/expo/workingdir/build/android/app. Am I missing something?
[ "It sounds like running npx expo prebuild is causing some issues with your Expo project. Expo uses the Android Gradle build system to build and run Android projects, so the error you're seeing about the build.gradle file indicates that there may be a problem with the build configuration.\nOne potential cause of this issue could be that the npx expo prebuild command is modifying or deleting the build.gradle file, which would prevent the project from building properly. Another possibility is that the npx expo prebuild command is changing the location of the build.gradle file, so that the Expo build process can't find it.\nTo resolve this issue, you may need to check the output of the npx expo prebuild command to see if it is making any changes to the build.gradle file or its location. You can also try running the npx expo build:android command to rebuild the Android project and see if that fixes the issue. If the problem persists, you may need to consult the Expo documentation or seek help from the Expo community for further assistance.\n", "Run the npx expo-updates in the root of your project in order to update the build.gradle file with the necessary changes.\nBy the way, as I saw your remarks under the other posts: The expo prebuild command generates an Android project in the android directory, which contains the build.gradle file that is used by the expo build:android command. The eas build command is a shorthand for the expo build:android command, so it expects the Android project to be present in the android directory.\nIf you run expo prebuild and then eas build, the eas build command should be able to find the build.gradle file and build the Android app successfully.\n", "Try running the expo prebuild command with the --clear flag, which will clear any existing pre-build files before generating the new ones.\nThis should ensure that the generated android folder includes the build.gradle file, and the eas build command should be able to use this file to build the app.\nnpx expo prebuild --clear\n\nAlternatively, you can try running the eas build command without running the expo prebuild command first. This will use the original Android project files in your app, which should include the build.gradle file and allow the eas build command to work correctly.\nHow to run the eas build command without running expo prebuild first:\nnpx eas build\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "android", "eas", "expo", "expo_build", "react_native" ]
stackoverflow_0074560557_android_eas_expo_expo_build_react_native.txt
Q: Valid JSON in jsonlint, but JSON.parse() not working I have a JSON which is verified in the JSONlint, but I cannot use JSON.parse() as it is not working. What is the problem with the JSON here, if JSON.prase() cannot be used what are my alternatives. JSON string : "{Products: [{Id: 1,Increment: 5,Max: 1000,Min: 25,allowed: false,Desc: product description,Name:Product Name,Qty: 0}]}" A: To a JSON be valid, your object keys must be inside double quotes: { "validKey": 123 } ^ ^ | | ------------- These double-quotes are required! JSONLint said that it's alright because you pasted the JSON as you pasted here, wrapped in quotes: "{Products: [{Id: 1,Increment: 5,Max: 1000,Min: 25,allowed: false,Desc: product description,Name:Product Name,Qty: 0}]}" And this is a json string with a JSON inside, not a JSON! If you try to JSONLint without the Quotes you will get this error: Error: Parse error on line 1: { Products: [{ Id: 1 --^ Expecting 'STRING', '}', got 'undefined' A: Your strings and keys should be quoted. This is valid JSON that will be correctly parsed by JSON.parse() { "Products": [ { "Id": 1, "Increment": 5, "Max": 1000, "Min": 25, "allowed": false, "Desc": "product description", "Name": "Product Name", "Qty": 0 } ] } You can read more about the standard here: https://www.json.org/ A: This can also happen when you are passing the JSON content inside a "string" variable, you need to using single quotes insted of double quotes of the outside string var data = "{ "nodes": [{ "id": 1, "text": "DefinitionFinder" },{ "id": 2, "text": "ProjectReference" },{ "id": 3, "text": "ReferenceManager" },{ "id": 4, "text": "ReferenceType" },{ "id": 5, "text": "EventStream" },{ "id": 6, "text": "AutoDisposable" },{ "id": 7, "text": "Handler" }], "links": [{ "from": 1, "to": 3 },{ "from": 2, "to": 4 },{ "from": 3, "to": 1 },{ "from": 3, "to": 2 }] }" This is the correct way var data = '{ "nodes": [{ "id": 1, "text": "DefinitionFinder" },{ "id": 2, "text": "ProjectReference" },{ "id": 3, "text": "ReferenceManager" },{ "id": 4, "text": "ReferenceType" },{ "id": 5, "text": "EventStream" },{ "id": 6, "text": "AutoDisposable" },{ "id": 7, "text": "Handler" }], "links": [{ "from": 1, "to": 3 },{ "from": 2, "to": 4 },{ "from": 3, "to": 1 },{ "from": 3, "to": 2 }] }'
Valid JSON in jsonlint, but JSON.parse() not working
I have a JSON which is verified in the JSONlint, but I cannot use JSON.parse() as it is not working. What is the problem with the JSON here, if JSON.prase() cannot be used what are my alternatives. JSON string : "{Products: [{Id: 1,Increment: 5,Max: 1000,Min: 25,allowed: false,Desc: product description,Name:Product Name,Qty: 0}]}"
[ "To a JSON be valid, your object keys must be inside double quotes:\n{ \"validKey\": 123 }\n ^ ^\n | |\n ------------- These double-quotes are required!\n\nJSONLint said that it's alright because you pasted the JSON as you pasted here, wrapped in quotes:\n\"{Products: [{Id: 1,Increment: 5,Max: 1000,Min: 25,allowed: false,Desc: product description,Name:Product Name,Qty: 0}]}\"\n\nAnd this is a json string with a JSON inside, not a JSON!\nIf you try to JSONLint without the Quotes you will get this error:\nError: Parse error on line 1:\n{ Products: [{ Id: 1\n--^\nExpecting 'STRING', '}', got 'undefined'\n\n", "Your strings and keys should be quoted. This is valid JSON that will be correctly parsed by JSON.parse()\n{\n \"Products\": [\n {\n \"Id\": 1,\n \"Increment\": 5,\n \"Max\": 1000,\n \"Min\": 25,\n \"allowed\": false,\n \"Desc\": \"product description\",\n \"Name\": \"Product Name\",\n \"Qty\": 0\n }\n ]\n}\n\nYou can read more about the standard here: https://www.json.org/\n", "This can also happen when you are passing the JSON content inside a \"string\" variable, you need to using single quotes insted of double quotes of the outside string\nvar data = \"{ \"nodes\": [{ \"id\": 1, \"text\": \"DefinitionFinder\" },{ \"id\": 2, \"text\": \"ProjectReference\" },{ \"id\": 3, \"text\": \"ReferenceManager\" },{ \"id\": 4, \"text\": \"ReferenceType\" },{ \"id\": 5, \"text\": \"EventStream\" },{ \"id\": 6, \"text\": \"AutoDisposable\" },{ \"id\": 7, \"text\": \"Handler\" }], \"links\": [{ \"from\": 1, \"to\": 3 },{ \"from\": 2, \"to\": 4 },{ \"from\": 3, \"to\": 1 },{ \"from\": 3, \"to\": 2 }] }\"\n\nThis is the correct way\nvar data = '{ \"nodes\": [{ \"id\": 1, \"text\": \"DefinitionFinder\" },{ \"id\": 2, \"text\": \"ProjectReference\" },{ \"id\": 3, \"text\": \"ReferenceManager\" },{ \"id\": 4, \"text\": \"ReferenceType\" },{ \"id\": 5, \"text\": \"EventStream\" },{ \"id\": 6, \"text\": \"AutoDisposable\" },{ \"id\": 7, \"text\": \"Handler\" }], \"links\": [{ \"from\": 1, \"to\": 3 },{ \"from\": 2, \"to\": 4 },{ \"from\": 3, \"to\": 1 },{ \"from\": 3, \"to\": 2 }] }'\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "javascript", "jquery", "json", "object" ]
stackoverflow_0048773832_javascript_jquery_json_object.txt
Q: Replacing NA's with a unique sequence in a list of dataframes I have example data as follows: library(data.table) datA <- fread("ID somevar NA 4 NA 3 2 5") datB <- fread("ID somevar 7 4 NA 3 NA 5") dat_list <- list(datA, datB) In dat_list I would like to replace all NA's in the ID column with a new ID-number. I would like this number to be unique and start at 100. I thought of something like this: for (i in seq_along(dat_list)){ temp <- dat_list[[i]] count_of_seq <- sum(is.na(temp$ID)) sequence_dat <- seq(100, 100+count_of_seq) temp <- setDT(temp)[is.na(ID), ID:=sequence_dat[i]] } But this does not work because, it uses only one number of the sequence for each list: How should I do this properly? Desired output: library(data.table) datA <- fread("ID somevar 100 4 101 3 2 5") datB <- fread("ID somevar 7 4 102 3 103 5") dat_list <- list(datA, datB) A: One dplyr option could be: dat_list %>% bind_rows(., .id = "dataset_ID") %>% mutate(ID = ifelse(is.na(ID), 99 + cumsum(is.na(ID)), ID)) %>% group_split(dataset_ID, .keep = FALSE) [[1]] # A tibble: 3 × 2 ID somevar <dbl> <int> 1 100 4 2 101 3 3 2 5 [[2]] # A tibble: 3 × 2 ID somevar <dbl> <int> 1 7 4 2 102 3 3 103 5 A: In base R: id <- 99 for (i in seq_along(dat_list)) { nas <- is.na(dat_list[[i]]$ID) dat_list[[i]]$ID[nas] <- id + seq_len(sum(nas)) id <- id + sum(nas) } dat_list # [[1]] # ID somevar # 1: 100 4 # 2: 101 3 # 3: 2 5 # # [[2]] # ID somevar # 1: 7 4 # 2: 102 3 # 3: 103 5 A: Using data.table library(data.table) df1 <- rbindlist(dat_list, idcol = 'grp')[is.na(ID), ID := 99 + .I] split(df1[,-1], df1$grp) $`1` ID somevar 1: 100 4 2: 101 3 3: 2 5 $`2` ID somevar 1: 7 4 2: 102 3 3: 103 5
Replacing NA's with a unique sequence in a list of dataframes
I have example data as follows: library(data.table) datA <- fread("ID somevar NA 4 NA 3 2 5") datB <- fread("ID somevar 7 4 NA 3 NA 5") dat_list <- list(datA, datB) In dat_list I would like to replace all NA's in the ID column with a new ID-number. I would like this number to be unique and start at 100. I thought of something like this: for (i in seq_along(dat_list)){ temp <- dat_list[[i]] count_of_seq <- sum(is.na(temp$ID)) sequence_dat <- seq(100, 100+count_of_seq) temp <- setDT(temp)[is.na(ID), ID:=sequence_dat[i]] } But this does not work because, it uses only one number of the sequence for each list: How should I do this properly? Desired output: library(data.table) datA <- fread("ID somevar 100 4 101 3 2 5") datB <- fread("ID somevar 7 4 102 3 103 5") dat_list <- list(datA, datB)
[ "One dplyr option could be:\ndat_list %>%\n bind_rows(., .id = \"dataset_ID\") %>%\n mutate(ID = ifelse(is.na(ID), 99 + cumsum(is.na(ID)), ID)) %>%\n group_split(dataset_ID, .keep = FALSE)\n\n[[1]]\n# A tibble: 3 × 2\n ID somevar\n <dbl> <int>\n1 100 4\n2 101 3\n3 2 5\n\n[[2]]\n# A tibble: 3 × 2\n ID somevar\n <dbl> <int>\n1 7 4\n2 102 3\n3 103 5\n\n", "In base R:\nid <- 99\nfor (i in seq_along(dat_list)) {\n nas <- is.na(dat_list[[i]]$ID)\n dat_list[[i]]$ID[nas] <- id + seq_len(sum(nas))\n id <- id + sum(nas)\n}\n\ndat_list\n# [[1]]\n# ID somevar\n# 1: 100 4\n# 2: 101 3\n# 3: 2 5\n# \n# [[2]]\n# ID somevar\n# 1: 7 4\n# 2: 102 3\n# 3: 103 5\n\n", "Using data.table\nlibrary(data.table)\ndf1 <- rbindlist(dat_list, idcol = 'grp')[is.na(ID), ID := 99 + .I]\nsplit(df1[,-1], df1$grp)\n$`1`\n ID somevar\n1: 100 4\n2: 101 3\n3: 2 5\n\n$`2`\n ID somevar\n1: 7 4\n2: 102 3\n3: 103 5\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "list", "r", "sequence" ]
stackoverflow_0074674141_list_r_sequence.txt
Q: Send Server Stored PDF File To another Server Via Curl PHP Form Data I am trying to send a PHP file which is stored on my server to another server via Curl PHP Form Data method. Usually, it is done by submitting a form and uploading file and sending the same file as form data to Curl PHP endpoint but in this case I have already that file on my server and I am stuck on the part how will I fetch that file and create its form data array and send it API Url as an post method. Below are some sort of programme I am trying. Out of which one is to create a tmp file and storing data in there and send that data from tmp location to curl form data. $source = file_get_contents("https://url/employee_manual3.pdf"); $tempFile = tempnam(sys_get_temp_dir(), 'File_'); rename($tempFile, $tempFile .= '.pdf'); file_put_contents($tempFile, $source); // var_dump($tempFile); // exit; // $post = array( // "uploadedFile" => "@" . $tempFile, //"@".$tempFile.";type=application/pdf", // ); // var_dump(file_get_contents($tempFile)); // var_dump(new CURLFILE($tempFile)); // exit; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://API_URL', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => array('file' => new CURLFILE($tempFile)), CURLOPT_HTTPHEADER => array( 'Authorization: Bearer API TOKEN HAI MERA', 'Content-Type: multipart/form-data', 'Cookie: MAIN NAHI BATAUNGA' ), )); $response = curl_exec($curl); curl_close($curl); echo $response; A: Hi You can check the answer below on how I managed to pull this off. // $source = file_get_contents("https://URL/assets/email_images/employee_manual3.pdf"); $file_path = __DIR__.'/../../../assets/email_images/employee_manual3.pdf'; // var_dump(__DIR__.'/../../../assets/email_images/employee_manual3.pdf'); // exit; // var_dump(new CURLFILE($file_path, 'application/pdf', 'file')); // exit; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'API URL', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => array('file' => new CURLFILE($file_path, 'application/pdf', 'file')), )); $response = curl_exec($curl); curl_close($curl); echo $response;
Send Server Stored PDF File To another Server Via Curl PHP Form Data
I am trying to send a PHP file which is stored on my server to another server via Curl PHP Form Data method. Usually, it is done by submitting a form and uploading file and sending the same file as form data to Curl PHP endpoint but in this case I have already that file on my server and I am stuck on the part how will I fetch that file and create its form data array and send it API Url as an post method. Below are some sort of programme I am trying. Out of which one is to create a tmp file and storing data in there and send that data from tmp location to curl form data. $source = file_get_contents("https://url/employee_manual3.pdf"); $tempFile = tempnam(sys_get_temp_dir(), 'File_'); rename($tempFile, $tempFile .= '.pdf'); file_put_contents($tempFile, $source); // var_dump($tempFile); // exit; // $post = array( // "uploadedFile" => "@" . $tempFile, //"@".$tempFile.";type=application/pdf", // ); // var_dump(file_get_contents($tempFile)); // var_dump(new CURLFILE($tempFile)); // exit; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://API_URL', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => array('file' => new CURLFILE($tempFile)), CURLOPT_HTTPHEADER => array( 'Authorization: Bearer API TOKEN HAI MERA', 'Content-Type: multipart/form-data', 'Cookie: MAIN NAHI BATAUNGA' ), )); $response = curl_exec($curl); curl_close($curl); echo $response;
[ "Hi You can check the answer below on how I managed to pull this off.\n // $source = file_get_contents(\"https://URL/assets/email_images/employee_manual3.pdf\");\n\n $file_path = __DIR__.'/../../../assets/email_images/employee_manual3.pdf';\n\n // var_dump(__DIR__.'/../../../assets/email_images/employee_manual3.pdf');\n // exit;\n\n // var_dump(new CURLFILE($file_path, 'application/pdf', 'file'));\n // exit;\n\n $curl = curl_init();\n\n curl_setopt_array($curl, array(\n CURLOPT_URL => 'API URL',\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => '',\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 0,\n CURLOPT_FOLLOWLOCATION => true,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => 'POST',\n CURLOPT_POSTFIELDS => array('file' => new CURLFILE($file_path, 'application/pdf', 'file')),\n ));\n\n $response = curl_exec($curl);\n\n curl_close($curl);\n echo $response;\n\n" ]
[ 0 ]
[]
[]
[ "codeigniter", "curl", "php" ]
stackoverflow_0074679715_codeigniter_curl_php.txt
Q: Translating code from JS to C#. I don't understand what this function does ` const yandexRequests = (function() { var protoRequest = new protobuf.Type("VideoTranslationRequest").add(new protobuf.Field("url", 3, "string")).add(new protobuf.Field("deviceId", 4, "string")).add(new protobuf.Field("unknown0", 5, "int32")).add(new protobuf.Field("unknown1", 6, "fixed64")).add(new protobuf.Field("unknown2", 7, "int32")).add(new protobuf.Field("language", 8, "string")).add(new protobuf.Field("unknown3", 9, "int32")).add(new protobuf.Field("unknown4", 10, "int32")); var protoResponse = new protobuf.Type("VideoTranslationResponse").add(new protobuf.Field("url", 1, "string")).add(new protobuf.Field("status", 4, "int32")); new protobuf.Root().define("yandex").add(protoRequest).add(protoResponse); return { encodeRequest: function(url, deviceId, unknown1) { return protoRequest.encode({url: url, deviceId: deviceId, unknown0: 1, unknown1: unknown1, unknown2: 1, language: "en", unknown3: 0, unknown4: 0}).finish(); }, decodeResponse: function(response) { return protoResponse.decode(new Uint8Array(response)); } }; })(); var body = yandexRequests.encodeRequest(url, deviceId, unknown1); ` I don't understand what this function does. A: It returns an object that contains two functions: encodeRequest and decodeResponse. Those functions call protoRequest.encode and protoResponse.decode when they are called. protobuf is a Google thing I think: https://www.tutorialspoint.com/protobuf/index.htm, but I didn't think they had a JavaScript version, so maybe it's a custom job.
Translating code from JS to C#. I don't understand what this function does
` const yandexRequests = (function() { var protoRequest = new protobuf.Type("VideoTranslationRequest").add(new protobuf.Field("url", 3, "string")).add(new protobuf.Field("deviceId", 4, "string")).add(new protobuf.Field("unknown0", 5, "int32")).add(new protobuf.Field("unknown1", 6, "fixed64")).add(new protobuf.Field("unknown2", 7, "int32")).add(new protobuf.Field("language", 8, "string")).add(new protobuf.Field("unknown3", 9, "int32")).add(new protobuf.Field("unknown4", 10, "int32")); var protoResponse = new protobuf.Type("VideoTranslationResponse").add(new protobuf.Field("url", 1, "string")).add(new protobuf.Field("status", 4, "int32")); new protobuf.Root().define("yandex").add(protoRequest).add(protoResponse); return { encodeRequest: function(url, deviceId, unknown1) { return protoRequest.encode({url: url, deviceId: deviceId, unknown0: 1, unknown1: unknown1, unknown2: 1, language: "en", unknown3: 0, unknown4: 0}).finish(); }, decodeResponse: function(response) { return protoResponse.decode(new Uint8Array(response)); } }; })(); var body = yandexRequests.encodeRequest(url, deviceId, unknown1); ` I don't understand what this function does.
[ "It returns an object that contains two functions: encodeRequest and decodeResponse. Those functions call protoRequest.encode and protoResponse.decode when they are called.\nprotobuf is a Google thing I think: https://www.tutorialspoint.com/protobuf/index.htm, but I didn't think they had a JavaScript version, so maybe it's a custom job.\n" ]
[ 0 ]
[]
[]
[ "c#", "javascript" ]
stackoverflow_0074678252_c#_javascript.txt
Q: Browser custom default print settings for specific URLs I regularly print a few different URLs each week (using Chrome and Firefox). Each URL requires different printer settings such as page size legal or letter, orientation portrait or landscape, sometimes margin adjustments and removal of options. I have to set the print settings each time when I switch to URL that requires different settings. Is there any way to "assign" a set of printer settings to a specific URL so that it always uses those settings without having to change the settings each time?
Browser custom default print settings for specific URLs
I regularly print a few different URLs each week (using Chrome and Firefox). Each URL requires different printer settings such as page size legal or letter, orientation portrait or landscape, sometimes margin adjustments and removal of options. I have to set the print settings each time when I switch to URL that requires different settings. Is there any way to "assign" a set of printer settings to a specific URL so that it always uses those settings without having to change the settings each time?
[]
[]
[ "Yes, you can save printer settings as a preset in your browser's print dialog box. In Chrome, you can access the print dialog box by pressing Ctrl + P or by clicking on the Menu icon in the top right corner and selecting Print. In the print dialog box, select the More settings option, which will open up additional settings for the printer. After adjusting the settings as desired, click on the Save button and give the preset a name. This preset will now be available in the printer drop-down menu in the print dialog box, and you can select it for use with any URL.\nIn Firefox, you can access the print dialog box by pressing Ctrl + P or by clicking on the Menu icon in the top right corner and selecting Print. In the print dialog box, select the Page Setup option, which will open up additional settings for the printer. After adjusting the settings as desired, click on the Save button and give the preset a name. This preset will now be available in the printer drop-down menu in the print dialog box, and you can select it for use with any URL.\nNote that these steps may vary slightly depending on the version of your browser and operating system.\n" ]
[ -1 ]
[ "browser", "printing", "settings" ]
stackoverflow_0074679710_browser_printing_settings.txt
Q: i'm filtering divs without java and idk where to put the div on css as you can see there's a div with an id named sidebar. idk what to put on css for it to work. css: button[data-filter="walks"]:focus ~ div div:not([class*="walks"]), button[data-filter="swims"]:focus ~ div div:not([class*="swims"]), button[data-filter="flies"]:focus ~ div div:not([class*="flies"]) { display:none; } html: <div class="filteredList"> <div id="sidebar"> <h3>Filters</h3> <button class="filter-option" data-filter="*" tabindex="-1">All</button> <button class="filter-option" data-filter="walks" tabindex="-1">Walks</button> <button class="filter-option" data-filter="swims" tabindex="-1">Swims</button> <button class="filter-option" data-filter="flies" tabindex="-1">Flies</button> </div> <div id="animals"> <h3>Animals</h3> <div class="dog walks">Dog</div> <div class="eagle flies">Eagle</div> <div class="cow walks">Cow</div> <div class="shark swims">Shark</div> <div class="canary flies">Canary</div> <div class="human walks">Human</div> <div class="salamander swims walks">Salamander</div> </div> </div> i've tried using this: #sidebar button[data-filter="walks"]:focus ~ div div:not([class*="walks"]), #sidebar button[data-filter="swims"]:focus ~ div div:not([class*="swims"]), #sidebar button[data-filter="flies"]:focus ~ div div:not([class*="flies"]) { display:none; and i expected it to work. A: The issue is that CSS is always cascading. You can't go up in structure, and CSS therefore expects the animals div to be a sibling of the buttons. You'd need to restructure your HTML so that the filters are not nested inside the sidebar div for the snippet to work. <div class="filteredList"> <div id="sidebar"> <h3>Filters</h3> <button class="filter-option" data-filter="*" tabindex="-1">All</button> <button class="filter-option" data-filter="walks" tabindex="-1">Walks</button> <button class="filter-option" data-filter="swims" tabindex="-1">Swims</button> <button class="filter-option" data-filter="flies" tabindex="-1">Flies</button> <div id="animals"> <h3>Animals</h3> <div class="dog walks">Dog</div> <div class="eagle flies">Eagle</div> <div class="cow walks">Cow</div> <div class="shark swims">Shark</div> <div class="canary flies">Canary</div> <div class="human walks">Human</div> <div class="salamander swims walks">Salamander</div> </div> </div> </div> With this change, your CSS code should work as expected and hide the div elements with the walks, swims, and flies class when the corresponding button element is focused. Besides that, I'd recommend you to use checkboxes and ::checked for accessibility reasons.
i'm filtering divs without java and idk where to put the div on css
as you can see there's a div with an id named sidebar. idk what to put on css for it to work. css: button[data-filter="walks"]:focus ~ div div:not([class*="walks"]), button[data-filter="swims"]:focus ~ div div:not([class*="swims"]), button[data-filter="flies"]:focus ~ div div:not([class*="flies"]) { display:none; } html: <div class="filteredList"> <div id="sidebar"> <h3>Filters</h3> <button class="filter-option" data-filter="*" tabindex="-1">All</button> <button class="filter-option" data-filter="walks" tabindex="-1">Walks</button> <button class="filter-option" data-filter="swims" tabindex="-1">Swims</button> <button class="filter-option" data-filter="flies" tabindex="-1">Flies</button> </div> <div id="animals"> <h3>Animals</h3> <div class="dog walks">Dog</div> <div class="eagle flies">Eagle</div> <div class="cow walks">Cow</div> <div class="shark swims">Shark</div> <div class="canary flies">Canary</div> <div class="human walks">Human</div> <div class="salamander swims walks">Salamander</div> </div> </div> i've tried using this: #sidebar button[data-filter="walks"]:focus ~ div div:not([class*="walks"]), #sidebar button[data-filter="swims"]:focus ~ div div:not([class*="swims"]), #sidebar button[data-filter="flies"]:focus ~ div div:not([class*="flies"]) { display:none; and i expected it to work.
[ "The issue is that CSS is always cascading.\nYou can't go up in structure, and CSS therefore expects the animals div to be a sibling of the buttons.\nYou'd need to restructure your HTML so that the filters are not nested inside the sidebar div for the snippet to work.\n<div class=\"filteredList\">\n <div id=\"sidebar\">\n <h3>Filters</h3>\n <button class=\"filter-option\" data-filter=\"*\" tabindex=\"-1\">All</button>\n <button class=\"filter-option\" data-filter=\"walks\" tabindex=\"-1\">Walks</button> \n <button class=\"filter-option\" data-filter=\"swims\" tabindex=\"-1\">Swims</button> \n <button class=\"filter-option\" data-filter=\"flies\" tabindex=\"-1\">Flies</button>\n \n <div id=\"animals\">\n <h3>Animals</h3>\n <div class=\"dog walks\">Dog</div>\n <div class=\"eagle flies\">Eagle</div>\n <div class=\"cow walks\">Cow</div>\n <div class=\"shark swims\">Shark</div>\n <div class=\"canary flies\">Canary</div>\n <div class=\"human walks\">Human</div>\n <div class=\"salamander swims walks\">Salamander</div>\n </div>\n </div>\n</div>\n\nWith this change, your CSS code should work as expected and hide the div elements with the walks, swims, and flies class when the corresponding button element is focused.\nBesides that, I'd recommend you to use checkboxes and ::checked for accessibility reasons.\n" ]
[ 0 ]
[]
[]
[ "css", "filter", "html" ]
stackoverflow_0074679619_css_filter_html.txt
Q: Using getter & setters with type guard in setter I would like to add a getter and setter to my class. However the setter is supposed to receive a querySelector but the getter returns a new type pageSections. My issue is that the getter and setter must have the same argument/return value, but I want to put the type guard in the setter. pageSections is defined in a type definition file and works fine. // in the code … this.parent(this.closest('page-sections')) // in the class PageSection { private _parent: pageSections = undefined /** * @method setter parent * @description set the parent property */ set parent (parent: pageSections) { if (this._parent === parent) return if (typeof parent.current === undefined) return // this validates it being a pageSections for now this._parent = parent } /** * @method getter parent * @description get the parent property */ get parent (): pageSections { return this._parent } } What am I missing? How should this be done? A: You cannot do that and why should it be possible? You can: create another method (setParent(q:querySelector)) create a converter that elaborates the querySelector and returns a pageSections to set using "set parent" You can find here an issue about it (still discussed from 2015). A: You can try this package, @p4ck493/ts-is there is an example of how it can be used to check arguments, @p4ck493/ts-is#-additional but in your case you need to have a declared class on which the checks will be performed.
Using getter & setters with type guard in setter
I would like to add a getter and setter to my class. However the setter is supposed to receive a querySelector but the getter returns a new type pageSections. My issue is that the getter and setter must have the same argument/return value, but I want to put the type guard in the setter. pageSections is defined in a type definition file and works fine. // in the code … this.parent(this.closest('page-sections')) // in the class PageSection { private _parent: pageSections = undefined /** * @method setter parent * @description set the parent property */ set parent (parent: pageSections) { if (this._parent === parent) return if (typeof parent.current === undefined) return // this validates it being a pageSections for now this._parent = parent } /** * @method getter parent * @description get the parent property */ get parent (): pageSections { return this._parent } } What am I missing? How should this be done?
[ "You cannot do that and why should it be possible?\nYou can:\n\ncreate another method (setParent(q:querySelector))\ncreate a converter that elaborates the querySelector and returns a pageSections to set using \"set parent\"\n\nYou can find here an issue about it (still discussed from 2015).\n", "You can try this package,\n@p4ck493/ts-is\nthere is an example of how it can be used to check arguments,\n@p4ck493/ts-is#-additional\nbut in your case you need to have a declared class on which the checks will be performed.\n" ]
[ 1, 0 ]
[]
[]
[ "getter_setter", "javascript", "typescript" ]
stackoverflow_0051065681_getter_setter_javascript_typescript.txt
Q: Using setTimeout continuously vs media query for handling different screen resolutions I am trying to make my website responsive. I'm currently using setTimeout every 100ms to check for screen width and to check layouts accordingly instead of media query. Is this a bad approach or can javascript handle this since it's a small website? function screen() { var screenWidth = window.innerWidth; if(screenWidth < 1100) { if(!sidebar.classList.contains('open')) sidebar.style.display = 'none'; hamburger.style.display = 'flex'; } else { sidebar.style.display = 'block'; hamburger.style.display = 'none'; } setTimeout(screen, 100); } screen(); A: Using setTimeout to check for screen width every 100ms is not a good approach for making any website responsive. Instead, you should use media queries in your CSS to specify how your website should look at different screen sizes. This will allow the browser to automatically adjust the layout of your website when the screen size changes, without needing to constantly poll the screen width using JavaScript. Using media queries is a better approach for making a website responsive because it is more efficient, maintainable, and user-friendly than constantly polling the screen width using JavaScript. Here are a few sources that you can use to learn more about using media queries to make your website responsive: The MDN Web Docs page on media queries: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries The CSS-Tricks page on media queries: https://css-tricks.com/snippets/css/media-queries-for-standard-devices/ A: It's way more readable and efficient to let css engine apply media queries for you But if you can't use it, it would be better if you would use matchMedia const sidebar = document.querySelector('nav') const hamburger = document.querySelector('button') const mql = matchMedia('(max-width: 1100px)') handleChange(mql) mql.addEventListener('change', handleChange) function handleChange(e) { if (e.matches) { if (!sidebar.classList.contains('open')) sidebar.style.display = 'none'; hamburger.style.display = 'flex'; } else { sidebar.style.display = 'block'; hamburger.style.display = 'none'; } } <button>-</button> <nav>test</nav>
Using setTimeout continuously vs media query for handling different screen resolutions
I am trying to make my website responsive. I'm currently using setTimeout every 100ms to check for screen width and to check layouts accordingly instead of media query. Is this a bad approach or can javascript handle this since it's a small website? function screen() { var screenWidth = window.innerWidth; if(screenWidth < 1100) { if(!sidebar.classList.contains('open')) sidebar.style.display = 'none'; hamburger.style.display = 'flex'; } else { sidebar.style.display = 'block'; hamburger.style.display = 'none'; } setTimeout(screen, 100); } screen();
[ "Using setTimeout to check for screen width every 100ms is not a good approach for making any website responsive. Instead, you should use media queries in your CSS to specify how your website should look at different screen sizes. This will allow the browser to automatically adjust the layout of your website when the screen size changes, without needing to constantly poll the screen width using JavaScript. Using media queries is a better approach for making a website responsive because it is more efficient, maintainable, and user-friendly than constantly polling the screen width using JavaScript.\nHere are a few sources that you can use to learn more about using media queries to make your website responsive:\n\nThe MDN Web Docs page on media queries:\nhttps://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries\nThe CSS-Tricks page on media queries:\nhttps://css-tricks.com/snippets/css/media-queries-for-standard-devices/\n\n", "It's way more readable and efficient to let css engine apply media queries for you\nBut if you can't use it, it would be better if you would use matchMedia\n\n\nconst sidebar = document.querySelector('nav')\nconst hamburger = document.querySelector('button')\nconst mql = matchMedia('(max-width: 1100px)')\nhandleChange(mql)\nmql.addEventListener('change', handleChange)\n\nfunction handleChange(e) {\n if (e.matches) {\n if (!sidebar.classList.contains('open'))\n sidebar.style.display = 'none';\n hamburger.style.display = 'flex';\n } else {\n sidebar.style.display = 'block';\n hamburger.style.display = 'none';\n }\n}\n<button>-</button>\n<nav>test</nav>\n\n\n\n" ]
[ 1, 0 ]
[]
[]
[ "javascript", "responsive_design" ]
stackoverflow_0074679538_javascript_responsive_design.txt
Q: while using 'fetch()', i got the answer, "failed to feth" I would like to ask question related to fetching. I'm required to create a weather website. For this, firstly, I registered in weather api, got a key, and formulated my 'url' by following api doc. Now, the url itself seems works; 'https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=01d9f2d66b5fb9c863aa86b5cb001cd2', because the details are shown when paste in browser. The problem itself is that, when I use 'url' in my code with 'fetch', the api doesn't provide any info. the code is the following: let weather = { fetchWeather : function() { fetch("https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=01d9f2d66b5fb9c863aa86b5cb001cd2") .then((response) => response.json()) .then((data) => console.log(data)); }, }; the result: VM1176:3 GET https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=01d9f2d66b5fb9c863aa86b5cb001cd2 net::ERR_FAILED fetchWeather @ VM1176:3 (anonymous) @ VM1217:1 VM1176:3 Uncaught (in promise) TypeError: Failed to fetch at Object.fetchWeather (<anonymous>:3:9) at <anonymous>:1:9 could you pls help me how to solve the problem? I want to know why the problem occurs and how to solve it A: Here is a working version. I added a form so that you can pass city and unit type as parameters. <!DOCTYPE html> <html lang="en"> <head> <script> function fetchWeather() { var city = document.getElementById('city').value; var metrics = document.getElementById('metrics').value; let weather = fetch( "https://api.openweathermap.org/data/2.5/weather?" + new URLSearchParams( { q: city, units: metrics, appid: '01d9f2d66b5fb9c863aa86b5cb001cd2' } ) ) .then(response => response.json()) .then(jsonObj => JSON.stringify(jsonObj)) .then(data => console.log(data)); } </script> </head> <body> <section> <form action="javascript:fetchWeather();"> <input type="text" id="city" name="city"><br> <input type="radio" id="metrics" name="unitType" value="metrics" checked="checked"> <label for="metrics">Metrics</label><br> <input type="radio" id="imperial" name="unitType" value="imperial"> <label for="imperial">Imperial</label><br> <input type="submit" value="Submit"> </form> </section> </body> </html>
while using 'fetch()', i got the answer, "failed to feth"
I would like to ask question related to fetching. I'm required to create a weather website. For this, firstly, I registered in weather api, got a key, and formulated my 'url' by following api doc. Now, the url itself seems works; 'https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=01d9f2d66b5fb9c863aa86b5cb001cd2', because the details are shown when paste in browser. The problem itself is that, when I use 'url' in my code with 'fetch', the api doesn't provide any info. the code is the following: let weather = { fetchWeather : function() { fetch("https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=01d9f2d66b5fb9c863aa86b5cb001cd2") .then((response) => response.json()) .then((data) => console.log(data)); }, }; the result: VM1176:3 GET https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=01d9f2d66b5fb9c863aa86b5cb001cd2 net::ERR_FAILED fetchWeather @ VM1176:3 (anonymous) @ VM1217:1 VM1176:3 Uncaught (in promise) TypeError: Failed to fetch at Object.fetchWeather (<anonymous>:3:9) at <anonymous>:1:9 could you pls help me how to solve the problem? I want to know why the problem occurs and how to solve it
[ "Here is a working version.\nI added a form so that you can pass city and unit type as parameters.\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <script> \n function fetchWeather() {\n var city = document.getElementById('city').value;\n var metrics = document.getElementById('metrics').value;\n \n let weather = fetch(\n \"https://api.openweathermap.org/data/2.5/weather?\"\n + new URLSearchParams(\n {\n q: city,\n units: metrics,\n appid: '01d9f2d66b5fb9c863aa86b5cb001cd2'\n }\n )\n )\n .then(response => response.json())\n .then(jsonObj => JSON.stringify(jsonObj))\n .then(data => console.log(data));\n }\n </script>\n</head>\n\n<body>\n <section>\n <form action=\"javascript:fetchWeather();\">\n <input type=\"text\" id=\"city\" name=\"city\"><br>\n <input type=\"radio\" id=\"metrics\" name=\"unitType\" value=\"metrics\" checked=\"checked\">\n <label for=\"metrics\">Metrics</label><br>\n <input type=\"radio\" id=\"imperial\" name=\"unitType\" value=\"imperial\">\n <label for=\"imperial\">Imperial</label><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </section>\n</body>\n</html>\n\n" ]
[ 0 ]
[ "Your code is totally correct and I expect it to work as expected. Could you try again by including the request options as below?\nlet weather = {\n fetchWeather : function() {\n const requestOptions = {\n method: 'GET',\n redirect: 'follow'\n };\n\nfetch(\"https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=01d9f2d66b5fb9c863aa86b5cb001cd2\", requestOptions)\n .then(response => response.json())\n .then(result => console.log(result))\n .catch(error => console.log('error', error));\n },\n};\n\n" ]
[ -1 ]
[ "javascript", "nsfetchrequest", "typeerror", "urlfetch" ]
stackoverflow_0074664861_javascript_nsfetchrequest_typeerror_urlfetch.txt
Q: Python : compare data frame row value with previous row value I am trying to create a new Column by comparing the value row with its previous value error that I get is ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I have checked the data type of columns. All of them are float64 But I am getting an error CODE: cols=['High', 'Low', 'Open', 'Volume', "Adj Close"] df = df.drop(columns = cols) df['EMA60'] = df['Close'].ewm(span=60, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['MACD_60_100'] = df['EMA60'] - df['EMA100'] df['SIGNAL_60_100'] = df['MACD_60_100'].ewm(span=9, adjust=False).mean() df['HIST_60_100'] = df['MACD_60_100'] - df['SIGNAL_60_100'] # Histogram df = df.iloc[1: , :] # Delete first row in DF as it contains NAN print(df.dtypes) print (df) if df[df['HIST_60_100'] > df['HIST_60_100'].shift(+1)]: # check if the valus is > previous row value df['COLOR-60-100'] = "GREEN" else: df['COLOR-60-100'] = "RED" print(df.to_string()) ERROR: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_10972/77395577.py in <module> 32 33 ---> 34 get_data_from_yahoo(symbol+".NS") 35 36 # df.to_excel(sheetXls, index=False) ~\AppData\Local\Temp/ipykernel_10972/520355426.py in get_data_from_yahoo(symbol, interval, start, end) 26 print(df.dtypes) 27 print (df) ---> 28 if df[df['HIST_60_100'] > df['HIST_60_100'].shift(+1)]: 29 df['COLOR-60-100'] = "GREEN" 30 else: ~\AppData\Roaming\Python\Python39\site-packages\pandas\core\generic.py in __nonzero__(self) 1327 1328 def __nonzero__(self): -> 1329 raise ValueError( 1330 f"The truth value of a {type(self).__name__} is ambiguous. " 1331 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). A: No need for an if.. else statement here. You can use numpy.where instead. numpy.where(condition, [x, y, ]/) Replace this : if df[df['HIST_60_100'] > df['HIST_60_100'].shift(+1)]: # check if the valus is > previous row value df['COLOR-60-100'] = "GREEN" else: df['COLOR-60-100'] = "RED" By this : df['COLOR-60-100'] = np.where(df['HIST_60_100'].gt(df['HIST_60_100'].shift(1), "GREEN", "RED")
Python : compare data frame row value with previous row value
I am trying to create a new Column by comparing the value row with its previous value error that I get is ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I have checked the data type of columns. All of them are float64 But I am getting an error CODE: cols=['High', 'Low', 'Open', 'Volume', "Adj Close"] df = df.drop(columns = cols) df['EMA60'] = df['Close'].ewm(span=60, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['MACD_60_100'] = df['EMA60'] - df['EMA100'] df['SIGNAL_60_100'] = df['MACD_60_100'].ewm(span=9, adjust=False).mean() df['HIST_60_100'] = df['MACD_60_100'] - df['SIGNAL_60_100'] # Histogram df = df.iloc[1: , :] # Delete first row in DF as it contains NAN print(df.dtypes) print (df) if df[df['HIST_60_100'] > df['HIST_60_100'].shift(+1)]: # check if the valus is > previous row value df['COLOR-60-100'] = "GREEN" else: df['COLOR-60-100'] = "RED" print(df.to_string()) ERROR: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_10972/77395577.py in <module> 32 33 ---> 34 get_data_from_yahoo(symbol+".NS") 35 36 # df.to_excel(sheetXls, index=False) ~\AppData\Local\Temp/ipykernel_10972/520355426.py in get_data_from_yahoo(symbol, interval, start, end) 26 print(df.dtypes) 27 print (df) ---> 28 if df[df['HIST_60_100'] > df['HIST_60_100'].shift(+1)]: 29 df['COLOR-60-100'] = "GREEN" 30 else: ~\AppData\Roaming\Python\Python39\site-packages\pandas\core\generic.py in __nonzero__(self) 1327 1328 def __nonzero__(self): -> 1329 raise ValueError( 1330 f"The truth value of a {type(self).__name__} is ambiguous. " 1331 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
[ "No need for an if.. else statement here. You can use numpy.where instead.\n\nnumpy.where(condition, [x, y, ]/)\n\nReplace this :\nif df[df['HIST_60_100'] > df['HIST_60_100'].shift(+1)]: # check if the valus is > previous row value\n df['COLOR-60-100'] = \"GREEN\"\nelse:\n df['COLOR-60-100'] = \"RED\"\n\nBy this :\ndf['COLOR-60-100'] = np.where(df['HIST_60_100'].gt(df['HIST_60_100'].shift(1), \"GREEN\", \"RED\")\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074679598_dataframe_numpy_pandas_python.txt
Q: Effective Java 3: item 31: using for producers, is not applicable for different data structures This code from the Item 31: public class Union { public static <E> Set<E> union(Set<? extends E> s1, Set<? extends E> s2) { // Bloch used HashSet, but I want natural ordering and still make freedom of producer type Set<E> result = new TreeSet<>(s1); result.addAll(s2); return result; } public static void main(String[] args) { Set<Integer> integers = new HashSet<>(); integers.add(1); integers.add(3); integers.add(5); Set<Double> doubles = new HashSet<>(); doubles.add(2.0); doubles.add(4.0); doubles.add(6.0); Set<Number> numbers = union(integers, doubles); System.out.println(numbers); } } Compiles, but gives runtime error: Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Double (java.lang.Integer and java.lang.Double are in module java.base of loader 'bootstrap') at java.base/java.lang.Double.compareTo(Double.java:49) at java.base/java.util.TreeMap.put(TreeMap.java:566) at java.base/java.util.TreeSet.add(TreeSet.java:255) at java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352) at java.base/java.util.TreeSet.addAll(TreeSet.java:312) at effectivejava.chapter5.item31.Union.union(Union.java:12) at effectivejava.chapter5.item31.Union.main(Union.java:27) The problem seems to be in using TreeSet instead of HashSet, because there is apparently no natural sort order of types Number and Integer. But this would make me thing to never use of TreeSet/TreeMap in cases where generics are used, because the assumed freedom of types would turn to not work if an operation of the underlying data structure cannot be accomplished (in this case, the operation of sort, because of natural ordering in trees, which uses comparisons operators that could not be used for "any producer type", but only the same type). Is there way in Java to use generics as well as the features of specific data structures at the same time? Maybe, if I used this union method declaration: public static <E extends Comparable<? super E>> Set<E> union2( Set<? extends E> s1, Set<? extends E> s2 ) That would allow me to properly used trees and catch types that does not implement Comparable at compile time? A: In the signature <E> Set<E> union(Set<? extends E> s1, Set<? extends E> s2) s1 and s2 are of different types. <? extends E> and <? extends E> do not describe the same type, each wildcard will be bound to a different type at compile time. Furthermore, Integer implements Number, Comparable<Integer> and Double implements Number, Comparable<Double>. Number does not implement the Comparable interface. So constraining E to extend Comparable<E> won't help either, because there is no such E which is valid for both Integer and Double instances. Integers and doubles are not comparable with each other, thus cannot be managed within a single TreeSet unless you provide a custom Comparator implementation at construction time which is able to compare Numbers of any concrete type. Here would be one such comparator implementation: Comparator<Number> comparator = Comparator.comparingDouble(Number::doubleValue); But of course this means that your method cannot handle arbitrary objects anymore, only objects of classes which implement the Number interface. The widest interface of your function that you can provide is a method which takes two collections of Comparable<T> instances; but both collections must contain the same types: you cannot compare integers to strings, doubles to lists, nor maps to bigdecimals.
Effective Java 3: item 31: using for producers, is not applicable for different data structures
This code from the Item 31: public class Union { public static <E> Set<E> union(Set<? extends E> s1, Set<? extends E> s2) { // Bloch used HashSet, but I want natural ordering and still make freedom of producer type Set<E> result = new TreeSet<>(s1); result.addAll(s2); return result; } public static void main(String[] args) { Set<Integer> integers = new HashSet<>(); integers.add(1); integers.add(3); integers.add(5); Set<Double> doubles = new HashSet<>(); doubles.add(2.0); doubles.add(4.0); doubles.add(6.0); Set<Number> numbers = union(integers, doubles); System.out.println(numbers); } } Compiles, but gives runtime error: Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Double (java.lang.Integer and java.lang.Double are in module java.base of loader 'bootstrap') at java.base/java.lang.Double.compareTo(Double.java:49) at java.base/java.util.TreeMap.put(TreeMap.java:566) at java.base/java.util.TreeSet.add(TreeSet.java:255) at java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352) at java.base/java.util.TreeSet.addAll(TreeSet.java:312) at effectivejava.chapter5.item31.Union.union(Union.java:12) at effectivejava.chapter5.item31.Union.main(Union.java:27) The problem seems to be in using TreeSet instead of HashSet, because there is apparently no natural sort order of types Number and Integer. But this would make me thing to never use of TreeSet/TreeMap in cases where generics are used, because the assumed freedom of types would turn to not work if an operation of the underlying data structure cannot be accomplished (in this case, the operation of sort, because of natural ordering in trees, which uses comparisons operators that could not be used for "any producer type", but only the same type). Is there way in Java to use generics as well as the features of specific data structures at the same time? Maybe, if I used this union method declaration: public static <E extends Comparable<? super E>> Set<E> union2( Set<? extends E> s1, Set<? extends E> s2 ) That would allow me to properly used trees and catch types that does not implement Comparable at compile time?
[ "In the signature\n<E> Set<E> union(Set<? extends E> s1, Set<? extends E> s2)\n\ns1 and s2 are of different types. <? extends E> and <? extends E> do not describe the same type, each wildcard will be bound to a different type at compile time.\nFurthermore, Integer implements Number, Comparable<Integer> and Double implements Number, Comparable<Double>. Number does not implement the Comparable interface. So constraining E to extend Comparable<E> won't help either, because there is no such E which is valid for both Integer and Double instances.\nIntegers and doubles are not comparable with each other, thus cannot be managed within a single TreeSet unless you provide a custom Comparator implementation at construction time which is able to compare Numbers of any concrete type.\nHere would be one such comparator implementation:\nComparator<Number> comparator = Comparator.comparingDouble(Number::doubleValue);\n\nBut of course this means that your method cannot handle arbitrary objects anymore, only objects of classes which implement the Number interface. The widest interface of your function that you can provide is a method which takes two collections of Comparable<T> instances; but both collections must contain the same types: you cannot compare integers to strings, doubles to lists, nor maps to bigdecimals.\n" ]
[ 0 ]
[]
[]
[ "java", "natural_sort", "treeset" ]
stackoverflow_0074677862_java_natural_sort_treeset.txt
Q: Google Sheets App Script Custom Function Re-executing [![ function TEST_APP(ticker, token) { return [ticker+ticker] } ]1]1I have a custom function in Apps Script that is calling an external TD Ameritrade API. My understanding is that custom functions do not re-execute unless its input parameters change. However my custom function keeps executing every so often, sometimes every 10 mins sometimes every 60 mins or so without the input parameters changing. How do I fix this? I have created a token to send the custom function to have it invoke only when I change the input to refresh the data. However the function is executing on its own. A: Custom functions get re-evaluated from time to time, for example every time you open the spreadsheet. To execute the custom function less often, try invoking it like this: =lambda( ticker, token, TEST_APP(ticker, token) )(A1, A2) Alternatively, use the Cache Service, like this: function TEST_APP(ticker, token) { const cache = CacheService.getScriptCache(); const cacheKey = [ticker, token].join('→'); const cached = cache.get(cacheKey); if (cached) { return JSON.parse(cached); } const result = ticker + ticker; cache.put(cacheKey, JSON.stringify(result), 6 * 60 * 60); // 6 hours return result; }
Google Sheets App Script Custom Function Re-executing
[![ function TEST_APP(ticker, token) { return [ticker+ticker] } ]1]1I have a custom function in Apps Script that is calling an external TD Ameritrade API. My understanding is that custom functions do not re-execute unless its input parameters change. However my custom function keeps executing every so often, sometimes every 10 mins sometimes every 60 mins or so without the input parameters changing. How do I fix this? I have created a token to send the custom function to have it invoke only when I change the input to refresh the data. However the function is executing on its own.
[ "Custom functions get re-evaluated from time to time, for example every time you open the spreadsheet.\nTo execute the custom function less often, try invoking it like this:\n=lambda( \n ticker, token, \n TEST_APP(ticker, token) \n)(A1, A2)\n\nAlternatively, use the Cache Service, like this:\nfunction TEST_APP(ticker, token) {\n const cache = CacheService.getScriptCache();\n const cacheKey = [ticker, token].join('→');\n const cached = cache.get(cacheKey);\n if (cached) {\n return JSON.parse(cached);\n }\n const result = ticker + ticker;\n cache.put(cacheKey, JSON.stringify(result), 6 * 60 * 60); // 6 hours\n return result;\n}\n\n" ]
[ 0 ]
[]
[]
[ "custom_function", "google_apps_script", "google_sheets" ]
stackoverflow_0074672128_custom_function_google_apps_script_google_sheets.txt
Q: Voice Recognition for Android in Unity I am searching for a way to make Unity recognize user's speech in Android build. I've found a solution for Windows: youtube.com/watch?v=29vyEOgsW8s&t=612s, but I need it for Android. I don't need it to turn speech into text, I just want a small image to appear after the right pronounced word. Will appreciate any advice, thanks! I've already tried some stuff, but it didn't work, and I am also not really good in c#. Still, will be happy to receive any help. A: The video you've referenced uses Windows.Speech API, for Android you probably want to use the Android.Speech package. I don't know if it's still the case but you may need to add the following to the manifest file to make use of it: <intent> <action android:name="android.speech.RecognitionService" /> </intent> As for the Unity integration, unity does have a built-in Microphone class, or if you have access to Android packages: private const int Voice = 10; private string _recognizedText; private void Start() { // Check if the device supports speech recognition if (!Android.Speech.Recognition.IsRecognitionAvailable(this)) { Debug.LogError("Speech recognition is not available on this device!"); return; } // Create a new intent for speech recognition var intent = new Intent(RecognizerIntent.ActionRecognizeSpeech); // Set the language for the intent intent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default); // Start the activity for speech recognition StartActivityForResult(intent, Voice); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == Voice && resultCode == Result.Ok) { // Get the recognized text from the intent _recognizedText = data.GetStringExtra(RecognizerIntent.ExtraResultsRecognition); Debug.Log("Recognized text: " + _recognizedText); } }
Voice Recognition for Android in Unity
I am searching for a way to make Unity recognize user's speech in Android build. I've found a solution for Windows: youtube.com/watch?v=29vyEOgsW8s&t=612s, but I need it for Android. I don't need it to turn speech into text, I just want a small image to appear after the right pronounced word. Will appreciate any advice, thanks! I've already tried some stuff, but it didn't work, and I am also not really good in c#. Still, will be happy to receive any help.
[ "The video you've referenced uses Windows.Speech API, for Android you probably want to use the Android.Speech package. I don't know if it's still the case but you may need to add the following to the manifest file to make use of it:\n<intent>\n <action android:name=\"android.speech.RecognitionService\" />\n</intent>\n\nAs for the Unity integration, unity does have a built-in Microphone class, or if you have access to Android packages:\nprivate const int Voice = 10;\nprivate string _recognizedText;\n\nprivate void Start()\n{\n // Check if the device supports speech recognition\n if (!Android.Speech.Recognition.IsRecognitionAvailable(this))\n {\n Debug.LogError(\"Speech recognition is not available on this device!\");\n return;\n }\n\n // Create a new intent for speech recognition\n var intent = new Intent(RecognizerIntent.ActionRecognizeSpeech);\n // Set the language for the intent\n intent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default);\n // Start the activity for speech recognition\n StartActivityForResult(intent, Voice);\n}\n\nprotected override void OnActivityResult(int requestCode, Result resultCode, Intent data)\n{\n base.OnActivityResult(requestCode, resultCode, data);\n\n if (requestCode == Voice && resultCode == Result.Ok)\n {\n // Get the recognized text from the intent\n _recognizedText = data.GetStringExtra(RecognizerIntent.ExtraResultsRecognition);\n Debug.Log(\"Recognized text: \" + _recognizedText);\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "android_build", "c#", "unity3d", "unityscript", "voice_recognition" ]
stackoverflow_0074679383_android_build_c#_unity3d_unityscript_voice_recognition.txt
Q: How to append csv data as a ROW to another existing csv and move to 1st row. When i try to append all the data is at the bottom of the first column I have a csv with one row of data. It represents legacy headers that I am trying to append as 1 new row (or consider it as many columns) in a second csv. I need to compare the legacy header with the second csv's current headers, so after i append the data from the first csv i want to move it so that it's the first row too. The issue right now is that when i append my data from the first csv it just all goes to the bottom of the first column. See below for my code. How can i make it so that it takes the 1 row of data in my first csv and appends it to my second csv as ONE NEW ROW. After how would i move it so that it becomes the first row in my data (not as a header) with open('filewith1row.csv', 'r', encoding='utf8') as reader: with open('mainfile.csv', 'a', encoding='utf8') as writer: for line in reader: writer.write(line) Please help!! Thank you in advanced A: You could use pandas to import the csv files, combine the two, and then overwrite the original mainfile.csv. I have created some dummy data to demonstrate. Here are the test files that I used: mainfile.csv Fruit,Animals,Numbers Apple,Cat,5 Banana,Dog,8 Cherry,Goat,2 Durian,Horse,4 filewith1row.csv Fruta,Animales,Números This is the code that I used to combine the two CSVs. Code: import pandas as pd mainfile = pd.read_csv('mainfile.csv', header=None) one_liner = pd.read_csv('filewith1row.csv', header=None) mainfile.loc[0.5]=one_liner.loc[0] mainfile = mainfile.sort_index() mainfile.to_csv('mainfile.csv', index=False, header=False) Output: mainfile.csv Fruit,Animals,Numbers Fruta,Animales,Números Apple,Cat,5 Banana,Dog,8 Cherry,Goat,2 Durian,Horse,4 A: Combine the two files into a new one. cat hdr.csv first_col,second_col,third_col cat data.csv 1,2,3 4,5,6 7,8,9 with open('new_file.csv', 'w') as new_file: with open('hdr.csv') as hdr_file: new_file.write(hdr_file.read()) with open('data.csv') as data_file: new_file.write(data_file.read()) cat new_file.csv first_col,second_col,third_col 1,2,3 4,5,6 7,8,9
How to append csv data as a ROW to another existing csv and move to 1st row. When i try to append all the data is at the bottom of the first column
I have a csv with one row of data. It represents legacy headers that I am trying to append as 1 new row (or consider it as many columns) in a second csv. I need to compare the legacy header with the second csv's current headers, so after i append the data from the first csv i want to move it so that it's the first row too. The issue right now is that when i append my data from the first csv it just all goes to the bottom of the first column. See below for my code. How can i make it so that it takes the 1 row of data in my first csv and appends it to my second csv as ONE NEW ROW. After how would i move it so that it becomes the first row in my data (not as a header) with open('filewith1row.csv', 'r', encoding='utf8') as reader: with open('mainfile.csv', 'a', encoding='utf8') as writer: for line in reader: writer.write(line) Please help!! Thank you in advanced
[ "You could use pandas to import the csv files, combine the two, and then overwrite the original mainfile.csv.\nI have created some dummy data to demonstrate. Here are the test files that I used:\nmainfile.csv\nFruit,Animals,Numbers\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n\nfilewith1row.csv\nFruta,Animales,Números\n\n\nThis is the code that I used to combine the two CSVs.\nCode:\nimport pandas as pd\n\nmainfile = pd.read_csv('mainfile.csv', header=None)\none_liner = pd.read_csv('filewith1row.csv', header=None)\n\nmainfile.loc[0.5]=one_liner.loc[0]\nmainfile = mainfile.sort_index() \nmainfile.to_csv('mainfile.csv', index=False, header=False)\n\nOutput:\nmainfile.csv\nFruit,Animals,Numbers\nFruta,Animales,Números\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n\n", "Combine the two files into a new one.\ncat hdr.csv \nfirst_col,second_col,third_col\n\ncat data.csv \n1,2,3\n4,5,6\n7,8,9\n\n\nwith open('new_file.csv', 'w') as new_file:\n with open('hdr.csv') as hdr_file:\n new_file.write(hdr_file.read())\n with open('data.csv') as data_file:\n new_file.write(data_file.read())\n\ncat new_file.csv \nfirst_col,second_col,third_col\n1,2,3\n4,5,6\n7,8,9\n\n\n\n" ]
[ 1, 0 ]
[]
[]
[ "append", "csv", "python", "row" ]
stackoverflow_0074678018_append_csv_python_row.txt
Q: How to convert a number into words based on a dictionary? First, the user inputs a number. Then I want to print a word for each digit in the number. Which word is determined by a dictionary. When a digit is not in the dictionary, then I want the program to print "!". Here is an example of how the code should work: Enter numbers : 12345 Result: one two three ! ! Because 4 and 5 are not in Exist our dictionary, the program has to print "!". DictN= { '1':'one', '2':'two', '3':'three' } InpN = input('Enter Ur Number: ') for i,j in DictN.items(): for numb in InpN: if numb in i: print(j) else: print('!') MY WRONG OUTPUT one ! ! ! ! two ! ! ! ! three ! Process finished with exit code 0 A: # Consider the input as an int indata = input('Enter Ur Number: ') for x in indata: print(DictN.get(x,'!')) A: a dict works like this: # the alphabetical letters are the keys, and the numbers are the values which belong to the keys a = {'a': 1, 'b': 2} # if you want to have value from a it would be print(a.get('a')) # or print(a['a']) # which is in your example: DictN= { '1':'one', '2':'two', '3':'three' } InpN = input('Enter Ur Number: ') print(DictN[InpN]) in your example you could do something like this DictN= { '1':'one', '2':'two', '3':'three' } InpN = input('Enter Ur Number: ') for i in InpN: print(InpN[i], '!') by the way you would not use these variable names in Python. This source is good for best practices: https://peps.python.org/pep-0008/ https://python-reference.readthedocs.io/en/latest/docs/dict/get.html A: The solution to your problem can be programmed pretty much exactly how it's written in english, like this: DictN = { '1':'one', '2':'two', '3':'three' } InpN = input('Enter Ur Number: ') for i in InpN: if i in DictN: print(DictN[i]) else: print("!") gerrel93 explained how to retrieve data from a dictionary, and for many methods regarding iterables (objects such as strings and lists), dictionaries are treated as a list of their keys. The in keyword is one example of this. A: Since the other answers already show you how to use a dictionary, thought I'd demonstrate an alternative way of solving your problem. Would have written this as a comment, but I don't have enough reputation :) The hope is that this helps you learn about iterators and some neat builtins inp = input("Enter Ur Number: ") words = ["one", "two", "three"] dict_n = dict(zip(range(1, len(words) + 1), words)) print(" ".join([dict_n.get(int(n), "!") for n in inp])) Breaking it down >>> range(1, len(words)) # iterator range(1, 3) >>> dict(zip([1,2,3], [4,5,6])) # eg: zip elements of two iterators {1: 4, 2: 5, 3: 6} >>> dict(zip(range(1, len(words)), words)) {1: 'one', 2: 'two'} >>> [n for n in range(3)] # list comprehension [0, 1, 2] >>> " ".join(["1", "2", "3"]) '1 2 3' Hope the above block helps break it down :) A: The problem with your code is that you loop over the dictionary, and then check whether a certain value is in the input. You should do this in the reverse way: Loop over the input and then check whether aech digit is in the dictionary: DictN= { '1':'one', '2':'two', '3':'three' } InpN = input('Enter Ur Number: ') for digit in InpN: if digit in DictN: print(DictN[digit], end=" ") else: print("!", end=" ") print("") The output is the following: Enter Ur Number: 12345 one two three ! ! So, first we define the dictionary DicN and receive the input in InpN exactly as you did. Then we loop over the string we received as input. We do this because we want to print a single character for each digit. In the loop, we check for each digit whether it is in the dictionary. If it is, then we retreive the correct word from the dictionary. If it isn't, then we print !. Do also note that I used end=" " in the prints. This is because otherwise every word or ! would be printed on a new line. The end argument of the print function determines what value is added after the printed string. By default this is "\n", a newline. That's why I changed it to a space. But this does also mean that we have to place print() after the code, because otherwise the following print call would print its text on the same line. A: Alternative using map: DictN={'1':'one','2':'two','3':'three'} print(*map(lambda i:DictN.get(i,'!'),input('Enter Ur Number: ')),sep=' ') # Enter Ur Number: 12345 # one two three ! !
How to convert a number into words based on a dictionary?
First, the user inputs a number. Then I want to print a word for each digit in the number. Which word is determined by a dictionary. When a digit is not in the dictionary, then I want the program to print "!". Here is an example of how the code should work: Enter numbers : 12345 Result: one two three ! ! Because 4 and 5 are not in Exist our dictionary, the program has to print "!". DictN= { '1':'one', '2':'two', '3':'three' } InpN = input('Enter Ur Number: ') for i,j in DictN.items(): for numb in InpN: if numb in i: print(j) else: print('!') MY WRONG OUTPUT one ! ! ! ! two ! ! ! ! three ! Process finished with exit code 0
[ "# Consider the input as an int\nindata = input('Enter Ur Number: ')\n\nfor x in indata: print(DictN.get(x,'!'))\n\n", "a dict works like this:\n# the alphabetical letters are the keys, and the numbers are the values which belong to the keys\na = {'a': 1, 'b': 2}\n\n# if you want to have value from a it would be \nprint(a.get('a'))\n# or\nprint(a['a'])\n\n# which is in your example:\nDictN= {\n '1':'one',\n '2':'two',\n '3':'three'\n}\nInpN = input('Enter Ur Number: ')\nprint(DictN[InpN])\n\nin your example you could do something like this\nDictN= {\n '1':'one',\n '2':'two',\n '3':'three'\n}\nInpN = input('Enter Ur Number: ')\nfor i in InpN:\n print(InpN[i], '!')\n\nby the way you would not use these variable names in Python. This source is good for best practices:\nhttps://peps.python.org/pep-0008/\nhttps://python-reference.readthedocs.io/en/latest/docs/dict/get.html\n", "The solution to your problem can be programmed pretty much exactly how it's written in english, like this:\nDictN = {\n '1':'one',\n '2':'two',\n '3':'three'\n}\nInpN = input('Enter Ur Number: ')\n\nfor i in InpN:\n if i in DictN:\n print(DictN[i])\n else:\n print(\"!\")\n\ngerrel93 explained how to retrieve data from a dictionary, and for many methods regarding iterables (objects such as strings and lists), dictionaries are treated as a list of their keys. The in keyword is one example of this.\n", "Since the other answers already show you how to use a dictionary, thought I'd demonstrate an alternative way of solving your problem. Would have written this as a comment, but I don't have enough reputation :)\nThe hope is that this helps you learn about iterators and some neat builtins\ninp = input(\"Enter Ur Number: \")\n\nwords = [\"one\", \"two\", \"three\"]\ndict_n = dict(zip(range(1, len(words) + 1), words))\nprint(\" \".join([dict_n.get(int(n), \"!\") for n in inp]))\n\nBreaking it down\n>>> range(1, len(words)) # iterator\nrange(1, 3)\n\n>>> dict(zip([1,2,3], [4,5,6])) # eg: zip elements of two iterators\n{1: 4, 2: 5, 3: 6}\n\n>>> dict(zip(range(1, len(words)), words))\n{1: 'one', 2: 'two'}\n\n>>> [n for n in range(3)] # list comprehension\n[0, 1, 2]\n\n>>> \" \".join([\"1\", \"2\", \"3\"])\n'1 2 3'\n\nHope the above block helps break it down :)\n", "The problem with your code is that you loop over the dictionary, and then check whether a certain value is in the input. You should do this in the reverse way: Loop over the input and then check whether aech digit is in the dictionary:\nDictN= {\n '1':'one',\n '2':'two',\n '3':'three'\n}\nInpN = input('Enter Ur Number: ')\n\nfor digit in InpN:\n if digit in DictN:\n print(DictN[digit], end=\" \")\n else:\n print(\"!\", end=\" \")\nprint(\"\")\n\nThe output is the following:\nEnter Ur Number: 12345\none two three ! ! \n\nSo, first we define the dictionary DicN and receive the input in InpN exactly as you did. Then we loop over the string we received as input. We do this because we want to print a single character for each digit. In the loop, we check for each digit whether it is in the dictionary. If it is, then we retreive the correct word from the dictionary. If it isn't, then we print !.\nDo also note that I used end=\" \" in the prints. This is because otherwise every word or ! would be printed on a new line. The end argument of the print function determines what value is added after the printed string. By default this is \"\\n\", a newline. That's why I changed it to a space. But this does also mean that we have to place print() after the code, because otherwise the following print call would print its text on the same line.\n", "Alternative using map:\nDictN={'1':'one','2':'two','3':'three'}\nprint(*map(lambda i:DictN.get(i,'!'),input('Enter Ur Number: ')),sep=' ')\n\n# Enter Ur Number: 12345\n# one two three ! !\n\n" ]
[ 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074679274_python_python_3.x.txt
Q: Multiple conditional rendering im doing a TODO list and in this tag P i would like render the 3 differents type of priority what im doing wrong return always Low Priority: {value.priority === 1 ? ( hight ) : value.priority === 2 ? ( Medium ) : ( Low )}
Multiple conditional rendering
im doing a TODO list and in this tag P i would like render the 3 differents type of priority what im doing wrong return always Low Priority: {value.priority === 1 ? ( hight ) : value.priority === 2 ? ( Medium ) : ( Low )}
[]
[]
[ "Assuming you want to render a list of elements in an Array of objects (in this case TODO items) in order of priority on a page, you would need to first order your list and then sort it.\nSomething like this:\n\n\nconst unorderedArray = [\n { priority: 2, todo: 'finish homework', state: 'active' },\n { priority: 1, todo: 'answer this SO question', state: 'completed' }\n]\n\nconst orderedArray = unorderedArray.sort((a, b) => {\n return a.priority - b.priority\n})\n\nconsole.log(orderedArray)\n\n\n\nVariables a and b stand for items in the list, in this case item 1 and item 2. We are then asking to compare based on the property priority\nYou can read more on the sort function on w3schools site here.\n" ]
[ -1 ]
[ "reactjs" ]
stackoverflow_0074679080_reactjs.txt
Q: Selenium Webdriver not able to locate and click button I am trying to create a scraper, and for accessing the page I need to click on the Accept Cookies button. The HTML referring to the button is: <div class="qc-cmp2-summary-buttons"> <button mode="secondary" size="large" class=" css-1hy2vtq"> <span>MORE OPTIONS</span> </button><button mode="primary" size="large" class=" css-47sehv"> <span>AGREE</span></button></div> The button I want to click is the second one, named "AGREE". I tried: driver.find_element(By.CLASS_NAME, " css-47sehv").click() and I get error selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified A: The error you received caused by a space before the class name value. Spaces between class names are used to separate between multiple class names. So, to use this specific class name you could try this (without the space): driver.find_element(By.CLASS_NAME, "css-47sehv").click() But css-47sehv seems to be a dynamically generated class name so I'd advice to use more fixed attribute for locating that element. Try this locator instead: driver.find_element(By.XPATH, "//button[contains(.,'AGREE')]").click() To give you better answer we need to see that web page and all your Selenium code A: Try to use By.CSS_SELECTOR. Find element and copy its selector
Selenium Webdriver not able to locate and click button
I am trying to create a scraper, and for accessing the page I need to click on the Accept Cookies button. The HTML referring to the button is: <div class="qc-cmp2-summary-buttons"> <button mode="secondary" size="large" class=" css-1hy2vtq"> <span>MORE OPTIONS</span> </button><button mode="primary" size="large" class=" css-47sehv"> <span>AGREE</span></button></div> The button I want to click is the second one, named "AGREE". I tried: driver.find_element(By.CLASS_NAME, " css-47sehv").click() and I get error selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
[ "The error you received caused by a space before the class name value.\nSpaces between class names are used to separate between multiple class names.\nSo, to use this specific class name you could try this (without the space):\ndriver.find_element(By.CLASS_NAME, \"css-47sehv\").click()\n\nBut css-47sehv seems to be a dynamically generated class name so I'd advice to use more fixed attribute for locating that element.\nTry this locator instead:\ndriver.find_element(By.XPATH, \"//button[contains(.,'AGREE')]\").click()\n\nTo give you better answer we need to see that web page and all your Selenium code\n", "Try to use By.CSS_SELECTOR. Find element and copy its selector\n" ]
[ 1, 0 ]
[]
[]
[ "css_selectors", "python", "selenium_chromedriver", "selenium_webdriver", "xpath" ]
stackoverflow_0074679681_css_selectors_python_selenium_chromedriver_selenium_webdriver_xpath.txt
Q: How to scale an HTML canvas without blur? I'm developing a small browser game where the map size is 300x300. Hence, I set my HMTL canvas's width and height to 300x300. Then, when I want to spawn an object at the center, I spawn it at position 150, 150. Also, when doing physics calculations involving position and velocity, I am likewise using static units that work well within the 300x300 size. However, some users have tiny screens, or much larger screens, and I would like to scale the canvas size to accommodate them. However, if I change the actual canvas's resolution, then all my calculations are thrown off. 150x150 is no longer the center, and likewise objects move either faster or slower. As a result, it seems ideal to keep the canvas resolution to be 300x300 and then simply scale the size via CSS, like this: const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); canvas.style.width = "600px"; canvas.style.height = "600px"; ctx.fillStyle = 'red'; ctx.font = "600 48px Arial"; ctx.fillText("hello", 150, 150); canvas { border: 1px solid #333; } <canvas width="300" height="300"></canvas> However, the issue with this is that the screen is now blurry. Is there a way to both scale the screen size without it looking blurry in addition to being able to still just use static values like 150x150 to refer to the center? I can't post an answer to this since it was closed for whatever reason, but I believe the solution is the following: export function resize2DContext(context, canvasWidth, canvasHeight) { context.setTransform(1, 0, 0, 1, 0, 0); const canvas = context.canvas; const gameWidth = 600; // native game width const gameHeight = 600; // native game height canvas.style.width = canvasWidth + "px"; canvas.style.height = canvasHeight + "px"; canvas.width = canvasWidth; canvas.height = canvasHeight; context.scale(canvasWidth / gameWidth, canvasHeight / gameHeight); } And by handling input events like this: function handlePointerMove(e) { const xRatio = gameWidth / canvasWidth; const yRatio = gameHeight / canvasHeight; pointerX = e.offsetX * xRatio; pointerY = e.offsetY * yRatio; }
How to scale an HTML canvas without blur?
I'm developing a small browser game where the map size is 300x300. Hence, I set my HMTL canvas's width and height to 300x300. Then, when I want to spawn an object at the center, I spawn it at position 150, 150. Also, when doing physics calculations involving position and velocity, I am likewise using static units that work well within the 300x300 size. However, some users have tiny screens, or much larger screens, and I would like to scale the canvas size to accommodate them. However, if I change the actual canvas's resolution, then all my calculations are thrown off. 150x150 is no longer the center, and likewise objects move either faster or slower. As a result, it seems ideal to keep the canvas resolution to be 300x300 and then simply scale the size via CSS, like this: const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); canvas.style.width = "600px"; canvas.style.height = "600px"; ctx.fillStyle = 'red'; ctx.font = "600 48px Arial"; ctx.fillText("hello", 150, 150); canvas { border: 1px solid #333; } <canvas width="300" height="300"></canvas> However, the issue with this is that the screen is now blurry. Is there a way to both scale the screen size without it looking blurry in addition to being able to still just use static values like 150x150 to refer to the center? I can't post an answer to this since it was closed for whatever reason, but I believe the solution is the following: export function resize2DContext(context, canvasWidth, canvasHeight) { context.setTransform(1, 0, 0, 1, 0, 0); const canvas = context.canvas; const gameWidth = 600; // native game width const gameHeight = 600; // native game height canvas.style.width = canvasWidth + "px"; canvas.style.height = canvasHeight + "px"; canvas.width = canvasWidth; canvas.height = canvasHeight; context.scale(canvasWidth / gameWidth, canvasHeight / gameHeight); } And by handling input events like this: function handlePointerMove(e) { const xRatio = gameWidth / canvasWidth; const yRatio = gameHeight / canvasHeight; pointerX = e.offsetX * xRatio; pointerY = e.offsetY * yRatio; }
[]
[]
[ "You either want to use image-rendering: pixelated;\n\n\nconst canvas = document.querySelector(\"canvas\");\nconst ctx = canvas.getContext(\"2d\");\n\ncanvas.style.width = \"600px\";\ncanvas.style.height = \"600px\";\n\nctx.fillStyle = 'red';\n\nctx.font = \"600 48px Arial\";\nctx.fillText(\"hello\", 150, 150);\ncanvas {\n border: 1px solid #333;\n image-rendering: pixelated;\n}\n<canvas width=\"300\" height=\"300\"></canvas>\n\n\n\nOr scale your variables according to the screen size\n" ]
[ -1 ]
[ "html", "html5_canvas", "javascript", "scale" ]
stackoverflow_0074679726_html_html5_canvas_javascript_scale.txt
Q: CLIPBRD_E_CANT_OPEN error when setting the Clipboard from .NET Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN": Clipboard.SetText(str); This usually occurs the first time the Clipboard is used in the application and not after that. A: This is caused by a bug/feature in Terminal Services clipboard (and possible other things) and the .NET implementation of the clipboard. A delay in opening the clipboard causes the error, which usually passes within a few milliseconds. The solution is to try multiple times within a loop and sleep in between. for (int i = 0; i < 10; i++) { try { Clipboard.SetText(str); return; } catch { } System.Threading.Thread.Sleep(10); } A: Actually, I think this is the fault of the Win32 API. To set data in the clipboard, you have to open it first. Only one process can have the clipboard open at a time. So, when you check, if another process has the clipboard open for any reason, your attempt to open it will fail. It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you. The only solution is to wait until Terminal Services closes the clipboard and try again. It's important to realize that this is not specific to Terminal Services, though: it can happen with anything. Working with the clipboard in Win32 is a giant race condition. But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem. A: I know this question is old, but the problem still exists. As mentioned before, this exception occurs when the system clipboard is blocked by another process. Unfortunately, there are many snipping tools, programs for screenshots and file copy tools which can block the Windows clipboard. So you will get the exception every time you try to use Clipboard.SetText(str) when such a tool is installed on your PC. Solution: never use Clipboard.SetText(str); use instead Clipboard.SetDataObject(str); A: I solved this issue for my own app using native Win32 functions: OpenClipboard(), CloseClipboard() and SetClipboardData(). Below the wrapper class I made. Could anyone please review it and tell if it is correct or not. Especially when the managed code is running as x64 app (I use Any CPU in the project options). What happens when I link to x86 libraries from x64 app? Thank you! Here's the code: public static class ClipboardNative { [DllImport("user32.dll")] private static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll")] private static extern bool CloseClipboard(); [DllImport("user32.dll")] private static extern bool SetClipboardData(uint uFormat, IntPtr data); private const uint CF_UNICODETEXT = 13; public static bool CopyTextToClipboard(string text) { if (!OpenClipboard(IntPtr.Zero)){ return false; } var global = Marshal.StringToHGlobalUni(text); SetClipboardData(CF_UNICODETEXT, global); CloseClipboard(); //------------------------------------------- // Not sure, but it looks like we do not need // to free HGLOBAL because Clipboard is now // responsible for the copied data. (?) // // Otherwise the second call will crash // the app with a Win32 exception // inside OpenClipboard() function //------------------------------------------- // Marshal.FreeHGlobal(global); return true; } } A: Actually there could be another issue at hand. The framework call (both the WPF and winform flavors) to something like this (code is from reflector): private static void SetDataInternal(string format, object data) { bool flag; if (IsDataFormatAutoConvert(format)) { flag = true; } else { flag = false; } IDataObject obj2 = new DataObject(); obj2.SetData(format, data, flag); SetDataObject(obj2, true); } Note that SetDataObject is always called with true in this case. Internally that triggers two calls to the win32 api, one to set the data and one to flush it from your app so it's available after the app closes. I've seen several apps (some chrome plugin, and a download manager) that listen to the clipboard event. As soon as the first call hits, the app will open the clipboard to look into the data, and the second call to flush will fail. Haven't found a good solution except to write my own clipboard class that uses direct win32 API or to call setDataObject directly with false for keeping data after the app closes. A: Use the WinForms version (yes, there is no harm using WinForms in WPF applications), it handles everything you need: System.Windows.Forms.Clipboard.SetDataObject(yourText, true, 10, 100); This will attempt to copy yourText to the clipboard, it remains after your app exists, will attempt up to 10 times, and will wait 100ms between each attempt. Ref. https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.clipboard.setdataobject?view=netframework-4.7.2#System_Windows_Forms_Clipboard_SetDataObject_System_Object_System_Boolean_System_Int32_System_Int32_ A: This happen to me in my WPF application. I got OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN)). i use ApplicationCommands.Copy.Execute(null, myDataGrid); solution is to clear the clipboard first Clipboard.Clear(); ApplicationCommands.Copy.Execute(null, myDataGrid); A: The difference between Cliboard.SetText and Cliboard.SetDataObject in WPF is that the text is not copied to the clipboard, only the pointer. I checked the source code. If we call SetDataObject(data, true) Clipoard.Flush() will also be called. Thanks to this, text or data is available even after closing the application. I think Windows applications only call Flush() when they are shutting down. Thanks to this, it saves memory and at the same time gives access to data without an active application. Copy to clipboard: IDataObject CopyStringToClipboard(string s) { var dataObject = new DataObject(s); Clipboard.SetDataObject(dataObject, false); return dataObject; } Code when app or window is closed: try { if ((clipboardData != null) && Clipboard.IsCurrent(clipboardData)) Clipboard.Flush(); } catch (COMException ex) {} clipboardData is a window class field or static variable. A: That's not a solution, just some additional information on how to reproduce it when all solutions work on your PC and fail somewhere else. As mentioned in the accepted answer - clipboard can be busy by some other app. You just need to handle this failure properly, to explain user somehow why it does not work. So, just create a new console app with few lines below and run it. And while it is running - test your primary app on how it is handles busy clipboard: class Program { [DllImport("user32.dll")] private static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll")] private static extern bool CloseClipboard(); static void Main(string[] args) { bool res = OpenClipboard(IntPtr.Zero); Console.Write(res); Console.Read(); CloseClipboard(); } }
CLIPBRD_E_CANT_OPEN error when setting the Clipboard from .NET
Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN": Clipboard.SetText(str); This usually occurs the first time the Clipboard is used in the application and not after that.
[ "This is caused by a bug/feature in Terminal Services clipboard (and possible other things) and the .NET implementation of the clipboard. A delay in opening the clipboard causes the error, which usually passes within a few milliseconds.\nThe solution is to try multiple times within a loop and sleep in between.\nfor (int i = 0; i < 10; i++)\n{\n try\n {\n Clipboard.SetText(str);\n return;\n }\n catch { }\n System.Threading.Thread.Sleep(10);\n} \n\n", "Actually, I think this is the fault of the Win32 API.\nTo set data in the clipboard, you have to open it first. Only one process can have the clipboard open at a time. So, when you check, if another process has the clipboard open for any reason, your attempt to open it will fail.\nIt just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you. The only solution is to wait until Terminal Services closes the clipboard and try again.\nIt's important to realize that this is not specific to Terminal Services, though: it can happen with anything. Working with the clipboard in Win32 is a giant race condition. But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem.\n", "I know this question is old, but the problem still exists. As mentioned before, this exception occurs when the system clipboard is blocked by another process. Unfortunately, there are many snipping tools, programs for screenshots and file copy tools which can block the Windows clipboard. So you will get the exception every time you try to use Clipboard.SetText(str) when such a tool is installed on your PC.\nSolution:\nnever use\nClipboard.SetText(str);\n\nuse instead\nClipboard.SetDataObject(str);\n\n", "I solved this issue for my own app using native Win32 functions: OpenClipboard(), CloseClipboard() and SetClipboardData().\nBelow the wrapper class I made. Could anyone please review it and tell if it is correct or not. Especially when the managed code is running as x64 app (I use Any CPU in the project options). What happens when I link to x86 libraries from x64 app?\nThank you!\nHere's the code:\npublic static class ClipboardNative\n{\n [DllImport(\"user32.dll\")]\n private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"user32.dll\")]\n private static extern bool CloseClipboard();\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetClipboardData(uint uFormat, IntPtr data);\n\n private const uint CF_UNICODETEXT = 13;\n\n public static bool CopyTextToClipboard(string text)\n {\n if (!OpenClipboard(IntPtr.Zero)){\n return false;\n }\n\n var global = Marshal.StringToHGlobalUni(text);\n\n SetClipboardData(CF_UNICODETEXT, global);\n CloseClipboard();\n\n //-------------------------------------------\n // Not sure, but it looks like we do not need \n // to free HGLOBAL because Clipboard is now \n // responsible for the copied data. (?)\n //\n // Otherwise the second call will crash\n // the app with a Win32 exception \n // inside OpenClipboard() function\n //-------------------------------------------\n // Marshal.FreeHGlobal(global);\n\n return true;\n }\n}\n\n", "Actually there could be another issue at hand. The framework call (both the WPF and winform flavors) to something like this (code is from reflector):\nprivate static void SetDataInternal(string format, object data)\n{\n bool flag;\n if (IsDataFormatAutoConvert(format))\n {\n flag = true;\n }\n else\n {\n flag = false;\n }\n IDataObject obj2 = new DataObject();\n obj2.SetData(format, data, flag);\n SetDataObject(obj2, true);\n}\n\nNote that SetDataObject is always called with true in this case.\nInternally that triggers two calls to the win32 api, one to set the data and one to flush it from your app so it's available after the app closes.\nI've seen several apps (some chrome plugin, and a download manager) that listen to the clipboard event. As soon as the first call hits, the app will open the clipboard to look into the data, and the second call to flush will fail.\nHaven't found a good solution except to write my own clipboard class that uses direct win32 API or to call setDataObject directly with false for keeping data after the app closes.\n", "Use the WinForms version (yes, there is no harm using WinForms in WPF applications), it handles everything you need:\nSystem.Windows.Forms.Clipboard.SetDataObject(yourText, true, 10, 100);\n\nThis will attempt to copy yourText to the clipboard, it remains after your app exists, will attempt up to 10 times, and will wait 100ms between each attempt.\nRef. https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.clipboard.setdataobject?view=netframework-4.7.2#System_Windows_Forms_Clipboard_SetDataObject_System_Object_System_Boolean_System_Int32_System_Int32_\n", "This happen to me in my WPF application. I got OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN)).\ni use\nApplicationCommands.Copy.Execute(null, myDataGrid);\n\nsolution is to clear the clipboard first\nClipboard.Clear();\nApplicationCommands.Copy.Execute(null, myDataGrid);\n\n", "The difference between Cliboard.SetText and Cliboard.SetDataObject in WPF is that the text is not copied to the clipboard, only the pointer. I checked the source code. If we call SetDataObject(data, true) Clipoard.Flush() will also be called. Thanks to this, text or data is available even after closing the application. I think Windows applications only call Flush() when they are shutting down. Thanks to this, it saves memory and at the same time gives access to data without an active application.\nCopy to clipboard:\nIDataObject CopyStringToClipboard(string s)\n{\n var dataObject = new DataObject(s);\n Clipboard.SetDataObject(dataObject, false);\n return dataObject;\n}\n\nCode when app or window is closed:\ntry\n{\n if ((clipboardData != null) && Clipboard.IsCurrent(clipboardData))\n Clipboard.Flush();\n}\ncatch (COMException ex) {}\n\nclipboardData is a window class field or static variable.\n", "That's not a solution, just some additional information on how to reproduce it when all solutions work on your PC and fail somewhere else. As mentioned in the accepted answer - clipboard can be busy by some other app. You just need to handle this failure properly, to explain user somehow why it does not work.\nSo, just create a new console app with few lines below and run it. And while it is running - test your primary app on how it is handles busy clipboard:\nclass Program\n{\n [DllImport(\"user32.dll\")]\n private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"user32.dll\")]\n private static extern bool CloseClipboard();\n\n static void Main(string[] args)\n {\n bool res = OpenClipboard(IntPtr.Zero);\n Console.Write(res);\n Console.Read();\n CloseClipboard();\n }\n}\n\n" ]
[ 45, 42, 29, 11, 10, 2, 1, 0, 0 ]
[]
[]
[ ".net", "clipboard", "wpf" ]
stackoverflow_0000068666_.net_clipboard_wpf.txt
Q: How to run InitState() upon back button in flutter? I have a two pages, in one page, i open Hive box but when I navigate to second page, the dispose() method runs and closes the Hive box. but the problem is, when i click on 'Back' button, the initState doesnt rerun on the first page, so I couldn't open the box again through initState. here is the code on First page, @override initState() { super.initState(); Hive.openBox<boxModel>('customTable'); } @override void dispose() { Hive.close(); super.dispose(); } Here is the back in appbar in second page, AppBar( leadingWidth: 100, leading: IconButton( onPressed: () => Navigator.of(context).pop(), icon: Icon( Icons.arrow_back, color: AppTheme.colors.greyFontColor, ), ), backgroundColor: AppTheme.colors.appBarColor, elevation: 0, iconTheme: IconThemeData(color: AppTheme.colors.greyFontColor),) so is there a way to re run to the initState upon the back button pressed on second page. Thanks for any help.. A: # To run an InitState() method when the back button is pressed in Flutter, you can use the WillPopScope widget. This widget provides a callback that is called when the user presses the back button. You can use this callback to run the InitState() method. # Here's an example of how you can use the WillPopScope widget # to run the InitState() method when the back button is pressed: Copy code WillPopScope( onWillPop: () async { // Run your InitState() method here return true; }, child: Scaffold( // Your app's content goes here ), ); # In this example, the WillPopScope widget is a parent to the Scaffold widget, which is the root widget for the screen. The onWillPop callback is called when the user presses the back button, and it returns true to indicate that the back button press should be handled by the app. # You can use this approach to run the InitState() method when the back button is pressed, and to prevent the app from closing or navigating back to the previous screen. A: try (context as Element).reassemble(); try this snippet refresh and build widgets again in current screen flutter. Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) =>PreviousPage() ,)); for previous using navigator. A: I don't think that dispose runs when you push a new route, at least not as long as there is a back button to go back, but anyways if you just want to open the box again you can add this to your Navigator.push Navigator.of(context) .push(MaterialPageRoute( builder: (context) => SecondPage(), )).then((_) { Hive.openBox<boxModel>('customTable'); });
How to run InitState() upon back button in flutter?
I have a two pages, in one page, i open Hive box but when I navigate to second page, the dispose() method runs and closes the Hive box. but the problem is, when i click on 'Back' button, the initState doesnt rerun on the first page, so I couldn't open the box again through initState. here is the code on First page, @override initState() { super.initState(); Hive.openBox<boxModel>('customTable'); } @override void dispose() { Hive.close(); super.dispose(); } Here is the back in appbar in second page, AppBar( leadingWidth: 100, leading: IconButton( onPressed: () => Navigator.of(context).pop(), icon: Icon( Icons.arrow_back, color: AppTheme.colors.greyFontColor, ), ), backgroundColor: AppTheme.colors.appBarColor, elevation: 0, iconTheme: IconThemeData(color: AppTheme.colors.greyFontColor),) so is there a way to re run to the initState upon the back button pressed on second page. Thanks for any help..
[ "# To run an InitState() method when the back button is pressed in Flutter, you can use the WillPopScope widget. This widget provides a callback that is called when the user presses the back button. You can use this callback to run the InitState() method.\n\n# Here's an example of how you can use the WillPopScope widget \n# to run the InitState() method when the back button is pressed:\n\n\nCopy code\nWillPopScope(\n onWillPop: () async {\n // Run your InitState() method here\n return true;\n },\n child: Scaffold(\n // Your app's content goes here\n ),\n);\n\n# In this example, the WillPopScope widget is a parent to the Scaffold widget, which is the root widget for the screen. The onWillPop callback is called when the user presses the back button, and it returns true to indicate that the back button press should be handled by the app.\n\n# You can use this approach to run the InitState() method when the back button is pressed, and to prevent the app from closing or navigating back to the previous screen.\n\n", "try (context as Element).reassemble(); try this snippet refresh and build widgets again in current screen flutter.\nNavigator.pushReplacement(context, MaterialPageRoute(builder: (context) =>PreviousPage() ,)); for previous using navigator.\n", "I don't think that dispose runs when you push a new route, at least not as long as there is a back button to go back, but anyways if you just want to open the box again you can add this to your Navigator.push\nNavigator.of(context)\n.push(MaterialPageRoute(\n builder: (context) => SecondPage(),\n)).then((_) {\n Hive.openBox<boxModel>('customTable');\n});\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "android", "flutter", "flutter_dependencies", "flutter_widget" ]
stackoverflow_0074679067_android_flutter_flutter_dependencies_flutter_widget.txt
Q: What is the thing you do to space apart images? I tried everything but nothing works? emphasized text A: I would suppose, both images are under the same element, so what you can do, is add css to your parent element: display: flex; gap: 10px or you can choose one of the images and add css: margin-left: 10px or margin-right: 10px
What is the thing you do to space apart images?
I tried everything but nothing works? emphasized text
[ "I would suppose, both images are under the same element, so what you can do, is add css to your parent element:\ndisplay: flex;\ngap: 10px\n\nor you can choose one of the images and add css:\nmargin-left: 10px\n\nor\nmargin-right: 10px\n\n" ]
[ 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074679706_css_html.txt
Q: why form.is_valid() is always false? I tried to create a contact us form in django but i got always false when i want to use .is_valid() function. this is my form: from django import forms from django.core import validators class ContactForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خود را وارد کنید'}), label="نام ", validators=[ validators.MaxLengthValidator(100, "نام شما نمیتواند بیش از 100 کاراکتر باشد")]) last_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خانوادگی خود را وارد کنید'}), label="نام خانوادگی", validators=[ validators.MaxLengthValidator(100, "نام خانوادگی شما نمیتواند بیش از 100 کاراکتر باشد")]) email = forms.EmailField( widget=forms.EmailInput( attrs={'placeholder': 'ایمیل خود را وارد کنید'}), label="ایمیل", validators=[ validators.MaxLengthValidator(200, "تعداد کاراکترهایایمیل شما نمیتواند بیش از ۲۰۰ کاراکتر باشد.") ]) title = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'عنوان پیام خود را وارد کنید'}), label="عنوان", validators=[ validators.MaxLengthValidator(250, "تعداد کاراکترهای شما نمیتواند بیش از 250 کاراکتر باشد.") ]) text = forms.CharField( widget=forms.Textarea( attrs={'placeholder': 'متن پیام خود را وارد کنید'}), label="متن پیام", ) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__() for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form_field require' this is my view: from django.shortcuts import render from .forms import ContactForm from .models import ContactUs def contact_us(request): contact_form = ContactForm(request.POST or None) if contact_form.is_valid(): first_name = contact_form.cleaned_data.get('first_name') last_name = contact_form.cleaned_data.get('last_name') email = contact_form.cleaned_data.get('email') title = contact_form.cleaned_data.get('title') text = contact_form.cleaned_data.get('text') ContactUs.objects.create(first_name=first_name, last_name=last_name, email=email, title=title, text=text) # todo: show user success message contact_form = ContactForm() context = { 'form': contact_form } return render(request, 'contact_us/contact_us.html', context) ** this is the codes in template** <form action="{% url 'contact' %}" id="contactform" method="post"> {% csrf_token %} <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ form.first_name }} {% for error in form.first_name.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ form.last_name }} {% for error in form.last_name.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ form.email }} {% for error in form.email.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ form.title }} {% for error in form.title.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> <div class="col-md-12 col-lg-12"> <div class="form_block"> {{ form.text }} {% for error in form.text.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} <div class="response"></div> </div> </div> <div class="col-md-12 col-lg-12"> <div class="form_block"> <button type="submit" class="clv_btn submitForm" data-type="contact">ارسال </button> </div> </div> </form> A: you can use CBVs to easily save data on form valid views.py from django.views import generic class ContactCreateView(generic.CreateView,): model = Contact fields = "__all__" success_url = reverse_lazy(url_name) then in in your templates templates/contact_form.html <form action="{% url 'contact' %}" id="contactform" method="post"> {% csrf_token %} {% for formfield in form %} <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ formfield}} {% for error in formfield.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> #add submit button here urls.py just remember to add as_view() when calling your view in url path("", views.ContactCreateView.as_view(), name="contact"), or using FBV you could try: def contact_us(request): contact_form = ContactForm(request.POST or None) if contact_form.is_valid(): contact_form.save() context = { 'form': contact_form } return render(request, 'contact_us/contact_us.html', context) A: Remove these lines from your forms.py: def __init__(self, *args, **kwargs): super(ContactForm, self).__init__() for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form_field require' Fix your view based on documentation: def contact_us(request): if request.method == 'POST': contact_form = ContactForm(request.POST) if contact_form.is_valid(): ContactUs.objects.create(**contact_form.cleaned_data) messages.success(request, 'My success message') # you want to send to your home return redirect('/contact') else: contact_form = ContactForm() context = { 'form': contact_form } return render(request, 'contact_us.html', context) I took the liberty to clean up your view by using **kwargs since you have many fields. Used Django messages to display successful message on obj creation. Here is how to display it.
why form.is_valid() is always false?
I tried to create a contact us form in django but i got always false when i want to use .is_valid() function. this is my form: from django import forms from django.core import validators class ContactForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خود را وارد کنید'}), label="نام ", validators=[ validators.MaxLengthValidator(100, "نام شما نمیتواند بیش از 100 کاراکتر باشد")]) last_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خانوادگی خود را وارد کنید'}), label="نام خانوادگی", validators=[ validators.MaxLengthValidator(100, "نام خانوادگی شما نمیتواند بیش از 100 کاراکتر باشد")]) email = forms.EmailField( widget=forms.EmailInput( attrs={'placeholder': 'ایمیل خود را وارد کنید'}), label="ایمیل", validators=[ validators.MaxLengthValidator(200, "تعداد کاراکترهایایمیل شما نمیتواند بیش از ۲۰۰ کاراکتر باشد.") ]) title = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'عنوان پیام خود را وارد کنید'}), label="عنوان", validators=[ validators.MaxLengthValidator(250, "تعداد کاراکترهای شما نمیتواند بیش از 250 کاراکتر باشد.") ]) text = forms.CharField( widget=forms.Textarea( attrs={'placeholder': 'متن پیام خود را وارد کنید'}), label="متن پیام", ) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__() for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form_field require' this is my view: from django.shortcuts import render from .forms import ContactForm from .models import ContactUs def contact_us(request): contact_form = ContactForm(request.POST or None) if contact_form.is_valid(): first_name = contact_form.cleaned_data.get('first_name') last_name = contact_form.cleaned_data.get('last_name') email = contact_form.cleaned_data.get('email') title = contact_form.cleaned_data.get('title') text = contact_form.cleaned_data.get('text') ContactUs.objects.create(first_name=first_name, last_name=last_name, email=email, title=title, text=text) # todo: show user success message contact_form = ContactForm() context = { 'form': contact_form } return render(request, 'contact_us/contact_us.html', context) ** this is the codes in template** <form action="{% url 'contact' %}" id="contactform" method="post"> {% csrf_token %} <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ form.first_name }} {% for error in form.first_name.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ form.last_name }} {% for error in form.last_name.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ form.email }} {% for error in form.email.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> <div class="col-md-6 col-lg-6"> <div class="form_block"> {{ form.title }} {% for error in form.title.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} </div> </div> <div class="col-md-12 col-lg-12"> <div class="form_block"> {{ form.text }} {% for error in form.text.errors %} <p class="text-danger">{{ error }}</p> {% endfor %} <div class="response"></div> </div> </div> <div class="col-md-12 col-lg-12"> <div class="form_block"> <button type="submit" class="clv_btn submitForm" data-type="contact">ارسال </button> </div> </div> </form>
[ "you can use CBVs to easily save data on form valid\n\nviews.py\n\nfrom django.views import generic\n\nclass ContactCreateView(generic.CreateView,):\n model = Contact\n fields = \"__all__\" \n success_url = reverse_lazy(url_name)\n\nthen in in your templates\n\ntemplates/contact_form.html\n\n\n<form action=\"{% url 'contact' %}\" id=\"contactform\" method=\"post\">\n {% csrf_token %}\n {% for formfield in form %}\n <div class=\"col-md-6 col-lg-6\">\n <div class=\"form_block\">\n {{ formfield}}\n {% for error in formfield.errors %}\n <p class=\"text-danger\">{{ error }}</p>\n {% endfor %}\n </div>\n </div>\n#add submit button here\n\n\n\nurls.py\njust remember to add as_view() when calling your view in url\n\n path(\"\", views.ContactCreateView.as_view(), name=\"contact\"),\n\nor using FBV you could try:\ndef contact_us(request):\n contact_form = ContactForm(request.POST or None)\n if contact_form.is_valid():\n contact_form.save()\n \n \n context = {\n 'form': contact_form\n }\n\n return render(request, 'contact_us/contact_us.html', context)\n\n\n\n", "Remove these lines from your forms.py:\n def __init__(self, *args, **kwargs):\n super(ContactForm, self).__init__()\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'form_field require'\n\nFix your view based on documentation:\ndef contact_us(request):\n if request.method == 'POST':\n contact_form = ContactForm(request.POST)\n if contact_form.is_valid():\n ContactUs.objects.create(**contact_form.cleaned_data)\n messages.success(request, 'My success message')\n # you want to send to your home\n return redirect('/contact')\n\n else:\n contact_form = ContactForm()\n context = {\n 'form': contact_form\n }\n\n return render(request, 'contact_us.html', context)\n\nI took the liberty to clean up your view by using **kwargs since you have many fields. Used Django messages to display successful message on obj creation. Here is how to display it.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074677222_django_python.txt
Q: Issues creating basic password system in python I need to create a basic password system that reads from a text file for a school project, however I can't get new passwords and usernames to append into a text file and with my current system I have the problem that any account can be accessed with any preexisting password. I've tried a couple different ways of trying to write into the text file however none have worked so far. Here is the code I have written so far: def login(): createusername = '' createuserpass = '' with open('password.txt') as f: passfile = [(passfile.strip()) for passfile in f.readlines()] with open('username.txt') as g: userpass = [(userpass.strip()) for userpass in g.readlines()] def createnewusername(): createusername = input("Enter a new username: ") return(createusername) def createuserpassword(): createuserpass = input("Enter a new password: ") return(createuserpass) haveusername = input("Do you have a login? Enter yes for yes, Enter no for no: ") if haveusername == "yes": username = input("Enter your username: ") password = input("Enter your password: ") if username in userpass: if password in passfile: print("Login in succesful. ""Logged into the account: " + username) else: print("incorrect password - restarting") login() else: print("incorrect username - restarting") login() elif haveusername == "no": wantlogin = input("Do you want to create a login? Enter yes for yes, Enter no for no: ") if wantlogin == "yes": createnewusername() print(userpass) if createusername in userpass: print("This username already exists - restarting") login() else: createuserpassword() if createuserpass in passfile: print("This password already exists - restarting") login() else: #Start of part that doesnt work with open("password.txt","a") as passcreation: passcreation.write(createuserpass) passcreation.write('\n') with open("username.txt","a") as namecreation: namecreation.write(createusername) namecreation.write('\n') #End of part that doesnt work print("Restarting - Please enter your new login") login() elif wantlogin == "no": print("Okay - restarting") login() else: print("Login not created - restarting") login() else: print("Invalid input - restarting") test = 1 if test == 1: login() A: This is not an answer to the question yet. It is a suggestion on how to monitor state changes for the files, since that seems to be the main issue. Added code to create the initial files. Added a function to be called before and after desired state changes. # Initialize the files print('*' * 20, 'passwords.txt', '*' * 20) with open('passwords.txt','w') as f: header = '*' * 20 + 'passwords.txt' + '*' * 20 f.write(header) with open('usernames.txt','w') as f: header = '*' * 20 + 'usernames.txt' + '*' * 20 f.write(header) def report_files(): """This function is used to look at the files before and after change""" with open('passwords.txt') as f: print(f.readlines()) with open('usernames.txt') as f: print(f.readlines()) def login(): createusername = '' createuserpass = '' with open('password.txt') as f: passfile = [(passfile.strip()) for passfile in f.readlines()] with open('username.txt') as g: userpass = [(userpass.strip()) for userpass in g.readlines()] def createnewusername(): createusername = input("Enter a new username: ") return createusername def createuserpassword(): createuserpass = input("Enter a new password: ") return createuserpass haveusername = input( "Do you have a login? Enter yes for yes, Enter no for no: ") if haveusername == "yes": username = input("Enter your username: ") password = input("Enter your password: ") report_files() # monitor state if username in userpass: if password in passfile: print( "Login in succesful. ""Logged into the account: " + username) else: print("incorrect password - restarting") login() else: print("incorrect username - restarting") login() elif haveusername == "no": wantlogin = input( "Do you want to create a login? Enter yes for yes, Enter no for no: ") if wantlogin == "yes": report_files() print(userpass) if createusername in userpass: print("This username already exists - restarting") login() else: createuserpassword() if createuserpass in passfile: print("This password already exists - restarting") login() else: # Start of part that doesnt work with open("password.txt", "a") as passcreation: passcreation.write(createuserpass) passcreation.write('\n') with open("username.txt", "a") as namecreation: namecreation.write(createusername) namecreation.write('\n') # End of part that doesnt work print("Restarting - Please enter your new login") login() report_files() createnewusername() elif wantlogin == "no": print("Okay - restarting") login() else: print("Login not created - restarting") login() else: print("Invalid input - restarting") test = 1 if test == 1: login()
Issues creating basic password system in python
I need to create a basic password system that reads from a text file for a school project, however I can't get new passwords and usernames to append into a text file and with my current system I have the problem that any account can be accessed with any preexisting password. I've tried a couple different ways of trying to write into the text file however none have worked so far. Here is the code I have written so far: def login(): createusername = '' createuserpass = '' with open('password.txt') as f: passfile = [(passfile.strip()) for passfile in f.readlines()] with open('username.txt') as g: userpass = [(userpass.strip()) for userpass in g.readlines()] def createnewusername(): createusername = input("Enter a new username: ") return(createusername) def createuserpassword(): createuserpass = input("Enter a new password: ") return(createuserpass) haveusername = input("Do you have a login? Enter yes for yes, Enter no for no: ") if haveusername == "yes": username = input("Enter your username: ") password = input("Enter your password: ") if username in userpass: if password in passfile: print("Login in succesful. ""Logged into the account: " + username) else: print("incorrect password - restarting") login() else: print("incorrect username - restarting") login() elif haveusername == "no": wantlogin = input("Do you want to create a login? Enter yes for yes, Enter no for no: ") if wantlogin == "yes": createnewusername() print(userpass) if createusername in userpass: print("This username already exists - restarting") login() else: createuserpassword() if createuserpass in passfile: print("This password already exists - restarting") login() else: #Start of part that doesnt work with open("password.txt","a") as passcreation: passcreation.write(createuserpass) passcreation.write('\n') with open("username.txt","a") as namecreation: namecreation.write(createusername) namecreation.write('\n') #End of part that doesnt work print("Restarting - Please enter your new login") login() elif wantlogin == "no": print("Okay - restarting") login() else: print("Login not created - restarting") login() else: print("Invalid input - restarting") test = 1 if test == 1: login()
[ "This is not an answer to the question yet.\nIt is a suggestion on how to monitor state changes for the files, since that\nseems to be the main issue.\nAdded code to create the initial files.\nAdded a function to be called before and after desired state changes.\n# Initialize the files\nprint('*' * 20, 'passwords.txt', '*' * 20)\nwith open('passwords.txt','w') as f:\n header = '*' * 20 + 'passwords.txt' + '*' * 20\n f.write(header)\nwith open('usernames.txt','w') as f:\n header = '*' * 20 + 'usernames.txt' + '*' * 20\n f.write(header)\n\n\ndef report_files():\n \"\"\"This function is used to look at the files before and after change\"\"\"\n with open('passwords.txt') as f:\n print(f.readlines())\n with open('usernames.txt') as f:\n print(f.readlines())\n\n\ndef login():\n createusername = ''\n createuserpass = ''\n\n with open('password.txt') as f:\n passfile = [(passfile.strip()) for passfile in f.readlines()]\n\n with open('username.txt') as g:\n userpass = [(userpass.strip()) for userpass in g.readlines()]\n\n def createnewusername():\n createusername = input(\"Enter a new username: \")\n return createusername\n\n def createuserpassword():\n createuserpass = input(\"Enter a new password: \")\n return createuserpass\n\n haveusername = input(\n \"Do you have a login? Enter yes for yes, Enter no for no: \")\n if haveusername == \"yes\":\n username = input(\"Enter your username: \")\n password = input(\"Enter your password: \")\n report_files() # monitor state\n if username in userpass:\n if password in passfile:\n print(\n \"Login in succesful. \"\"Logged into the account: \" + username)\n else:\n print(\"incorrect password - restarting\")\n login()\n else:\n print(\"incorrect username - restarting\")\n login()\n elif haveusername == \"no\":\n wantlogin = input(\n \"Do you want to create a login? Enter yes for yes, Enter no for no: \")\n if wantlogin == \"yes\":\n report_files()\n print(userpass)\n if createusername in userpass:\n print(\"This username already exists - restarting\")\n login()\n else:\n createuserpassword()\n if createuserpass in passfile:\n print(\"This password already exists - restarting\")\n login()\n else:\n # Start of part that doesnt work\n with open(\"password.txt\", \"a\") as passcreation:\n passcreation.write(createuserpass)\n passcreation.write('\\n')\n with open(\"username.txt\", \"a\") as namecreation:\n namecreation.write(createusername)\n namecreation.write('\\n')\n # End of part that doesnt work\n print(\"Restarting - Please enter your new login\")\n login()\n report_files()\n createnewusername()\n elif wantlogin == \"no\":\n print(\"Okay - restarting\")\n login()\n else:\n print(\"Login not created - restarting\")\n login()\n else:\n print(\"Invalid input - restarting\")\n\n\ntest = 1\nif test == 1:\n login()\n\n" ]
[ 0 ]
[]
[]
[ "passwords", "python", "text_files" ]
stackoverflow_0074679154_passwords_python_text_files.txt
Q: Python Dataframe Split the list into 2 columns on a single space Im looking for help Splitting this list into 2 columns. The split needs to happen between the two words inside the comas. [JJL108995.161270128.23630-02.YF.JABI , NORMAL ROTATION MODE , +27.0 DARKNESS , 8 IPS PRINT SPEED , 8 IPS SLEW SPEED , 2 IPS BACKFEED SPEED , +040 TEAR OFF , APPLICATOR PRINT MODE , MODE 2 APPLICATOR PORT , PULSE MODE START PRINT SIG , NON-CONTINUOUS MEDIA TYPE , WEB SENSOR TYPE , DIRECT-THERMAL PRINT METHOD , 1200 PRINT WIDTH , 1877 LABEL LENGTH , 8.0IN 202MM MAXIMUM LENGTH , MEDIA DISABLED EARLY WARNING , MAINT. OFF EARLY WARNING , NOT CONNECTED USB COMM. , READY EXTERNAL 5V , BIDIRECTIONAL PARALLEL COMM. , RS232 SERIAL COMM. , 9600 BAUD , 8 BITS DATA BITS , NONE PARITY , XON/XOFF HOST HANDSHAKE , NONE PROTOCOL , 000 NETWORK ID , NORMAL MODE COMMUNICATIONS , <~> 7EH CONTROL PREFIX , <^> 5EH FORMAT PREFIX , <,> 2CH DELIMITER CHAR , ZPL II ZPL MODE , INACTIVE COMMAND OVERRIDE , HIGH RIBBON TENSION , NO MOTION MEDIA POWER UP , LENGTH HEAD CLOSE , AFTER BACKFEED , +000 LABEL TOP , +0020 LEFT POSITION , 1486 HEAD RESISTOR , ENABLED ERROR ON PAUSE , DISABLED RIBBON LOW MODE , ACTIVE HIGH RIB LOW OUTPUT , DISABLED REPRINT MODE , 076 WEB S. , 079 MEDIA S. , 065 RIBBON S. , 025 MARK S. , 025 MARK MED S. , 103 TRANS GAIN , 025 TRANS BASE , 196 TRANS BRIGHT , 181 RIBBON GAIN , 000 MARK GAIN , DPCSWFX. MODES ENABLED , .......M MODES DISABLED , 1248 12/MM FULL RESOLUTION , SP53-004402C <- FIRMWARE , 1.3 XML SCHEMA , V52 ---------- 19 HARDWARE ID , CUSTOMIZED CONFIGURATION , 9560k............R: RAM , 59392k...........E: ONBOARD FLASH , NONE FORMAT CONVERT , 021 PAX170 RTS P32 INTERFACE , 015 POWER SUPPLY P33 INTERFACE , *** APPLICATOR P34 INTERFACE , FW VERSION IDLE DISPLAY , 10/03/19 RTC DATE , 22:40 RTC TIME , DISABLED ZBI , 2.1 ZBI VERSION , 110,222,932 IN NONRESET CNTR , 110,222,932 IN RESET CNTR1 , 110,222,932 IN RESET CNTR2 , 279,990,514 CM NONRESET CNTR , 279,990,514 CM RESET CNTR1 , 279,990,514 CM RESET CNTR2 , ALL ITEMS PASSWORD LEVEL] Here is how im looking to split it: A: I went about it a different way . turns out the pre element can be predictable in length. import pandas as pd import requests from bs4 import BeautifulSoup as bs r = requests.get('LINK') soup = bs(r.content, 'lxml') pre = soup.select_one('pre').text results = [] for line in pre.split('\n')[1:-1]: if '--' not in line: row = [line[i:i+20].strip() for i in range(0, len(line), 22)] results.append(row) df = pd.DataFrame(results) print(df)
Python Dataframe Split the list into 2 columns on a single space
Im looking for help Splitting this list into 2 columns. The split needs to happen between the two words inside the comas. [JJL108995.161270128.23630-02.YF.JABI , NORMAL ROTATION MODE , +27.0 DARKNESS , 8 IPS PRINT SPEED , 8 IPS SLEW SPEED , 2 IPS BACKFEED SPEED , +040 TEAR OFF , APPLICATOR PRINT MODE , MODE 2 APPLICATOR PORT , PULSE MODE START PRINT SIG , NON-CONTINUOUS MEDIA TYPE , WEB SENSOR TYPE , DIRECT-THERMAL PRINT METHOD , 1200 PRINT WIDTH , 1877 LABEL LENGTH , 8.0IN 202MM MAXIMUM LENGTH , MEDIA DISABLED EARLY WARNING , MAINT. OFF EARLY WARNING , NOT CONNECTED USB COMM. , READY EXTERNAL 5V , BIDIRECTIONAL PARALLEL COMM. , RS232 SERIAL COMM. , 9600 BAUD , 8 BITS DATA BITS , NONE PARITY , XON/XOFF HOST HANDSHAKE , NONE PROTOCOL , 000 NETWORK ID , NORMAL MODE COMMUNICATIONS , <~> 7EH CONTROL PREFIX , <^> 5EH FORMAT PREFIX , <,> 2CH DELIMITER CHAR , ZPL II ZPL MODE , INACTIVE COMMAND OVERRIDE , HIGH RIBBON TENSION , NO MOTION MEDIA POWER UP , LENGTH HEAD CLOSE , AFTER BACKFEED , +000 LABEL TOP , +0020 LEFT POSITION , 1486 HEAD RESISTOR , ENABLED ERROR ON PAUSE , DISABLED RIBBON LOW MODE , ACTIVE HIGH RIB LOW OUTPUT , DISABLED REPRINT MODE , 076 WEB S. , 079 MEDIA S. , 065 RIBBON S. , 025 MARK S. , 025 MARK MED S. , 103 TRANS GAIN , 025 TRANS BASE , 196 TRANS BRIGHT , 181 RIBBON GAIN , 000 MARK GAIN , DPCSWFX. MODES ENABLED , .......M MODES DISABLED , 1248 12/MM FULL RESOLUTION , SP53-004402C <- FIRMWARE , 1.3 XML SCHEMA , V52 ---------- 19 HARDWARE ID , CUSTOMIZED CONFIGURATION , 9560k............R: RAM , 59392k...........E: ONBOARD FLASH , NONE FORMAT CONVERT , 021 PAX170 RTS P32 INTERFACE , 015 POWER SUPPLY P33 INTERFACE , *** APPLICATOR P34 INTERFACE , FW VERSION IDLE DISPLAY , 10/03/19 RTC DATE , 22:40 RTC TIME , DISABLED ZBI , 2.1 ZBI VERSION , 110,222,932 IN NONRESET CNTR , 110,222,932 IN RESET CNTR1 , 110,222,932 IN RESET CNTR2 , 279,990,514 CM NONRESET CNTR , 279,990,514 CM RESET CNTR1 , 279,990,514 CM RESET CNTR2 , ALL ITEMS PASSWORD LEVEL] Here is how im looking to split it:
[ "I went about it a different way . turns out the pre element can be predictable in length.\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup as bs\n \nr = requests.get('LINK')\nsoup = bs(r.content, 'lxml')\npre = soup.select_one('pre').text\nresults = []\n \nfor line in pre.split('\\n')[1:-1]:\n if '--' not in line:\n row = [line[i:i+20].strip() for i in range(0, len(line), 22)]\n results.append(row)\n \n df = pd.DataFrame(results)\n print(df)\n\n" ]
[ 0 ]
[]
[]
[ "mysql", "pandas", "parsing", "python", "selenium" ]
stackoverflow_0074679276_mysql_pandas_parsing_python_selenium.txt
Q: When number is not found in array it does not give me the desired output Below code finds the desired key in array and prints it but when key is not found, I expect the search return -1 and print "Key not found." But this is not printed. Is there a mistake? #include<stdio.h> int binarySearch(int* arr, int size, int key){ int low=0; int high=size-1; int mid=(low+high)/2; while(arr[mid]!=key){ if(key>arr[mid]){ low=mid+1; mid=(low+high)/2; } if(key<arr[mid]){ low=0; high=mid-1; mid=(low+high)/2; } if(key==arr[mid]){ return mid; } } } int main(){ int intArr[10]={4,5,12,44,232,326,654,776,987,999}; int res=binarySearch(intArr, 10, 1); if(res){ printf("Key found at index: %d.", res); }else ("Key not found."); } Note: I made a mistake on syntax of this part. I corrected. this else ("Key not found."); to else (printf("Key not found.\n")); It is working as intended after this correction. I also added @weatherwane' s suggestion and @poepew's suggestions. Here is the working code: #include<stdio.h> int binarySearch(int* arr, int size, int key){ int low=0; int high=size-1; int mid=(low+high)/2; while(high-low>0){ if(key>arr[mid]){ low=mid+1; mid=(low+high)/2; } if(key<arr[mid]){ low=0; high=mid-1; mid=(low+high)/2; } if(key==arr[mid]){ return mid; } } return -1; } int main(){ int intArr[10]={4,5,12,44,232,326,654,776,987,999}; int res=binarySearch(intArr, 10, 43); if(res>=0){ printf("Key found at index: %d.\n", res); } else (printf("Key not found.\n")); } A: This problem occurs because you do not have a return statement for the so called 'not found' case. After your while statement add a return -1 case. #include<stdio.h> int binarySearch(int* arr, int size, int key){ int low=0; int high=size-1; int mid=(low+high)/2; int i = 0; while(arr[mid]!=key ){ i = mid; if(key>arr[mid]){ low=mid+1; mid=(low+high)/2; } if(key<arr[mid]){ low=0; high=mid-1; mid=(low+high)/2; } if(key==arr[mid]){ return mid; } if(i == mid){ return -1; } } return -1; } int main(){ int intArr[10]={4,5,12,44,232,326,654,776,987,999}; int res=binarySearch(intArr, 10, 99); typeof(res); if(res){ printf("Key found at index: %d.", res); } else { printf("Key not found"); } } EDIT: Also there was an infinite loop caused by the while loop, in order for the while loop presented in the question arr[mid] should not be equal to the key. which if the array does not contain the wanted element results in infinite loop. The solution I have added is to check if the new mid value is added or not. it is set to the initial value at the start of the loop and if it is not muted, it returns -1. A: Your implementation of an iterative bsearch using the test while (arr[mid] != key), is a bit awkward compared to the normal loop condition of while (low <= high), but you can write it this way. You have three exit conditions to protect against: key is less than 1st element in array, key is greater than last element in array, and key is within the range of 1st - last, but not present in the array. The primary error in your logic is you only adjust low if key > arr[mid], and you only adjust high if key < arr[mid]. You never adjust both in response to a condition. Putting it altogether, you would edit your approach and do: int binarySearch (int *arr, int size, int key) { int low = 0, high = size - 1, mid; while (arr[mid] != key) { /* loop while key not found */ if (low > high) { /* all possible values searched */ return -1; /* return key not found */ } mid = (low + high) / 2; /* compute mid once per-iteration */ if (key > arr[mid]) { low = mid + 1; /* only adjust low if key > element */ } else if (key < arr[mid]) { high = mid - 1; /* only adjust high if key < element */ } } return mid; /* return index to key */ } The traditional implementation of a bsearch controlling the loop with low <= high is written as follows: int binarySearch (int *arr, int size, int key) { int low = 0, high = size - 1, mid; while (low <= high) { mid = low + ((high - low) / 2); if (arr[mid] == key) { return mid; } else if (key < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } You would need to dump to assembly to determine which provided the most efficient implementation. They will be within a few instructions of each other. Let me know if you have questions. (note: while the compiler may not care if there are no spaces in your code, your aging professor will -- always space your code adequately for readability)
When number is not found in array it does not give me the desired output
Below code finds the desired key in array and prints it but when key is not found, I expect the search return -1 and print "Key not found." But this is not printed. Is there a mistake? #include<stdio.h> int binarySearch(int* arr, int size, int key){ int low=0; int high=size-1; int mid=(low+high)/2; while(arr[mid]!=key){ if(key>arr[mid]){ low=mid+1; mid=(low+high)/2; } if(key<arr[mid]){ low=0; high=mid-1; mid=(low+high)/2; } if(key==arr[mid]){ return mid; } } } int main(){ int intArr[10]={4,5,12,44,232,326,654,776,987,999}; int res=binarySearch(intArr, 10, 1); if(res){ printf("Key found at index: %d.", res); }else ("Key not found."); } Note: I made a mistake on syntax of this part. I corrected. this else ("Key not found."); to else (printf("Key not found.\n")); It is working as intended after this correction. I also added @weatherwane' s suggestion and @poepew's suggestions. Here is the working code: #include<stdio.h> int binarySearch(int* arr, int size, int key){ int low=0; int high=size-1; int mid=(low+high)/2; while(high-low>0){ if(key>arr[mid]){ low=mid+1; mid=(low+high)/2; } if(key<arr[mid]){ low=0; high=mid-1; mid=(low+high)/2; } if(key==arr[mid]){ return mid; } } return -1; } int main(){ int intArr[10]={4,5,12,44,232,326,654,776,987,999}; int res=binarySearch(intArr, 10, 43); if(res>=0){ printf("Key found at index: %d.\n", res); } else (printf("Key not found.\n")); }
[ "This problem occurs because you do not have a return statement for the so called 'not found' case. After your while statement add a return -1 case.\n\n#include<stdio.h>\n\nint binarySearch(int* arr, int size, int key){\n\n int low=0;\n int high=size-1;\n int mid=(low+high)/2; \n int i = 0;\n\n while(arr[mid]!=key ){\n i = mid;\n if(key>arr[mid]){\n low=mid+1;\n mid=(low+high)/2;\n }\n if(key<arr[mid]){\n low=0;\n high=mid-1;\n mid=(low+high)/2; \n } \n if(key==arr[mid]){\n return mid;\n } \n if(i == mid){\n return -1;\n }\n } \n return -1;\n}\n\nint main(){\n\n int intArr[10]={4,5,12,44,232,326,654,776,987,999};\n\n int res=binarySearch(intArr, 10, 99);\n typeof(res);\n if(res){\n printf(\"Key found at index: %d.\", res);\n }\n else {\n printf(\"Key not found\");\n \n }\n}\n\nEDIT: Also there was an infinite loop caused by the while loop, in order for the while loop presented in the question arr[mid] should not be equal to the key. which if the array does not contain the wanted element results in infinite loop. The solution I have added is to check if the new mid value is added or not. it is set to the initial value at the start of the loop and if it is not muted, it returns -1.\n", "Your implementation of an iterative bsearch using the test while (arr[mid] != key), is a bit awkward compared to the normal loop condition of while (low <= high), but you can write it this way.\nYou have three exit conditions to protect against:\n\nkey is less than 1st element in array,\nkey is greater than last element in array, and\nkey is within the range of 1st - last, but not present in the array.\n\nThe primary error in your logic is you only adjust low if key > arr[mid], and you only adjust high if key < arr[mid]. You never adjust both in response to a condition.\nPutting it altogether, you would edit your approach and do:\nint binarySearch (int *arr, int size, int key) {\n\n int low = 0,\n high = size - 1,\n mid;\n\n while (arr[mid] != key) { /* loop while key not found */\n \n if (low > high) { /* all possible values searched */\n return -1; /* return key not found */\n }\n \n mid = (low + high) / 2; /* compute mid once per-iteration */\n \n if (key > arr[mid]) {\n low = mid + 1; /* only adjust low if key > element */\n }\n else if (key < arr[mid]) {\n high = mid - 1; /* only adjust high if key < element */\n }\n }\n \n return mid; /* return index to key */\n}\n\nThe traditional implementation of a bsearch controlling the loop with low <= high is written as follows:\nint binarySearch (int *arr, int size, int key)\n{\n int low = 0,\n high = size - 1,\n mid;\n\n while (low <= high) {\n \n mid = low + ((high - low) / 2);\n \n if (arr[mid] == key) {\n return mid;\n }\n else if (key < arr[mid]) {\n high = mid - 1;\n }\n else {\n low = mid + 1;\n }\n }\n\n return -1;\n}\n\nYou would need to dump to assembly to determine which provided the most efficient implementation. They will be within a few instructions of each other.\nLet me know if you have questions.\n(note: while the compiler may not care if there are no spaces in your code, your aging professor will -- always space your code adequately for readability)\n" ]
[ 0, 0 ]
[]
[]
[ "binary_search", "c" ]
stackoverflow_0074679181_binary_search_c.txt
Q: How insert code for Radio Button selector in R Shiny as HTML code? I am looking a way how to insert code for R Shiny Radio Button selector inside "tags" type code. Here is an example of code. library(shiny) runApp(list( # UI ui = fluidPage(mainPanel(uiOutput('tests'))), # SERVER server = function(input, output) { # Radio button selector output$uo_range <- renderUI({ list_values <- c("all", "365d", "180d", "90d", "30d") names(list_values) <- c("All days", "365 days", "180 days", "90 days", "30 days") radioButtons("rbtn_days", "Date range", choices = list_values, selected = "30d", inline = TRUE) }) # Render UI output$tests <- renderUI({ result <- tags$table( tags$tr(tags$td(align="center", tags$h3("Tests UI"))), # Radio button selector # I would like to have in 'rbtn_days_code' code for 'uo_range' component tags$tr(tags$td(rbtn_days_code)) ) # Result result }) } )) Any ideas and solutions are welcome and will be Liked! A: To insert the code for your radio button selector inside the tags code, you can first render the UI for the radio buttons to a variable, and then insert that variable into the tags code. Here is one way you could do this: library(shiny) runApp(list( # UI ui = fluidPage(mainPanel(uiOutput('tests'))), # SERVER server = function(input, output) { # Radio button selector output$uo_range <- renderUI({ list_values <- c("all", "365d", "180d", "90d", "30d") names(list_values) <- c("All days", "365 days", "180 days", "90 days", "30 days") radioButtons("rbtn_days", "Date range", choices = list_values, selected = "30d", inline = TRUE) }) # Render UI output$tests <- renderUI({ # Get the rendered UI for the radio button selector and save it to a variable rbtn_days_code <- uiOutput('uo_range') result <- tags$table( tags$tr(tags$td(align="center", tags$h3("Tests UI"))), # Insert the radio button selector code into the tags code tags$tr(tags$td(rbtn_days_code)) ) # Result result }) } )) This code first renders the radio button selector to the uo_range output, and then inserts the rendered UI for that output into the tags code. You can then use the rbtn_days_code variable to insert the radio buttons into the tags code.
How insert code for Radio Button selector in R Shiny as HTML code?
I am looking a way how to insert code for R Shiny Radio Button selector inside "tags" type code. Here is an example of code. library(shiny) runApp(list( # UI ui = fluidPage(mainPanel(uiOutput('tests'))), # SERVER server = function(input, output) { # Radio button selector output$uo_range <- renderUI({ list_values <- c("all", "365d", "180d", "90d", "30d") names(list_values) <- c("All days", "365 days", "180 days", "90 days", "30 days") radioButtons("rbtn_days", "Date range", choices = list_values, selected = "30d", inline = TRUE) }) # Render UI output$tests <- renderUI({ result <- tags$table( tags$tr(tags$td(align="center", tags$h3("Tests UI"))), # Radio button selector # I would like to have in 'rbtn_days_code' code for 'uo_range' component tags$tr(tags$td(rbtn_days_code)) ) # Result result }) } )) Any ideas and solutions are welcome and will be Liked!
[ "To insert the code for your radio button selector inside the tags code, you can first render the UI for the radio buttons to a variable, and then insert that variable into the tags code. Here is one way you could do this:\nlibrary(shiny)\n\nrunApp(list(\n\n # UI\n ui = fluidPage(mainPanel(uiOutput('tests'))),\n\n # SERVER\n server = function(input, output) {\n\n # Radio button selector\n output$uo_range <- renderUI({\n list_values <- c(\"all\", \"365d\", \"180d\", \"90d\", \"30d\")\n names(list_values) <- c(\"All days\", \"365 days\", \"180 days\", \"90 days\", \"30 days\")\n radioButtons(\"rbtn_days\", \"Date range\", choices = list_values, selected = \"30d\", inline = TRUE)\n })\n\n # Render UI\n output$tests <- renderUI({\n \n # Get the rendered UI for the radio button selector and save it to a variable\n rbtn_days_code <- uiOutput('uo_range')\n \n result <- tags$table(\n tags$tr(tags$td(align=\"center\", tags$h3(\"Tests UI\"))),\n \n # Insert the radio button selector code into the tags code\n tags$tr(tags$td(rbtn_days_code))\n )\n \n # Result\n result\n })\n\n }\n))\n\nThis code first renders the radio button selector to the uo_range output, and then inserts the rendered UI for that output into the tags code. You can then use the rbtn_days_code variable to insert the radio buttons into the tags code.\n" ]
[ 0 ]
[]
[]
[ "r", "radio_button", "shiny" ]
stackoverflow_0074679279_r_radio_button_shiny.txt
Q: MS Access SQL, How to return only the newest row before a given date joined to a master table I have two tables in a MS Access database as shown below. CustomerId is a primary key and fkCustomerId is a foreign key linked to the CustomerId in the other table. Customer table CustomerId Name 1 John 2 Bob 3 David Purchase table fkCustomerId OrderDate fkStockId 1 01/02/2010 100 3 08/07/2010 101 2 14/01/2011 102 2 21/10/2011 103 3 02/03/2012 104 1 30/09/2012 105 3 01/01/2013 106 1 18/04/2014 107 3 22/11/2015 108 I am trying to return a list of customers showing the last fkStockId for each customer ordered before a given date. So for the date 01/10/2012, I'd be looking for a return of fkCustomerId Name fkStockId 1 John 105 2 Bob 103 3 David 104 A solution seems to be escaping me, any help would be greatly appreciated. A: You can use nested select to get last order date. SELECT Purchase.fkCustomerId, Name, fkStockId FROM Purchase JOIN ( SELECT fkCustomerId, MAX(OrderDate) as last_OrderDate FROM Purchase WHERE OrderDate < '01/10/2012' GROUP BY fkCustomerId ) AS lastOrder ON lastOrder.fkCustomerId = Purchase.fkCustomerId AND last_OrderDate = OrderDate LEFT JOIN Customer ON Customer.CustomerId = Purchase.fkCustomerId This example assumes OrderDate before '01/10/2012'. You might need to change it if you want it to be filtered by a different value. Another assumption is that there's only one corresponding fkStockId for each OrderDate
MS Access SQL, How to return only the newest row before a given date joined to a master table
I have two tables in a MS Access database as shown below. CustomerId is a primary key and fkCustomerId is a foreign key linked to the CustomerId in the other table. Customer table CustomerId Name 1 John 2 Bob 3 David Purchase table fkCustomerId OrderDate fkStockId 1 01/02/2010 100 3 08/07/2010 101 2 14/01/2011 102 2 21/10/2011 103 3 02/03/2012 104 1 30/09/2012 105 3 01/01/2013 106 1 18/04/2014 107 3 22/11/2015 108 I am trying to return a list of customers showing the last fkStockId for each customer ordered before a given date. So for the date 01/10/2012, I'd be looking for a return of fkCustomerId Name fkStockId 1 John 105 2 Bob 103 3 David 104 A solution seems to be escaping me, any help would be greatly appreciated.
[ "You can use nested select to get last order date.\nSELECT Purchase.fkCustomerId,\n Name,\n fkStockId\nFROM Purchase\nJOIN \n(\n SELECT fkCustomerId,\n MAX(OrderDate) as last_OrderDate\n FROM Purchase\n WHERE OrderDate < '01/10/2012'\n GROUP BY fkCustomerId\n) AS lastOrder\n ON lastOrder.fkCustomerId = Purchase.fkCustomerId\n AND last_OrderDate = OrderDate \nLEFT JOIN Customer\n ON Customer.CustomerId = Purchase.fkCustomerId\n\nThis example assumes OrderDate before '01/10/2012'. You might need to change it if you want it to be filtered by a different value.\nAnother assumption is that there's only one corresponding fkStockId for each OrderDate\n" ]
[ 0 ]
[]
[]
[ "ms_access", "sql" ]
stackoverflow_0074679522_ms_access_sql.txt
Q: Handle the payload of a POST request from Node-RED with deno fresh framework When I sent a POST request to an endpoint with node-red I can't find a way to access the data that I sent in msg.payload with the POST handler that I made with deno fresh. I tried to get the data from the req.body but it returns: ReadableStream { locked: false } so I printed the hole request of the handler and the data aren't anywhere in the request. The handler code is the following: import { Handlers, HandlerContext } from "$fresh/server.ts"; export const handler: Handlers = { async POST(req: Request, ctx: HandlerContext){ const payload = await req.body console.log(payload) return new Response(payload) } }; A: The data is in the request body, but it has to be read from the ReadableStream in chunks of bytes. You can do this with a for await loop: for await (const chunk of req.body) { // Do stuff } So if for example you wanted to just log the data, the handler would look something like this: export const handler: Handlers = { async POST(req: Request, ctx: HandlerContext){ const payload = req.body if (payload === null) { return new Response("Invalid request: body is null"); } const decoder = new TextDecoder() for await (const chunk of payload) { // decode the bytes into a string and print it console.log(decoder.decode(chunk)) } return new Response(payload) } };
Handle the payload of a POST request from Node-RED with deno fresh framework
When I sent a POST request to an endpoint with node-red I can't find a way to access the data that I sent in msg.payload with the POST handler that I made with deno fresh. I tried to get the data from the req.body but it returns: ReadableStream { locked: false } so I printed the hole request of the handler and the data aren't anywhere in the request. The handler code is the following: import { Handlers, HandlerContext } from "$fresh/server.ts"; export const handler: Handlers = { async POST(req: Request, ctx: HandlerContext){ const payload = await req.body console.log(payload) return new Response(payload) } };
[ "The data is in the request body, but it has to be read from the ReadableStream in chunks of bytes. You can do this with a for await loop:\nfor await (const chunk of req.body) {\n // Do stuff\n}\n\nSo if for example you wanted to just log the data, the handler would look something like this:\nexport const handler: Handlers = {\n async POST(req: Request, ctx: HandlerContext){\n const payload = req.body\n\n if (payload === null) {\n return new Response(\"Invalid request: body is null\");\n }\n\n const decoder = new TextDecoder()\n for await (const chunk of payload) {\n // decode the bytes into a string and print it\n console.log(decoder.decode(chunk))\n }\n\n return new Response(payload)\n }\n};\n\n" ]
[ 0 ]
[]
[]
[ "deno", "freshjs", "httphandler", "request" ]
stackoverflow_0074641426_deno_freshjs_httphandler_request.txt
Q: Powershell JSON Building I am having problems getting assembling this Json in Powershell { "totalCount": 1, "list": [ { "type": "ToggleLightingState", "order": 1, "delay": null, "postDelay": null, "name": "Toggle lighting state of light L-17E-611-KB-1", "parameters": { "relayIds": [], "curveType": null, "behavior": null, "duration": null, "useAssignedSpace": false, "spaceIds": [], "lightIds": [ 2408 ], "spaceGroupIds": [] } } ] } I am Iterating through an array using a for loop to fill in the values. I am just struggling to generate a list inside a list in JSON $ActionList = @{ @( @{ type = 'ToggleLightingState' order = 1 delay = 'null' postDelay = 'null' name = $actionSets[$i][0] } ) } ConvertTo-Json -InputObject $ActionList A: You don't have the name of the array "list" inside the object. It looks like you can't have an unnamed array inside an object. I don't know what $actionsets is, so I took off the indexes. Plus fixing your syntax errors results in the below. Note that 'null' and $null are different things. $ActionList = @{ list = @( @{ type = 'ToggleLightingState' order = 1 delay = 'null' postDelay = 'null' name = $actionSets } ) } ConvertTo-Json -InputObject $ActionList { "list": [ { "delay": "null", "name": null, "postDelay": "null", "type": "ToggleLightingState", "order": 1 } ] } A: Using this ConvertTo-Expression cmdlet: $Json = @' { "totalCount": 1, "list": [ { "type": "ToggleLightingState", "order": 1, "delay": null, "postDelay": null, "name": "Toggle lighting state of light L-17E-611-KB-1", "parameters": { "relayIds": [], "curveType": null, "behavior": null, "duration": null, "useAssignedSpace": false, "spaceIds": [], "lightIds": [ 2408 ], "spaceGroupIds": [] } } ] } '@ $Json | ConvertFrom-Json |ConvertTo-Expression [pscustomobject]@{ totalCount = 1 list = ,[pscustomobject]@{ type = 'ToggleLightingState' order = 1 delay = $Null postDelay = $Null name = 'Toggle lighting state of light L-17E-611-KB-1' parameters = [pscustomobject]@{ relayIds = @() curveType = $Null behavior = $Null duration = $Null useAssignedSpace = $False spaceIds = @() lightIds = ,2408 spaceGroupIds = @() } } } Or: $Json |ConvertFrom-Json -AsHashTable |ConvertTo-Expression @{ totalCount = 1 list = ,@{ postDelay = $Null parameters = @{ duration = $Null spaceGroupIds = @() relayIds = @() spaceIds = @() useAssignedSpace = $False curveType = $Null behavior = $Null lightIds = ,2408 } type = 'ToggleLightingState' delay = $Null order = 1 name = 'Toggle lighting state of light L-17E-611-KB-1' } }
Powershell JSON Building
I am having problems getting assembling this Json in Powershell { "totalCount": 1, "list": [ { "type": "ToggleLightingState", "order": 1, "delay": null, "postDelay": null, "name": "Toggle lighting state of light L-17E-611-KB-1", "parameters": { "relayIds": [], "curveType": null, "behavior": null, "duration": null, "useAssignedSpace": false, "spaceIds": [], "lightIds": [ 2408 ], "spaceGroupIds": [] } } ] } I am Iterating through an array using a for loop to fill in the values. I am just struggling to generate a list inside a list in JSON $ActionList = @{ @( @{ type = 'ToggleLightingState' order = 1 delay = 'null' postDelay = 'null' name = $actionSets[$i][0] } ) } ConvertTo-Json -InputObject $ActionList
[ "You don't have the name of the array \"list\" inside the object. It looks like you can't have an unnamed array inside an object. I don't know what $actionsets is, so I took off the indexes. Plus fixing your syntax errors results in the below. Note that 'null' and $null are different things.\n$ActionList = @{\n list = @(\n @{\n type = 'ToggleLightingState'\n order = 1\n delay = 'null'\n postDelay = 'null'\n name = $actionSets\n }\n )\n}\nConvertTo-Json -InputObject $ActionList\n\n\n{\n \"list\": [\n {\n \"delay\": \"null\",\n \"name\": null,\n \"postDelay\": \"null\",\n \"type\": \"ToggleLightingState\",\n \"order\": 1\n }\n ]\n}\n\n", "Using this ConvertTo-Expression cmdlet:\n\n\n$Json = @'\n{\n \"totalCount\": 1,\n \"list\": [\n {\n \"type\": \"ToggleLightingState\",\n \"order\": 1,\n \"delay\": null,\n \"postDelay\": null,\n \"name\": \"Toggle lighting state of light L-17E-611-KB-1\",\n \"parameters\": {\n \"relayIds\": [],\n \"curveType\": null,\n \"behavior\": null,\n \"duration\": null,\n \"useAssignedSpace\": false,\n \"spaceIds\": [],\n \"lightIds\": [\n 2408\n ],\n \"spaceGroupIds\": []\n }\n }\n ]\n}\n'@\n\n\n\n$Json | ConvertFrom-Json |ConvertTo-Expression\n\n[pscustomobject]@{\n totalCount = 1\n list = ,[pscustomobject]@{\n type = 'ToggleLightingState'\n order = 1\n delay = $Null\n postDelay = $Null\n name = 'Toggle lighting state of light L-17E-611-KB-1'\n parameters = [pscustomobject]@{\n relayIds = @()\n curveType = $Null\n behavior = $Null\n duration = $Null\n useAssignedSpace = $False\n spaceIds = @()\n lightIds = ,2408\n spaceGroupIds = @()\n }\n }\n}\n\nOr:\n$Json |ConvertFrom-Json -AsHashTable |ConvertTo-Expression\n@{\n totalCount = 1\n list = ,@{\n postDelay = $Null\n parameters = @{\n duration = $Null\n spaceGroupIds = @()\n relayIds = @()\n spaceIds = @()\n useAssignedSpace = $False\n curveType = $Null\n behavior = $Null\n lightIds = ,2408\n }\n type = 'ToggleLightingState'\n delay = $Null\n order = 1\n name = 'Toggle lighting state of light L-17E-611-KB-1'\n }\n}\n\n" ]
[ 1, 1 ]
[]
[]
[ "convertto_json", "json", "powershell" ]
stackoverflow_0074679311_convertto_json_json_powershell.txt
Q: What happens to class level variables in Junits? I have a test class that have a class level date time formatter defined as class testClass{ DateTimeFormatter dateTimeFormatter = new DateTimeFormat.forPattern(settings.getFormatFromUser()); @Test public void test01(){ ... DateTime date = dateTimeFormatter.print(new DateTime()); .... } } And then I have a test written in same class which will use this formatter. If I change the formatter string from UI in between running the test what will happen? Will this be a good practice to have this instantiation in test method or class level? Just asking for my understanding of how junits run. A: Will this be a good practice to have this instantiation in test method or class level? Without seeing the rest of your code under test and the tests themselves it's difficult for anyone to answer this question. However, it's generally a good practice to have each test method self contained so there are no unexpected side effects between each test method execution. If you are looking for ways to do setup before each test method executes (to ensure the code under test is in the same known state before each test executes, look at using the @Before annotations to help with your setup.
What happens to class level variables in Junits?
I have a test class that have a class level date time formatter defined as class testClass{ DateTimeFormatter dateTimeFormatter = new DateTimeFormat.forPattern(settings.getFormatFromUser()); @Test public void test01(){ ... DateTime date = dateTimeFormatter.print(new DateTime()); .... } } And then I have a test written in same class which will use this formatter. If I change the formatter string from UI in between running the test what will happen? Will this be a good practice to have this instantiation in test method or class level? Just asking for my understanding of how junits run.
[ "\nWill this be a good practice to have this instantiation in test method or class level?\n\nWithout seeing the rest of your code under test and the tests themselves it's difficult for anyone to answer this question. However, it's generally a good practice to have each test method self contained so there are no unexpected side effects between each test method execution.\nIf you are looking for ways to do setup before each test method executes (to ensure the code under test is in the same known state before each test executes, look at using the @Before annotations to help with your setup.\n" ]
[ 0 ]
[]
[]
[ "java", "junit" ]
stackoverflow_0074679646_java_junit.txt
Q: How to integrate AVFoundation in a flutter project? I am trying to integrate AVFoundation in my flutter project to scan QR code. I have followed the docs and wrote the following code class CealScanQrView extends StatelessWidget { const CealScanQrView({super.key}); @override Widget build(BuildContext context) { final Map<String, dynamic> creationParams = <String, dynamic>{}; return Platform.isAndroid ? AndroidView( viewType: cealScanQrView, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ) : UiKitView( viewType: cealScanQrView, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } } I have created CealScanViewNativeViewFactory, CealScanViewNativeView and registered in my AppDelegate using below code weak var registrar = self.registrar(forPlugin: "ceal-views") let cealQrViewfactory = CealQrViewNativeViewFactory(messenger: registrar!.messenger()) let viewRegistrar = self.registrar(forPlugin: "<ceal-views>")! viewRegistrar.register( cealQrViewfactory, withId: "cealQrView") Below is my CealScanViewNativeView code import Foundation import UIKit import AVFoundation class CealScanViewNativeView: NSObject, FlutterPlatformView,AVCaptureMetadataOutputObjectsDelegate { private var _view: UIView var captureSession: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! init( frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?, binaryMessenger messenger: FlutterBinaryMessenger? ) { _view = UIView() super.init() setUpView() } func view() -> UIView { return _view } private func setUpView(){ _view.backgroundColor = UIColor.clear captureSession = AVCaptureSession() guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return } let videoInput: AVCaptureDeviceInput do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if (captureSession.canAddInput(videoInput)) { captureSession.addInput(videoInput) } else { failed() return } let metadataOutput = AVCaptureMetadataOutput() if (captureSession.canAddOutput(metadataOutput)) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metadataOutput.metadataObjectTypes = [.qr] } else { failed() return } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = _view.layer.bounds previewLayer.videoGravity = .resizeAspectFill _view.layer.addSublayer(previewLayer) self.captureSession.startRunning() } func failed() { let ac = UIAlertController(title: "Scanning not supported", message: "Device does not support scanning", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Ok", style: .default)) UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] } .first { $0.isKeyWindow }?.rootViewController?.present(ac, animated: true) captureSession = nil } func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { captureSession.stopRunning() if let metadataObject = metadataObjects.first { guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return } guard let stringValue = readableObject.stringValue else { return } AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) found(code: stringValue) } UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] } .first { $0.isKeyWindow }?.rootViewController?.dismiss(animated: true) } func found(code: String) { debugPrint("Code is \(code)") } } I have given the camera permission as well but as soon as I open the view, I don't see the camera. I tried changing the _view.backgroundColor to red and it is visible so the view is setup correctly but I don't get the camera. In my Xcode logs I see below warning Thread Performance Checker: -[AVCaptureSession startRunning] should be called from background thread. Calling it on the main thread can lead to UI unresponsiveness PID: 1107, TID: 125465 A: I don't see where you are adding the view holding the preview layer to the hierarchy. Make sure you add it too. There are a couple of things that you can do to make this work. Session configuration takes time and it needs to be done on a separate serial queue, like so: private let sessionQueue = DispatchQueue(label: "session queue") ... sessionQueue.async { self.setUpView() } Make variables class properties, like so: private let metadataOutput = AVCaptureMetadataOutput() private let metadataObjectsQueue = DispatchQueue(label: "metadata objects queue", attributes: [], target: nil) Process output on a separate queue metadataOutput.setMetadataObjectsDelegate(self, queue: metadataObjectsQueue) metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes Start session on the session queue sessionQueue.async { if self.isSessionRunning { self.session.startRunning() self.isSessionRunning = self.session.isRunning } } You can find complete sample at https://developer.apple.com/documentation/avfoundation/capture_setup/avcambarcode_detecting_barcodes_and_faces
How to integrate AVFoundation in a flutter project?
I am trying to integrate AVFoundation in my flutter project to scan QR code. I have followed the docs and wrote the following code class CealScanQrView extends StatelessWidget { const CealScanQrView({super.key}); @override Widget build(BuildContext context) { final Map<String, dynamic> creationParams = <String, dynamic>{}; return Platform.isAndroid ? AndroidView( viewType: cealScanQrView, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ) : UiKitView( viewType: cealScanQrView, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } } I have created CealScanViewNativeViewFactory, CealScanViewNativeView and registered in my AppDelegate using below code weak var registrar = self.registrar(forPlugin: "ceal-views") let cealQrViewfactory = CealQrViewNativeViewFactory(messenger: registrar!.messenger()) let viewRegistrar = self.registrar(forPlugin: "<ceal-views>")! viewRegistrar.register( cealQrViewfactory, withId: "cealQrView") Below is my CealScanViewNativeView code import Foundation import UIKit import AVFoundation class CealScanViewNativeView: NSObject, FlutterPlatformView,AVCaptureMetadataOutputObjectsDelegate { private var _view: UIView var captureSession: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! init( frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?, binaryMessenger messenger: FlutterBinaryMessenger? ) { _view = UIView() super.init() setUpView() } func view() -> UIView { return _view } private func setUpView(){ _view.backgroundColor = UIColor.clear captureSession = AVCaptureSession() guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return } let videoInput: AVCaptureDeviceInput do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if (captureSession.canAddInput(videoInput)) { captureSession.addInput(videoInput) } else { failed() return } let metadataOutput = AVCaptureMetadataOutput() if (captureSession.canAddOutput(metadataOutput)) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metadataOutput.metadataObjectTypes = [.qr] } else { failed() return } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = _view.layer.bounds previewLayer.videoGravity = .resizeAspectFill _view.layer.addSublayer(previewLayer) self.captureSession.startRunning() } func failed() { let ac = UIAlertController(title: "Scanning not supported", message: "Device does not support scanning", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Ok", style: .default)) UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] } .first { $0.isKeyWindow }?.rootViewController?.present(ac, animated: true) captureSession = nil } func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { captureSession.stopRunning() if let metadataObject = metadataObjects.first { guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return } guard let stringValue = readableObject.stringValue else { return } AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) found(code: stringValue) } UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] } .first { $0.isKeyWindow }?.rootViewController?.dismiss(animated: true) } func found(code: String) { debugPrint("Code is \(code)") } } I have given the camera permission as well but as soon as I open the view, I don't see the camera. I tried changing the _view.backgroundColor to red and it is visible so the view is setup correctly but I don't get the camera. In my Xcode logs I see below warning Thread Performance Checker: -[AVCaptureSession startRunning] should be called from background thread. Calling it on the main thread can lead to UI unresponsiveness PID: 1107, TID: 125465
[ "I don't see where you are adding the view holding the preview layer to the hierarchy. Make sure you add it too.\nThere are a couple of things that you can do to make this work.\n\nSession configuration takes time and it needs to be done on a separate serial queue, like so:\n\n private let sessionQueue = DispatchQueue(label: \"session queue\")\n ...\n sessionQueue.async {\n self.setUpView()\n }\n\n\nMake variables class properties, like so:\n\n private let metadataOutput = AVCaptureMetadataOutput()\n private let metadataObjectsQueue = DispatchQueue(label: \"metadata objects queue\", attributes: [], target: nil)\n\n\nProcess output on a separate queue\n\n metadataOutput.setMetadataObjectsDelegate(self, queue: metadataObjectsQueue)\n metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes\n\n\nStart session on the session queue\n\nsessionQueue.async {\n if self.isSessionRunning {\n self.session.startRunning()\n self.isSessionRunning = self.session.isRunning\n }\n}\n\nYou can find complete sample at https://developer.apple.com/documentation/avfoundation/capture_setup/avcambarcode_detecting_barcodes_and_faces\n" ]
[ 0 ]
[]
[]
[ "dart", "flutter", "ios", "swift" ]
stackoverflow_0074649596_dart_flutter_ios_swift.txt
Q: How to read JSON object in kotlin with Volle Android Studio? I'm using volley to read a Get Request from the Google Places API and I want to get some information from this JSON OUTPUT: "results": [ { "business_status": "OPERATIONAL", "geometry": { "location": { "lat": 25.7239497, "lng": -100.1915475 }, "viewport": { "northeast": { "lat": 25.7252242302915, "lng": -100.1902086197085 }, "southwest": { "lat": 25.7225262697085, "lng": -100.1929065802915 } } }, "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png", "icon_background_color": "#FF9E67", "icon_mask_base_uri": "https://maps.gstatic.com/mapfiles/place_api/icons/v2/restaurant_pinlet", "name": "El Texanito", "opening_hours": {}, "photos": [], "place_id": "ChIJJdu3AjbqYoYRPJyEgQwBT-0", "plus_code": {}, "price_level": 2, "rating": 4, "reference": "ChIJJdu3AjbqYoYRPJyEgQwBT-0", "scope": "GOOGLE", "types": [], "user_ratings_total": 563, "vicinity": "Boulevard Acapulco #141, Josefa Zozaya, Guadalupe" }, My kotlin Code: fun methodToGetInfo(){ tbUsuarios?.removeAllViews() var queue = Volley.newRequestQueue(this) var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?fields=price_level&location=25.7299374%2C-100.2096866&radius=2500&type=restaurant&key=AIzaSyDV6aFItX960hrbAaI229-8iDa3xTZ-RXU" var myJsonObjectRequest = JsonObjectRequest(Request.Method.GET,url,null, Response.Listener { response -> try{ var myJsonArray = response.getJSONArray("results") for(i in 0 until myJsonArray.length()){ var myJSONObject = myJsonArray.getJSONObject(i) val registro = LayoutInflater.from(this).inflate(R.layout.table_row_np,null,false) val colName = registro.findViewById<View>(R.id.columnaNombre) as TextView val colPrice = registro.findViewById<View>(R.id.columnaEmail) as TextView val colLatitude = registro.findViewById<View>(R.id.colEditar) val colBorrar = registro.findViewById<View>(R.id.colBorrar) colName.text= myJSONObject.getString("name") Log.d(TAG, "Nombre: ${ myJSONObject.getString("name")}" ) Log.d(TAG, "Rating: ${ myJSONObject.getString("price_level")}" ) colPrice.text=myJSONObject.getString("price_level") Log.d(TAG, "Latitude: ${myJSONObject.getString("location")}") tbUsuarios?.addView(registro) } I can easily get information like the name, price rating, place_id, etc but when I need to get data inside some properties like for example lat, I am getting an error. I know that simply searching for "lat" is wrong because I need to travel "geometry" -> "location" -> "lat" I want to know how to travel through these properties and get that information A: Assuming the type is org.json.JSONObject, you can use something like myJSONObject.getJSONObject("geometry").getJSONObject("location").getString("lat") If the fields aren't guaranteed to be present, use safe calls: myJSONObject.getJSONObject("geometry")?.getJSONObject("location")?.getString("lat") Of course if you want to access more than one property from the same path it can make sense to use a local variable too, e.g. val location = myJSONObject.getJSONObject("geometry").getJSONObject("location") val latitude = location.getString("lat") val longitude = location.getString("lng")
How to read JSON object in kotlin with Volle Android Studio?
I'm using volley to read a Get Request from the Google Places API and I want to get some information from this JSON OUTPUT: "results": [ { "business_status": "OPERATIONAL", "geometry": { "location": { "lat": 25.7239497, "lng": -100.1915475 }, "viewport": { "northeast": { "lat": 25.7252242302915, "lng": -100.1902086197085 }, "southwest": { "lat": 25.7225262697085, "lng": -100.1929065802915 } } }, "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png", "icon_background_color": "#FF9E67", "icon_mask_base_uri": "https://maps.gstatic.com/mapfiles/place_api/icons/v2/restaurant_pinlet", "name": "El Texanito", "opening_hours": {}, "photos": [], "place_id": "ChIJJdu3AjbqYoYRPJyEgQwBT-0", "plus_code": {}, "price_level": 2, "rating": 4, "reference": "ChIJJdu3AjbqYoYRPJyEgQwBT-0", "scope": "GOOGLE", "types": [], "user_ratings_total": 563, "vicinity": "Boulevard Acapulco #141, Josefa Zozaya, Guadalupe" }, My kotlin Code: fun methodToGetInfo(){ tbUsuarios?.removeAllViews() var queue = Volley.newRequestQueue(this) var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?fields=price_level&location=25.7299374%2C-100.2096866&radius=2500&type=restaurant&key=AIzaSyDV6aFItX960hrbAaI229-8iDa3xTZ-RXU" var myJsonObjectRequest = JsonObjectRequest(Request.Method.GET,url,null, Response.Listener { response -> try{ var myJsonArray = response.getJSONArray("results") for(i in 0 until myJsonArray.length()){ var myJSONObject = myJsonArray.getJSONObject(i) val registro = LayoutInflater.from(this).inflate(R.layout.table_row_np,null,false) val colName = registro.findViewById<View>(R.id.columnaNombre) as TextView val colPrice = registro.findViewById<View>(R.id.columnaEmail) as TextView val colLatitude = registro.findViewById<View>(R.id.colEditar) val colBorrar = registro.findViewById<View>(R.id.colBorrar) colName.text= myJSONObject.getString("name") Log.d(TAG, "Nombre: ${ myJSONObject.getString("name")}" ) Log.d(TAG, "Rating: ${ myJSONObject.getString("price_level")}" ) colPrice.text=myJSONObject.getString("price_level") Log.d(TAG, "Latitude: ${myJSONObject.getString("location")}") tbUsuarios?.addView(registro) } I can easily get information like the name, price rating, place_id, etc but when I need to get data inside some properties like for example lat, I am getting an error. I know that simply searching for "lat" is wrong because I need to travel "geometry" -> "location" -> "lat" I want to know how to travel through these properties and get that information
[ "Assuming the type is org.json.JSONObject, you can use something like\nmyJSONObject.getJSONObject(\"geometry\").getJSONObject(\"location\").getString(\"lat\")\n\nIf the fields aren't guaranteed to be present, use safe calls:\nmyJSONObject.getJSONObject(\"geometry\")?.getJSONObject(\"location\")?.getString(\"lat\")\n\nOf course if you want to access more than one property from the same path it can make sense to use a local variable too, e.g.\nval location = myJSONObject.getJSONObject(\"geometry\").getJSONObject(\"location\")\nval latitude = location.getString(\"lat\")\nval longitude = location.getString(\"lng\")\n\n" ]
[ 0 ]
[]
[]
[ "android_volley", "get_request", "google_api", "json", "kotlin" ]
stackoverflow_0074592696_android_volley_get_request_google_api_json_kotlin.txt
Q: Real time updating Axios array imagine having custom hook like this : import React from "react"; import axios from "axios"; export const useFetchListDetails = () => { let token = JSON.parse(localStorage.getItem("AuthToken")); const [listDetails, setListDetails] = React.useState(); const HandleFetchDetails = (idConfer) => { axios({ method: "post", url: `${process.env.REACT_APP_API_URL_API_LIST_SERVICECONFER}`, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, data: JSON.stringify({ idConfer: parseInt(idConfer), }), }) .then((r) => { setListDetails(r.data.Data.ListService); }) .catch(() => alert("خطا در شبکه")); }; return { HandleFetchDetails, listDetails }; }; the listDetails is an array with object that I use it to map and return element per each object. I have a button, and when I click on that button, it deletes selected detail. after this I recall my hook like this: <button onClick={() => { fetchDelete() HandleFetchDetails(factor.ID) }} >Click</button> now I should have new array, and that means I should have an updated UI but it doesn't. when I console.log r.data.Data.ListService in then. it shows me an updated array but for some reason my listDetails remains the same. useState is async. I still don't know why this happens. fetch delete itself is also a custom hook with Axios inside of it. so I also tried to bring the function inside of it. like this: .then((r) => { if (r.data.resCode === 1) { HandleFetchListServiceConfer( ErjaView.ErjaInfo.ID, ErjaView.ErjaInfo.IdPatient ); HandleFetchDetails(idConfer); } } it didn't work either. A: If I understand correctly, the fetchDelete method should receive a callback that you should invoke only after you got the delete response: <button onClick={() => fetchDelete({ onSuccess: () => HandleFetchDetails(factor.ID) })} /> and in your delete hook: const fetchDelete = (options) => { callDeleteRequest().then(() => { options.onSuccess(); } } This will ensure that you don't suffer from any race conditions between state updates.
Real time updating Axios array
imagine having custom hook like this : import React from "react"; import axios from "axios"; export const useFetchListDetails = () => { let token = JSON.parse(localStorage.getItem("AuthToken")); const [listDetails, setListDetails] = React.useState(); const HandleFetchDetails = (idConfer) => { axios({ method: "post", url: `${process.env.REACT_APP_API_URL_API_LIST_SERVICECONFER}`, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, data: JSON.stringify({ idConfer: parseInt(idConfer), }), }) .then((r) => { setListDetails(r.data.Data.ListService); }) .catch(() => alert("خطا در شبکه")); }; return { HandleFetchDetails, listDetails }; }; the listDetails is an array with object that I use it to map and return element per each object. I have a button, and when I click on that button, it deletes selected detail. after this I recall my hook like this: <button onClick={() => { fetchDelete() HandleFetchDetails(factor.ID) }} >Click</button> now I should have new array, and that means I should have an updated UI but it doesn't. when I console.log r.data.Data.ListService in then. it shows me an updated array but for some reason my listDetails remains the same. useState is async. I still don't know why this happens. fetch delete itself is also a custom hook with Axios inside of it. so I also tried to bring the function inside of it. like this: .then((r) => { if (r.data.resCode === 1) { HandleFetchListServiceConfer( ErjaView.ErjaInfo.ID, ErjaView.ErjaInfo.IdPatient ); HandleFetchDetails(idConfer); } } it didn't work either.
[ "If I understand correctly, the fetchDelete method should receive a callback that you should invoke only after you got the delete response:\n<button onClick={() => fetchDelete({ onSuccess: () => HandleFetchDetails(factor.ID) })} />\n\nand in your delete hook:\nconst fetchDelete = (options) => {\n callDeleteRequest().then(() => {\n options.onSuccess();\n }\n}\n\nThis will ensure that you don't suffer from any race conditions between state updates.\n" ]
[ 1 ]
[]
[]
[ "axios", "javascript", "react_hooks", "reactjs" ]
stackoverflow_0074679673_axios_javascript_react_hooks_reactjs.txt
Q: Convert dataframe of two columns into fasta format I have a data frame like this: data.frame(x = c(">Seq1", ">Seq2"), y = c("AAAA", "BBBB")) Wished output: data.frame(x = c(">Seq1", "AAAA", ">Seq2", "BBBB")) Thank you in advance! A: library(dplyr) data.frame(x = c(">Seq1", ">Seq2"), y = c("AAAA", "BBBB")) %>% rowwise() %>% summarise(x = c(x,y)) x <chr> 1 >Seq1 2 AAAA 3 >Seq2 4 BBBB A: Using base R, just transpose the data, convert to a vector (c) and create a new data.frame data.frame(x = c(t(df1))) -output x 1 >Seq1 2 AAAA 3 >Seq2 4 BBBB data df1 <- data.frame(x = c(">Seq1", ">Seq2"), y = c("AAAA", "BBBB")) A: library(tidyr) data.frame(x = c(">Seq1", ">Seq2"), y = c("AAAA", "BBBB")) |> pivot_longer(everything()) |> subset(select=-name) value <chr> 1 >Seq1 2 AAAA 3 >Seq2 4 BBBB
Convert dataframe of two columns into fasta format
I have a data frame like this: data.frame(x = c(">Seq1", ">Seq2"), y = c("AAAA", "BBBB")) Wished output: data.frame(x = c(">Seq1", "AAAA", ">Seq2", "BBBB")) Thank you in advance!
[ "library(dplyr)\n\ndata.frame(x = c(\">Seq1\", \">Seq2\"), y = c(\"AAAA\", \"BBBB\")) %>% \n rowwise() %>% \n summarise(x = c(x,y))\n\n x \n <chr>\n1 >Seq1\n2 AAAA \n3 >Seq2\n4 BBBB \n\n", "Using base R, just transpose the data, convert to a vector (c) and create a new data.frame\ndata.frame(x = c(t(df1)))\n\n-output\n x\n1 >Seq1\n2 AAAA\n3 >Seq2\n4 BBBB\n\ndata\ndf1 <- data.frame(x = c(\">Seq1\", \">Seq2\"), y = c(\"AAAA\", \"BBBB\"))\n\n", "library(tidyr) \ndata.frame(x = c(\">Seq1\", \">Seq2\"), y = c(\"AAAA\", \"BBBB\")) |>\n pivot_longer(everything()) |> \n subset(select=-name)\n\n value\n <chr>\n1 >Seq1\n2 AAAA \n3 >Seq2\n4 BBBB \n\n" ]
[ 4, 2, 1 ]
[]
[]
[ "r" ]
stackoverflow_0074679368_r.txt
Q: How to convert if-else statement to map or other statement using java I am new to Java, I am bored with if else statement I want to refactor my code and relief from if-else statement, not I am not able to reduce my code, In my code nothing is static every thing comes from user side. I share my codes for your reference. if (orderDetail != null && item != null && !orderDetail.isUnitPriceModified()) { ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()); if (origin != null && (origin.contains("b2baccess") || (origin.contains(".myappdev") && !origin.contains("apps.myappdev")))) { RepGroupManufacturer repGroupManufacturer = repGroupManufacturerRepository.findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED); if (repGroupManufacturer != null && repGroupManufacturer.getB2bItemPricingPolicy() != null && repGroupManufacturer.getB2bItemPricingPolicy().equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE)) { if (orderDetail.getItemSCSID() == null && item.getRetailPrice() != null) { orderDetail.setUnitPrice(item.getRetailPrice()); } else { // ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()); if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() != null) { orderDetail.setUnitPrice(itemSizeColorStyle.getRetailPrice()); } else if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() == null && item.getRetailPrice() != null) { orderDetail.setUnitPrice(item.getRetailPrice()); } else if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() == null && item.getRetailPrice() == null) { throw new NullPointerException("item price can not be null."); } } } } How to convert this if else to map. A: Since i dont know what types you are returning and what type of objects some variables are i had to improvise but this should still work you just need to change to the correct values public static void main(String[] args) { setUnitPrice(orderDetail,origin); } public static void setUnitPrice(OrderDetail orderDetail,Origin origin){ if (orderDetail == null && item == null && orderDetail.isUnitPriceModified()) return; if (origin == null && !origin.contains("b2baccess") || !origin.contains(".myappdev") && origin.contains("apps.myappdev")) return; RepGroupManufacturer repGroupManufacturer = repGroupManufacturerRepository .findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED); if (repGroupManufacturer == null && repGroupManufacturer.getB2bItemPricingPolicy() == null && !repGroupManufacturer.getB2bItemPricingPolicy().equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE)) return; ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()); orderDetail.setUnitPrice(getUnitPrice(itemSizeColorStyle,item,orderDetail)); } public static int getUnitPrice(ItemSizeColorStyle itemSizeColorStyle, Item item, OrderDetail orderDetail) { if (orderDetail.getItemSCSID() == null && item.getRetailPrice() != null) return item.getRetailPrice(); if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() != null) return itemSizeColorStyle.getRetailPrice(); if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() == null && item.getRetailPrice() != null) return item.getRetailPrice(); throw new NullPointerException("item price can not be null."); } A: At-least break into multiple small methods to start with. This will make if-else less scary, easy to understand. Also there are areas / paths to avoid duplicate checks. Maybe you could break responsibility of validation checks into different classes as well. import java.util.Optional; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; class Scratch { private static String NOT_DELETED = "not-deleted"; private ItemSizeColorStyleRepository itemSizeColorStyleRepository; private RepGroupManufacturerRepository repGroupManufacturerRepository; public void setUnitPrice(OrderDetail orderDetail, Item item, String origin, Integer repGroupID, Integer manufacturerID) { if (isValidOrderDetail(orderDetail) && nonNull(item)) { if (isValidOrigin(origin)) { if (isValidRepGroupManufacturer(repGroupID, manufacturerID)) { if (isNull(orderDetail.getItemSCSID()) && nonNull(item.getRetailPrice())) { orderDetail.setUnitPrice(item.getRetailPrice()); } else { ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()); if (nonNull(itemSizeColorStyle)) { if (nonNull(itemSizeColorStyle.getRetailPrice())) { orderDetail.setUnitPrice(itemSizeColorStyle.getRetailPrice()); } else { if (nonNull(item.getRetailPrice())) { orderDetail.setUnitPrice(item.getRetailPrice()); } else { throw new NullPointerException("item price can not be null."); } } } } } } } } private boolean isValidOrderDetail(OrderDetail orderDetail) { return Optional .ofNullable(orderDetail) .map(e -> !e.isUnitPriceModified()) .orElse(false); } private boolean isValidOrigin(String origin) { return nonNull(origin) && (origin.contains("b2baccess") || (origin.contains(".myappdev") && !origin.contains("apps.myappdev"))); } private boolean isValidRepGroupManufacturer(Integer repGroupID, Integer manufacturerID) { RepGroupManufacturer repGroupManufacturer = repGroupManufacturerRepository .findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED); return Optional .ofNullable(repGroupManufacturer) .flatMap(e -> Optional.ofNullable(e.getB2bItemPricingPolicy())) .map(e -> e.equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE)) .orElse(false); } } Note: I have assumed certain datatypes, which I don't have any impact on overall solution. A: Some if-else statements express business logic which should be anything but boring. The code you posted appears to contain at least some business logic but the manner in which it is written makes it difficult to read and maintain. There are some rules I follow when refactoring this type of code: "positive thinking" - avoid if not statements, that is what else is for. replace nested if-statements with functions. be as lazy as possible, only lookup values when needed. use variable names that have a meaning. On 1, replace this if (x is not null) { // more code } with if (x is null) { return; } // more code On 2, replace this if (x > 1 ) { // lots of code } with if (x > 1) { updateStuff(x); } function updateStuff(int x) { // lots of code } This also opens up the opportunity to let the function return a value that can be used further on. On 3, replace this x = queryDatabase(y); if (y > 1) { // use x } with if (y > 1) { x = queryDatabase(y); // use x } Finally, on 4, I sometimes introduce boolean values to convey meaning to complex conditions. E.g. compare this: if ((x < 1 and y > 100) || (z not 0 and y < 1)) { // do stuff } with boolean findPrice = (x < 1 and y > 100); boolean findProduct = (z not 0 and y < 1); if (findPrice || findProduct) { // do stuff } When all these rules are applied it becomes much easier to read the code and also easier to maintain and (unit) test the code. A: Disclaimer: it merely impossible to reimplement a chunk of code containing so much logic and guaranty that you can simply copy-past it, and it would work just fine. The very first advice I can give to change the return type in your Repositories and leverage the Optional API (that alone wouldn't resolve all the issues, but it would give some room for improvement). Secondly, you need to break presented logic into self-contained meaningful peaces and give them names. The current code violates the first principle of SOLID - Single responsibility principle in a very obvious way. How can you test it, or how can change this functionality without rewriting from scratch? Such code is very hard to maintain. Here's my attempt to reimplement this logic, assuming that both Repositories would produce an Optional as a result: public void foo(OrderDetail orderDetail, Item item) { if (!isValid(orderDetail, item, origin)) return; repGroupManufacturerRepository .findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED); .filter(manufacturer -> manufacturer.getB2bItemPricingPolicy() != null) .filter(manufacturer -> manufacturer.getB2bItemPricingPolicy().equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE)) .ifPresent(manufacturer -> itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()) .filter(itemStyle -> itemSizeColorStyle.getRetailPrice() != null) .ifPresent(itemStyle -> { if (needToApplyItemPrice(orderDetail, item, itemStyle)) orderDetail.setUnitPrice(item.getRetailPrice()); else if (needToApplyItemStylePrice(orderDetail, item, itemStyle)) orderDetail.setUnitPrice(item.getRetailPrice()); else throw new NullPointerException("item price can not be null."); }) ); } public boolean isValid(OrderDetail orderDetail, Item item, Origin origin) { return orderDetail != null && item != null && !orderDetail.isUnitPriceModified() && origin != null && (origin.contains("b2baccess") || origin.contains(".myappdev") && !origin.contains("apps.myappdev")); } public boolean needToApplyItemPrice(OrderDetail orderDetail, Item item, ItemSizeColorStyle itemStyle) { return (orderDetail.getItemSCSID() == null || itemStyle.getRetailPrice() == null) && item.getRetailPrice() != null; } public boolean needToApplyItemStylePrice(OrderDetail orderDetail, Item item, ItemSizeColorStyle itemStyle) { return !(orderDetail.getItemSCSID() == null && item.getRetailPrice() != null) && itemStyle.getRetailPrice() != null; }
How to convert if-else statement to map or other statement using java
I am new to Java, I am bored with if else statement I want to refactor my code and relief from if-else statement, not I am not able to reduce my code, In my code nothing is static every thing comes from user side. I share my codes for your reference. if (orderDetail != null && item != null && !orderDetail.isUnitPriceModified()) { ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()); if (origin != null && (origin.contains("b2baccess") || (origin.contains(".myappdev") && !origin.contains("apps.myappdev")))) { RepGroupManufacturer repGroupManufacturer = repGroupManufacturerRepository.findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED); if (repGroupManufacturer != null && repGroupManufacturer.getB2bItemPricingPolicy() != null && repGroupManufacturer.getB2bItemPricingPolicy().equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE)) { if (orderDetail.getItemSCSID() == null && item.getRetailPrice() != null) { orderDetail.setUnitPrice(item.getRetailPrice()); } else { // ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID()); if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() != null) { orderDetail.setUnitPrice(itemSizeColorStyle.getRetailPrice()); } else if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() == null && item.getRetailPrice() != null) { orderDetail.setUnitPrice(item.getRetailPrice()); } else if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() == null && item.getRetailPrice() == null) { throw new NullPointerException("item price can not be null."); } } } } How to convert this if else to map.
[ "Since i dont know what types you are returning and what type of objects some variables are i had to improvise but this should still work you just need to change to the correct values\npublic static void main(String[] args) {\n setUnitPrice(orderDetail,origin);\n}\npublic static void setUnitPrice(OrderDetail orderDetail,Origin origin){\n if (orderDetail == null && item == null && orderDetail.isUnitPriceModified()) return;\n if (origin == null && !origin.contains(\"b2baccess\") ||\n !origin.contains(\".myappdev\") && origin.contains(\"apps.myappdev\")) return;\n \n RepGroupManufacturer repGroupManufacturer = repGroupManufacturerRepository\n .findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED);\n \n if (repGroupManufacturer == null &&\n repGroupManufacturer.getB2bItemPricingPolicy() == null &&\n !repGroupManufacturer.getB2bItemPricingPolicy().equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE)) return;\n \n ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID());\n orderDetail.setUnitPrice(getUnitPrice(itemSizeColorStyle,item,orderDetail));\n}\npublic static int getUnitPrice(ItemSizeColorStyle itemSizeColorStyle, Item item, OrderDetail orderDetail) {\n if (orderDetail.getItemSCSID() == null && item.getRetailPrice() != null) return item.getRetailPrice();\n if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() != null) return itemSizeColorStyle.getRetailPrice();\n if (itemSizeColorStyle != null && itemSizeColorStyle.getRetailPrice() == null && item.getRetailPrice() != null) return item.getRetailPrice();\n throw new NullPointerException(\"item price can not be null.\");\n}\n\n", "At-least break into multiple small methods to start with. This will make if-else less scary, easy to understand.\nAlso there are areas / paths to avoid duplicate checks.\nMaybe you could break responsibility of validation checks into different classes as well.\nimport java.util.Optional;\n\nimport static java.util.Objects.isNull;\nimport static java.util.Objects.nonNull;\n\nclass Scratch {\n private static String NOT_DELETED = \"not-deleted\";\n private ItemSizeColorStyleRepository itemSizeColorStyleRepository;\n private RepGroupManufacturerRepository repGroupManufacturerRepository;\n\n\n public void setUnitPrice(OrderDetail orderDetail, Item item, String origin, Integer repGroupID, Integer manufacturerID) {\n if (isValidOrderDetail(orderDetail) && nonNull(item)) {\n if (isValidOrigin(origin)) {\n if (isValidRepGroupManufacturer(repGroupID, manufacturerID)) {\n if (isNull(orderDetail.getItemSCSID()) && nonNull(item.getRetailPrice())) {\n orderDetail.setUnitPrice(item.getRetailPrice());\n } else {\n ItemSizeColorStyle itemSizeColorStyle = itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID());\n if (nonNull(itemSizeColorStyle)) {\n if (nonNull(itemSizeColorStyle.getRetailPrice())) {\n orderDetail.setUnitPrice(itemSizeColorStyle.getRetailPrice());\n } else {\n if (nonNull(item.getRetailPrice())) {\n orderDetail.setUnitPrice(item.getRetailPrice());\n } else {\n throw new NullPointerException(\"item price can not be null.\");\n }\n }\n }\n }\n }\n }\n }\n }\n\n private boolean isValidOrderDetail(OrderDetail orderDetail) {\n return Optional\n .ofNullable(orderDetail)\n .map(e -> !e.isUnitPriceModified())\n .orElse(false);\n }\n\n private boolean isValidOrigin(String origin) {\n return nonNull(origin) &&\n (origin.contains(\"b2baccess\") || (origin.contains(\".myappdev\") && !origin.contains(\"apps.myappdev\")));\n }\n\n private boolean isValidRepGroupManufacturer(Integer repGroupID, Integer manufacturerID) {\n RepGroupManufacturer repGroupManufacturer = repGroupManufacturerRepository\n .findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED);\n return Optional\n .ofNullable(repGroupManufacturer)\n .flatMap(e -> Optional.ofNullable(e.getB2bItemPricingPolicy()))\n .map(e -> e.equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE))\n .orElse(false);\n }\n}\n\nNote: I have assumed certain datatypes, which I don't have any impact on overall solution.\n", "Some if-else statements express business logic which should be anything but boring. The code you posted appears to contain at least some business logic but the manner in which it is written makes it difficult to read and maintain.\nThere are some rules I follow when refactoring this type of code:\n\n\"positive thinking\" - avoid if not statements, that is what else is for.\nreplace nested if-statements with functions.\nbe as lazy as possible, only lookup values when needed.\nuse variable names that have a meaning.\n\nOn 1, replace this\nif (x is not null) {\n // more code\n}\n\nwith\nif (x is null) {\n return;\n}\n// more code\n\nOn 2, replace this\nif (x > 1 ) {\n // lots of code\n}\n\nwith\nif (x > 1) {\n updateStuff(x);\n}\n\nfunction updateStuff(int x) {\n // lots of code\n}\n\nThis also opens up the opportunity to let the function return a value that can be used further on.\nOn 3, replace this\nx = queryDatabase(y);\nif (y > 1) {\n // use x\n}\n\nwith\nif (y > 1) {\n x = queryDatabase(y); \n // use x\n}\n\nFinally, on 4, I sometimes introduce boolean values to convey meaning to complex conditions. E.g. compare this:\nif ((x < 1 and y > 100) || (z not 0 and y < 1)) {\n // do stuff\n}\n\nwith\nboolean findPrice = (x < 1 and y > 100);\nboolean findProduct = (z not 0 and y < 1);\nif (findPrice || findProduct) {\n // do stuff\n}\n\nWhen all these rules are applied it becomes much easier to read the code and also easier to maintain and (unit) test the code.\n", "Disclaimer: it merely impossible to reimplement a chunk of code containing so much logic and guaranty that you can simply copy-past it, and it would work just fine.\nThe very first advice I can give to change the return type in your Repositories and leverage the Optional API (that alone wouldn't resolve all the issues, but it would give some room for improvement).\nSecondly, you need to break presented logic into self-contained meaningful peaces and give them names. The current code violates the first principle of SOLID - Single responsibility principle in a very obvious way. How can you test it, or how can change this functionality without rewriting from scratch? Such code is very hard to maintain.\nHere's my attempt to reimplement this logic, assuming that both Repositories would produce an Optional as a result:\npublic void foo(OrderDetail orderDetail, Item item) {\n if (!isValid(orderDetail, item, origin)) return;\n\n repGroupManufacturerRepository\n .findByRepGroupIDAndManufacturerIDAndRecordDeleted(repGroupID, manufacturerID, NOT_DELETED);\n .filter(manufacturer -> manufacturer.getB2bItemPricingPolicy() != null)\n .filter(manufacturer -> manufacturer.getB2bItemPricingPolicy().equalsIgnoreCase(ReptimeConstants.SHOWRETAILPRICE))\n .ifPresent(manufacturer -> itemSizeColorStyleRepository.findByRecordID(orderDetail.getItemSCSID())\n .filter(itemStyle -> itemSizeColorStyle.getRetailPrice() != null)\n .ifPresent(itemStyle -> {\n if (needToApplyItemPrice(orderDetail, item, itemStyle)) orderDetail.setUnitPrice(item.getRetailPrice());\n else if (needToApplyItemStylePrice(orderDetail, item, itemStyle)) orderDetail.setUnitPrice(item.getRetailPrice());\n else throw new NullPointerException(\"item price can not be null.\");\n })\n );\n}\n\npublic boolean isValid(OrderDetail orderDetail, Item item, Origin origin) {\n return orderDetail != null && item != null && !orderDetail.isUnitPriceModified()\n && origin != null\n && (origin.contains(\"b2baccess\") || origin.contains(\".myappdev\") && !origin.contains(\"apps.myappdev\"));\n}\n\npublic boolean needToApplyItemPrice(OrderDetail orderDetail, Item item, ItemSizeColorStyle itemStyle) {\n return (orderDetail.getItemSCSID() == null || itemStyle.getRetailPrice() == null)\n && item.getRetailPrice() != null;\n}\n\npublic boolean needToApplyItemStylePrice(OrderDetail orderDetail, Item item, ItemSizeColorStyle itemStyle) {\n return !(orderDetail.getItemSCSID() == null && item.getRetailPrice() != null)\n && itemStyle.getRetailPrice() != null;\n}\n\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "java", "spring_boot" ]
stackoverflow_0074678058_java_spring_boot.txt
Q: forEach vs for in: Different Behavior When Calling a Method I noticed that forEach and for in to produce different behavior. I have a list of RegExp and want to run hasMatch on each one. When iterating through the list using forEach, hasMatch never returns true. However, if I use for in, hasMatch returns true. Sample code: class Foo { final str = "Hello"; final regexes = [new RegExp(r"(\w+)")]; String a() { regexes.forEach((RegExp reg) { if (reg.hasMatch(str)) { return 'match'; } }); return 'no match'; } String b() { for (RegExp reg in regexes) { if (reg.hasMatch(str)) { return 'match'; } } return 'no match'; } } void main() { Foo foo = new Foo(); print(foo.a()); // prints "no match" print(foo.b()); // prints "match" } (DartPad with the above sample code) The only difference between the methods a and b is that a uses forEach and b uses for in, yet they produce different results. Why is this? A: Although there is a prefer_foreach lint, that recommendation is specifically for cases where you can use it with a tear-off (a reference to an existing function). Effective Dart recommends against using Iterable.forEach with anything else, and there is a corresponding avoid_function_literals_in_foreach_calls lint to enforce it. Except for those simple cases where the callback is a tear-off, Iterable.forEach is not any simpler than using a basic and more general for loop. There are more pitfalls using Iterable.forEach, and this is one of them. Iterable.forEach is a function that takes a callback as an argument. Iterable.forEach is not a control structure, and the callback is an ordinary function. You therefore cannot use break to stop iterating early or use continue to skip to the next iteration. A return statement in the callback returns from the callback, and the return value is ignored. The caller of Iterable.forEach will never receive the returned value and will never have an opportunity to propagate it. For example, in: bool f(List<int> list) { for (var i in list) { if (i == 42) { return true; } } return false; } the return true statement returns from the function f and stops iteration. In contrast, with forEach: bool g(List<int> list) { list.forEach((i) { if (i == 42) { return true; } }); return false; } the return true statement returns from only the callback. The function g will not return until it completes all iterations and reaches the return false statement at the end. This perhaps is clearer as: bool callback(int i) { if (i == 42) { return true; } } bool g(List<int> list) { list.forEach(callback); return false; } which makes it more obvious that: There is no way for callback to cause g to return true. callback does not return a value along all paths. (That's the problem you encountered.) Iterable.forEach must not be used with asynchronous callbacks. Because any value returned by the callback is ignored, asynchronous callbacks can never be waited upon. I should also point out that if you enable Dart's new null-safety features, which enable stricter type-checking, your forEach code will generate an error because it returns a value in a callback that is expected to have a void return value. A notable case where Iterable.forEach can be simpler than a regular for loop is if the object you're iterating over might be null: List<int>? nullableList; nullableList?.forEach((e) => ...); whereas a regular for loop would require an additional if check or doing: List<int>? nullableList; for (var e in nullableList ?? []) { ... } (In JavaScript, for-in has unintuitive pitfalls, so Array.forEach often is recommended instead. Perhaps that's why a lot of people seem to be conditioned to use a .forEach method over a built-in language construct. However, Dart does not share those pitfalls with JavaScript.) A: jamesdin! Everything you have shared about the limitations of forEach is correct however there's one part where you are wrong. In the code snippet showing the example of how you the return value from forEach is ignored, you have return true; inside the callback function for forEach which is not allowed as the callback has a return type of void and returning any other value from the callback is not allowed. Although you have mentioned that returning a value from within the callback will result in an error, I'm just pointing at the code snippet. Here's the signature for forEach Also, some more pitfalls of forEach are: One can't use break or continue statements. One can't get access to the index of the item as opposed to using the regular for loop
forEach vs for in: Different Behavior When Calling a Method
I noticed that forEach and for in to produce different behavior. I have a list of RegExp and want to run hasMatch on each one. When iterating through the list using forEach, hasMatch never returns true. However, if I use for in, hasMatch returns true. Sample code: class Foo { final str = "Hello"; final regexes = [new RegExp(r"(\w+)")]; String a() { regexes.forEach((RegExp reg) { if (reg.hasMatch(str)) { return 'match'; } }); return 'no match'; } String b() { for (RegExp reg in regexes) { if (reg.hasMatch(str)) { return 'match'; } } return 'no match'; } } void main() { Foo foo = new Foo(); print(foo.a()); // prints "no match" print(foo.b()); // prints "match" } (DartPad with the above sample code) The only difference between the methods a and b is that a uses forEach and b uses for in, yet they produce different results. Why is this?
[ "Although there is a prefer_foreach lint, that recommendation is specifically for cases where you can use it with a tear-off (a reference to an existing function). Effective Dart recommends against using Iterable.forEach with anything else, and there is a corresponding avoid_function_literals_in_foreach_calls lint to enforce it.\nExcept for those simple cases where the callback is a tear-off, Iterable.forEach is not any simpler than using a basic and more general for loop. There are more pitfalls using Iterable.forEach, and this is one of them.\n\nIterable.forEach is a function that takes a callback as an argument. Iterable.forEach is not a control structure, and the callback is an ordinary function. You therefore cannot use break to stop iterating early or use continue to skip to the next iteration.\n\nA return statement in the callback returns from the callback, and the return value is ignored. The caller of Iterable.forEach will never receive the returned value and will never have an opportunity to propagate it. For example, in:\nbool f(List<int> list) {\n for (var i in list) {\n if (i == 42) {\n return true;\n }\n }\n return false;\n}\n\nthe return true statement returns from the function f and stops iteration. In contrast, with forEach:\nbool g(List<int> list) {\n list.forEach((i) {\n if (i == 42) {\n return true;\n }\n });\n return false;\n}\n\nthe return true statement returns from only the callback. The function g will not return until it completes all iterations and reaches the return false statement at the end. This perhaps is clearer as:\nbool callback(int i) {\n if (i == 42) {\n return true;\n }\n}\n\nbool g(List<int> list) {\n list.forEach(callback);\n return false;\n}\n\nwhich makes it more obvious that:\n\nThere is no way for callback to cause g to return true.\ncallback does not return a value along all paths.\n\n(That's the problem you encountered.)\n\nIterable.forEach must not be used with asynchronous callbacks. Because any value returned by the callback is ignored, asynchronous callbacks can never be waited upon.\n\n\nI should also point out that if you enable Dart's new null-safety features, which enable stricter type-checking, your forEach code will generate an error because it returns a value in a callback that is expected to have a void return value.\nA notable case where Iterable.forEach can be simpler than a regular for loop is if the object you're iterating over might be null:\nList<int>? nullableList;\nnullableList?.forEach((e) => ...);\n\nwhereas a regular for loop would require an additional if check or doing:\nList<int>? nullableList;\nfor (var e in nullableList ?? []) {\n ...\n}\n\n(In JavaScript, for-in has unintuitive pitfalls, so Array.forEach often is recommended instead. Perhaps that's why a lot of people seem to be conditioned to use a .forEach method over a built-in language construct. However, Dart does not share those pitfalls with JavaScript.)\n", " jamesdin! Everything you have shared about the limitations of forEach is correct however there's one part where you are wrong. In the code snippet showing the example of how you the return value from forEach is ignored, you have return true; inside the callback function for forEach which is not allowed as the callback has a return type of void and returning any other value from the callback is not allowed.\nAlthough you have mentioned that returning a value from within the callback will result in an error, I'm just pointing at the code snippet.\nHere's the signature for forEach\nAlso, some more pitfalls of forEach are:\n\nOne can't use break or continue statements.\nOne can't get access to the index of the item as opposed to using the regular for loop\n\n" ]
[ 20, 0 ]
[]
[]
[ "dart" ]
stackoverflow_0065417146_dart.txt
Q: How to lookup with nested ref in aggregate Mongodb? I am using $lookup aggregate to join collection but I am facing a problem from the result. Specifically, I have three collections look like: Post: id: 1, title: 'my title', content: 'bla bla bla', ... Comment: post_id: 1, user_id: '123', content: 'great article!!!', User: id: '123', name: 'Ferb' My code to query post and this post also contain comment: $lookup: { from: 'comments', localField: 'id', foreignField: 'post_id', as: 'comments', }, $project: { id: 1, title: 1, content: 1, comments: '$comments' } According to the results i got: id: 1, title: 'my title', content: 'bla bla bla', comments: [ post_id: 1, user_id: '123', // needs to $lookup from User model content: 'great article!!!', ] But this is not what I expected, I want to $lookup user_id in comments list with nested $lookup. What should I do to get the expected results? A: Personally, I am against the idea of nested $lookup, as that is likely to reduce the readability of query. I prefer something simple as $lookup twice. db.posts.aggregate([ { "$lookup": { "from": "comments", "localField": "id", "foreignField": "post_id", "as": "commentsLookup" } }, { "$unwind": "$commentsLookup" }, { "$lookup": { "from": "users", "localField": "commentsLookup.user_id", "foreignField": "id", "as": "commentsLookup.usersLookup" } }, { "$unwind": "$commentsLookup.usersLookup" }, { $group: { _id: "$_id", title: { $first: "$title" }, content: { $first: "$content" }, commentsLookup: { $push: "$commentsLookup" } } } ]) Mongo Playground However, if you insists in nested $lookup, here is one way. db.posts.aggregate([ { "$lookup": { "from": "comments", "localField": "id", "foreignField": "post_id", "pipeline": [ { "$lookup": { "from": "users", "localField": "user_id", "foreignField": "id", "as": "usersLookup" } }, { "$unwind": "$usersLookup" } ], "as": "commentsLookup" } }, { "$unwind": "$commentsLookup" } ]) Mongo Playground
How to lookup with nested ref in aggregate Mongodb?
I am using $lookup aggregate to join collection but I am facing a problem from the result. Specifically, I have three collections look like: Post: id: 1, title: 'my title', content: 'bla bla bla', ... Comment: post_id: 1, user_id: '123', content: 'great article!!!', User: id: '123', name: 'Ferb' My code to query post and this post also contain comment: $lookup: { from: 'comments', localField: 'id', foreignField: 'post_id', as: 'comments', }, $project: { id: 1, title: 1, content: 1, comments: '$comments' } According to the results i got: id: 1, title: 'my title', content: 'bla bla bla', comments: [ post_id: 1, user_id: '123', // needs to $lookup from User model content: 'great article!!!', ] But this is not what I expected, I want to $lookup user_id in comments list with nested $lookup. What should I do to get the expected results?
[ "Personally, I am against the idea of nested $lookup, as that is likely to reduce the readability of query.\nI prefer something simple as $lookup twice.\ndb.posts.aggregate([\n {\n \"$lookup\": {\n \"from\": \"comments\",\n \"localField\": \"id\",\n \"foreignField\": \"post_id\",\n \"as\": \"commentsLookup\"\n }\n },\n {\n \"$unwind\": \"$commentsLookup\"\n },\n {\n \"$lookup\": {\n \"from\": \"users\",\n \"localField\": \"commentsLookup.user_id\",\n \"foreignField\": \"id\",\n \"as\": \"commentsLookup.usersLookup\"\n }\n },\n {\n \"$unwind\": \"$commentsLookup.usersLookup\"\n },\n {\n $group: {\n _id: \"$_id\",\n title: {\n $first: \"$title\"\n },\n content: {\n $first: \"$content\"\n },\n commentsLookup: {\n $push: \"$commentsLookup\"\n }\n }\n }\n])\n\nMongo Playground\n\nHowever, if you insists in nested $lookup, here is one way.\ndb.posts.aggregate([\n {\n \"$lookup\": {\n \"from\": \"comments\",\n \"localField\": \"id\",\n \"foreignField\": \"post_id\",\n \"pipeline\": [\n {\n \"$lookup\": {\n \"from\": \"users\",\n \"localField\": \"user_id\",\n \"foreignField\": \"id\",\n \"as\": \"usersLookup\"\n }\n },\n {\n \"$unwind\": \"$usersLookup\"\n }\n ],\n \"as\": \"commentsLookup\"\n }\n },\n {\n \"$unwind\": \"$commentsLookup\"\n }\n])\n\nMongo Playground\n" ]
[ 1 ]
[]
[]
[ "aggregation_framework", "mongodb", "mongodb_query", "mongoose", "node.js" ]
stackoverflow_0074679728_aggregation_framework_mongodb_mongodb_query_mongoose_node.js.txt
Q: Problem with Spring Batch reader from PostgreSQL DB1 to write in PostgreSQL DB2 I have a problem when I want to read data from PostgreSQL Author DB and write to the PostgreSQL Book DB. I create configurations for the two DB and this is work well. My problem is in ItemReader. This is my error: Encountered an error executing step ETL-file-load in job ETL-Load error: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author] This is my SpringBatchConfig configuration class: @Configuration @EnableBatchProcessing public class SpringBatchConfig { @Autowired private EntityManagerFactory entityManagerFactory; @Bean public Job job(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, ItemReader<Author> itemReader, ItemProcessor<Author, Book> itemProcessor, ItemWriter<Book> itemWriter ) { Step step = stepBuilderFactory.get("ETL-file-load") .<Author, Book>chunk(100) .reader(itemReader) .processor(itemProcessor) .writer(itemWriter) .build(); return jobBuilderFactory.get("ETL-Load") .incrementer(new RunIdIncrementer()) .start(step) .build(); } @Bean public ItemReader<Author> itemReader() throws Exception { JpaPagingItemReader<Author> reader = new JpaPagingItemReader<Author>(); reader.setEntityManagerFactory(entityManagerFactory); reader.setQueryString("select id,firstname,lastname from author"); reader.setPageSize(5); reader.afterPropertiesSet(); return reader; } } This is my Processor class: @Component public class Processor implements ItemProcessor<Author, Book> { @Override public Book process(Author item) throws Exception { Book book = new Book(); book.setName(item.getFirstname()); return book; } } This is my DBWriter Class: @Component public class DBWriter implements ItemWriter<Book> { @Autowired private BookRepository bookRepository; @Override public void write(List<? extends Book> book) throws Exception { System.out.println("Data Saved for Users: " + book); bookRepository.save(book); } } This is my Author JPA: @Entity @Table(name = "author") public class Author implements Serializable { private static final long serialVersionUID = -1848119459950659679L; @Id @Column(name = "id") private Long id; @Column(name = "firstname") private String firstname; @Column(name = "lastname") private String lastname; This is my application.properties file: spring.postgresql.datasource.url=jdbc:postgresql://localhost:5432/book_db spring.postgresql.datasource.username=admin spring.postgresql.datasource.password=admin spring.postgresql.datasource.driver-class-name=org.postgresql.Driver # ------------------------------ # POSTGRESQL DATABASE 2 CONFIGURATION # ------------------------------ spring.mysql.datasource.url=jdbc:postgresql://localhost:5432/author_db spring.mysql.datasource.username=admin spring.mysql.datasource.password=admin spring.mysql.datasource.driver-class-name=org.postgresql.Driver This is Auhtor in DB: This is my full output: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1679) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1608) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191] at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE] at com.sun.proxy.$Proxy80.createQuery(Unknown Source) ~[na:na] at org.springframework.batch.item.database.JpaPagingItemReader.createQuery(JpaPagingItemReader.java:112) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.item.database.JpaPagingItemReader.doReadPage(JpaPagingItemReader.java:203) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.item.database.AbstractPagingItemReader.doRead(AbstractPagingItemReader.java:108) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:88) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:91) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.SimpleChunkProvider.read(SimpleChunkProvider.java:157) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:116) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:110) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:69) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191] at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at com.sun.proxy.$Proxy89.run(Unknown Source) [na:na] at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:216) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:233) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:125) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:119) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:800) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:784) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:771) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at com.roufid.tutorial.Application.main(Application.java:10) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.4.2.RELEASE.jar:1.4.2.RELEASE] Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author] at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1894) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] ... 62 common frames omitted Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:76) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:321) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3687) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3576) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:716) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:572) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:309) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:257) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] ... 70 common frames omitted A: Your query is not a valid JPA Query. This would be a valid query: select a.id, a.firstname, a.lastname from Author a BUT you want to select the whole Author so it must be select a from Author a A: I don't know if your problem is solved, but I found the solution. "select id,firstname,lastname from author" replace "from id,firstname,lastname from author"
Problem with Spring Batch reader from PostgreSQL DB1 to write in PostgreSQL DB2
I have a problem when I want to read data from PostgreSQL Author DB and write to the PostgreSQL Book DB. I create configurations for the two DB and this is work well. My problem is in ItemReader. This is my error: Encountered an error executing step ETL-file-load in job ETL-Load error: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author] This is my SpringBatchConfig configuration class: @Configuration @EnableBatchProcessing public class SpringBatchConfig { @Autowired private EntityManagerFactory entityManagerFactory; @Bean public Job job(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, ItemReader<Author> itemReader, ItemProcessor<Author, Book> itemProcessor, ItemWriter<Book> itemWriter ) { Step step = stepBuilderFactory.get("ETL-file-load") .<Author, Book>chunk(100) .reader(itemReader) .processor(itemProcessor) .writer(itemWriter) .build(); return jobBuilderFactory.get("ETL-Load") .incrementer(new RunIdIncrementer()) .start(step) .build(); } @Bean public ItemReader<Author> itemReader() throws Exception { JpaPagingItemReader<Author> reader = new JpaPagingItemReader<Author>(); reader.setEntityManagerFactory(entityManagerFactory); reader.setQueryString("select id,firstname,lastname from author"); reader.setPageSize(5); reader.afterPropertiesSet(); return reader; } } This is my Processor class: @Component public class Processor implements ItemProcessor<Author, Book> { @Override public Book process(Author item) throws Exception { Book book = new Book(); book.setName(item.getFirstname()); return book; } } This is my DBWriter Class: @Component public class DBWriter implements ItemWriter<Book> { @Autowired private BookRepository bookRepository; @Override public void write(List<? extends Book> book) throws Exception { System.out.println("Data Saved for Users: " + book); bookRepository.save(book); } } This is my Author JPA: @Entity @Table(name = "author") public class Author implements Serializable { private static final long serialVersionUID = -1848119459950659679L; @Id @Column(name = "id") private Long id; @Column(name = "firstname") private String firstname; @Column(name = "lastname") private String lastname; This is my application.properties file: spring.postgresql.datasource.url=jdbc:postgresql://localhost:5432/book_db spring.postgresql.datasource.username=admin spring.postgresql.datasource.password=admin spring.postgresql.datasource.driver-class-name=org.postgresql.Driver # ------------------------------ # POSTGRESQL DATABASE 2 CONFIGURATION # ------------------------------ spring.mysql.datasource.url=jdbc:postgresql://localhost:5432/author_db spring.mysql.datasource.username=admin spring.mysql.datasource.password=admin spring.mysql.datasource.driver-class-name=org.postgresql.Driver This is Auhtor in DB: This is my full output: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1679) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1608) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191] at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE] at com.sun.proxy.$Proxy80.createQuery(Unknown Source) ~[na:na] at org.springframework.batch.item.database.JpaPagingItemReader.createQuery(JpaPagingItemReader.java:112) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.item.database.JpaPagingItemReader.doReadPage(JpaPagingItemReader.java:203) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.item.database.AbstractPagingItemReader.doRead(AbstractPagingItemReader.java:108) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:88) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:91) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.SimpleChunkProvider.read(SimpleChunkProvider.java:157) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:116) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:110) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:69) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191] at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) [spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) [spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE] at com.sun.proxy.$Proxy89.run(Unknown Source) [na:na] at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:216) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:233) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:125) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:119) [spring-boot-autoconfigure-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:800) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:784) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:771) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE] at com.roufid.tutorial.Application.main(Application.java:10) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.4.2.RELEASE.jar:1.4.2.RELEASE] Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped [select id,firstname,lastname from author] at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1894) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] ... 62 common frames omitted Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: author is not mapped at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:76) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:321) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3687) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3576) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:716) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:572) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:309) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:257) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] ... 70 common frames omitted
[ "Your query is not a valid JPA Query.\nThis would be a valid query:\nselect a.id, a.firstname, a.lastname from Author a\n\nBUT you want to select the whole Author so it must be\nselect a from Author a\n\n", "I don't know if your problem is solved, but I found the solution.\n\"select id,firstname,lastname from author\"\n\nreplace\n\"from id,firstname,lastname from author\"\n\n" ]
[ 0, 0 ]
[]
[]
[ "jpa", "postgresql", "spring_batch", "spring_boot" ]
stackoverflow_0056073664_jpa_postgresql_spring_batch_spring_boot.txt
Q: Can't insert row into Cockroachdb table using pg I have an AWS Lamda function that gets some computed data and then is supposed to insert it into a table in Cockroach. I can create the table, but I cannot add rows into it. Here is the pg part of my code: (I'll end up using pooling, but the connection is for testing and should do the trick): It's also worth noting that my query looks exactly like the ones in node-postgres' examples, as well as cockroach's documentation. const dbClient = new Client("omitted but it works") try { await dbClient.connect() await dbClient.query(`CREATE TABLE IF NOT EXISTS outputs(user_id STRING NOT NULL, date_created TIMESTAMPTZ, date_modified TIMESTAMPTZ, content STRING NOT NULL, image_url STRING NOT NULL)`) await dbClient.query(`INSERT INTO outputs( user_id, content, image_url) VALUES( $1, $2, $3 )`, [ userID, response.results.choices[0].text, response.imageResponse[0].url, ]) } catch (e) { } finally { dbClient.end() } } A: Apparently I just didn't understand how pg/node-postgres handles dynamic values. I had to install and use pg-format to allow me to safely use dynamic values. Here is an example: const date = new Date() await dbClient.query(`CREATE TABLE IF NOT EXISTS outputs(_id STRING PRIMARY KEY, user_id STRING NOT NULL, date_created TIMESTAMPTZ, date_modified TIMESTAMPTZ, content STRING NOT NULL, image_url STRING NOT NULL)`) const query = format(`INSERT INTO tablename ( _id, user_id, date_created, content, image_url) VALUES( %L, %L, %L, %L, %L )`, response.id, userID, date.toISOString(), response.choices[0].text, response.url
Can't insert row into Cockroachdb table using pg
I have an AWS Lamda function that gets some computed data and then is supposed to insert it into a table in Cockroach. I can create the table, but I cannot add rows into it. Here is the pg part of my code: (I'll end up using pooling, but the connection is for testing and should do the trick): It's also worth noting that my query looks exactly like the ones in node-postgres' examples, as well as cockroach's documentation. const dbClient = new Client("omitted but it works") try { await dbClient.connect() await dbClient.query(`CREATE TABLE IF NOT EXISTS outputs(user_id STRING NOT NULL, date_created TIMESTAMPTZ, date_modified TIMESTAMPTZ, content STRING NOT NULL, image_url STRING NOT NULL)`) await dbClient.query(`INSERT INTO outputs( user_id, content, image_url) VALUES( $1, $2, $3 )`, [ userID, response.results.choices[0].text, response.imageResponse[0].url, ]) } catch (e) { } finally { dbClient.end() } }
[ "Apparently I just didn't understand how pg/node-postgres handles dynamic values. I had to install and use pg-format to allow me to safely use dynamic values. Here is an example:\n const date = new Date()\n await dbClient.query(`CREATE TABLE IF NOT EXISTS outputs(_id STRING PRIMARY KEY, user_id STRING NOT NULL, date_created TIMESTAMPTZ, date_modified TIMESTAMPTZ, content STRING NOT NULL, image_url STRING NOT NULL)`)\n const query = format(`INSERT INTO tablename (\n _id,\n user_id,\n date_created,\n content, \n image_url) \n VALUES(\n %L,\n %L,\n %L,\n %L,\n %L\n )`,\n response.id,\n userID,\n date.toISOString(),\n response.choices[0].text,\n response.url\n\n" ]
[ 0 ]
[]
[]
[ "aws_lambda", "cockroachdb", "node.js", "node_postgres", "postgresql" ]
stackoverflow_0074325315_aws_lambda_cockroachdb_node.js_node_postgres_postgresql.txt
Q: Invalid Python SDK in PyCharm Since this morning, I'm no longer able to run projects in PyCharm. When generating a new virtual environment, I get an "Invalid Python SDK" error. Cannot set up a python SDK at Python 3.11... The SDK seems invalid. What I noticed: No matter what base interpreter I select (3.8, 3.9, 3.10) Pycharm always generates a Python 3.11 interpreter. I did completely uninstall PyCharm, as well as all my python installations and reinstalled everything. I also went through the "Repair IDE" option in PyCharm. I also removed and recreated all virtual environments. When I run "cmd" and type 'python' then python 3.10.1 opens without a problem. This morning, I installed a new antivirus software that did some checks and deleted some "unnecessary files" - maybe it is related (antivirus software is uninstalled again). A: I had the same problem on Linux. Solved it by invalidating caches as suggested here: https://stackoverflow.com/a/45099651/3990607 In pycharm click on File menu, then choose Invalidate caches..., tick all 4 boxes and then restart PyCharm. Solved the problem for me. A: Dealt with the same issue despite using python and pycharm without issue for months. Recently kept giving me the error despite changing the PATH variable of my system and even manually pathing within pycharm. After hours of reinstalling pycharm, python and even jumping around versions with no success it turned out it was because my python directory had a space in it that it just randomly decided to break. For anyone who has tried what seems like everything to no avail ensure that NO part of the path to your python directory contains spaces A: Had the same issue just today. I was able to resolve it by uninstalling python 3.10.1 and then reinstalling it under directory "C:/Program Files" instead of the default directory where it goes. There are many other fixes also suggested by people all over the internet such as: Installing an older version of Pycharm i.e. 2021.2 Allowing the pycharmProjects folder in windows defender But the change of installation directory is what worked for me. A: Python 3.10 version installed through windows store didn't have any spaces in default directory names (as my username doesn't have a space within itself). I id invalidated caches through the file menu. However, patapouf_ai had suggested doing it for Linux. The problem was resolved for me after installing and then reinstalling it through windows' remove and store, and it seems it's been caused by changing windows' user account control level to "never notify." The other possibility is that somehow python 3.10 has stopped functioning without a good reason and lost recognition by windows (not updated or modified by any means). A: using IDLE import sys print(sys.executable) #output is a path to where the interpreter is, copy path PyCharm / file / settings / Project / Python Interpreter / show all / paste path A: I had the same issue. I got around it by installing an older version of PyCharm. A: Check if your python executable is named python.exe! I had the same problem and I solved it by going into C:\Users<user>\AppData\Local\Programs\Python\Python310. My python executable was named python3.exe, but Pycharm needs python.exe for some unknown reason. So I copied python3.exe, pasted it in the same directory and renamed it to python.exe, and all started working magically. Maybe just renaming will also work. A: I had this same error on windows, none of the answers in this thread worked. But i found a solution so i will share it. Go to %appdata%/Jetbrains/ and search for jdk.table, backup the file and delete it (this will delete all your interpreters configs) close all your pycharm instances, and start them again. After that just add your interpreter like you normally would. This is what worked for me.
Invalid Python SDK in PyCharm
Since this morning, I'm no longer able to run projects in PyCharm. When generating a new virtual environment, I get an "Invalid Python SDK" error. Cannot set up a python SDK at Python 3.11... The SDK seems invalid. What I noticed: No matter what base interpreter I select (3.8, 3.9, 3.10) Pycharm always generates a Python 3.11 interpreter. I did completely uninstall PyCharm, as well as all my python installations and reinstalled everything. I also went through the "Repair IDE" option in PyCharm. I also removed and recreated all virtual environments. When I run "cmd" and type 'python' then python 3.10.1 opens without a problem. This morning, I installed a new antivirus software that did some checks and deleted some "unnecessary files" - maybe it is related (antivirus software is uninstalled again).
[ "I had the same problem on Linux. Solved it by invalidating caches as suggested here:\nhttps://stackoverflow.com/a/45099651/3990607\nIn pycharm click on File menu, then choose Invalidate caches..., tick all 4 boxes and then restart PyCharm. Solved the problem for me.\n", "Dealt with the same issue despite using python and pycharm without issue for months. Recently kept giving me the error despite changing the PATH variable of my system and even manually pathing within pycharm. After hours of reinstalling pycharm, python and even jumping around versions with no success it turned out it was because my python directory had a space in it that it just randomly decided to break.\nFor anyone who has tried what seems like everything to no avail ensure that NO part of the path to your python directory contains spaces\n", "Had the same issue just today. I was able to resolve it by uninstalling python 3.10.1 and then reinstalling it under directory \"C:/Program Files\" instead of the default directory where it goes.\nThere are many other fixes also suggested by people all over the internet such as:\n\nInstalling an older version of Pycharm i.e. 2021.2\nAllowing the pycharmProjects folder in windows defender\n\nBut the change of installation directory is what worked for me.\n", "Python 3.10 version installed through windows store didn't have any spaces in default directory names (as my username doesn't have a space within itself).\nI id invalidated caches through the file menu. However, patapouf_ai had suggested doing it for Linux.\nThe problem was resolved for me after installing and then reinstalling it through windows' remove and store, and it seems it's been caused by changing windows' user account control level to \"never notify.\" The other possibility is that somehow python 3.10 has stopped functioning without a good reason and lost recognition by windows (not updated or modified by any means).\n", "using IDLE\nimport sys\nprint(sys.executable)\n#output is a path to where the interpreter is, copy path\nPyCharm / file / settings / Project / Python Interpreter / show all / paste path\n", "I had the same issue. I got around it by installing an older version of PyCharm.\n", "Check if your python executable is named python.exe!\nI had the same problem and I solved it by going into C:\\Users<user>\\AppData\\Local\\Programs\\Python\\Python310. My python executable was named python3.exe, but Pycharm needs python.exe for some unknown reason. So I\n\ncopied python3.exe,\npasted it in the same directory and\nrenamed it to python.exe, and all started working magically. Maybe just renaming will also work.\n\n", "I had this same error on windows, none of the answers in this thread worked.\nBut i found a solution so i will share it.\nGo to %appdata%/Jetbrains/ and search for jdk.table, backup the file and delete it (this will delete all your interpreters configs) close all your pycharm instances, and start them again. After that just add your interpreter like you normally would.\nThis is what worked for me.\n" ]
[ 7, 4, 0, 0, 0, 0, 0, 0 ]
[ "on Pycharm, click on up right corner search button --> wrire swştch python interpreter --> add new interpreter --> add local interpreter --> hit OK\n" ]
[ -1 ]
[ "pycharm", "python" ]
stackoverflow_0070664467_pycharm_python.txt
Q: Why @auth0/angular-jwt not woking for Angular9? I tried to install @auth0/angular-jwtfor angular9 project. module.ts imports: [ HttpClientModule, BrowserAnimationsModule, JwtModule.forRoot({ config: { tokenGetter: tokenGetter, allowedDomains: ["example.com"], disallowedRoutes: ["http://example.com/examplebadroute/"], }, }), ] but when run the program it give me following error enter image description here @auth0/angular-jwt A: Quick look at the @auth0/angular-jwt npm site: Supported Angular versions This project only supports the actively supported versions of Angular as stated in the Angular documentation. Whilst other versions might be compatible they are not actively supported The active versions of Angular are 13 and above: https://angular.io/guide/releases#actively-supported-versions
Why @auth0/angular-jwt not woking for Angular9?
I tried to install @auth0/angular-jwtfor angular9 project. module.ts imports: [ HttpClientModule, BrowserAnimationsModule, JwtModule.forRoot({ config: { tokenGetter: tokenGetter, allowedDomains: ["example.com"], disallowedRoutes: ["http://example.com/examplebadroute/"], }, }), ] but when run the program it give me following error enter image description here @auth0/angular-jwt
[ "Quick look at the @auth0/angular-jwt npm site:\nSupported Angular versions\n\nThis project only supports the actively supported versions of Angular as stated in the Angular documentation. Whilst other versions might be compatible they are not actively supported\n\nThe active versions of Angular are 13 and above:\nhttps://angular.io/guide/releases#actively-supported-versions\n" ]
[ 0 ]
[]
[]
[ "angular" ]
stackoverflow_0074679113_angular.txt
Q: Read and write to binary files in C? Does anyone have an example of code that can write to a binary file. And also code that can read a binary file and output to screen. Looking at examples I can write to a file ok But when I try to read from a file it is not outputting correctly. A: Reading and writing binary files is pretty much the same as any other file, the only difference is how you open it: unsigned char buffer[10]; FILE *ptr; ptr = fopen("test.bin","rb"); // r for read, b for binary fread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer You said you can read it, but it's not outputting correctly... keep in mind that when you "output" this data, you're not reading ASCII, so it's not like printing a string to the screen: for(int i = 0; i<10; i++) printf("%u ", buffer[i]); // prints a series of bytes Writing to a file is pretty much the same, with the exception that you're using fwrite() instead of fread(): FILE *write_ptr; write_ptr = fopen("test.bin","wb"); // w for write, b for binary fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer Since we're talking Linux.. there's an easy way to do a sanity check. Install hexdump on your system (if it's not already on there) and dump your file: mike@mike-VirtualBox:~/C$ hexdump test.bin 0000000 457f 464c 0102 0001 0000 0000 0000 0000 0000010 0001 003e 0001 0000 0000 0000 0000 0000 ... Now compare that to your output: mike@mike-VirtualBox:~/C$ ./a.out 127 69 76 70 2 1 1 0 0 0 hmm, maybe change the printf to a %x to make this a little clearer: mike@mike-VirtualBox:~/C$ ./a.out 7F 45 4C 46 2 1 1 0 0 0 Hey, look! The data matches up now*. Awesome, we must be reading the binary file correctly! *Note the bytes are just swapped on the output but that data is correct, you can adjust for this sort of thing A: There are a few ways to do it. If I want to read and write binary I usually use open(), read(), write(), close(). Which are completely different than doing a byte at a time. You work with integer file descriptors instead of FILE * variables. fileno will get an integer descriptor from a FILE * BTW. You read a buffer full of data, say 32k bytes at once. The buffer is really an array which you can read from really fast because it's in memory. And reading and writing many bytes at once is faster than one at a time. It's called a blockread in Pascal I think, but read() is the C equivalent. I looked but I don't have any examples handy. OK, these aren't ideal because they also are doing stuff with JPEG images. Here's a read, you probably only care about the part from open() to close(). fbuf is the array to read into, sb.st_size is the file size in bytes from a stat() call. fd = open(MASKFNAME,O_RDONLY); if (fd != -1) { read(fd,fbuf,sb.st_size); close(fd); splitmask(fbuf,(uint32_t)sb.st_size); // look at lines, etc have_mask = 1; } Here's a write: (here pix is the byte array, jwidth and jheight are the JPEG width and height so for RGB color we write height * width * 3 color bytes). It's the # of bytes to write. void simpdump(uint8_t *pix, char *nm) { // makes a raw aka .data file int sdfd; sdfd = open(nm,O_WRONLY | O_CREAT); if (sdfd == -1) { printf("bad open\n"); exit(-1); } printf("width: %i height: %i\n",jwidth,jheight); // to the console write(sdfd,pix,(jwidth*jheight*3)); close(sdfd); } Look at man 2 open, also read, write, close. Also this old-style jpeg example.c: https://github.com/LuaDist/libjpeg/blob/master/example.c I'm reading and writing an entire image at once here. But they're binary reads and writes of bytes, just a lot at once. "But when I try to read from a file it is not outputting correctly." Hmmm. If you read a number 65 that's (decimal) ASCII for an A. Maybe you should look at man ascii too. If you want a 1 that's ASCII 0x31. A char variable is a tiny 8-bit integer really, if you do a printf as a %i you get the ASCII value, if you do a %c you get the character. Do %x for hexadecimal. All from the same number between 0 and 255. A: I'm quite happy with my "make a weak pin storage program" solution. Maybe it will help people who need a very simple binary file IO example to follow. $ ls WeakPin my_pin_code.pin weak_pin.c $ ./WeakPin Pin: 45 47 49 32 $ ./WeakPin 8 2 $ Need 4 ints to write a new pin! $./WeakPin 8 2 99 49 Pin saved. $ ./WeakPin Pin: 8 2 99 49 $ $ cat weak_pin.c // a program to save and read 4-digit pin codes in binary format #include <stdio.h> #include <stdlib.h> #define PIN_FILE "my_pin_code.pin" typedef struct { unsigned short a, b, c, d; } PinCode; int main(int argc, const char** argv) { if (argc > 1) // create pin { if (argc != 5) { printf("Need 4 ints to write a new pin!\n"); return -1; } unsigned short _a = atoi(argv[1]); unsigned short _b = atoi(argv[2]); unsigned short _c = atoi(argv[3]); unsigned short _d = atoi(argv[4]); PinCode pc; pc.a = _a; pc.b = _b; pc.c = _c; pc.d = _d; FILE *f = fopen(PIN_FILE, "wb"); // create and/or overwrite if (!f) { printf("Error in creating file. Aborting.\n"); return -2; } // write one PinCode object pc to the file *f fwrite(&pc, sizeof(PinCode), 1, f); fclose(f); printf("Pin saved.\n"); return 0; } // else read existing pin FILE *f = fopen(PIN_FILE, "rb"); if (!f) { printf("Error in reading file. Abort.\n"); return -3; } PinCode pc; fread(&pc, sizeof(PinCode), 1, f); fclose(f); printf("Pin: "); printf("%hu ", pc.a); printf("%hu ", pc.b); printf("%hu ", pc.c); printf("%hu\n", pc.d); return 0; } $ A: This is an example to read and write binary jjpg or wmv video file. FILE *fout; FILE *fin; Int ch; char *s; fin=fopen("D:\\pic.jpg","rb"); if(fin==NULL) { printf("\n Unable to open the file "); exit(1); } fout=fopen("D:\\ newpic.jpg","wb"); ch=fgetc(fin); while (ch!=EOF) { s=(char *)ch; printf("%c",s); ch=fgetc (fin): fputc(s,fout); s++; } printf("data read and copied"); fclose(fin); fclose(fout); A: I really struggled to find a way to read a binary file into a byte array in C++ that would output the same hex values I see in a hex editor. After much trial and error, this seems to be the fastest way to do so without extra casts. By default it loads the entire file into memory, but only prints the first 1000 bytes. string Filename = "BinaryFile.bin"; FILE* pFile; pFile = fopen(Filename.c_str(), "rb"); fseek(pFile, 0L, SEEK_END); size_t size = ftell(pFile); fseek(pFile, 0L, SEEK_SET); uint8_t* ByteArray; ByteArray = new uint8_t[size]; if (pFile != NULL) { int counter = 0; do { ByteArray[counter] = fgetc(pFile); counter++; } while (counter <= size); fclose(pFile); } for (size_t i = 0; i < 800; i++) { printf("%02X ", ByteArray[i]); } A: this questions is linked with the question How to write binary data file on C and plot it using Gnuplot by CAMILO HG. I know that the real problem have two parts: 1) Write the binary data file, 2) Plot it using Gnuplot. The first part has been very clearly answered here, so I do not have something to add. For the second, the easy way is send the people to the Gnuplot manual, and I sure someone find a good answer, but I do not find it in the web, so I am going to explain one solution (which must be in the real question, but I new in stackoverflow and I can not answer there): After write your binary data file using fwrite(), you should create a very simple program in C, a reader. The reader only contains the same structure as the writer, but you use fread() instead fwrite(). So it is very ease to generate this program: copy in the reader.c file the writing part of your original code and change write for read (and "wb" for "rb"). In addition, you could include some checks for the data, for example, if the length of the file is correct. And finally, your program need to print the data in the standard output using a printf(). For be clear: your program run like this $ ./reader data.dat X_position Y_position (it must be a comment for Gnuplot)* 1.23 2.45 2.54 3.12 5.98 9.52 Okey, with this program, in Gnuplot you only need to pipe the standard output of the reader to the Gnuplot, something like this: plot '< ./reader data.dat' This line, run the program reader, and the output is connected with Gnuplot and it plot the data. *Because Gnuplot is going to read the output of the program, you must know what can Gnuplot read and plot and what can not. A: #include <stdio.h> #include <stdlib.h> main(int argc, char **argv) //int argc; char **argv; { int wd; FILE *in, *out; if(argc != 3) { printf("Input and output file are to be specified\n"); exit(1); } in = fopen(argv[1], "rb"); out = fopen(argv[2], "wb"); if(in == NULL || out == NULL) { /* open for write */ printf("Cannot open an input and an output file.\n"); getchar(); exit(0); } while(wd = getw(in), !feof(in)) putw(wd, out); fclose(in); fclose(out); }
Read and write to binary files in C?
Does anyone have an example of code that can write to a binary file. And also code that can read a binary file and output to screen. Looking at examples I can write to a file ok But when I try to read from a file it is not outputting correctly.
[ "Reading and writing binary files is pretty much the same as any other file, the only difference is how you open it:\nunsigned char buffer[10];\nFILE *ptr;\n\nptr = fopen(\"test.bin\",\"rb\"); // r for read, b for binary\n\nfread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer\n\nYou said you can read it, but it's not outputting correctly... keep in mind that when you \"output\" this data, you're not reading ASCII, so it's not like printing a string to the screen:\nfor(int i = 0; i<10; i++)\n printf(\"%u \", buffer[i]); // prints a series of bytes\n\nWriting to a file is pretty much the same, with the exception that you're using fwrite() instead of fread():\nFILE *write_ptr;\n\nwrite_ptr = fopen(\"test.bin\",\"wb\"); // w for write, b for binary\n\nfwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer\n\n\nSince we're talking Linux.. there's an easy way to do a sanity check. Install hexdump on your system (if it's not already on there) and dump your file:\nmike@mike-VirtualBox:~/C$ hexdump test.bin\n0000000 457f 464c 0102 0001 0000 0000 0000 0000\n0000010 0001 003e 0001 0000 0000 0000 0000 0000\n...\n\nNow compare that to your output:\nmike@mike-VirtualBox:~/C$ ./a.out \n127 69 76 70 2 1 1 0 0 0\n\nhmm, maybe change the printf to a %x to make this a little clearer:\nmike@mike-VirtualBox:~/C$ ./a.out \n7F 45 4C 46 2 1 1 0 0 0\n\nHey, look! The data matches up now*. Awesome, we must be reading the binary file correctly!\n*Note the bytes are just swapped on the output but that data is correct, you can adjust for this sort of thing\n", "There are a few ways to do it. If I want to read and write binary I usually use open(), read(), write(), close(). Which are completely different than doing a byte at a time. You work with integer file descriptors instead of FILE * variables. fileno will get an integer descriptor from a FILE * BTW. You read a buffer full of data, say 32k bytes at once. The buffer is really an array which you can read from really fast because it's in memory. And reading and writing many bytes at once is faster than one at a time. It's called a blockread in Pascal I think, but read() is the C equivalent.\nI looked but I don't have any examples handy. OK, these aren't ideal because they also are doing stuff with JPEG images. Here's a read, you probably only care about the part from open() to close(). fbuf is the array to read into,\nsb.st_size is the file size in bytes from a stat() call.\n fd = open(MASKFNAME,O_RDONLY);\n if (fd != -1) {\n read(fd,fbuf,sb.st_size);\n close(fd);\n splitmask(fbuf,(uint32_t)sb.st_size); // look at lines, etc\n have_mask = 1;\n }\n\nHere's a write: (here pix is the byte array, jwidth and jheight are the JPEG width and height so for RGB color we write height * width * 3 color bytes). It's the # of bytes to write.\nvoid simpdump(uint8_t *pix, char *nm) { // makes a raw aka .data file\n int sdfd;\n sdfd = open(nm,O_WRONLY | O_CREAT);\n if (sdfd == -1) {\n printf(\"bad open\\n\");\n exit(-1);\n }\n printf(\"width: %i height: %i\\n\",jwidth,jheight); // to the console\n write(sdfd,pix,(jwidth*jheight*3));\n close(sdfd);\n}\n\nLook at man 2 open, also read, write, close. Also this old-style jpeg example.c: https://github.com/LuaDist/libjpeg/blob/master/example.c I'm reading and writing an entire image at once here. But they're binary reads and writes of bytes, just a lot at once.\n\"But when I try to read from a file it is not outputting correctly.\" Hmmm. If you read a number 65 that's (decimal) ASCII for an A. Maybe you should look at man ascii too. If you want a 1 that's ASCII 0x31. A char variable is a tiny 8-bit integer really, if you do a printf as a %i you get the ASCII value, if you do a %c you get the character. Do %x for hexadecimal. All from the same number between 0 and 255.\n", "I'm quite happy with my \"make a weak pin storage program\" solution. Maybe it will help people who need a very simple binary file IO example to follow.\n$ ls\nWeakPin my_pin_code.pin weak_pin.c\n$ ./WeakPin\nPin: 45 47 49 32\n$ ./WeakPin 8 2\n$ Need 4 ints to write a new pin!\n$./WeakPin 8 2 99 49\nPin saved.\n$ ./WeakPin\nPin: 8 2 99 49\n$\n$ cat weak_pin.c\n// a program to save and read 4-digit pin codes in binary format\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#define PIN_FILE \"my_pin_code.pin\"\n\ntypedef struct { unsigned short a, b, c, d; } PinCode;\n\n\nint main(int argc, const char** argv)\n{\n if (argc > 1) // create pin\n {\n if (argc != 5)\n {\n printf(\"Need 4 ints to write a new pin!\\n\");\n return -1;\n }\n unsigned short _a = atoi(argv[1]);\n unsigned short _b = atoi(argv[2]);\n unsigned short _c = atoi(argv[3]);\n unsigned short _d = atoi(argv[4]);\n PinCode pc;\n pc.a = _a; pc.b = _b; pc.c = _c; pc.d = _d;\n FILE *f = fopen(PIN_FILE, \"wb\"); // create and/or overwrite\n if (!f)\n {\n printf(\"Error in creating file. Aborting.\\n\");\n return -2;\n }\n\n // write one PinCode object pc to the file *f\n fwrite(&pc, sizeof(PinCode), 1, f); \n\n fclose(f);\n printf(\"Pin saved.\\n\");\n return 0;\n }\n\n // else read existing pin\n FILE *f = fopen(PIN_FILE, \"rb\");\n if (!f)\n {\n printf(\"Error in reading file. Abort.\\n\");\n return -3;\n }\n PinCode pc;\n fread(&pc, sizeof(PinCode), 1, f);\n fclose(f);\n\n printf(\"Pin: \");\n printf(\"%hu \", pc.a);\n printf(\"%hu \", pc.b);\n printf(\"%hu \", pc.c);\n printf(\"%hu\\n\", pc.d);\n return 0;\n}\n$\n\n", "This is an example to read and write binary jjpg or wmv video file.\n FILE *fout;\n FILE *fin;\nInt ch;\nchar *s;\nfin=fopen(\"D:\\\\pic.jpg\",\"rb\");\nif(fin==NULL)\n { printf(\"\\n Unable to open the file \");\n exit(1);\n }\n\n fout=fopen(\"D:\\\\ newpic.jpg\",\"wb\");\n ch=fgetc(fin);\n while (ch!=EOF)\n { \n s=(char *)ch;\n printf(\"%c\",s);\n ch=fgetc (fin):\n fputc(s,fout);\n s++;\n }\n\n printf(\"data read and copied\");\n fclose(fin);\n fclose(fout);\n\n", "I really struggled to find a way to read a binary file into a byte array in C++ that would output the same hex values I see in a hex editor. After much trial and error, this seems to be the fastest way to do so without extra casts. By default it loads the entire file into memory, but only prints the first 1000 bytes.\nstring Filename = \"BinaryFile.bin\";\nFILE* pFile;\npFile = fopen(Filename.c_str(), \"rb\");\nfseek(pFile, 0L, SEEK_END);\nsize_t size = ftell(pFile);\nfseek(pFile, 0L, SEEK_SET);\nuint8_t* ByteArray;\nByteArray = new uint8_t[size];\nif (pFile != NULL)\n{\n int counter = 0;\n do {\n ByteArray[counter] = fgetc(pFile);\n counter++;\n } while (counter <= size);\n fclose(pFile);\n}\nfor (size_t i = 0; i < 800; i++) {\n printf(\"%02X \", ByteArray[i]);\n}\n\n", "this questions is linked with the question How to write binary data file on C and plot it using Gnuplot by CAMILO HG. I know that the real problem have two parts: 1) Write the binary data file, 2) Plot it using Gnuplot.\nThe first part has been very clearly answered here, so I do not have something to add.\nFor the second, the easy way is send the people to the Gnuplot manual, and I sure someone find a good answer, but I do not find it in the web, so I am going to explain one solution (which must be in the real question, but I new in stackoverflow and I can not answer there):\nAfter write your binary data file using fwrite(), you should create a very simple program in C, a reader. The reader only contains the same structure as the writer, but you use fread() instead fwrite(). So it is very ease to generate this program: copy in the reader.c file the writing part of your original code and change write for read (and \"wb\" for \"rb\"). In addition, you could include some checks for the data, for example, if the length of the file is correct. And finally, your program need to print the data in the standard output using a printf().\nFor be clear: your program run like this\n$ ./reader data.dat\n\nX_position Y_position (it must be a comment for Gnuplot)*\n\n1.23 2.45\n\n2.54 3.12\n\n5.98 9.52\n\n\nOkey, with this program, in Gnuplot you only need to pipe the standard output of the reader to the Gnuplot, something like this:\nplot '< ./reader data.dat'\n\nThis line, run the program reader, and the output is connected with Gnuplot and it plot the data.\n*Because Gnuplot is going to read the output of the program, you must know what can Gnuplot read and plot and what can not.\n", "#include <stdio.h> \n#include <stdlib.h> \n\nmain(int argc, char **argv) //int argc; char **argv;\n{ \n int wd;\n FILE *in, *out; \n\n if(argc != 3) {\n printf(\"Input and output file are to be specified\\n\");\n exit(1);\n }\n in = fopen(argv[1], \"rb\");\n out = fopen(argv[2], \"wb\");\n if(in == NULL || out == NULL) { /* open for write */ \n printf(\"Cannot open an input and an output file.\\n\");\n getchar();\n exit(0); \n } \n while(wd = getw(in), !feof(in)) putw(wd, out); \n\n fclose(in);\n fclose(out);\n\n}\n\n" ]
[ 136, 4, 2, 1, 1, 0, 0 ]
[]
[]
[ "binary", "c", "file_io", "linux" ]
stackoverflow_0017598572_binary_c_file_io_linux.txt
Q: Rendering HTML in AG Grid Column Header (Community v20.0.0 +) I previously upgraded my AG Grid package from an 18x to 20.0.0 (Community Version). In the previous version, I was simply able to pass an HTML string to the colDefs.headerName property and it would render HTML in the header. This new version renders header and cell data as a string by default. So now the column headers are rendering like this: <span ref="eText" class="ag-header-cell-text" role="columnheader"> "<span id="header-span-1" style="visibility: visible; position: static; display: inline-block; padding-bottom: 5px;">Some Text</span>" </span> I obviously want to go with the easiest solution, which seems to be using a Cell Renderer (or something similar as described on https://www.ag-grid.com/javascript-grid-cell-rendering-components/) that simply returns the HTML. How could the following be achieved in using the headerName property? colDef.cellRenderer = function(params) { var html = '<span id="header-span-1" style="visibility: visible; position: static; display: inline-block; padding-bottom: 5px;">Some Text</span>'; return html; } If it can't, would someone please provide a working example of how to use a header component for what I'm specifically after? I saw where I could define a template, but it seems like overkill considering I only need what I've described above. I've searched around and can't seem to find an example. UPDATE Thanks to Dominic's response below, I was able to come up with a solution that didn't require excessive (and unnecessary) effort. Again, for my particular use case, I have limited control over the column data coming back from the server, but needed to have a way to format it - beyond the functionality provided by AG Grid's formatter and getter properties. In my project, the column definitions are provided via a class... export class colDefs { constructor( public headerName: any, public field: any, ... ) { } } ...and instantiated in the applicable typescript components like this: for (var i = 0; i < arr.length; i++) { ... // Do stuff this.columnDefs[i] = new colDefs(headerName, field, ...); ... // Do stuff } Taking Dominic's advice, I simply created a new class named HTMLRenderer (extended from HeaderComp). I also added a new property to exported class colDefs named "headerComponent", and I pass the HTMLRenderer as its value. import { HeaderComp } from 'ag-grid-community/dist/lib/headerRendering/header/headerComp'; class HTMLRenderer extends HeaderComp { init(params) { super.init(params); // @ts-ignore: Unreachable code error this.eGui.querySelector('[ref="eText"]').innerHTML = params.displayName; } } export class colDefs { constructor( public headerName: any, public headerComponent: any = HTMLRenderer, public field: any, ... ) { } } Please take note of the // @ts-ignore: Unreachable code error comment. It's needed. Otherwise, if you're using typescript, it will throw an error and fail to compile. Finally, in my typescript components that instantiate the colDefs class, I pass the applicable values. But for the headerComponent property, you MUST pass undefined, which basically says that we want to go with the default value as defined in the exported class: for (var i = 0; i < arr.length; i++) { ... // Do stuff this.columnDefs[i] = new colDefs(headerName, undefined, field, ...); ... // Do stuff } This did it for me without the overkill that would have been involved with creating a full header component for just a small string of HTML in the header. The HTML in my AG Grid column headers are rendering now! Please note there is actually another approach for accomplishing this that involves isolating the HTMLRenderer in its own class file. You ultimately have to register it as a provider in app.module AND in each typescript file you want to use it in...NOT to mention you also have to export the class AND make it an Injectable. To me, this approach seems like too much work for the little bit of HTML I have in the column headers. A: Sadly they decided that HTML wouldn't be useful in the header or accidentally broke it so you can't even use something like ° or Δ for units. Even worse is that the architecture around the header renderer is awful - in order to customize it they want you to also take over handling for sorting, filtering, menu etc. Bizarre that this would be their first assumption but anyway... At least they should provide an innerRenderer like they do with cells. The only thing they export is headerRootComp which seems totally useless. In order to not take over all the responsibility for the sorting etc mentioned you have to get the component that they use to render the default header. Note that this isn't officially exported and could change: import { HeaderComp } from 'ag-grid-community/dist/lib/headerRendering/header/headerComp'; class HeaderHTMLRenderer extends HeaderComp { init(params) { super.init(params); this.eGui.querySelector('[ref="eText"]').innerHTML = params.displayName; } } Pass this in as your default renderer: defaultColDef={{ headerComponent: HeaderHTMLRenderer, }} A: If you do not want to create a rendering component, really the simplest approach is to apply a css class: gridOptions.columnDefs = [ { headerName: 'MyCol', headerClass: 'col-css-class', ... }; If you need something more complex, you won't be able to do it without a rendering component. A: This functionality was changed in AG Grid 27, now you MUST use a rendering component to display HTML. (Unfortunately) A: For anyone who wants to extend default HeaderComp, here is a solution in plain JavaScript (ES6) which does not require Babel class CustomHeaderComp extends (new agGrid.UserComponentRegistry()).agGridDefaults['agColumnHeader'] { init(params) { super.init(params) this.eGui.querySelector('[ref="eText"]').innerHTML = params.displayName } } For some reason HeaderComp is not exposed in latest version (28.2.1), that's why here we have to resolve it from UserComponentRegistry
Rendering HTML in AG Grid Column Header (Community v20.0.0 +)
I previously upgraded my AG Grid package from an 18x to 20.0.0 (Community Version). In the previous version, I was simply able to pass an HTML string to the colDefs.headerName property and it would render HTML in the header. This new version renders header and cell data as a string by default. So now the column headers are rendering like this: <span ref="eText" class="ag-header-cell-text" role="columnheader"> "<span id="header-span-1" style="visibility: visible; position: static; display: inline-block; padding-bottom: 5px;">Some Text</span>" </span> I obviously want to go with the easiest solution, which seems to be using a Cell Renderer (or something similar as described on https://www.ag-grid.com/javascript-grid-cell-rendering-components/) that simply returns the HTML. How could the following be achieved in using the headerName property? colDef.cellRenderer = function(params) { var html = '<span id="header-span-1" style="visibility: visible; position: static; display: inline-block; padding-bottom: 5px;">Some Text</span>'; return html; } If it can't, would someone please provide a working example of how to use a header component for what I'm specifically after? I saw where I could define a template, but it seems like overkill considering I only need what I've described above. I've searched around and can't seem to find an example. UPDATE Thanks to Dominic's response below, I was able to come up with a solution that didn't require excessive (and unnecessary) effort. Again, for my particular use case, I have limited control over the column data coming back from the server, but needed to have a way to format it - beyond the functionality provided by AG Grid's formatter and getter properties. In my project, the column definitions are provided via a class... export class colDefs { constructor( public headerName: any, public field: any, ... ) { } } ...and instantiated in the applicable typescript components like this: for (var i = 0; i < arr.length; i++) { ... // Do stuff this.columnDefs[i] = new colDefs(headerName, field, ...); ... // Do stuff } Taking Dominic's advice, I simply created a new class named HTMLRenderer (extended from HeaderComp). I also added a new property to exported class colDefs named "headerComponent", and I pass the HTMLRenderer as its value. import { HeaderComp } from 'ag-grid-community/dist/lib/headerRendering/header/headerComp'; class HTMLRenderer extends HeaderComp { init(params) { super.init(params); // @ts-ignore: Unreachable code error this.eGui.querySelector('[ref="eText"]').innerHTML = params.displayName; } } export class colDefs { constructor( public headerName: any, public headerComponent: any = HTMLRenderer, public field: any, ... ) { } } Please take note of the // @ts-ignore: Unreachable code error comment. It's needed. Otherwise, if you're using typescript, it will throw an error and fail to compile. Finally, in my typescript components that instantiate the colDefs class, I pass the applicable values. But for the headerComponent property, you MUST pass undefined, which basically says that we want to go with the default value as defined in the exported class: for (var i = 0; i < arr.length; i++) { ... // Do stuff this.columnDefs[i] = new colDefs(headerName, undefined, field, ...); ... // Do stuff } This did it for me without the overkill that would have been involved with creating a full header component for just a small string of HTML in the header. The HTML in my AG Grid column headers are rendering now! Please note there is actually another approach for accomplishing this that involves isolating the HTMLRenderer in its own class file. You ultimately have to register it as a provider in app.module AND in each typescript file you want to use it in...NOT to mention you also have to export the class AND make it an Injectable. To me, this approach seems like too much work for the little bit of HTML I have in the column headers.
[ "Sadly they decided that HTML wouldn't be useful in the header or accidentally broke it so you can't even use something like ° or Δ for units. Even worse is that the architecture around the header renderer is awful - in order to customize it they want you to also take over handling for sorting, filtering, menu etc. Bizarre that this would be their first assumption but anyway... At least they should provide an innerRenderer like they do with cells.\nThe only thing they export is headerRootComp which seems totally useless. In order to not take over all the responsibility for the sorting etc mentioned you have to get the component that they use to render the default header. Note that this isn't officially exported and could change:\nimport { HeaderComp } from 'ag-grid-community/dist/lib/headerRendering/header/headerComp';\n\nclass HeaderHTMLRenderer extends HeaderComp {\n init(params) {\n super.init(params);\n this.eGui.querySelector('[ref=\"eText\"]').innerHTML = params.displayName;\n }\n}\n\nPass this in as your default renderer:\ndefaultColDef={{\n headerComponent: HeaderHTMLRenderer,\n}}\n\n", "If you do not want to create a rendering component, really the simplest approach is to apply a css class:\ngridOptions.columnDefs = [\n {\n headerName: 'MyCol',\n headerClass: 'col-css-class',\n ...\n };\n\nIf you need something more complex, you won't be able to do it without a rendering component.\n", "This functionality was changed in AG Grid 27, now you MUST use a rendering component to display HTML. (Unfortunately)\n", "For anyone who wants to extend default HeaderComp, here is a solution in plain JavaScript (ES6) which does not require Babel\nclass CustomHeaderComp extends (new agGrid.UserComponentRegistry()).agGridDefaults['agColumnHeader'] {\n init(params) {\n super.init(params)\n this.eGui.querySelector('[ref=\"eText\"]').innerHTML = params.displayName\n }\n}\n\nFor some reason HeaderComp is not exposed in latest version (28.2.1), that's why here we have to resolve it from UserComponentRegistry\n" ]
[ 3, 0, 0, 0 ]
[]
[]
[ "ag_grid", "angular5", "javascript" ]
stackoverflow_0055291002_ag_grid_angular5_javascript.txt
Q: Blazor - What is the correct way to extend another component? I'm using MudBlazor component library. In order to show loading on form buttons, the documentation guides like this: <MudButton Disabled="@_processing" OnClick="ProcessSomething" Variant="Variant.Filled" Color="Color.Primary"> @if (_processing) { <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true"/> <MudText Class="ms-2">Processing</MudText> } else { <MudText>Click me</MudText> } </MudButton> Now since I'm doing this a lot, I wanted to wrap this logic inside another component. The following component does not do the job: @inherits MudButton @code { bool _loading; [Parameter] public bool Loading { get => _loading; set { _loading = value; Disabled = value; } } [Parameter] public new RenderFragment ChildContent { get => base.ChildContent; set => base.ChildContent = ExtendContent(value); } private RenderFragment ExtendContent(RenderFragment baseContent) => __builder => { if (Loading) { <MudProgressCircular Class="ms-n2" Size="Size.Small" Indeterminate="true" /> } @baseContent }; } I get this error: The type '<my_component>' declares more than one parameter matching the name 'childcontent'. Parameter names are case-insensitive and must be unique. A: MudButton already has ChildContent Parameter, you don't need to inherit it, Just use it inside your new component, and redefine the parameters you need to pass them to the inner components A: MudBlazor's component library inherits from ComponentBase which isn't really designed for Razor inheritance. You're trying to replace the ChildContent with your own markup. You need to lift the markup stuff from the base component, hope there's no privates being used, and copy it into the child markup. Here's my inherited component: @inherits MudButton @using MudBlazor.Extensions <MudElement @bind-Ref="@_elementReference" HtmlTag="@HtmlTag" Class="@Classname" Style="@Style" @attributes="UserAttributes" @onclick="OnClickHandler" type="@ButtonType.ToDescriptionString()" href="@Href" target="@Target" rel="@(Target=="_blank"?"noopener":null)" disabled="@Disabled"> <span class="mud-button-label"> @if (!string.IsNullOrWhiteSpace(StartIcon)) { <span class="@StartIconClass"> <MudIcon Icon="@StartIcon" Size="@Size" Color="@IconColor" /> </span> } @if (this.Loading) { <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" /> <MudText Class="ms-2">Processing</MudText> } else { <MudText>@ChildContent</MudText> } @if (!string.IsNullOrWhiteSpace(@EndIcon)) { <span class="@EndIconClass"> <MudIcon Icon="@EndIcon" Size="@Size" Color="@IconColor" /> </span> } </span> </MudElement> @code { [Parameter] public bool Loading { get; set; } } The code comes from the MubBlazor Github repo here - https://github.com/MudBlazor/MudBlazor/blob/dev/src/MudBlazor/Components/Button/MudButton.razor. My Demo Page: @page "/" <PageTitle>Index</PageTitle> <MudText Typo="Typo.h3" GutterBottom="true">Hello, world!</MudText> <MudText Class="mb-8">Welcome to your new app, powered by MudBlazor!</MudText> <MudAlert Severity="Severity.Normal">You can find documentation and examples on our website here: <MudLink Href="https://mudblazor.com" Typo="Typo.body2" Color="Color.Inherit"><b>www.mudblazor.com</b></MudLink></MudAlert> <MudText class="mt-6"> <MudButton Disabled="@_processing" OnClick="ProcessSomething" Variant="Variant.Filled" Color="Color.Primary"> @if (_processing) { <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" /> <MudText Class="ms-2">Processing</MudText> } else { <MudText>Click me</MudText> } </MudButton> <MyButton Loading=_processing Disabled="@_processing" OnClick="ProcessSomething" Variant="Variant.Filled" Color="Color.Primary"> Hello </MyButton> </MudText> @code { private bool _processing; private async Task ProcessSomething() { _processing = true; await Task.Delay(5000); _processing = false; } } A: Create a component for the loading content: ButtonLoadingContent.razor @using MudBlazor <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" /> <MudText Class="ms-2">Processing</MudText> BaseLoadingMudButton.cs using MudBlazor; public class BaseLoadingMudButton<TComponent> : MudButton where TComponent : ComponentBase { protected override void OnParametersSet() { Disabled = Loading; if (Loading is true) { ChildContent = builder => { builder.OpenComponent<TComponent>(sequence: 1); builder.CloseComponent(); }; } base.OnParametersSet(); } [Parameter] public bool Loading { get; set; } } LoadingMudButton.cs public class LoadingMudButton : BaseLoadingMudButton<ButtonLoadingContent> { } Usage <LoadingMudButton Loading=_processing OnClick="ProcessSomething" Variant="Variant.Filled" Color="Color.Primary"> <MudText>Click me</MudText> </LoadingMudButton> Why does it work? I didn't use .razor files for the inheritance. The base component does not have to use generics I included this to make it more flexible and as an example.
Blazor - What is the correct way to extend another component?
I'm using MudBlazor component library. In order to show loading on form buttons, the documentation guides like this: <MudButton Disabled="@_processing" OnClick="ProcessSomething" Variant="Variant.Filled" Color="Color.Primary"> @if (_processing) { <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true"/> <MudText Class="ms-2">Processing</MudText> } else { <MudText>Click me</MudText> } </MudButton> Now since I'm doing this a lot, I wanted to wrap this logic inside another component. The following component does not do the job: @inherits MudButton @code { bool _loading; [Parameter] public bool Loading { get => _loading; set { _loading = value; Disabled = value; } } [Parameter] public new RenderFragment ChildContent { get => base.ChildContent; set => base.ChildContent = ExtendContent(value); } private RenderFragment ExtendContent(RenderFragment baseContent) => __builder => { if (Loading) { <MudProgressCircular Class="ms-n2" Size="Size.Small" Indeterminate="true" /> } @baseContent }; } I get this error: The type '<my_component>' declares more than one parameter matching the name 'childcontent'. Parameter names are case-insensitive and must be unique.
[ "MudButton already has ChildContent Parameter,\nyou don't need to inherit it,\nJust use it inside your new component, and redefine the parameters you need to pass them to the inner components\n", "MudBlazor's component library inherits from ComponentBase which isn't really designed for Razor inheritance. You're trying to replace the ChildContent with your own markup.\nYou need to lift the markup stuff from the base component, hope there's no privates being used, and copy it into the child markup.\nHere's my inherited component:\n@inherits MudButton\n@using MudBlazor.Extensions\n\n<MudElement @bind-Ref=\"@_elementReference\"\n HtmlTag=\"@HtmlTag\"\n Class=\"@Classname\"\n Style=\"@Style\"\n @attributes=\"UserAttributes\"\n @onclick=\"OnClickHandler\"\n type=\"@ButtonType.ToDescriptionString()\"\n href=\"@Href\"\n target=\"@Target\"\n rel=\"@(Target==\"_blank\"?\"noopener\":null)\"\n disabled=\"@Disabled\">\n\n <span class=\"mud-button-label\">\n @if (!string.IsNullOrWhiteSpace(StartIcon))\n {\n <span class=\"@StartIconClass\">\n <MudIcon Icon=\"@StartIcon\" Size=\"@Size\" Color=\"@IconColor\" />\n </span>\n }\n\n @if (this.Loading)\n {\n <MudProgressCircular Class=\"ms-n1\" Size=\"Size.Small\" Indeterminate=\"true\" />\n <MudText Class=\"ms-2\">Processing</MudText>\n }\n else\n {\n <MudText>@ChildContent</MudText>\n }\n\n @if (!string.IsNullOrWhiteSpace(@EndIcon))\n {\n <span class=\"@EndIconClass\">\n <MudIcon Icon=\"@EndIcon\" Size=\"@Size\" Color=\"@IconColor\" />\n </span>\n }\n </span>\n\n</MudElement>\n\n@code {\n [Parameter] public bool Loading { get; set; }\n}\n\nThe code comes from the MubBlazor Github repo here - https://github.com/MudBlazor/MudBlazor/blob/dev/src/MudBlazor/Components/Button/MudButton.razor.\nMy Demo Page:\n@page \"/\"\n\n<PageTitle>Index</PageTitle>\n\n<MudText Typo=\"Typo.h3\" GutterBottom=\"true\">Hello, world!</MudText>\n<MudText Class=\"mb-8\">Welcome to your new app, powered by MudBlazor!</MudText>\n<MudAlert Severity=\"Severity.Normal\">You can find documentation and examples on our website here: <MudLink Href=\"https://mudblazor.com\" Typo=\"Typo.body2\" Color=\"Color.Inherit\"><b>www.mudblazor.com</b></MudLink></MudAlert>\n\n<MudText class=\"mt-6\">\n\n <MudButton Disabled=\"@_processing\" OnClick=\"ProcessSomething\" Variant=\"Variant.Filled\" Color=\"Color.Primary\">\n @if (_processing)\n {\n <MudProgressCircular Class=\"ms-n1\" Size=\"Size.Small\" Indeterminate=\"true\" />\n <MudText Class=\"ms-2\">Processing</MudText>\n }\n else\n {\n <MudText>Click me</MudText>\n }\n </MudButton>\n\n <MyButton Loading=_processing Disabled=\"@_processing\" OnClick=\"ProcessSomething\" Variant=\"Variant.Filled\" Color=\"Color.Primary\">\n Hello\n </MyButton>\n\n</MudText>\n@code {\n private bool _processing;\n\n private async Task ProcessSomething()\n {\n _processing = true;\n await Task.Delay(5000);\n _processing = false;\n }\n}\n\n\n", "Create a component for the loading content:\nButtonLoadingContent.razor\n@using MudBlazor\n<MudProgressCircular Class=\"ms-n1\" Size=\"Size.Small\" Indeterminate=\"true\" />\n<MudText Class=\"ms-2\">Processing</MudText>\n\nBaseLoadingMudButton.cs\nusing MudBlazor;\n\npublic class BaseLoadingMudButton<TComponent> : MudButton\n where TComponent : ComponentBase\n{\n protected override void OnParametersSet()\n {\n Disabled = Loading;\n\n if (Loading is true)\n {\n ChildContent = builder =>\n {\n builder.OpenComponent<TComponent>(sequence: 1);\n builder.CloseComponent();\n };\n }\n base.OnParametersSet();\n }\n\n [Parameter]\n public bool Loading { get; set; }\n}\n\nLoadingMudButton.cs\npublic class LoadingMudButton : BaseLoadingMudButton<ButtonLoadingContent> { }\n\nUsage\n<LoadingMudButton Loading=_processing OnClick=\"ProcessSomething\" Variant=\"Variant.Filled\" Color=\"Color.Primary\">\n <MudText>Click me</MudText>\n</LoadingMudButton>\n\n \nWhy does it work? I didn't use .razor files for the inheritance.\nThe base component does not have to use generics I included this to make it more flexible and as an example.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "blazor", "blazor_webassembly", "razor_components" ]
stackoverflow_0074668605_blazor_blazor_webassembly_razor_components.txt
Q: Sum values in InfluxDB I’m tryingto sum values in InfluxDB but I’m struggling a bit. So, I have a _measurement "plug" with a field "value". I have different records within the same bucket with a different ID tag. I can get the evolution of 1 plug with this query: from(bucket: "test-bucket") |> range(start: v.timeRangeStart, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "plug") |> filter(fn: (r) => r["_field"] == "value") |> filter(fn: (r) => r["id"] == "tag1") |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false) |> yield(name: "mean") What I would like is the exact same graph with the sum of all r["id"]. So, if there is 34 for tag ID "tag1", 11.2 for "tag2" and 0 for "tag3", I would like a graph with 45.2 for that given time. I’ve tried to use «group()» method, but I get a strange value, more like an average than a sum. I’ve also tried to use «sum» method, but then, I feel like Influx is summing all the values across the whole timeline. That’s not what I want. I just like to have a graph with with the sum of «value» field of all "tag" at a given time. Thanks a lot for you help. A: Right now you have a table per tag value. You can use pivot function to merge into a single table, where all the different _value columns are now named after their corresponding tag value: from(bucket: "test-bucket") |> range(start: v.timeRangeStart, stop: v.timeRangeStop) |> filter(fn: (r) => r._measurement == "plug") |> filter(fn: (r) => r._field == "value") |> pivot(rowKey: ["_time"], columnKey: ["id"], valueColumn: "_value") If you know the tag values in advance, the next step is easy: |> map(fn: (r) => ({ _time: r._time, _value: r["tag1"] + r["tag2"] + r["tag3]})) If you don't, it gets a bit more complicated. What I would try next in this case is to write a function that combines experimental.unpivot() (note: available since InfluxDB 2.4) with sum(). The trick here is to call this method within map(), so it will operate on a single row (ie, single timestamp) at a time: sumColumns = (r) => r |>experimental.unpivot() |>group |>sum() |>findRecord(fn: (key) => true, idx: 0) from(bucket: "test-bucket") |> range(start: v.timeRangeStart, stop: v.timeRangeStop) |> filter(fn: (r) => r._measurement == "plug") |> filter(fn: (r) => r._field == "value") |> pivot(rowKey: ["_time"], columnKey: ["id"], valueColumn: "_value") |> map(fn: sumColumns) Note that I have not tested this. It is just to give you an idea.
Sum values in InfluxDB
I’m tryingto sum values in InfluxDB but I’m struggling a bit. So, I have a _measurement "plug" with a field "value". I have different records within the same bucket with a different ID tag. I can get the evolution of 1 plug with this query: from(bucket: "test-bucket") |> range(start: v.timeRangeStart, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "plug") |> filter(fn: (r) => r["_field"] == "value") |> filter(fn: (r) => r["id"] == "tag1") |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false) |> yield(name: "mean") What I would like is the exact same graph with the sum of all r["id"]. So, if there is 34 for tag ID "tag1", 11.2 for "tag2" and 0 for "tag3", I would like a graph with 45.2 for that given time. I’ve tried to use «group()» method, but I get a strange value, more like an average than a sum. I’ve also tried to use «sum» method, but then, I feel like Influx is summing all the values across the whole timeline. That’s not what I want. I just like to have a graph with with the sum of «value» field of all "tag" at a given time. Thanks a lot for you help.
[ "Right now you have a table per tag value. You can use pivot function to merge into a single table, where all the different _value columns are now named after their corresponding tag value:\nfrom(bucket: \"test-bucket\")\n|> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n|> filter(fn: (r) => r._measurement == \"plug\")\n|> filter(fn: (r) => r._field == \"value\")\n|> pivot(rowKey: [\"_time\"], columnKey: [\"id\"], valueColumn: \"_value\")\n\nIf you know the tag values in advance, the next step is easy:\n|> map(fn: (r) => ({ _time: r._time, _value: r[\"tag1\"] + r[\"tag2\"] + r[\"tag3]}))\n\nIf you don't, it gets a bit more complicated. What I would try next in this case is to write a function that combines experimental.unpivot() (note: available since InfluxDB 2.4) with sum(). The trick here is to call this method within map(), so it will operate on a single row (ie, single timestamp) at a time:\nsumColumns = (r) => r\n |>experimental.unpivot()\n |>group\n |>sum()\n |>findRecord(fn: (key) => true, idx: 0)\n\nfrom(bucket: \"test-bucket\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"plug\")\n |> filter(fn: (r) => r._field == \"value\")\n |> pivot(rowKey: [\"_time\"], columnKey: [\"id\"], valueColumn: \"_value\")\n |> map(fn: sumColumns)\n\nNote that I have not tested this. It is just to give you an idea.\n" ]
[ 0 ]
[]
[]
[ "influxdb" ]
stackoverflow_0074679313_influxdb.txt
Q: Kotlin test if float is in open or semi open range In Kotlin - is there an idiomatic way to test if a float is in a range where either (or both) the start or the end of the range is exclusive? E.g something like val inRange = 10.f in (0.0f until 20f) I can't seem to find anything on this in the docs. Update: How would one deal with semi-open ranges as well? A: The until function creates the semi-closed integer (not float) range, where the left part is included and the right part is excluded. https://kotlinlang.org/docs/reference/ranges.html There is closed float ranges support in Koltin https://kotlinlang.org/docs/reference/ranges.html#utility-functions You may implement that yourself data class OpenFloatRange(val from: Float, val to: Float) infix fun Float.open(to: Float) = OpenFloatRange(this, to) operator fun OpenFloatRange.contains(f: Float) = from < f && f < to val inRange = 10f in (0.0f open 20f) Here I use several tricks from Kotlin: https://kotlinlang.org/docs/reference/functions.html#infix-notation https://kotlinlang.org/docs/reference/operator-overloading.html#in A: Inspired by what i selected as answer i came up with this solution, posting it here if anyone wants to reuse it. class Range(private val fromInclusive: Boolean, val from: Float, val to: Float, private val toInclusive: Boolean) { infix fun contains(value: Float): Boolean { return when { fromInclusive && toInclusive -> value in from..to !fromInclusive && !toInclusive -> value > from && value < to !fromInclusive && toInclusive -> value > from && value <= to fromInclusive && !toInclusive -> value >= from && value < to else -> false } } } Usage: val inRange = Range(true, 0f, 10f, false) contains 5f A: There is a new end-enclusive operator ..< (called rangeUntil) which is still experimental and can be enabled in Kotlin 1.7.20 and newer. Add the following in build.gradle.kts (Kotlin 1.8 won't need this): kotlin { jvm { compilations.all { kotlinOptions.languageVersion = "1.8" // Treat Kotlin code as version 1.8 // ... } It opens possibilities that could not be done with until: val floatRange = 0f ..< 10f val dateRange = LocalDate.of(2022, 1, 1) ..< LocalDate.of(2023, 1, 1) val stringRange = "1z" ..< "9a" // OR anything implementing Comparable when (7.89f) { in floatRange -> println("Number is in range") else -> println("Number is NOT in range") } NOTE: Remember to add @OptIn(ExperimentalStdlibApi::class) to your functions where you use this operator See official Kotlin video introducing the rangeUntil operator.
Kotlin test if float is in open or semi open range
In Kotlin - is there an idiomatic way to test if a float is in a range where either (or both) the start or the end of the range is exclusive? E.g something like val inRange = 10.f in (0.0f until 20f) I can't seem to find anything on this in the docs. Update: How would one deal with semi-open ranges as well?
[ "The until function creates the semi-closed integer (not float) range, where the left part is included and the right part is excluded.\nhttps://kotlinlang.org/docs/reference/ranges.html\nThere is closed float ranges support in Koltin\nhttps://kotlinlang.org/docs/reference/ranges.html#utility-functions\nYou may implement that yourself\ndata class OpenFloatRange(val from: Float, val to: Float)\ninfix fun Float.open(to: Float) = OpenFloatRange(this, to)\noperator fun OpenFloatRange.contains(f: Float) = from < f && f < to\n\nval inRange = 10f in (0.0f open 20f)\n\nHere I use several tricks from Kotlin:\nhttps://kotlinlang.org/docs/reference/functions.html#infix-notation\nhttps://kotlinlang.org/docs/reference/operator-overloading.html#in\n", "Inspired by what i selected as answer i came up with this solution, posting it here if anyone wants to reuse it.\nclass Range(private val fromInclusive: Boolean, val from: Float, val to: Float, private val toInclusive: Boolean) {\n\n infix fun contains(value: Float): Boolean {\n return when {\n fromInclusive && toInclusive -> value in from..to\n !fromInclusive && !toInclusive -> value > from && value < to\n !fromInclusive && toInclusive -> value > from && value <= to\n fromInclusive && !toInclusive -> value >= from && value < to\n else -> false\n }\n }\n}\n\nUsage: val inRange = Range(true, 0f, 10f, false) contains 5f\n", "There is a new end-enclusive operator ..< (called rangeUntil) which is still experimental and can be enabled in Kotlin 1.7.20 and newer.\nAdd the following in build.gradle.kts (Kotlin 1.8 won't need this):\nkotlin {\n jvm {\n compilations.all {\n kotlinOptions.languageVersion = \"1.8\" // Treat Kotlin code as version 1.8\n // ...\n }\n\nIt opens possibilities that could not be done with until:\nval floatRange = 0f ..< 10f\nval dateRange = LocalDate.of(2022, 1, 1) ..< LocalDate.of(2023, 1, 1)\nval stringRange = \"1z\" ..< \"9a\"\n// OR anything implementing Comparable\n\nwhen (7.89f) {\n in floatRange -> println(\"Number is in range\")\n else -> println(\"Number is NOT in range\")\n}\n\nNOTE: Remember to add @OptIn(ExperimentalStdlibApi::class) to your functions where you use this operator\nSee official Kotlin video introducing the rangeUntil operator.\n" ]
[ 11, 3, 0 ]
[]
[]
[ "kotlin", "range" ]
stackoverflow_0054637512_kotlin_range.txt
Q: Python-CSV write column(s) at given indices to new file I am trying to write the column(s) in a csv file where a word is present. the example shown here is for "car". NOTE: CANNOT USE PANDAS here is the sample in_file: 12,life,car,good,exellent 10,gift,truck,great,great 11,time,car,great,perfect the desired output for out_file is: car truck car This is the current code: def project_columns(in_file, out_file, indices): with open(in_file) as f: reader = csv.reader(f) data = list(reader) with open(out_file, 'w') as o: writer = csv.writer(o) for i in indices: writer.writerow(data[i]) the variable indices contains the indices of the column. for "car" indices = [2,2]. out_file currently contains: 11,time,car,great,perfect 11,time,car,great,perfect How should I fix this to get the desired output? A: cat car.csv 12,life,car,good,exellent 10,gift,truck,great,great 11,time,car,great,perfect import csv with open('car.csv') as car_file: r = csv.reader(car_file) with open('out.csv', 'w') as out_file: w = csv.writer(out_file) for row in r: w.writerow([row[2]]) cat out.csv car truck car
Python-CSV write column(s) at given indices to new file
I am trying to write the column(s) in a csv file where a word is present. the example shown here is for "car". NOTE: CANNOT USE PANDAS here is the sample in_file: 12,life,car,good,exellent 10,gift,truck,great,great 11,time,car,great,perfect the desired output for out_file is: car truck car This is the current code: def project_columns(in_file, out_file, indices): with open(in_file) as f: reader = csv.reader(f) data = list(reader) with open(out_file, 'w') as o: writer = csv.writer(o) for i in indices: writer.writerow(data[i]) the variable indices contains the indices of the column. for "car" indices = [2,2]. out_file currently contains: 11,time,car,great,perfect 11,time,car,great,perfect How should I fix this to get the desired output?
[ "cat car.csv \n12,life,car,good,exellent\n10,gift,truck,great,great\n11,time,car,great,perfect\n\nimport csv\n\nwith open('car.csv') as car_file:\n r = csv.reader(car_file)\n with open('out.csv', 'w') as out_file:\n w = csv.writer(out_file)\n for row in r:\n w.writerow([row[2]])\n\ncat out.csv \ncar\ntruck\ncar\n\n\n\n\n" ]
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074671720_csv_python.txt
Q: python: How can I check if user input is in dataframe I am building a S&P500 app using streamlit, the functionality of the app prompts user to either choose number of plots to be shown from the slider or to type a specific symbol to show its plot, however, I am facing problems in trying to check if the symbol exists in the pandas series which contains all the symbols,(note both the user input and the symbol in the series is of type string) can anybody please tell me how can I fix it import streamlit as st import pandas as pd import base64 import matplotlib.pyplot as plt import yfinance as yf @st.cache def load_data(): url = "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies" html = pd.read_html(url, header=0) df = html[0] return df df = load_data() df = df[0] sector_unique = sorted( df['GICS Sector'].unique() ) selected_sector = st.sidebar.multiselect('Sector', sector_unique, sector_unique) df_selected_sector = df[(df['GICS Sector'].isin(selected_sector))] data = yf.download( tickers = list(df_selected_sector[:10].Symbol), period = "ytd", interval = "1d", group_by = 'ticker', auto_adjust = True, prepost = True, threads = True, proxy = None ) num_company = st.sidebar.slider('Number of companies for plots', 1, 10) spec_symbol = st.sidebar.text_input("OR choose a specific symbol ") if spec_symbol: if(spec_symbol == (a for a in df['Symbol'].items())): spec_data = yf.download( tickers = spec_symbol, period = "ytd", interval = "1d", group_by = 'ticker', auto_adjust = True, prepost = True, threads = True, proxy = None ) else: st.sidebar.write("Symbol not found") despite the user input symbol being valid or not, it keeps giving me the else statement("symbol not found") here is a sample of the output of df["Symbol"] to make it clearer: Symbol 0 MMM 1 AOS 2 ABT 3 ABBV 4 ABMD 5 ACN 6 ATVI 7 ADM 8 ADBE A: You should use pandas.Series.tolist (that returns a list) instead of pandas.Series.items (that returns an iterable). Replace this : if(spec_symbol == (a for a in df['Symbol'].items())): By this : if(spec_symbol == (a for a in df['Symbol'].tolist())): Or simply : if spec_symbol in df['Symbol'].tolist():
python: How can I check if user input is in dataframe
I am building a S&P500 app using streamlit, the functionality of the app prompts user to either choose number of plots to be shown from the slider or to type a specific symbol to show its plot, however, I am facing problems in trying to check if the symbol exists in the pandas series which contains all the symbols,(note both the user input and the symbol in the series is of type string) can anybody please tell me how can I fix it import streamlit as st import pandas as pd import base64 import matplotlib.pyplot as plt import yfinance as yf @st.cache def load_data(): url = "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies" html = pd.read_html(url, header=0) df = html[0] return df df = load_data() df = df[0] sector_unique = sorted( df['GICS Sector'].unique() ) selected_sector = st.sidebar.multiselect('Sector', sector_unique, sector_unique) df_selected_sector = df[(df['GICS Sector'].isin(selected_sector))] data = yf.download( tickers = list(df_selected_sector[:10].Symbol), period = "ytd", interval = "1d", group_by = 'ticker', auto_adjust = True, prepost = True, threads = True, proxy = None ) num_company = st.sidebar.slider('Number of companies for plots', 1, 10) spec_symbol = st.sidebar.text_input("OR choose a specific symbol ") if spec_symbol: if(spec_symbol == (a for a in df['Symbol'].items())): spec_data = yf.download( tickers = spec_symbol, period = "ytd", interval = "1d", group_by = 'ticker', auto_adjust = True, prepost = True, threads = True, proxy = None ) else: st.sidebar.write("Symbol not found") despite the user input symbol being valid or not, it keeps giving me the else statement("symbol not found") here is a sample of the output of df["Symbol"] to make it clearer: Symbol 0 MMM 1 AOS 2 ABT 3 ABBV 4 ABMD 5 ACN 6 ATVI 7 ADM 8 ADBE
[ "You should use pandas.Series.tolist (that returns a list) instead of pandas.Series.items (that returns an iterable).\nReplace this :\nif(spec_symbol == (a for a in df['Symbol'].items())):\n\nBy this :\nif(spec_symbol == (a for a in df['Symbol'].tolist())):\n\nOr simply :\nif spec_symbol in df['Symbol'].tolist():\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "streamlit" ]
stackoverflow_0074679765_pandas_python_streamlit.txt
Q: Flutter:How to handle list in model? I am trying to handle a model which has a list but I stucking in between I am not getting any idea how to handle list which is in my model first of all I am getting data from api and I am storing Jason object in my model which is working perfect following is my json model { "statusCode": 200, "success": true, "messages": [], "data": [ { "id": 35, "title": "Astrology", "filename": "Astrology.jpg", "mimetype": "image/jpeg", "directcalling": 1, "parentid": null, "subcat": [] }, { "id": 36, "title": "Muhurtam", "filename": "Muhurtam.jpg", "mimetype": "image/jpeg", "directcalling": 1, "parentid": null, "subcat": [ { "id": 50, "title": "abc", "filename": "abc.png", "mimetype": "image/png", "directcalling": 0, "parentid": 36, "subcat": [] } in the above json object only few of them has subcategories now in flutter I had created a dropdown list where all categories will displayed upon selecting a category it navigate to another screen where user can update selected category details.If selected category has a sub categories then it will displayed in a dropdown list where user can update details of selected category but here I face a problem.I want to give user a option to select sub category or not but here if user does not select a sub category I am facing following error if selected I am not facing above error and if user selected a category.And if user selected a category and hit on save button I am facing following error I know that I am calling data model directly without calling id from my data model basically my code should be something like final catIndex = id.subcat.indexWhere((prod) => prod.id == id); but here in above code how do I return id which is in data model to my update function following is my model where I am saving all data in model class Categories { Categories({ required this.statusCode, required this.success, required this.messages, required this.data, }); late final int statusCode; late final bool success; late final List<dynamic> messages; late final List<Data> data; Categories.fromJson(Map<String, dynamic> json) { statusCode = json['statusCode']; success = json['success']; messages = List.castFrom<dynamic, dynamic>(json['messages']); data = List.from(json['data']).map((e) => Data.fromJson(e)).toList(); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['statusCode'] = statusCode; _data['success'] = success; _data['messages'] = messages; _data['data'] = data.map((e) => e.toJson()).toList(); return _data; } } class Data { Data({ this.id, required this.title, required this.filename, required this.mimetype, required this.directcalling, this.parentid, this.subcat, }); late final int? id; late final String title; late final String filename; late final String mimetype; late final int directcalling; late final Null parentid; late final List<Subcat>? subcat; Data.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; filename = json['filename']; mimetype = json['mimetype']; directcalling = json['directcalling']; parentid = null; subcat = List.from(json['subcat']).map((e) => Subcat.fromJson(e)).toList(); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; // _data['id'] = id; _data['title'] = title; _data['filename'] = filename; // _data['mimetype'] = mimetype; _data['directcalling'] = directcalling; // _data['parentid'] = parentid; // _data['subcat'] = subcat.map((e) => e.toJson()).toList(); return _data; } } class Subcat { Subcat({ this.id, required this.title, required this.filename, required this.mimetype, required this.directcalling, this.parentid, this.subcat, }); late final int? id; late final String title; late final String filename; late final String mimetype; late final int directcalling; late final int? parentid; late final List<dynamic>? subcat; Subcat.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; filename = json['filename']; mimetype = json['mimetype']; directcalling = json['directcalling']; parentid = json['parentid']; subcat = List.castFrom<dynamic, dynamic>(json['subcat']); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; //_data['id'] = id; _data['title'] = title; _data['filename'] = filename; //_data['mimetype'] = mimetype; _data['directcalling'] = directcalling; //_data['parentid'] = parentid; //_data['subcat'] = subcat; return _data; } } now I am receiving id from my data model by below code Data findById(int id) { return categories!.data.firstWhere((cat) => cat.id == id); } now I want to pass this id in function parameter to get id subcategories.now my question is how to pass this particular id detail as parameter in function following is my widget tree where I am getting data model id and sub categories of that id.By using below code I am getting id details which is in my data model final catId = ModalRoute.of(context)!.settings.arguments as int; final loadedProduct = Provider.of<Category>( context, listen: false, ).findById(catId); below code describes dropdown list if my id has subcategories loadedProduct.subcat == null ? Container() : Consumer<Category>( builder: (context, value, child) { return Column( children: [ DropdownButton<String>( elevation: 16, isExpanded: true, hint: Text('please select sub category'), items: loadedProduct.subcat!.map((v) { return DropdownMenuItem<String>( onTap: () { subcat = v.id; _initValues = { 'title': v.title, }; }, value: v.title, child: Text(v.title)); }).toList(), onChanged: (val) { value.updatesubcat(val!); print(val); }, value: value.sub, ), in below code I am trying to call update function where I want to send id as parameter void _saveForm() async { print('save form'); final isValid = _form.currentState!.validate(); if (!isValid) { return; } _form.currentState!.save(); if (_editedCategory.id != null) { await Provider.of<Category>(context, listen: false) .updateCatAtributes(_editedSubCategory.id!, context, _editedCategory); } } above are the 2 issues that I am facing 1.Dropdown list error if user does not select item and click save button 2.passing parameter in update function A: To handle the case where the user does not select a subcategory, you can add a null check before accessing the id property of the selected subcategory. This will prevent the error from occurring if the id property is not defined. Here is an example of how you could do this: final catIndex = id.subcat.indexWhere((prod) => prod.id == (id.subcat?.id ?? null)); In the above code, the ?? operator will return null if the id property of the selected subcategory is not defined. This will prevent the error from occurring and allow the user to save the category without a subcategory selected. Alternatively, you could also handle this error by using a try-catch block to catch the error and handle it gracefully. Here is an example of how you could do this: try { final catIndex = id.subcat.indexWhere((prod) => prod.id == id.subcat.id); } catch (error) { // Handle the error here } In the above code, the error will be caught and handled in the catch block, allowing you to handle the error gracefully without the application crashing.
Flutter:How to handle list in model?
I am trying to handle a model which has a list but I stucking in between I am not getting any idea how to handle list which is in my model first of all I am getting data from api and I am storing Jason object in my model which is working perfect following is my json model { "statusCode": 200, "success": true, "messages": [], "data": [ { "id": 35, "title": "Astrology", "filename": "Astrology.jpg", "mimetype": "image/jpeg", "directcalling": 1, "parentid": null, "subcat": [] }, { "id": 36, "title": "Muhurtam", "filename": "Muhurtam.jpg", "mimetype": "image/jpeg", "directcalling": 1, "parentid": null, "subcat": [ { "id": 50, "title": "abc", "filename": "abc.png", "mimetype": "image/png", "directcalling": 0, "parentid": 36, "subcat": [] } in the above json object only few of them has subcategories now in flutter I had created a dropdown list where all categories will displayed upon selecting a category it navigate to another screen where user can update selected category details.If selected category has a sub categories then it will displayed in a dropdown list where user can update details of selected category but here I face a problem.I want to give user a option to select sub category or not but here if user does not select a sub category I am facing following error if selected I am not facing above error and if user selected a category.And if user selected a category and hit on save button I am facing following error I know that I am calling data model directly without calling id from my data model basically my code should be something like final catIndex = id.subcat.indexWhere((prod) => prod.id == id); but here in above code how do I return id which is in data model to my update function following is my model where I am saving all data in model class Categories { Categories({ required this.statusCode, required this.success, required this.messages, required this.data, }); late final int statusCode; late final bool success; late final List<dynamic> messages; late final List<Data> data; Categories.fromJson(Map<String, dynamic> json) { statusCode = json['statusCode']; success = json['success']; messages = List.castFrom<dynamic, dynamic>(json['messages']); data = List.from(json['data']).map((e) => Data.fromJson(e)).toList(); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['statusCode'] = statusCode; _data['success'] = success; _data['messages'] = messages; _data['data'] = data.map((e) => e.toJson()).toList(); return _data; } } class Data { Data({ this.id, required this.title, required this.filename, required this.mimetype, required this.directcalling, this.parentid, this.subcat, }); late final int? id; late final String title; late final String filename; late final String mimetype; late final int directcalling; late final Null parentid; late final List<Subcat>? subcat; Data.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; filename = json['filename']; mimetype = json['mimetype']; directcalling = json['directcalling']; parentid = null; subcat = List.from(json['subcat']).map((e) => Subcat.fromJson(e)).toList(); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; // _data['id'] = id; _data['title'] = title; _data['filename'] = filename; // _data['mimetype'] = mimetype; _data['directcalling'] = directcalling; // _data['parentid'] = parentid; // _data['subcat'] = subcat.map((e) => e.toJson()).toList(); return _data; } } class Subcat { Subcat({ this.id, required this.title, required this.filename, required this.mimetype, required this.directcalling, this.parentid, this.subcat, }); late final int? id; late final String title; late final String filename; late final String mimetype; late final int directcalling; late final int? parentid; late final List<dynamic>? subcat; Subcat.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; filename = json['filename']; mimetype = json['mimetype']; directcalling = json['directcalling']; parentid = json['parentid']; subcat = List.castFrom<dynamic, dynamic>(json['subcat']); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; //_data['id'] = id; _data['title'] = title; _data['filename'] = filename; //_data['mimetype'] = mimetype; _data['directcalling'] = directcalling; //_data['parentid'] = parentid; //_data['subcat'] = subcat; return _data; } } now I am receiving id from my data model by below code Data findById(int id) { return categories!.data.firstWhere((cat) => cat.id == id); } now I want to pass this id in function parameter to get id subcategories.now my question is how to pass this particular id detail as parameter in function following is my widget tree where I am getting data model id and sub categories of that id.By using below code I am getting id details which is in my data model final catId = ModalRoute.of(context)!.settings.arguments as int; final loadedProduct = Provider.of<Category>( context, listen: false, ).findById(catId); below code describes dropdown list if my id has subcategories loadedProduct.subcat == null ? Container() : Consumer<Category>( builder: (context, value, child) { return Column( children: [ DropdownButton<String>( elevation: 16, isExpanded: true, hint: Text('please select sub category'), items: loadedProduct.subcat!.map((v) { return DropdownMenuItem<String>( onTap: () { subcat = v.id; _initValues = { 'title': v.title, }; }, value: v.title, child: Text(v.title)); }).toList(), onChanged: (val) { value.updatesubcat(val!); print(val); }, value: value.sub, ), in below code I am trying to call update function where I want to send id as parameter void _saveForm() async { print('save form'); final isValid = _form.currentState!.validate(); if (!isValid) { return; } _form.currentState!.save(); if (_editedCategory.id != null) { await Provider.of<Category>(context, listen: false) .updateCatAtributes(_editedSubCategory.id!, context, _editedCategory); } } above are the 2 issues that I am facing 1.Dropdown list error if user does not select item and click save button 2.passing parameter in update function
[ "To handle the case where the user does not select a subcategory, you can add a null check before accessing the id property of the selected subcategory. This will prevent the error from occurring if the id property is not defined.\nHere is an example of how you could do this:\nfinal catIndex = id.subcat.indexWhere((prod) => prod.id == (id.subcat?.id ?? null));\n\nIn the above code, the ?? operator will return null if the id property of the selected subcategory is not defined. This will prevent the error from occurring and allow the user to save the category without a subcategory selected.\nAlternatively, you could also handle this error by using a try-catch block to catch the error and handle it gracefully. Here is an example of how you could do this:\ntry {\nfinal catIndex = id.subcat.indexWhere((prod) => prod.id == id.subcat.id);\n} catch (error) {\n// Handle the error here\n}\n\nIn the above code, the error will be caught and handled in the catch block, allowing you to handle the error gracefully without the application crashing.\n" ]
[ 0 ]
[]
[]
[ "flutter" ]
stackoverflow_0074679824_flutter.txt
Q: Server apache-tomcat-9.0.55 at localhost failed to start -- maven eclipse project I am working on a Maven Project on Eclipse and need apache tomcat to run the application on a server. For some reason, it is not working for me and I get an error that says "Server apache-tomcat-9.0.55 at localhost failed to start.". This happened to me yesterday but I just right clicked on the server section and added the same server again and it worked. This is not working anymore. I have attached photos of my library, build path, preferences, and the error message. Below is my pom.xml file. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.prog</groupId> <artifactId>sampleApp</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>sampleApp Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.1</version> </plugin> </plugins> <finalName>sampleApp</finalName> </build> </project> Any help at all would be extremely appreciated. I really have no idea what else to try. I've been working on this for several hours now and have made no progress after watching dozens of videos. Thank you so much for your time. A: Check this website. I think it can help you out. https://websparrow.org/misc/server-tomcat-server-at-localhost-failed-to-start-in-eclipse
Server apache-tomcat-9.0.55 at localhost failed to start -- maven eclipse project
I am working on a Maven Project on Eclipse and need apache tomcat to run the application on a server. For some reason, it is not working for me and I get an error that says "Server apache-tomcat-9.0.55 at localhost failed to start.". This happened to me yesterday but I just right clicked on the server section and added the same server again and it worked. This is not working anymore. I have attached photos of my library, build path, preferences, and the error message. Below is my pom.xml file. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.prog</groupId> <artifactId>sampleApp</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>sampleApp Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.1</version> </plugin> </plugins> <finalName>sampleApp</finalName> </build> </project> Any help at all would be extremely appreciated. I really have no idea what else to try. I've been working on this for several hours now and have made no progress after watching dozens of videos. Thank you so much for your time.
[ "Check this website. I think it can help you out.\nhttps://websparrow.org/misc/server-tomcat-server-at-localhost-failed-to-start-in-eclipse\n" ]
[ 0 ]
[]
[]
[ "eclipse", "java", "maven", "tomcat" ]
stackoverflow_0074679722_eclipse_java_maven_tomcat.txt
Q: Calling a service inside a Blazor component does not work I have a service that look like this: namespace Hydra.Services { public class Employee { public string url { get; set; } public async Task<EmployeeModel> GetEmployee(){ // return JSON data } } } I would like to call the service inside my Commpany component as: @page "/" <div> @company ... </div> <!-- OK, company details are rendered --> <div> @Employee ... </div> <!-- System.NullReferenceException: 'Object reference not set to an instance of an object.' --> @code { company string; emlpoyee string; protected override async Task OnInitializedAsync() using (HttpClient client = new HttpClient()) { // Get company details // HERE is the problem: EmployeeModel emp = new Employee(); emp.url = "http://google.com"; emlpoyee = await emp.Employee(); } } } So, the logic to show the company works without any issue, the Employee service I am calling inside using() doesn't seem to work. I don't know what the issue is other than the error. This is not a problem about forgetting to include models or injecting services. I am just a beginner so the issue is simpler than that A: You created the variable: @emlpoyee but you are calling @Employee which is going to be null. Try switching to the variable you actually put the employee into which is: @emlpoyee Also I think you spelt the variable wrong. I think you meant @employee perhaps. You populate everything here: emlpoyee = await emp.Employee(); so calling @emlpoyee is what makes sense from the code you've provided. So change <div> @Employee ... </div> to <div> @emlpoyee ... </div>
Calling a service inside a Blazor component does not work
I have a service that look like this: namespace Hydra.Services { public class Employee { public string url { get; set; } public async Task<EmployeeModel> GetEmployee(){ // return JSON data } } } I would like to call the service inside my Commpany component as: @page "/" <div> @company ... </div> <!-- OK, company details are rendered --> <div> @Employee ... </div> <!-- System.NullReferenceException: 'Object reference not set to an instance of an object.' --> @code { company string; emlpoyee string; protected override async Task OnInitializedAsync() using (HttpClient client = new HttpClient()) { // Get company details // HERE is the problem: EmployeeModel emp = new Employee(); emp.url = "http://google.com"; emlpoyee = await emp.Employee(); } } } So, the logic to show the company works without any issue, the Employee service I am calling inside using() doesn't seem to work. I don't know what the issue is other than the error. This is not a problem about forgetting to include models or injecting services. I am just a beginner so the issue is simpler than that
[ "You created the variable:\n@emlpoyee \n\nbut you are calling @Employee which is going to be null.\nTry switching to the variable you actually put the employee into which is:\n@emlpoyee \n\nAlso I think you spelt the variable wrong. I think you meant @employee perhaps.\nYou populate everything here:\nemlpoyee = await emp.Employee(); \n\nso calling @emlpoyee is what makes sense from the code you've provided.\nSo change <div> @Employee ... </div> to <div> @emlpoyee ... </div>\n" ]
[ 2 ]
[]
[]
[ "blazor", "c#" ]
stackoverflow_0074679505_blazor_c#.txt
Q: TypeScript: How to obtain return type of the instance of a generic function that has a specified parameter tuple type? Suppose I have generic function function example<T>(a: T, b: number): SomeType<T> { // code goes here } But let's say for the sake of argument that I don't know whether example was generic on the type of the first or second parameter, or maybe it was generic with two type parameters. My goal is to determine the return type of the instantiation of example that takes argument tuple [string, number]. (So it would be nice to have something like InstantiatedReturnType<F, ParamTuple> so that in this case InstantiatedReturnType<typeof example, [string, number]> would be SomeType<string>.) I have verified that typeof example does extend the type (...args: [string, number]) => any, but I have not been able to find a way to extract the return type of the instantiation that has this parameter tuple type. In particular, if I take the intersection of the function types typeof Example and (...args: [string, number]) => any it has ReturnType< > equal to either any or unknown depending on the order I list the two types in the intersection. Also, because function types are contravariant in their parameters, I tried taking ReturnType< > of the union of these two types, but that didn't help either. Any suggestions or guidance would be welcome. (My point about not knowing the structure of the template is I don't have the information to be able to say ReturnType<typeof example<string>> because maybe the instantiation that matches arguments [string, number] is actually example<number> because example was actually generic on the second parameter type, and explicit in the first parameter as a string. The use case is that I am given an object whose values are alternative functions I might want to call, some of which might be generic, and I am selecting the one to call based on matching the type of an argument tuple I have. That part works -- I can successfully extract the key (as a concrete type with just the one string inhabitant) whose value is a (possibly generic) function callable on the tuple type of the arguments I've got, but I also need to express the return type of what the call will produce, and I can't seem to manage that.) UPDATE: A stripped down example of what I am trying to accomplish is in this playground. It shows selecting the proper key, and one unsuccessful attempt to obtain the return type of the "matching instantiation". A: No, this is unfortunately not possible in TypeScript as of TS4.9. There is no way to express operations on generics at the type level; there are no "generic generics" or higher kinded types, as requested in the longstanding open feature request at microsoft/TypeScript#1213. So, while the compiler can figure out the output type of a generic function given a particular input if you actually call the function at the expression level (if example("abc", 123) appears in your code), and while there's even some support for higher order generic functions (e.g., you could get call(example, "abc", 123) to yield string if call has type <A extends any[], R>(f: (...args: A)=>R, ...args: A)=>R), there is no pure type-level equivalent. At some point you have to actually call the functions with the actual inputs (or convince the compiler that you are doing so) to see what the output types will be. There was a pull request at microsoft/TypeScript#17961 which would have enabled type-level function application, so that, armed with, type Example = typeof example you could write type RetType = Example(string, number). But this was never merged into the language, and was essentially abandoned along with most of microsoft/TypeScript#6606 a general request to be able to query types for all expressions without actually needing to emit these expressions to JavaScript. This all means that the compiler can't do this for you, and you'll need to either give up completely, or refactor your code so that you are doing the type processing manually (and maybe you can get the compiler to check that you've done it correctly). But such workarounds are not pleasant, and are not directly in scope for this question.
TypeScript: How to obtain return type of the instance of a generic function that has a specified parameter tuple type?
Suppose I have generic function function example<T>(a: T, b: number): SomeType<T> { // code goes here } But let's say for the sake of argument that I don't know whether example was generic on the type of the first or second parameter, or maybe it was generic with two type parameters. My goal is to determine the return type of the instantiation of example that takes argument tuple [string, number]. (So it would be nice to have something like InstantiatedReturnType<F, ParamTuple> so that in this case InstantiatedReturnType<typeof example, [string, number]> would be SomeType<string>.) I have verified that typeof example does extend the type (...args: [string, number]) => any, but I have not been able to find a way to extract the return type of the instantiation that has this parameter tuple type. In particular, if I take the intersection of the function types typeof Example and (...args: [string, number]) => any it has ReturnType< > equal to either any or unknown depending on the order I list the two types in the intersection. Also, because function types are contravariant in their parameters, I tried taking ReturnType< > of the union of these two types, but that didn't help either. Any suggestions or guidance would be welcome. (My point about not knowing the structure of the template is I don't have the information to be able to say ReturnType<typeof example<string>> because maybe the instantiation that matches arguments [string, number] is actually example<number> because example was actually generic on the second parameter type, and explicit in the first parameter as a string. The use case is that I am given an object whose values are alternative functions I might want to call, some of which might be generic, and I am selecting the one to call based on matching the type of an argument tuple I have. That part works -- I can successfully extract the key (as a concrete type with just the one string inhabitant) whose value is a (possibly generic) function callable on the tuple type of the arguments I've got, but I also need to express the return type of what the call will produce, and I can't seem to manage that.) UPDATE: A stripped down example of what I am trying to accomplish is in this playground. It shows selecting the proper key, and one unsuccessful attempt to obtain the return type of the "matching instantiation".
[ "No, this is unfortunately not possible in TypeScript as of TS4.9. There is no way to express operations on generics at the type level; there are no \"generic generics\" or higher kinded types, as requested in the longstanding open feature request at microsoft/TypeScript#1213.\nSo, while the compiler can figure out the output type of a generic function given a particular input if you actually call the function at the expression level (if example(\"abc\", 123) appears in your code), and while there's even some support for higher order generic functions (e.g., you could get call(example, \"abc\", 123) to yield string if call has type <A extends any[], R>(f: (...args: A)=>R, ...args: A)=>R), there is no pure type-level equivalent. At some point you have to actually call the functions with the actual inputs (or convince the compiler that you are doing so) to see what the output types will be.\nThere was a pull request at microsoft/TypeScript#17961 which would have enabled type-level function application, so that, armed with, type Example = typeof example you could write type RetType = Example(string, number). But this was never merged into the language, and was essentially abandoned along with most of microsoft/TypeScript#6606 a general request to be able to query types for all expressions without actually needing to emit these expressions to JavaScript.\nThis all means that the compiler can't do this for you, and you'll need to either give up completely, or refactor your code so that you are doing the type processing manually (and maybe you can get the compiler to check that you've done it correctly). But such workarounds are not pleasant, and are not directly in scope for this question.\n" ]
[ 0 ]
[]
[]
[ "generics", "return_type", "typescript" ]
stackoverflow_0074679105_generics_return_type_typescript.txt
Q: In Envoy , how to perform zone aware routing only for request with specific header values? click here for image Goal is to allow cross zone routing for request with header header_value=1 and for header_value=2 , only to local cluster as shown in attached image. How can i achieve this.? A: manged to solve this with adding new cluster and route based on header.
In Envoy , how to perform zone aware routing only for request with specific header values?
click here for image Goal is to allow cross zone routing for request with header header_value=1 and for header_value=2 , only to local cluster as shown in attached image. How can i achieve this.?
[ "manged to solve this with adding new cluster and route based on header.\n" ]
[ 0 ]
[]
[]
[ "envoyproxy" ]
stackoverflow_0072589434_envoyproxy.txt
Q: Lodash : how to do a Non-ASCII characters sorting on a collection using orderBy? I need to sort an multidimentional array with Non-ASCII characters and multiple objects. tried this but doesn't worked const users = [ { name: 'A', age: 48 }, { name: 'B', age: 34 }, { name: 'á', age: 40 }, { name: 'b', age: 36 } ] const nameLocale = users.sort((a, b) => (a.name.localeCompare(b.name))); const sortedUsers = _.orderBy(users, [nameLocale, 'age'], ['asc', 'asc']) the sorted array i need would be like this: { name: 'á', age: 40 } { name: 'A', age: 48 }, { name: 'B', age: 34 }, { name: 'b', age: 36 } but the responde i got is this: [ { name: 'B', age: 34 }, { name: 'b', age: 36 }, { name: 'á', age: 40 }, { name: 'A', age: 48 } ] A: You can remove diacritics with the following code, from: https://www.davidbcalhoun.com/2019/matching-accented-strings-in-javascript/ Then it seems like you consider uppercase and lowercase letters equal, so you can convert to lowercase. Also, orderBy takes a function as a parameter, not a sorted array. const users = [ { name: 'A', age: 48 }, { name: 'B', age: 34 }, { name: 'á', age: 40 }, { name: 'b', age: 36 } ] sortByName = (user) => user.name.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLocaleLowerCase(); const sortedUsers = _.orderBy(users, [sortByName, 'age'], ['asc', 'asc']); console.log(sortedUsers); <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
Lodash : how to do a Non-ASCII characters sorting on a collection using orderBy?
I need to sort an multidimentional array with Non-ASCII characters and multiple objects. tried this but doesn't worked const users = [ { name: 'A', age: 48 }, { name: 'B', age: 34 }, { name: 'á', age: 40 }, { name: 'b', age: 36 } ] const nameLocale = users.sort((a, b) => (a.name.localeCompare(b.name))); const sortedUsers = _.orderBy(users, [nameLocale, 'age'], ['asc', 'asc']) the sorted array i need would be like this: { name: 'á', age: 40 } { name: 'A', age: 48 }, { name: 'B', age: 34 }, { name: 'b', age: 36 } but the responde i got is this: [ { name: 'B', age: 34 }, { name: 'b', age: 36 }, { name: 'á', age: 40 }, { name: 'A', age: 48 } ]
[ "You can remove diacritics with the following code, from: https://www.davidbcalhoun.com/2019/matching-accented-strings-in-javascript/\nThen it seems like you consider uppercase and lowercase letters equal, so you can convert to lowercase.\nAlso, orderBy takes a function as a parameter, not a sorted array.\n\n\nconst users = [\n { name: 'A', age: 48 },\n { name: 'B', age: 34 },\n { name: 'á', age: 40 },\n { name: 'b', age: 36 }\n]\n\nsortByName = (user) => user.name.normalize(\"NFD\").replace(/[\\u0300-\\u036f]/g, \"\").toLocaleLowerCase();\n\nconst sortedUsers = _.orderBy(users, [sortByName, 'age'], ['asc', 'asc']);\n\nconsole.log(sortedUsers);\n<script src=\"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js\"></script>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "javascript" ]
stackoverflow_0074679345_arrays_javascript.txt
Q: Reading Apache Arrow files in Spark I am using Pyspark and I would like to read files of type Apache Arrow, which have ".arrow" as extension. I unfortunately couldn't find any way to do this, would be grateful for any help. A: To read Apache Arrow files in PySpark, you can use the spark.read.parquet() method, which supports reading Apache Arrow files. The .parquet() method takes the path to the Arrow file as an argument and returns a DataFrame. For example, to read an Apache Arrow file located at /path/to/file.arrow, you could use the following code: df = spark.read.parquet("/path/to/file.arrow") If you want to read all files that end with .arrow then you can use the wild card '*' df = spark.read.parquet("/path/to/*.arrow")
Reading Apache Arrow files in Spark
I am using Pyspark and I would like to read files of type Apache Arrow, which have ".arrow" as extension. I unfortunately couldn't find any way to do this, would be grateful for any help.
[ "To read Apache Arrow files in PySpark, you can use the spark.read.parquet() method, which supports reading Apache Arrow files. The .parquet() method takes the path to the Arrow file as an argument and returns a DataFrame. For example, to read an Apache Arrow file located at /path/to/file.arrow, you could use the following code:\ndf = spark.read.parquet(\"/path/to/file.arrow\")\n\nIf you want to read all files that end with .arrow then you can use the wild card '*'\ndf = spark.read.parquet(\"/path/to/*.arrow\")\n\n" ]
[ 0 ]
[]
[]
[ "apache_arrow", "pyspark" ]
stackoverflow_0074679453_apache_arrow_pyspark.txt
Q: Problem with adding property in map function to an object Please review this stackblitz code and let me know why there is error in user.state property in ngOninit() function. ngOnInit(){ this.users = this.users.map((user) => { `**user.state = 'orig';**` return user; }); } I have run this code in my installed version of visual code but the same error occurs here too. A: According to your example stackblitz we can see that you didn't provide a type for the user array. So the Typescript language try to get some from the array. And as your objects in this array dint't recognize state it is not there for typescript and can't be applied. Option 1: Add a not set state property to your objects { name: 'Vincent Vega', occupation: 'Sceptic', membership: 'Admin', status: 'Active', created_at: '1994-11-03', url:'https://www.coditty.com/code/angular-animation-how-to-animate-single-item-from-ngfor-loop?utm_source=Stackblitz&utm_medium=Code&utm_campaign=Animation_List_and_Items', state: null } Option 2: Use a Type for your array and make the state optional interface User { name: string; occupation: string; membership: string; status: string; created_at: string; url: string; state?: string; } users: User[] = []
Problem with adding property in map function to an object
Please review this stackblitz code and let me know why there is error in user.state property in ngOninit() function. ngOnInit(){ this.users = this.users.map((user) => { `**user.state = 'orig';**` return user; }); } I have run this code in my installed version of visual code but the same error occurs here too.
[ "According to your example stackblitz we can see that you didn't provide a type for the user array. So the Typescript language try to get some from the array. And as your objects in this array dint't recognize state it is not there for typescript and can't be applied.\nOption 1:\nAdd a not set state property to your objects\n { \n name: 'Vincent Vega',\n occupation: 'Sceptic',\n membership: 'Admin',\n status: 'Active',\n created_at: '1994-11-03',\n url:'https://www.coditty.com/code/angular-animation-how-to-animate-single-item-from-ngfor-loop?utm_source=Stackblitz&utm_medium=Code&utm_campaign=Animation_List_and_Items',\n state: null\n }\n\nOption 2:\nUse a Type for your array and make the state optional\n\ninterface User {\n name: string;\n occupation: string;\n membership: string;\n status: string;\n created_at: string;\n url: string;\n state?: string;\n}\n\nusers: User[] = []\n\n" ]
[ 0 ]
[]
[]
[ "angular", "javascript", "typescript", "typescript2.0" ]
stackoverflow_0074679796_angular_javascript_typescript_typescript2.0.txt
Q: How to read excel line by line in pandas I want to ask how can How to read excel line by line in pandas. I want it to be in a loop that will get line by line information for facebook login with selenium. Hope everyone is easygoing because I'm a newbie import pandas as pd pd.options.display.max_rows = 28 data = pd.read_excel(r'file.xlsx') #load data into a DataFrame object: df = pd.DataFrame(data) username = pd.DataFrame(f1,columns=['Name']) password = pd.DataFrame(f1,columns=['Pass']) for i in df: print('Current row:', i) A: Is it important that you read your Excel file line-by-line? Or is it also okay for you to read the entirety of your Excel file into a Dataframe and just iterate through that? A: since you're new to programming, a good counsel I can give is to read and search the documentation when doubts first appear. Many tools even have tutorials to help you start coding and search to help you find basic code. Check this link, I think it will help a lot! https://pandas.pydata.org/docs/getting_started/intro_tutorials/02_read_write.html?highlight=read%20excel
How to read excel line by line in pandas
I want to ask how can How to read excel line by line in pandas. I want it to be in a loop that will get line by line information for facebook login with selenium. Hope everyone is easygoing because I'm a newbie import pandas as pd pd.options.display.max_rows = 28 data = pd.read_excel(r'file.xlsx') #load data into a DataFrame object: df = pd.DataFrame(data) username = pd.DataFrame(f1,columns=['Name']) password = pd.DataFrame(f1,columns=['Pass']) for i in df: print('Current row:', i)
[ "Is it important that you read your Excel file line-by-line? Or is it also okay for you to read the entirety of your Excel file into a Dataframe and just iterate through that?\n", "since you're new to programming, a good counsel I can give is to read and search the documentation when doubts first appear.\nMany tools even have tutorials to help you start coding and search to help you find basic code.\nCheck this link, I think it will help a lot!\nhttps://pandas.pydata.org/docs/getting_started/intro_tutorials/02_read_write.html?highlight=read%20excel\n" ]
[ 0, 0 ]
[]
[]
[ "excel", "pandas", "python", "python_3.x", "selenium" ]
stackoverflow_0074679803_excel_pandas_python_python_3.x_selenium.txt
Q: Shopify adding   to content and css not working properly On my Shopify homepage, Shopify compiles the text with &nbsp's, and thus the words don't break correctly and CSS doesn't work. https://www.sylvesterzagato.com/ As you can see the word horticulture is cut in the middle, the same happens with other words at different window widths. Any tips? A: It seems like you figured this out yourself, because I couldn't find any &nbsp; on your site. However, you can add hyphens: auto; to allow the browser to have correct work breaks based on syllables. Message me if you want my address, my walls are still empty haha :)
Shopify adding   to content and css not working properly
On my Shopify homepage, Shopify compiles the text with &nbsp's, and thus the words don't break correctly and CSS doesn't work. https://www.sylvesterzagato.com/ As you can see the word horticulture is cut in the middle, the same happens with other words at different window widths. Any tips?
[ "It seems like you figured this out yourself, because I couldn't find any &nbsp; on your site. However, you can add hyphens: auto; to allow the browser to have correct work breaks based on syllables.\nMessage me if you want my address, my walls are still empty haha :)\n" ]
[ 0 ]
[]
[]
[ "css", "html", "shopify" ]
stackoverflow_0074675834_css_html_shopify.txt
Q: Power BI average between different dates I want to calculate average time between to dates. The data looks like this: Step Datetime 2 14.11.2022 13:02:56 4 14.11.2022 13:05:15 2 14.11.2022 13:11:23 4 14.11.2022 13:13:38 2 14.11.2022 13:24:03 4 14.11.2022 13:26:21 2 15.11.2022 12:16:58 4 15.11.2022 12:19:28 I need to get an average time between all the steps number 4 and steps number 2. 14.11.2022 13:05:15 - 14.11.2022 13:02:56 = 00:02:19 14.11.2022 13:13:38 - 14.11.2022 13:11:23 = 00:02:15 14.11.2022 13:26:21 - 14.11.2022 13:24:03 = 00:02:18 15.11.2022 12:19:28 - 15.11.2022 12:16:58 = 00:02:30 The average between all four equals to 00:02:20. When I use formula measure = CALCULATE(SUM(Logging[CreatedAt]),Logging[Step] = 4) - CALCULATE(SUM(Logging[CreatedAt]),Logging[Step] = 2) it calculates the total of all four rows. The result of the formula above 30.12.1899 0:09:22. (by the way, how to get rid of this strange date result 30.12.1899?) If I use formula measure = AVERAGEX(Logging, CALCULATETABLE(VALUES(Logging[CreatedAt]), FILTER(Logging, Logging[Step] = 4)) - CALCULATETABLE(VALUES(Logging[CreatedAt]), FILTER(Logging, Logging[Step] = 4))) it delivers nothing. A: Try this: Avg Time Delta = VAR T2 = CALCULATE( AVERAGE('Table'[Datetime]), 'Table'[Step] = 2 ) VAR T4 = CALCULATE( AVERAGE('Table'[Datetime]), 'Table'[Step] = 4 ) VAR Seconds = DATEDIFF(T2, T4, SECOND) VAR Minutes = INT ( Seconds / 60 ) VAR RemSeconds = MOD ( Seconds, 60 ) VAR Hours = INT ( Minutes / 60 ) VAR RemMinutes = MOD ( Minutes, 60 ) RETURN TIME(Hours, RemMinutes, RemSeconds) You can get rid of the "30.12.1899" prefix if you change the display format from General Date to Long Time.
Power BI average between different dates
I want to calculate average time between to dates. The data looks like this: Step Datetime 2 14.11.2022 13:02:56 4 14.11.2022 13:05:15 2 14.11.2022 13:11:23 4 14.11.2022 13:13:38 2 14.11.2022 13:24:03 4 14.11.2022 13:26:21 2 15.11.2022 12:16:58 4 15.11.2022 12:19:28 I need to get an average time between all the steps number 4 and steps number 2. 14.11.2022 13:05:15 - 14.11.2022 13:02:56 = 00:02:19 14.11.2022 13:13:38 - 14.11.2022 13:11:23 = 00:02:15 14.11.2022 13:26:21 - 14.11.2022 13:24:03 = 00:02:18 15.11.2022 12:19:28 - 15.11.2022 12:16:58 = 00:02:30 The average between all four equals to 00:02:20. When I use formula measure = CALCULATE(SUM(Logging[CreatedAt]),Logging[Step] = 4) - CALCULATE(SUM(Logging[CreatedAt]),Logging[Step] = 2) it calculates the total of all four rows. The result of the formula above 30.12.1899 0:09:22. (by the way, how to get rid of this strange date result 30.12.1899?) If I use formula measure = AVERAGEX(Logging, CALCULATETABLE(VALUES(Logging[CreatedAt]), FILTER(Logging, Logging[Step] = 4)) - CALCULATETABLE(VALUES(Logging[CreatedAt]), FILTER(Logging, Logging[Step] = 4))) it delivers nothing.
[ "Try this:\nAvg Time Delta = \nVAR T2 =\n CALCULATE(\n AVERAGE('Table'[Datetime]),\n 'Table'[Step] = 2\n )\nVAR T4 = \n CALCULATE(\n AVERAGE('Table'[Datetime]),\n 'Table'[Step] = 4\n )\nVAR Seconds = \n DATEDIFF(T2, T4, SECOND)\nVAR Minutes = \n INT ( Seconds / 60 )\nVAR RemSeconds =\n MOD ( Seconds, 60 )\nVAR Hours =\n INT ( Minutes / 60 )\nVAR RemMinutes =\n MOD ( Minutes, 60 )\nRETURN\n TIME(Hours, RemMinutes, RemSeconds) \n\n\nYou can get rid of the \"30.12.1899\" prefix if you change the display format from General Date to Long Time.\n\n" ]
[ 0 ]
[]
[]
[ "dax", "powerbi", "powerbi_desktop", "powerquery" ]
stackoverflow_0074679660_dax_powerbi_powerbi_desktop_powerquery.txt
Q: Hyperparameter Tuning of Tensorflow Model | Hidden Layer size and number of hidden layers I need to tune the number of hidden layers and their hidden size of a regression model. As I tested before, generic hyperparameter optimization algorithms (grid search and random search) are not enough due to a large number of hyperparameters. Could I use PBT or Bayesian optimization to tune the network structure? In general, is there any optimization methods for tuning the hidden layer size or number of hidden layers except grid search and random search? A: You might want to give a try to Hyperband tuner. As an example, please see a section "Fine-Tuning Neural Network Hyperparameters" in https://github.com/ageron/handson-ml3/blob/main/10_neural_nets_with_keras.ipynb It is described in "Hands-on Machine Learning with Scikit-Learn, Keras and TensorFlow (3rd edition)" (p.347). A: If you're using PyTorch, the easiest way to do this is Auto-PyTorch -- it takes care of finding the best neural architecture for you (within the specified budget) and is more efficient than random search. There's a lot more information on its website, including pointers to papers describing the implemented methodology and benchmark comparisons to other approaches.
Hyperparameter Tuning of Tensorflow Model | Hidden Layer size and number of hidden layers
I need to tune the number of hidden layers and their hidden size of a regression model. As I tested before, generic hyperparameter optimization algorithms (grid search and random search) are not enough due to a large number of hyperparameters. Could I use PBT or Bayesian optimization to tune the network structure? In general, is there any optimization methods for tuning the hidden layer size or number of hidden layers except grid search and random search?
[ "You might want to give a try to Hyperband tuner. As an example, please see a section \"Fine-Tuning Neural Network Hyperparameters\" in https://github.com/ageron/handson-ml3/blob/main/10_neural_nets_with_keras.ipynb\nIt is described in \"Hands-on Machine Learning with Scikit-Learn, Keras and TensorFlow (3rd edition)\" (p.347).\n", "If you're using PyTorch, the easiest way to do this is Auto-PyTorch -- it takes care of finding the best neural architecture for you (within the specified budget) and is more efficient than random search.\nThere's a lot more information on its website, including pointers to papers describing the implemented methodology and benchmark comparisons to other approaches.\n" ]
[ 1, 1 ]
[]
[]
[ "deep_learning", "hyperparameters", "optimization", "tensorflow" ]
stackoverflow_0074671936_deep_learning_hyperparameters_optimization_tensorflow.txt
Q: Class is using Angular features but is not decorated. Please add an explicit Angular decorator I have some components like CricketComponent, FootballComponent, TennisComponent etc. All These Classes have some common properties :- TeamName, teamSize, players etc which are @Input(). Now I created a BaseComponent class, defined all these properties in there and this baseComponent class will be extended by cricket/football/tennis/etcComponents. baseComponent.ts export class BaseComponent { @Input() TeamName: string; @Input() teamSize: number; @Input() players: any; } CricketComponent.ts @Component({ selector: 'app-cricket', templateUrl: './cricket.component.html', styleUrls: ['./cricket.component.scss'] }) export class cricketComponent extends BaseComponent implements OnInit { constructor() { super(); } ngOnInit(): void { } } I am getting this error: ERROR in src/app/base-screen.ts:4:14 - error NG2007: Class is using Angular features but is not decorated. Please add an explicit Angular decorator. A: You'll need to add a @Component decorator to that base class (which should probably also be declared abstract). This is the bare minimum you can get away with in Angular 9: @Component({ template: '' }) export abstract class BaseComponent { @Input() teamName: string; @Input() teamSize: number; @Input() players: any; } For Angular 10+, see this answer. A: From Angular 10, you can fix this issue by adding the decorator @Injectable() to your abstract base class like this: @Injectable() export abstract class BaseComponent { @Input() teamName: string; @Input() teamSize: number; @Input() players: any; } A: While the accepted answer is correct in using @Component, one minor downside is that it requires all constructor argument types to be resolvable by DI. So if your base class constructor takes a constant/literal - say, an enum - as a flag, you're going to have to set up a corresponding DI provider/token just to get it to compile. You can however also resolve NG2007 using the @Directive decorator instead, which doesn't require DI compatibility A: See also: Missing @Directive()/@Component() decorator migration Before: export class BaseComponent { @Input() TeamName: string; @Input() teamSize: number; @Input() players: any; } After: @Directive() export class BaseComponent { @Input() TeamName: string; @Input() teamSize: number; @Input() players: any; } A: I had a similar situation when running ng serve. I was getting that error for 3rd party libraries and for all my Angular components even though they were decorated. If you're having this problem, see this answer for Angular 11 'error NG2007: Class is using Angular features but is not decorated.' But the class is Decorated A: For These errors : NG6001: The class 'XComponent' is listed in the declarations of the NgModule 'AppModule', but is not a directive, a component, or a pipe. Either remove it from the NgModule's declarations, or add an appropriate Angular decorator. NG2003: No suitable injection token for parameter 'A' of class 'Y'. NG2007: Class is using Angular features but is not decorated. Please add an explicit Angular decorator. You may be writing the new class between @Component declaration and Component class. ex. // export class Y{ // } @Component({ selector: 'app-X', templateUrl: './X.component.html', styleUrls: ['./X.component.css'] }) export class XComponent implements OnInit { todos : Y[] = [ new Y(1 ), new Y(2 ), new Y(3 ) ] constructor() { } ngOnInit(): void { } } //export class Y{ //} i.e. if you have more than one class . let say class XComponent and Class Y, where class Y is being used in class XComponent , then write code for class Y either above @Component({}) or below class XComponent A: If you are experiencing this in Angular 15, use an exact version of TypeScript. 4.8.2 worked for me. npm i typescript@4.8.2 -D --save-exact
Class is using Angular features but is not decorated. Please add an explicit Angular decorator
I have some components like CricketComponent, FootballComponent, TennisComponent etc. All These Classes have some common properties :- TeamName, teamSize, players etc which are @Input(). Now I created a BaseComponent class, defined all these properties in there and this baseComponent class will be extended by cricket/football/tennis/etcComponents. baseComponent.ts export class BaseComponent { @Input() TeamName: string; @Input() teamSize: number; @Input() players: any; } CricketComponent.ts @Component({ selector: 'app-cricket', templateUrl: './cricket.component.html', styleUrls: ['./cricket.component.scss'] }) export class cricketComponent extends BaseComponent implements OnInit { constructor() { super(); } ngOnInit(): void { } } I am getting this error: ERROR in src/app/base-screen.ts:4:14 - error NG2007: Class is using Angular features but is not decorated. Please add an explicit Angular decorator.
[ "You'll need to add a @Component decorator to that base class (which should probably also be declared abstract).\nThis is the bare minimum you can get away with in Angular 9:\n@Component({\n template: ''\n})\nexport abstract class BaseComponent {\n\n @Input() teamName: string;\n @Input() teamSize: number;\n @Input() players: any;\n}\n\nFor Angular 10+, see this answer.\n", "From Angular 10, you can fix this issue by adding the decorator @Injectable() to your abstract base class like this:\n@Injectable()\nexport abstract class BaseComponent { \n @Input() teamName: string;\n @Input() teamSize: number;\n @Input() players: any;\n}\n\n", "While the accepted answer is correct in using @Component, one minor downside is that it requires all constructor argument types to be resolvable by DI. So if your base class constructor takes a constant/literal - say, an enum - as a flag, you're going to have to set up a corresponding DI provider/token just to get it to compile.\nYou can however also resolve NG2007 using the @Directive decorator instead, which doesn't require DI compatibility\n", "See also: Missing @Directive()/@Component() decorator migration\nBefore:\nexport class BaseComponent {\n @Input() TeamName: string;\n @Input() teamSize: number;\n @Input() players: any;\n}\n\nAfter:\n@Directive()\nexport class BaseComponent {\n @Input() TeamName: string;\n @Input() teamSize: number;\n @Input() players: any;\n}\n\n", "I had a similar situation when running ng serve. I was getting that error for 3rd party libraries and for all my Angular components even though they were decorated.\nIf you're having this problem, see this answer for Angular 11 'error NG2007: Class is using Angular features but is not decorated.' But the class is Decorated\n", "For These errors :\nNG6001: The class 'XComponent' is listed in the declarations of the NgModule 'AppModule', but is not a directive, a component, or a pipe. Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.\nNG2003: No suitable injection token for parameter 'A' of class 'Y'.\nNG2007: Class is using Angular features but is not decorated. Please add an explicit Angular decorator.\nYou may be writing the new class between @Component declaration and Component class.\nex.\n// export class Y{\n// }\n@Component({\n selector: 'app-X',\n templateUrl: './X.component.html',\n styleUrls: ['./X.component.css']\n})\n\n\n\nexport class XComponent implements OnInit {\n\ntodos : Y[] = [\n new Y(1 ),\n new Y(2 ),\n new Y(3 )\n]\n \n constructor() { }\n\n ngOnInit(): void {\n }\n\n}\n\n//export class Y{\n//}\ni.e. if you have more than one class . let say class XComponent and Class Y, where class Y is being used in class XComponent , then write code for class Y either above @Component({}) or below class XComponent\n", "If you are experiencing this in Angular 15, use an exact version of TypeScript. 4.8.2 worked for me.\nnpm i typescript@4.8.2 -D --save-exact\n\n" ]
[ 118, 87, 36, 13, 0, 0, 0 ]
[]
[]
[ "angular", "typescript" ]
stackoverflow_0063126067_angular_typescript.txt
Q: Convert date in MySQL to yyyy-mm-dd I have a DB where the dates are stored as varchar mm/dd/yyy (12/10/2022) But I can't figure out how to convert them to yyyy-mm-dd (2022-12-10 or 2022/12/10) This doesn't work SELECT DATE_FORMAT("06/15/2022", "%Y-%m-%d"); P.S. I also want to issue a SQL command to change all the dates in the DB A: Here is one way to convert the dates in your database to the yyyy-mm-dd format: UPDATE yourTable SET yourDateColumn = STR_TO_DATE(yourDateColumn, '%m/%d/%Y') This will update the values in the yourDateColumn to the yyyy-mm-dd format. Alternatively, you can use the DATE_FORMAT() function to convert the dates to the yyyy-mm-dd format. Here is an example: SELECT DATE_FORMAT(yourDateColumn, '%Y-%m-%d') AS formatted_date FROM yourTable A: You can convert a string to a date with the function str_to_date(): select str_to_date('12/10/2022',"%m/%d/%Y"); https://www.w3schools.com/Sql/func_mysql_str_to_date.asp
Convert date in MySQL to yyyy-mm-dd
I have a DB where the dates are stored as varchar mm/dd/yyy (12/10/2022) But I can't figure out how to convert them to yyyy-mm-dd (2022-12-10 or 2022/12/10) This doesn't work SELECT DATE_FORMAT("06/15/2022", "%Y-%m-%d"); P.S. I also want to issue a SQL command to change all the dates in the DB
[ "Here is one way to convert the dates in your database to the yyyy-mm-dd format:\nUPDATE yourTable\nSET yourDateColumn = STR_TO_DATE(yourDateColumn, '%m/%d/%Y')\n\nThis will update the values in the yourDateColumn to the yyyy-mm-dd format.\nAlternatively, you can use the DATE_FORMAT() function to convert the dates to the yyyy-mm-dd format. Here is an example:\nSELECT DATE_FORMAT(yourDateColumn, '%Y-%m-%d') AS formatted_date\nFROM yourTable\n\n", "You can convert a string to a date with the function str_to_date():\nselect str_to_date('12/10/2022',\"%m/%d/%Y\");\nhttps://www.w3schools.com/Sql/func_mysql_str_to_date.asp\n" ]
[ 1, 1 ]
[]
[]
[ "date", "mysql" ]
stackoverflow_0074679825_date_mysql.txt
Q: How to enable http2 protocol in nuxt.js How to enable http2 protocol in nuxt.js app? I have added SSL certificates and enabled modern mode, played with render>http2 settings in nuxt.config.js, but no matter what I try app still serves request with standard http/1.1 protocol. I can't seem to find anything about it in the documentation either. Here is my nuxt.config.js: import path from 'path' import fs from 'fs' export default { server: { https: { key: fs.readFileSync(path.resolve(__dirname, 'certs/localhost.key')), cert: fs.readFileSync(path.resolve(__dirname, 'certs/localhost.crt')) } }, mode: 'universal', modern: true, render: { http2: { push: true, pushAssets: null } }, /* ** Headers of the page */ head: { title: process.env.npm_package_name || '', meta: [ {charset: 'utf-8'}, {name: 'viewport', content: 'width=device-width, initial-scale=1'}, {hid: 'description', name: 'description', content: process.env.npm_package_description || ''} ], link: [ {rel: 'icon', type: 'image/x-icon', href: '/favicon.ico'} ] }, /* ** Customize the progress-bar color */ loading: {color: '#fff'}, /* ** Global CSS */ css: [ ], /* ** Plugins to load before mounting the App */ plugins: [ ], /* ** Nuxt.js dev-modules */ buildModules: [ // Doc: https://github.com/nuxt-community/eslint-module '@nuxtjs/eslint-module', // Doc: https://github.com/nuxt-community/nuxt-tailwindcss '@nuxtjs/tailwindcss' ], /* ** Nuxt.js modules */ modules: [ // Doc: https://axios.nuxtjs.org/usage '@nuxtjs/axios', '@nuxtjs/pwa', // Doc: https://github.com/nuxt-community/dotenv-module '@nuxtjs/dotenv' ], /* ** Axios module configuration ** See https://axios.nuxtjs.org/options */ axios: { }, /* ** Build configuration */ build: { /* ** You can extend webpack config here */ extend(config, ctx) { } } } Thank in advance. A: You should set your mode to modern: mode: 'modern' And specify in the render.http2.pushAssets the actual assets that should be pushed (you currently have null in your sample code). For example: export default { // ... render: { http2: { push: true, pushAssets: [ '/css/main.css', '/js/main.js' ] } } };
How to enable http2 protocol in nuxt.js
How to enable http2 protocol in nuxt.js app? I have added SSL certificates and enabled modern mode, played with render>http2 settings in nuxt.config.js, but no matter what I try app still serves request with standard http/1.1 protocol. I can't seem to find anything about it in the documentation either. Here is my nuxt.config.js: import path from 'path' import fs from 'fs' export default { server: { https: { key: fs.readFileSync(path.resolve(__dirname, 'certs/localhost.key')), cert: fs.readFileSync(path.resolve(__dirname, 'certs/localhost.crt')) } }, mode: 'universal', modern: true, render: { http2: { push: true, pushAssets: null } }, /* ** Headers of the page */ head: { title: process.env.npm_package_name || '', meta: [ {charset: 'utf-8'}, {name: 'viewport', content: 'width=device-width, initial-scale=1'}, {hid: 'description', name: 'description', content: process.env.npm_package_description || ''} ], link: [ {rel: 'icon', type: 'image/x-icon', href: '/favicon.ico'} ] }, /* ** Customize the progress-bar color */ loading: {color: '#fff'}, /* ** Global CSS */ css: [ ], /* ** Plugins to load before mounting the App */ plugins: [ ], /* ** Nuxt.js dev-modules */ buildModules: [ // Doc: https://github.com/nuxt-community/eslint-module '@nuxtjs/eslint-module', // Doc: https://github.com/nuxt-community/nuxt-tailwindcss '@nuxtjs/tailwindcss' ], /* ** Nuxt.js modules */ modules: [ // Doc: https://axios.nuxtjs.org/usage '@nuxtjs/axios', '@nuxtjs/pwa', // Doc: https://github.com/nuxt-community/dotenv-module '@nuxtjs/dotenv' ], /* ** Axios module configuration ** See https://axios.nuxtjs.org/options */ axios: { }, /* ** Build configuration */ build: { /* ** You can extend webpack config here */ extend(config, ctx) { } } } Thank in advance.
[ "You should set your mode to modern:\n mode: 'modern'\n\nAnd specify in the render.http2.pushAssets the actual assets that should be pushed (you currently have null in your sample code).\nFor example:\nexport default {\n // ...\n render: {\n http2: {\n push: true,\n pushAssets: [\n '/css/main.css',\n '/js/main.js'\n ]\n }\n }\n};\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "node.js", "nuxt.js" ]
stackoverflow_0059601910_javascript_node.js_nuxt.js.txt
Q: Verifiable Credential - Presentation request gives an Internal Server Error Microsoft Entra, a new Home of Microsoft Verifiable Credential is really new and nice feature. While I am playing around the items, I found an issue which I am not sure is an issue from my code rather Its more from the platform. To give you little detail: Company A: I have one Microsoft Verifiable Account to create the credentials for Company A employee. Company B: I have one Microsoft Verifiable Account to verify (who likes to give a discount to those employees who are from Company A). Step 1: using Company A, I have created the Verifiable Credential and It is stored in my Microsoft Authenticator App successfully. Step 2: Coming to the next part of the story, Company B generates the presentation request where It likes to verify Company A employees' identity. I am able to create that presentation request and QR code for that as well. Issue comes: Now, when I scan that presentation QR code using the authenticator app, It finds my stored crednetial is matching with this request. so, It gives me an option to share that credential against this presentation reuqest which is good and correct. But the moment I press "Share" it wait for a second and gives me an error message. The error message is user friendly: Oops, failed to connect. It seems there is a problem with one of our services connecting to your device. Check your network connection and try again. But in technical detail, It says: Error Code: internalServerError Error Details: A generic error has occurred on the server.; Not Found; Not Found TimeStamp: Dec1, 2022 10:02:48 AM EST Request ID: 438395be97f20bbcc31511351121bbaa Correlation ID: 3sg46/0ARha0zS/XHYKGfA.6.4 It also gives an option to see the track which is way long and can not be copy in mobile clipboard. But I took a part of that and that is below: 2022-11-30 17:49:33,560 INFO/Broker: [com.microsoft.identity.common.internal.result.MsalBrokerResultAdapter:authenticationResultFromBundle][2022-11-30 17:49:33 - thread_name: pool-27-thread-2, correlation_id: b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b - Android 30] Broker Result returned from Bundle, constructing authentication result ThreadPoolExecutor$Worker.run()@641 [pool-14-thread-1] 2022-11-30 17:49:33,562 INFO/App: MSAL acquire token silently success: com.microsoft.identity.client.AuthenticationResult@5709e74 MsalTokenRefreshManager$getTokenSilentlyAsync$4$1$onTaskCompleted$acquireTokenSilentParameters$1.onSuccess()@567 [main] 2022-11-30 17:49:33,563 INFO/Broker: [com.microsoft.identity.common.java.result.LocalAuthenticationResult][2022-11-30 17:49:33 - thread_name: pool-27-thread-2, correlation_id: b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b - Android 30] Id Token type: IdToken ThreadPoolExecutor$Worker.run()@641 [pool-14-thread-1] 2022-11-30 17:49:33,563 INFO/Broker: [com.microsoft.identity.common.java.result.LocalAuthenticationResult][2022-11-30 17:49:33 - thread_name: pool-27-thread-2, correlation_id: b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b - Android 30] Constructing LocalAuthentication result, AccessTokenRecord null: false, AccountRecord null: false, RefreshTokenRecord null or empty: false, IdTokenRecord null: false ThreadPoolExecutor$Worker.run()@641 [pool-14-thread-1] 2022-11-30 17:49:33,564 INFO/App: Token result: Success AadRemoteNgcAuthCheckUseCase$checkForAuth$2.invokeSuspend()@88 [DefaultDispatcher-worker-5] 2022-11-30 17:49:33,564 INFO/Broker: [CommandDispatcher:submitSilent][2022-11-30 17:49:33 - thread_name: pool-27-thread-2, correlation_id: b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b - Android 30] Completed silent request as owner for correlation id : **b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b, with the status : COMPLETED is cacheable : true ThreadPoolExecutor$Worker.run()@641 [pool-14-thread-1] 2022-11-30 17:49:33,564 INFO/App: ListSessionsUseCase request with client request ID: 09871643-7561-4d9a-8e43-567c4d0480cb RemoteAuthenticationManager.listSessions()@201 [DefaultDispatcher-worker-5] Just to troubleshoot: I have tried to restart my phone. Connected with wi-fi and data card. I tried to check the previous Company A issuer Credential flow is still working and giving me the credential and all are working. So, it is not an issue from my device and neither is the issue with authenticator connectivity issue from my side. A: I think your implementation is based on the https://github.com/Azure-Samples/active-directory-verifiable-credentials-dotnet If so, please comment out the line on VerifierController.cs file under PresentationCallback() method which has a statement like //payload = presentationResponse["issuers"].ToString(). The data in the incoming request pay load doesn't have have "issuers". Instead of commenting out, you can also use the following... payload = presentationResponse["verifiedCredentialsData"][0]["issuer"];
Verifiable Credential - Presentation request gives an Internal Server Error
Microsoft Entra, a new Home of Microsoft Verifiable Credential is really new and nice feature. While I am playing around the items, I found an issue which I am not sure is an issue from my code rather Its more from the platform. To give you little detail: Company A: I have one Microsoft Verifiable Account to create the credentials for Company A employee. Company B: I have one Microsoft Verifiable Account to verify (who likes to give a discount to those employees who are from Company A). Step 1: using Company A, I have created the Verifiable Credential and It is stored in my Microsoft Authenticator App successfully. Step 2: Coming to the next part of the story, Company B generates the presentation request where It likes to verify Company A employees' identity. I am able to create that presentation request and QR code for that as well. Issue comes: Now, when I scan that presentation QR code using the authenticator app, It finds my stored crednetial is matching with this request. so, It gives me an option to share that credential against this presentation reuqest which is good and correct. But the moment I press "Share" it wait for a second and gives me an error message. The error message is user friendly: Oops, failed to connect. It seems there is a problem with one of our services connecting to your device. Check your network connection and try again. But in technical detail, It says: Error Code: internalServerError Error Details: A generic error has occurred on the server.; Not Found; Not Found TimeStamp: Dec1, 2022 10:02:48 AM EST Request ID: 438395be97f20bbcc31511351121bbaa Correlation ID: 3sg46/0ARha0zS/XHYKGfA.6.4 It also gives an option to see the track which is way long and can not be copy in mobile clipboard. But I took a part of that and that is below: 2022-11-30 17:49:33,560 INFO/Broker: [com.microsoft.identity.common.internal.result.MsalBrokerResultAdapter:authenticationResultFromBundle][2022-11-30 17:49:33 - thread_name: pool-27-thread-2, correlation_id: b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b - Android 30] Broker Result returned from Bundle, constructing authentication result ThreadPoolExecutor$Worker.run()@641 [pool-14-thread-1] 2022-11-30 17:49:33,562 INFO/App: MSAL acquire token silently success: com.microsoft.identity.client.AuthenticationResult@5709e74 MsalTokenRefreshManager$getTokenSilentlyAsync$4$1$onTaskCompleted$acquireTokenSilentParameters$1.onSuccess()@567 [main] 2022-11-30 17:49:33,563 INFO/Broker: [com.microsoft.identity.common.java.result.LocalAuthenticationResult][2022-11-30 17:49:33 - thread_name: pool-27-thread-2, correlation_id: b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b - Android 30] Id Token type: IdToken ThreadPoolExecutor$Worker.run()@641 [pool-14-thread-1] 2022-11-30 17:49:33,563 INFO/Broker: [com.microsoft.identity.common.java.result.LocalAuthenticationResult][2022-11-30 17:49:33 - thread_name: pool-27-thread-2, correlation_id: b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b - Android 30] Constructing LocalAuthentication result, AccessTokenRecord null: false, AccountRecord null: false, RefreshTokenRecord null or empty: false, IdTokenRecord null: false ThreadPoolExecutor$Worker.run()@641 [pool-14-thread-1] 2022-11-30 17:49:33,564 INFO/App: Token result: Success AadRemoteNgcAuthCheckUseCase$checkForAuth$2.invokeSuspend()@88 [DefaultDispatcher-worker-5] 2022-11-30 17:49:33,564 INFO/Broker: [CommandDispatcher:submitSilent][2022-11-30 17:49:33 - thread_name: pool-27-thread-2, correlation_id: b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b - Android 30] Completed silent request as owner for correlation id : **b27725eb-c6fc-4a0f-bdd5-dd5f3f74270b, with the status : COMPLETED is cacheable : true ThreadPoolExecutor$Worker.run()@641 [pool-14-thread-1] 2022-11-30 17:49:33,564 INFO/App: ListSessionsUseCase request with client request ID: 09871643-7561-4d9a-8e43-567c4d0480cb RemoteAuthenticationManager.listSessions()@201 [DefaultDispatcher-worker-5] Just to troubleshoot: I have tried to restart my phone. Connected with wi-fi and data card. I tried to check the previous Company A issuer Credential flow is still working and giving me the credential and all are working. So, it is not an issue from my device and neither is the issue with authenticator connectivity issue from my side.
[ "I think your implementation is based on the https://github.com/Azure-Samples/active-directory-verifiable-credentials-dotnet\nIf so, please comment out the line on VerifierController.cs file under PresentationCallback() method which has a statement like //payload = presentationResponse[\"issuers\"].ToString(). The data in the incoming request pay load doesn't have have \"issuers\". Instead of commenting out, you can also use the following...\npayload = presentationResponse[\"verifiedCredentialsData\"][0][\"issuer\"];\n" ]
[ 0 ]
[]
[]
[ "azure_ad_verifiable_credentials" ]
stackoverflow_0074511252_azure_ad_verifiable_credentials.txt
Q: How to get a specific column from a csv file? Here I tried to get a specific column from a csv file but I am getting an error on ptr[rowIdx].push_back(value) statement. It gives an error on "value" which is no suitable conversion from string to char. Here is my code: #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include<string.h> #include<cstdlib> //std::find #include<cstring> using namespace std; int main(int argc, char** argv) { ifstream fin("filename"); string line; int rowCount = 0; int rowIdx = 0; //keep track of inserted rows //count the total nb of lines in your file while (getline(fin, line)) { rowCount++; } //this will be your table. A row is represented by data[row_number]. //If you want to access the name of the column #47, you would //cout << data[0][46]. 0 being the first row(assuming headers) //and 46 is the 47 column. //But first you have to input the data. See below. string *ptr=new string[rowCount]; fin.clear(); //remove failbit (ie: continue using fin.) fin.seekg(fin.beg); //rewind stream to start while (getline(fin, line)) //for every line in input file { stringstream ss(line); //copy line to stringstream string value; while (getline(ss, value, ',')) { //for every value in that stream (ie: every cell on that row) ptr[rowIdx].push_back(value);//add that value at the end of the current row in our table } rowIdx++; //increment row number before reading in next line } fin.close(); //Now you can choose to access the data however you like. //If you want to printout only column 47... int colNum = 1; //set this number to the column you want to printout for (int row = 0; row < rowCount; row++) { cout << ptr[row][colNum] << "\t"; //print every value in column 47 only } cout << endl; return 0; } Kindly tell me where is the problem. A: You'd be much better off using a matrix of strings to read in the CSV file: No need to parse the file twice. No need to keep count of the lines in the file. You avoid newing memory. The code below uses a std::istringstream instead of a std::ifstream. [Demo] #include <cassert> #include <iostream> // cout #include <sstream> // istringstream #include <string> #include <vector> int main() { std::istringstream file_iss{R"(a,b,c,d,e 1,2,3,4,5 !,@,#,¿,* )"}; using row_t = std::vector<std::string>; using file_t = std::vector<row_t>; file_t file{}; std::string line{}; while (getline(file_iss, line)) { std::istringstream line_iss{ line }; std::string value{}; row_t row{}; while (getline(line_iss, value, ',')) { row.push_back(std::move(value)); } file.push_back(std::move(row)); } size_t col{ 1 }; assert((not file.empty()) and (col < file[0].size())); for (size_t row{ 0 }; row < file.size(); ++row) { std::cout << file[row][col] << "\t"; } std::cout << "\n"; } // Outputs: b 2 @ Notice string* ptr = new string[rowCount]; is not correct for a number of reasons: You are creating an array of strings. That would serve for storing each row. But, if you want to store each column as well, you'd need an array of arrays of strings, something like string** ptr = new string*[rowCount];. Then, once you read a line, you should parse it to know the number of columns, and create an array of strings for that given row: file[rowIdx] = new std::string[colCount];. Finally, you'd also need a second counter, e.g. colIdx, to access each column's value: file[rowIdx][colIdx] = value;. The code below hardcodes the number of rows and columns to focus on the handling of the matrix of values. It doesn't free any memory either, which should be done. [Demo] #include <iostream> // cout #include <sstream> // istringstream #include <string> int main() { std::istringstream file_iss{R"(a,b,c,d,e 1,2,3,4,5 !,@,#,¿,* )"}; std::string** file = new std::string*[3]; std::string line{}; for (size_t rowIdx{ 0 }; std::getline(file_iss, line); ++rowIdx) { file[rowIdx] = new std::string[5]; std::istringstream line_iss(line); std::string value{}; for (size_t colIdx{ 0 }; std::getline(line_iss, value, ','); ++colIdx) { file[rowIdx][colIdx] = value; } } size_t col{ 1 }; for (size_t row{ 0 }; row < 3; ++row) { std::cout << file[row][col] << "\t"; } std::cout << "\n"; }
How to get a specific column from a csv file?
Here I tried to get a specific column from a csv file but I am getting an error on ptr[rowIdx].push_back(value) statement. It gives an error on "value" which is no suitable conversion from string to char. Here is my code: #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include<string.h> #include<cstdlib> //std::find #include<cstring> using namespace std; int main(int argc, char** argv) { ifstream fin("filename"); string line; int rowCount = 0; int rowIdx = 0; //keep track of inserted rows //count the total nb of lines in your file while (getline(fin, line)) { rowCount++; } //this will be your table. A row is represented by data[row_number]. //If you want to access the name of the column #47, you would //cout << data[0][46]. 0 being the first row(assuming headers) //and 46 is the 47 column. //But first you have to input the data. See below. string *ptr=new string[rowCount]; fin.clear(); //remove failbit (ie: continue using fin.) fin.seekg(fin.beg); //rewind stream to start while (getline(fin, line)) //for every line in input file { stringstream ss(line); //copy line to stringstream string value; while (getline(ss, value, ',')) { //for every value in that stream (ie: every cell on that row) ptr[rowIdx].push_back(value);//add that value at the end of the current row in our table } rowIdx++; //increment row number before reading in next line } fin.close(); //Now you can choose to access the data however you like. //If you want to printout only column 47... int colNum = 1; //set this number to the column you want to printout for (int row = 0; row < rowCount; row++) { cout << ptr[row][colNum] << "\t"; //print every value in column 47 only } cout << endl; return 0; } Kindly tell me where is the problem.
[ "You'd be much better off using a matrix of strings to read in the CSV file:\n\nNo need to parse the file twice.\nNo need to keep count of the lines in the file.\nYou avoid newing memory.\n\nThe code below uses a std::istringstream instead of a std::ifstream.\n[Demo]\n#include <cassert>\n#include <iostream> // cout\n#include <sstream> // istringstream\n#include <string>\n#include <vector>\n\nint main() {\n std::istringstream file_iss{R\"(a,b,c,d,e\n1,2,3,4,5\n!,@,#,¿,*\n)\"};\n\n using row_t = std::vector<std::string>;\n using file_t = std::vector<row_t>;\n file_t file{};\n\n std::string line{};\n while (getline(file_iss, line)) {\n std::istringstream line_iss{ line };\n std::string value{};\n row_t row{};\n while (getline(line_iss, value, ',')) {\n row.push_back(std::move(value));\n }\n file.push_back(std::move(row));\n }\n\n size_t col{ 1 };\n assert((not file.empty()) and (col < file[0].size()));\n for (size_t row{ 0 }; row < file.size(); ++row) {\n std::cout << file[row][col] << \"\\t\";\n }\n std::cout << \"\\n\";\n}\n\n// Outputs: b 2 @\n\n\nNotice string* ptr = new string[rowCount]; is not correct for a number of reasons:\n\nYou are creating an array of strings. That would serve for storing each row. But, if you want to store each column as well, you'd need an array of arrays of strings, something like string** ptr = new string*[rowCount];.\nThen, once you read a line, you should parse it to know the number of columns, and create an array of strings for that given row: file[rowIdx] = new std::string[colCount];.\nFinally, you'd also need a second counter, e.g. colIdx, to access each column's value: file[rowIdx][colIdx] = value;.\n\nThe code below hardcodes the number of rows and columns to focus on the handling of the matrix of values.\nIt doesn't free any memory either, which should be done.\n[Demo]\n#include <iostream> // cout\n#include <sstream> // istringstream\n#include <string>\n\nint main() {\n std::istringstream file_iss{R\"(a,b,c,d,e\n1,2,3,4,5\n!,@,#,¿,*\n)\"};\n\n std::string** file = new std::string*[3];\n std::string line{};\n for (size_t rowIdx{ 0 }; std::getline(file_iss, line); ++rowIdx) {\n file[rowIdx] = new std::string[5];\n std::istringstream line_iss(line);\n std::string value{};\n for (size_t colIdx{ 0 }; std::getline(line_iss, value, ','); ++colIdx) {\n file[rowIdx][colIdx] = value;\n }\n }\n size_t col{ 1 };\n for (size_t row{ 0 }; row < 3; ++row) {\n std::cout << file[row][col] << \"\\t\";\n }\n std::cout << \"\\n\";\n}\n\n" ]
[ 0 ]
[]
[]
[ "c++" ]
stackoverflow_0074678604_c++.txt
Q: Inherited Style Properties? [FLEX - CSS] I am trying to use Flex Boxes in order to style a nav bar on my website. I'm not sure what I'm doing wrong, but there's default properties being applied on my UL. I have attached screenshots and code snippets below. Image of Issue (spacing) Inherited Properties? HTML <body> <div class="container"> <header class="navbar"> <img id="icon" src="logo.png" alt="logo" href="#index"> <nav> <ul> <li><a href="#menu">Menu</a></li> <li><a href="#combos">Combos</a></li> <li><a href="#reservation">Reservation</a></li> <li><a href="#about">About Us</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> <img id="cart" src="cart.png" alt="cart" href="#cart"> </header> </div> </body> CSS * { font-family: Montserrat, sans-serif; text-transform: uppercase; text-align: center; color:white; } body { background: #FF9292; } .container { width: 100%; min-height: 100vh; padding-left: 8%; padding-right: 8%; box-sizing: border-box; overflow: hidden; } .navbar{ margin-top: 2.5%; width: 100%; display: flex; justify-content: center; align-items: center; } #icon { width: 65px; cursor: pointer; } #cart { width: 25px; cursor: pointer; } nav ul li { list-style: none; display: inline-block; } nav ul li a { text-decoration: none; color: white; font-size: 14px; } nav ul li a:hover { color: #3f3e3e; } A: Those are not inherited properties, but the default styles supplied by your browser, the so-called user agent stylesheet. The styles in a user agent stylesheet are typically applied to all elements on the page, and are used to provide a basic layout and appearance for the page. The purpose of a user agent stylesheet is to provide a consistent and predictable default appearance for web pages, so that all users have a similar experience when viewing web pages. The styles in a user agent stylesheet are typically based on the default styles provided by the World Wide Web Consortium (W3C), the organization that sets standards for the web. User agent stylesheets can vary depending on the web browser that is being used. Different web browsers can have different default styles for the same HTML elements, so the appearance of a webpage can vary depending on which web browser is used to view it. For example, the default font size and font family for a p element may be different in Chrome and Firefox. In Chrome, the default font size for a p element may be 16 pixels, and the default font family may be Arial, sans-serif, whereas in Firefox, the default font size for a p element may be 15 pixels, and the default font family may be Verdana, sans-serif. You'd need to manually override those styles in your case. To make this easier, people, especially back in the day, started using so-called "CSS Resets" which are boilerplate stylesheets that set all of those values to 0, so you have a de-facto standard without worrying about cross-browser styles and don't need to override such values. A: what are you expecting from this code if you are thinking why 'li' are aligned horizontally without adding display: flex; in 'ul' then it is because you added display:inline-block; in 'li'.
Inherited Style Properties? [FLEX - CSS]
I am trying to use Flex Boxes in order to style a nav bar on my website. I'm not sure what I'm doing wrong, but there's default properties being applied on my UL. I have attached screenshots and code snippets below. Image of Issue (spacing) Inherited Properties? HTML <body> <div class="container"> <header class="navbar"> <img id="icon" src="logo.png" alt="logo" href="#index"> <nav> <ul> <li><a href="#menu">Menu</a></li> <li><a href="#combos">Combos</a></li> <li><a href="#reservation">Reservation</a></li> <li><a href="#about">About Us</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> <img id="cart" src="cart.png" alt="cart" href="#cart"> </header> </div> </body> CSS * { font-family: Montserrat, sans-serif; text-transform: uppercase; text-align: center; color:white; } body { background: #FF9292; } .container { width: 100%; min-height: 100vh; padding-left: 8%; padding-right: 8%; box-sizing: border-box; overflow: hidden; } .navbar{ margin-top: 2.5%; width: 100%; display: flex; justify-content: center; align-items: center; } #icon { width: 65px; cursor: pointer; } #cart { width: 25px; cursor: pointer; } nav ul li { list-style: none; display: inline-block; } nav ul li a { text-decoration: none; color: white; font-size: 14px; } nav ul li a:hover { color: #3f3e3e; }
[ "Those are not inherited properties, but the default styles supplied by your browser, the so-called user agent stylesheet.\nThe styles in a user agent stylesheet are typically applied to all elements on the page, and are used to provide a basic layout and appearance for the page.\nThe purpose of a user agent stylesheet is to provide a consistent and predictable default appearance for web pages, so that all users have a similar experience when viewing web pages. The styles in a user agent stylesheet are typically based on the default styles provided by the World Wide Web Consortium (W3C), the organization that sets standards for the web.\nUser agent stylesheets can vary depending on the web browser that is being used. Different web browsers can have different default styles for the same HTML elements, so the appearance of a webpage can vary depending on which web browser is used to view it.\nFor example, the default font size and font family for a p element may be different in Chrome and Firefox. In Chrome, the default font size for a p element may be 16 pixels, and the default font family may be Arial, sans-serif, whereas in Firefox, the default font size for a p element may be 15 pixels, and the default font family may be Verdana, sans-serif.\nYou'd need to manually override those styles in your case.\nTo make this easier, people, especially back in the day, started using so-called \"CSS Resets\" which are boilerplate stylesheets that set all of those values to 0, so you have a de-facto standard without worrying about cross-browser styles and don't need to override such values.\n", "what are you expecting from this code\nif you are thinking why 'li' are aligned horizontally without adding display: flex; in 'ul' then it is because you added display:inline-block; in 'li'.\n" ]
[ 0, 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074679016_css_html.txt
Q: Installation of SDL2 on WSL: Why can't the Dbus_Context be found? I have an issue on my WSL2 Ubuntu on Windows. I try to install SDL2 following the instruction on the website at the Linux/Unix section. When I try to make inside the build/ folder. I get the following error message: path/SDL_fcitx.c:50:5: error: unknown type name ‘SDL_DBusContext’ 50 | SDL_DBusContext *dbus; I tried to check inside the SDL_fcitx.c file and it does include "SDL_dbus.h". Just so you know, I had an issue before like: "/bin/bash^M: bad interpreter:" where I could fix it using the following command on all of my file: sed -i -e 's\r$//' <file>. Weirdly enough, I can use SDL on C and 'C++' project, but I cannot find the 'SDL2.dll' that is necessary for me for a C# project. I wanted to know if I should fix the installation and how, or how can I find the 'SDL2.dll'. A: Ok. So I could have fix the issue. It was really easy, I downloaded the SDL2.dll file online then I put it inside the C:/Windows/system32 and the C:/Windows/SysWOW64. I don't think you have to put it inside both directories and I also don't know if there was not any other solution.
Installation of SDL2 on WSL: Why can't the Dbus_Context be found?
I have an issue on my WSL2 Ubuntu on Windows. I try to install SDL2 following the instruction on the website at the Linux/Unix section. When I try to make inside the build/ folder. I get the following error message: path/SDL_fcitx.c:50:5: error: unknown type name ‘SDL_DBusContext’ 50 | SDL_DBusContext *dbus; I tried to check inside the SDL_fcitx.c file and it does include "SDL_dbus.h". Just so you know, I had an issue before like: "/bin/bash^M: bad interpreter:" where I could fix it using the following command on all of my file: sed -i -e 's\r$//' <file>. Weirdly enough, I can use SDL on C and 'C++' project, but I cannot find the 'SDL2.dll' that is necessary for me for a C# project. I wanted to know if I should fix the installation and how, or how can I find the 'SDL2.dll'.
[ "Ok. So I could have fix the issue.\nIt was really easy, I downloaded the SDL2.dll file online then I put it inside the C:/Windows/system32 and the C:/Windows/SysWOW64.\nI don't think you have to put it inside both directories and I also don't know if there was not any other solution.\n" ]
[ 0 ]
[]
[]
[ "c#", "sdl", "sdl_2", "windows_subsystem_for_linux", "wsl_2" ]
stackoverflow_0074655339_c#_sdl_sdl_2_windows_subsystem_for_linux_wsl_2.txt
Q: Error! Finding the position of the number in a Text String. (Excel 2016 Formula) So below are two different text strings. I am trying to get the position of four digit number which is a dynamic number in every text string (8555) to extract the store name (Amazing Stores 2584 or what ever is in that place again dynamic no fixed width so can't use =right). 04/12/2022 13:01:00 00 K 18.30 18.30 USD 926 4 DLKY 1 000 05 8555 0 AMAZING STORES 2584 02/12/2022 13:01:00 00 K 18.30 18.30 USD 926 4 DLKY 1 000 05 8555 0 AMAZING STORES Now my formula works for the second text string but not for the first. even thought everything is similar with just a change in date (04 instead of 02) and a number after store i.e (Amazing Stores 2584) Workflow to find the first character of the Four digit number & Store Name Formula Used : =FIND(LOOKUP(10^15,MID(A2,ROW(INDIRECT("1:"&LEN(A2))),5)+0),A2)+6 in cell b1 Formula Len : =len(a1) in cell c1 Final Result : = right(a1,c1-b1) to extract the store name. **Few things to note: ** I can't convert text to columns so this option wont work There is no Fixed length its dynamic as data is dynamic The Start position cannot be fixed length so can't use mid function either as amount could differ Text Split not an option as i can only use excel 2016 for this project I am fairly new to excel so Any help from you experts is greatly appreciated. Thanks. Tried using multiple formula's and spent close to hours on trying to figure this out on my own, Please help me. A: So I would go with either: FIND(8555,A1,1) Or FIND("8555 0",A1,1) Both return the position of the start of 8555. The first one looks for the number, while the second looks for the number, space, 0. Both return the start position. Then I would use find() to get the position of the second space, assuming that all store names have a space in them, if not you need to just find the positon of the next space. As far not being able to use mid(), you can by using find() to define the start position of mid() and also the end position based on finding the position of spaces AFTER "8555 0". A: =MID(A1, FIND(" "&MATCH(10^15,FIND(TEXT(ROW($1:$9999),"0000"),A1))&" ",A1)+7, LEN(A1)) This avoids using the volatile INDIRECT function and finds the position of the first 4 digit number surrounded by a space character and adds 7 to get the start position of the store name. Than it will add all characters from there.
Error! Finding the position of the number in a Text String. (Excel 2016 Formula)
So below are two different text strings. I am trying to get the position of four digit number which is a dynamic number in every text string (8555) to extract the store name (Amazing Stores 2584 or what ever is in that place again dynamic no fixed width so can't use =right). 04/12/2022 13:01:00 00 K 18.30 18.30 USD 926 4 DLKY 1 000 05 8555 0 AMAZING STORES 2584 02/12/2022 13:01:00 00 K 18.30 18.30 USD 926 4 DLKY 1 000 05 8555 0 AMAZING STORES Now my formula works for the second text string but not for the first. even thought everything is similar with just a change in date (04 instead of 02) and a number after store i.e (Amazing Stores 2584) Workflow to find the first character of the Four digit number & Store Name Formula Used : =FIND(LOOKUP(10^15,MID(A2,ROW(INDIRECT("1:"&LEN(A2))),5)+0),A2)+6 in cell b1 Formula Len : =len(a1) in cell c1 Final Result : = right(a1,c1-b1) to extract the store name. **Few things to note: ** I can't convert text to columns so this option wont work There is no Fixed length its dynamic as data is dynamic The Start position cannot be fixed length so can't use mid function either as amount could differ Text Split not an option as i can only use excel 2016 for this project I am fairly new to excel so Any help from you experts is greatly appreciated. Thanks. Tried using multiple formula's and spent close to hours on trying to figure this out on my own, Please help me.
[ "So I would go with either:\nFIND(8555,A1,1)\n\nOr\nFIND(\"8555 0\",A1,1)\n\nBoth return the position of the start of 8555. The first one looks for the number, while the second looks for the number, space, 0. Both return the start position.\nThen I would use find() to get the position of the second space, assuming that all store names have a space in them, if not you need to just find the positon of the next space.\nAs far not being able to use mid(), you can by using find() to define the start position of mid() and also the end position based on finding the position of spaces AFTER \"8555 0\".\n", "=MID(A1,\n FIND(\" \"&MATCH(10^15,FIND(TEXT(ROW($1:$9999),\"0000\"),A1))&\" \",A1)+7,\n LEN(A1))\n\nThis avoids using the volatile INDIRECT function and finds the position of the first 4 digit number surrounded by a space character and adds 7 to get the start position of the store name. Than it will add all characters from there.\n" ]
[ 0, 0 ]
[]
[]
[ "excel", "excel_2016", "excel_formula" ]
stackoverflow_0074677244_excel_excel_2016_excel_formula.txt
Q: Removing only one element of the duplicate elements using collections in java I have to find all the duplicates and return them using collections. For example, if list = {1,1,2,2,2} it will return {1,2,2}. So in other words, the pattern is you return -1 of the number of duplicates. Here is the method: public static Integer[] returnDuplicate (Integer[] list ){ // Insert your code here. You may want to change the return value. return null } public static Integer[] returnDuplicate (Integer[] list ){ List<Integer> uniqueList = new ArrayList<Integer>(); for (int k = 0; k < list.length; k++) { for (int j = 0; j < list.length; j++) { if (list[k] == list[j] && k != j && !uniqueList.contains(list[k])) { uniqueList.add(list[k]); } } } Integer[] result = new Integer[uniqueList.size()]; int i = 0; for (Integer val : uniqueList) { result[i++] = val; } return result; } This is my code but it's returning {1,2} instead of {1,2,2} A: Since you're allowed to use Collections, you can maintain a HashSet of elements that have been already encountered (it would be more performant than maintain List because contains() check on a list performs iteration over the whole list under the hood which results in O(n) time complexity, meanwhile HashSet produces the result almost instantly in O(1)). And while iterating offer you need to offer the next element to the Set, if the element gets rejected, i.e. method Set.add() returns false, would mean that it's a duplicate, and we can add it to the resulting list of duplicated values. public static Integer[] returnDuplicates(Integer[] list){ List<Integer> duplicates = new ArrayList<>(); Set<Integer> seen = new HashSet<>(); for (Integer next: list) { if (!seen.add(next)) duplicates.add(next); } return duplicates.toArray(Integer[]::new); } main() public static void main(String[] args) { System.out.println(Arrays.toString(returnDuplicates(new Integer[]{1, 1, 2, 2, 2}))); } Output: [1, 2, 2] A: This should do the trick: public static List<Integer> returnDuplicate (Integer[] list ){ List<Integer> uniqueList = new ArrayList<Integer>(); int prev = -1; for(Integer el : list){ if(el == prev && prev != -1) uniqueList.add(el); prev = el; } return uniqueList; }
Removing only one element of the duplicate elements using collections in java
I have to find all the duplicates and return them using collections. For example, if list = {1,1,2,2,2} it will return {1,2,2}. So in other words, the pattern is you return -1 of the number of duplicates. Here is the method: public static Integer[] returnDuplicate (Integer[] list ){ // Insert your code here. You may want to change the return value. return null } public static Integer[] returnDuplicate (Integer[] list ){ List<Integer> uniqueList = new ArrayList<Integer>(); for (int k = 0; k < list.length; k++) { for (int j = 0; j < list.length; j++) { if (list[k] == list[j] && k != j && !uniqueList.contains(list[k])) { uniqueList.add(list[k]); } } } Integer[] result = new Integer[uniqueList.size()]; int i = 0; for (Integer val : uniqueList) { result[i++] = val; } return result; } This is my code but it's returning {1,2} instead of {1,2,2}
[ "Since you're allowed to use Collections, you can maintain a HashSet of elements that have been already encountered (it would be more performant than maintain List because contains() check on a list performs iteration over the whole list under the hood which results in O(n) time complexity, meanwhile HashSet produces the result almost instantly in O(1)).\nAnd while iterating offer you need to offer the next element to the Set, if the element gets rejected, i.e. method Set.add() returns false, would mean that it's a duplicate, and we can add it to the resulting list of duplicated values.\npublic static Integer[] returnDuplicates(Integer[] list){\n List<Integer> duplicates = new ArrayList<>();\n Set<Integer> seen = new HashSet<>();\n for (Integer next: list) {\n if (!seen.add(next)) duplicates.add(next);\n }\n return duplicates.toArray(Integer[]::new);\n}\n\nmain()\npublic static void main(String[] args) {\n System.out.println(Arrays.toString(returnDuplicates(new Integer[]{1, 1, 2, 2, 2})));\n}\n\nOutput:\n[1, 2, 2]\n\n", "This should do the trick:\n public static List<Integer> returnDuplicate (Integer[] list ){\n List<Integer> uniqueList = new ArrayList<Integer>();\n int prev = -1;\n for(Integer el : list){\n if(el == prev && prev != -1)\n uniqueList.add(el);\n prev = el;\n }\n \n return uniqueList;\n \n }\n\n" ]
[ 2, 0 ]
[]
[]
[ "collections", "java" ]
stackoverflow_0074679760_collections_java.txt
Q: Serverless Framework AWS Fine-Grained Access Control I am attempting secure my AWS API such that DynamoDB rows can only be accessed by the corresponding authenticated Cognito user by implementing fine grained access control in my Serverless Framework config (serverless.yml) See example of what I am attempting in the AWS Documentation I have tried to convert the Cloudformation syntax to Serverless without success; when I try something like the following expression in my policy statement: Condition: ForAllValues:StringEquals: dynamodb:LeadingKeys: ["${cognito-identity.amazonaws.com:sub}"] I then get an error: Invalid variable reference syntax for variable cognito-identity.amazonaws.com:sub. You can only reference env vars, options, & files. You can check our docs for more info. Is this even possible in Serverless? Or is it Cloudformation and SAM only? A: It is possible in serverless. If I were you I will use AWS Lambda to verify the id_token which is sent to the user. In this scenario, you should first transfer the key to AWS Lambda function using Api Gateway or other methods. Then follow this guide to verify the token. The code can be found in: https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt After verifying it you can add your code here: ...... if claims['aud'] != app_client_id: print('Token was not issued for this audience') return False # now we can use the claims # add your code here # print(claims) return claims A: I was encountring same problem and solve it this way: Condition: ForAnyValue:StringLike: "dynamodb:LeadingKeys": - !Join ["", [ "$", "{cognito-identity.amazonaws.com:sub}" ]] That's not very clean, but as per now variables syntax collides with AWS params syntax. See this for more details - https://github.com/serverless/serverless/issues/2601
Serverless Framework AWS Fine-Grained Access Control
I am attempting secure my AWS API such that DynamoDB rows can only be accessed by the corresponding authenticated Cognito user by implementing fine grained access control in my Serverless Framework config (serverless.yml) See example of what I am attempting in the AWS Documentation I have tried to convert the Cloudformation syntax to Serverless without success; when I try something like the following expression in my policy statement: Condition: ForAllValues:StringEquals: dynamodb:LeadingKeys: ["${cognito-identity.amazonaws.com:sub}"] I then get an error: Invalid variable reference syntax for variable cognito-identity.amazonaws.com:sub. You can only reference env vars, options, & files. You can check our docs for more info. Is this even possible in Serverless? Or is it Cloudformation and SAM only?
[ "It is possible in serverless. If I were you I will use AWS Lambda to verify the id_token which is sent to the user.\nIn this scenario, you should first transfer the key to AWS Lambda function using Api Gateway or other methods. Then follow this guide to verify the token. The code can be found in: https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt\nAfter verifying it you can add your code here:\n ...... \nif claims['aud'] != app_client_id:\n print('Token was not issued for this audience')\n return False\n# now we can use the claims\n\n# add your code here #\n\nprint(claims)\nreturn claims\n\n", "I was encountring same problem and solve it this way:\nCondition:\n ForAnyValue:StringLike:\n \"dynamodb:LeadingKeys\":\n - !Join [\"\", [ \"$\", \"{cognito-identity.amazonaws.com:sub}\" ]]\n\nThat's not very clean, but as per now variables syntax collides with AWS params syntax. See this for more details - https://github.com/serverless/serverless/issues/2601\n" ]
[ 0, 0 ]
[]
[]
[ "amazon_cognito", "amazon_dynamodb", "amazon_web_services", "aws_lambda", "serverless_framework" ]
stackoverflow_0053797848_amazon_cognito_amazon_dynamodb_amazon_web_services_aws_lambda_serverless_framework.txt
Q: Tenant mode is working in angularjs but not in angular 14 In the old angularjs code and spring backend (both js and spring are build in to same war) we have tenant mode and normal mode. in normal mode the url looks like http://localhost:4200/#!/dashboard in tenant mode the url looks like. http://localhost:4200/tenant/tenant1/#!/dashboard to access the tenant mode we accessed as follows. http://localhost:4200/tenant/tenant1 then in the back end we have filter to checks whether the url has /tenant/some-id and the backend return the index.html and then it is redirected to dashboard so the dashboard url looks like http://localhost:4200/tenant/tenant1/#!/dashboard Now i have migrated to angular 14 and backend is spring framework and now also both FE and BE are coupled into single war. and when i try to access the same tenant in angular 14 using the url. http://localhost:4200/tenant/tenant1 so i get the index.html from the backend but the url is getting changed to http://localhost:4200/#/dashboard instead of http://localhost:4200/tenant/tenant1/#!/dashboard I cant able to understand why /tenant/tenant1 is getting removed from the url. which was not the case of angularjs. A: You have to change the baseurl tag in the index.html from <base href="/" /> to <base href="./" />
Tenant mode is working in angularjs but not in angular 14
In the old angularjs code and spring backend (both js and spring are build in to same war) we have tenant mode and normal mode. in normal mode the url looks like http://localhost:4200/#!/dashboard in tenant mode the url looks like. http://localhost:4200/tenant/tenant1/#!/dashboard to access the tenant mode we accessed as follows. http://localhost:4200/tenant/tenant1 then in the back end we have filter to checks whether the url has /tenant/some-id and the backend return the index.html and then it is redirected to dashboard so the dashboard url looks like http://localhost:4200/tenant/tenant1/#!/dashboard Now i have migrated to angular 14 and backend is spring framework and now also both FE and BE are coupled into single war. and when i try to access the same tenant in angular 14 using the url. http://localhost:4200/tenant/tenant1 so i get the index.html from the backend but the url is getting changed to http://localhost:4200/#/dashboard instead of http://localhost:4200/tenant/tenant1/#!/dashboard I cant able to understand why /tenant/tenant1 is getting removed from the url. which was not the case of angularjs.
[ "You have to change the baseurl tag in the index.html from\n <base href=\"/\" />\n\nto\n <base href=\"./\" />\n\n" ]
[ 0 ]
[]
[]
[ "angular", "angularjs", "multi_tenant", "spring" ]
stackoverflow_0074674101_angular_angularjs_multi_tenant_spring.txt
Q: How do I get the domain originating the request in express.js? I'm using express.js and I need to know the domain which is originating the call. This is the simple code app.get( '/verify_license_key.json', function( req, res ) { // do something How do I get the domain from the req or the res object? I mean I need to know if the API was called by somesite.example or someothersite.example. I tried doing a console.dir of both req and res but I got no idea from there, also read the documentation but it gave me no help. A: You have to retrieve it from the HOST header. var host = req.get('host'); It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own. If this is for supporting cross-origin requests, you would instead use the Origin header. var origin = req.get('origin'); Note that some cross-origin requests require validation through a "preflight" request: req.options('/route', function (req, res) { var origin = req.get('origin'); // ... }); If you're looking for the client's IP, you can retrieve that with: var userIP = req.socket.remoteAddress; message.socket. socket.remoteAddress Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well. A: Instead of: var host = req.get('host'); var origin = req.get('origin'); you can also use: var host = req.headers.host; var origin = req.headers.origin; A: In Express 4.x you can use req.hostname, which returns the domain name, without port. i.e.: // Host: "example.com:3000" req.hostname // => "example.com" See: http://expressjs.com/en/4x/api.html#req.hostname A: req.get('host') is now deprecated, using it will give Undefined. Use, req.header('Origin'); req.header('Host'); // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc. A: Year 2022, I use express v4.17.1 get following result var host = req.get('host'); // works, localhost:3000 var host = req.headers.host; // works, localhost:3000 var host = req.hostname; // works, localhost var origin = req.get('origin'); // not work, undefined var origin = req.headers.origin; // not work, undefined
How do I get the domain originating the request in express.js?
I'm using express.js and I need to know the domain which is originating the call. This is the simple code app.get( '/verify_license_key.json', function( req, res ) { // do something How do I get the domain from the req or the res object? I mean I need to know if the API was called by somesite.example or someothersite.example. I tried doing a console.dir of both req and res but I got no idea from there, also read the documentation but it gave me no help.
[ "You have to retrieve it from the HOST header.\nvar host = req.get('host');\n\nIt is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.\n\nIf this is for supporting cross-origin requests, you would instead use the Origin header.\nvar origin = req.get('origin');\n\nNote that some cross-origin requests require validation through a \"preflight\" request:\nreq.options('/route', function (req, res) {\n var origin = req.get('origin');\n // ...\n});\n\n\nIf you're looking for the client's IP, you can retrieve that with:\nvar userIP = req.socket.remoteAddress;\n\n\nmessage.socket.\nsocket.remoteAddress\n\nNote that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.\n", "Instead of:\nvar host = req.get('host');\nvar origin = req.get('origin');\n\nyou can also use:\nvar host = req.headers.host;\nvar origin = req.headers.origin;\n\n", "In Express 4.x you can use req.hostname, which returns the domain name, without port. i.e.:\n// Host: \"example.com:3000\"\nreq.hostname\n// => \"example.com\"\n\nSee: http://expressjs.com/en/4x/api.html#req.hostname\n", "req.get('host') is now deprecated, using it will give Undefined.\nUse,\n req.header('Origin');\n req.header('Host');\n // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.\n\n", "Year 2022, I use express v4.17.1 get following result\n\nvar host = req.get('host'); // works, localhost:3000\n\n\nvar host = req.headers.host; // works, localhost:3000\n\n\nvar host = req.hostname; // works, localhost\n\n\nvar origin = req.get('origin'); // not work, undefined\n\n\nvar origin = req.headers.origin; // not work, undefined\n\n\n\n\n" ]
[ 196, 52, 16, 4, 0 ]
[]
[]
[ "express", "javascript", "node.js" ]
stackoverflow_0018498726_express_javascript_node.js.txt
Q: Is there a way to simplify the last three lines of code? race = "The rabbit will run with the turtle in the race." first_r = race.find("r") last_r = race.rfind("r") result1 = race[:first_r + 1] + race[first_r + 1:last_r].replace("r", "R") + race[last_r:] print(result1) A: One way are regular expressions: import re race = "The rabbit will run with the turtle in the race." m = re.match(r'([^r]*r)(.*)(r[^r]*)$', race) result1 = m.group(1) + m.group(2).replace('r', 'R') + m.group(3) print(result1)
Is there a way to simplify the last three lines of code?
race = "The rabbit will run with the turtle in the race." first_r = race.find("r") last_r = race.rfind("r") result1 = race[:first_r + 1] + race[first_r + 1:last_r].replace("r", "R") + race[last_r:] print(result1)
[ "One way are regular expressions:\nimport re\n\nrace = \"The rabbit will run with the turtle in the race.\"\n\nm = re.match(r'([^r]*r)(.*)(r[^r]*)$', race)\n\nresult1 = m.group(1) + m.group(2).replace('r', 'R') + m.group(3)\n\nprint(result1)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074679782_python.txt
Q: Docker mysql had degraded performance after re-install ubuntu server I use MySQL for the official docker image(Ver 8.0.27) on the ubuntu server(20.04 lts). And I re-installed the server due to expanding storage. The versions of MySQL and the ubuntu server are the same. However, MySQL's performance is quite degraded. I'm trying to collect addresses of the Ehtereum(This is a kind of crypto currency.) network. The way to collect that is simple. Get transaction info. Extract addresses(To, and From). If the addresses have been recorded in a MySQL table, then ignore it. If the addresses have not been recorded, then record the addresses. Get the next transaction info. Back to 2. I execute the above loop by using a program in Typescript(With Node.js, mysql2, and Web3.js). Regarding the if statement of the 3rd item in the above list, I use the unique constraint of MySQL, not Typescript. In short, at first, make the table like below, CREATE TABLE `addressList` ( `timestampReadable` varchar(32) DEFAULT NULL, `timestamp` int DEFAULT NULL, `showUpBlock` int DEFAULT NULL, `firstTransactionHash` varchar(66) DEFAULT NULL, `address` varchar(42) DEFAULT NULL, UNIQUE KEY `addressList_address_uindex` (`address`), KEY `addressList2_timestamp_index` (`timestamp`), KEY `addressList2_firstTransactionHash_index` (`firstTransactionHash`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci And, in the program, run only the following query. INSERT INTO addressList values (123456, 123456, 123456, 'hfuwheohg', 'jhfoiehhfs'); If the address is unique, the address is recorded, if the address is not unique, the address is not recorded. The current number of the record is around 160,000,000~. This may large table, but the program was running at practical performance before the re-install. So, I can't find the cause of the problem. Just in case, I run check table, but the result seems to be no problem like below. Table Op Msg_type Msg_text ethereum.addressList check status OK I tried to set some MySQL configurations like below. SET GLOBAL max_connections=1500; SET GLOBAL sort_buffer_size=1024 * 1024 * 1024; But, the performance is not improved. I forget the MySQL configuration the first time it launches(I really regret it). Does anyone know what to do with it? Please, help me! A: If a column cannot be NULL, then say NOT NULL No PRIMARY KEY is specified, so one is generated for you. If address were never NULL, then I strongly recommend PRIMARY KEY(address) and remove UNQIQUE(address) [potential design flaw] What kind of hashes are you using? Certain hashes do not want a "ci" collation -- they depend on "A" and "a" being different. Consider changing hashes to ascii_bin. [save lots of space] If the hashes are hex strings, consider converting to binary. For example, any standard UUID will shrink from 36 bytes (of ascii characters) to 16 bytes (of binary stuff). (If I understand the data), you have two very random values being indexed. Before continuing, let me discuss the ramification of that. Each index (including any UNIQUE and the hidden PK) is stored in a "B+Tree". This structure is well ordered, but by whatever is indexed. If the INSERTs are performed approximately in chronological order, the index on TIMESTAMP will have all the activity at the "end" of the BTree. Such a 'hotspot' is easily cached. That is, it is very efficient and should never slow down, regardless of table size. If firstTransactionHash is MD5 or SHAnnn or similar, then the values are very random. Caching of the blocks of its BTree are essentially useless. So, at some point, the 'next' block needed for the next INSERT is very unlikely to be in RAM. This necessitates an I/O. I/O is time-consuming. I don't know what address is like, but I suspect its index works like one of the above. The "randomness" applies whether it is a varchar or binary. Shrinking the size of the table is the main goal. But it is only a partial 'fix'. Eventually, your table will again be so big relative to the cache size that performance will decline. The cache size is controlled by MySQL's innodb_buffer_pool_size; what is the current value? That setting is constrained to a large fraction of the RAM available to MySQL; how much do you have? Check whether Docker is further constraining the "ram" under its control.
Docker mysql had degraded performance after re-install ubuntu server
I use MySQL for the official docker image(Ver 8.0.27) on the ubuntu server(20.04 lts). And I re-installed the server due to expanding storage. The versions of MySQL and the ubuntu server are the same. However, MySQL's performance is quite degraded. I'm trying to collect addresses of the Ehtereum(This is a kind of crypto currency.) network. The way to collect that is simple. Get transaction info. Extract addresses(To, and From). If the addresses have been recorded in a MySQL table, then ignore it. If the addresses have not been recorded, then record the addresses. Get the next transaction info. Back to 2. I execute the above loop by using a program in Typescript(With Node.js, mysql2, and Web3.js). Regarding the if statement of the 3rd item in the above list, I use the unique constraint of MySQL, not Typescript. In short, at first, make the table like below, CREATE TABLE `addressList` ( `timestampReadable` varchar(32) DEFAULT NULL, `timestamp` int DEFAULT NULL, `showUpBlock` int DEFAULT NULL, `firstTransactionHash` varchar(66) DEFAULT NULL, `address` varchar(42) DEFAULT NULL, UNIQUE KEY `addressList_address_uindex` (`address`), KEY `addressList2_timestamp_index` (`timestamp`), KEY `addressList2_firstTransactionHash_index` (`firstTransactionHash`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci And, in the program, run only the following query. INSERT INTO addressList values (123456, 123456, 123456, 'hfuwheohg', 'jhfoiehhfs'); If the address is unique, the address is recorded, if the address is not unique, the address is not recorded. The current number of the record is around 160,000,000~. This may large table, but the program was running at practical performance before the re-install. So, I can't find the cause of the problem. Just in case, I run check table, but the result seems to be no problem like below. Table Op Msg_type Msg_text ethereum.addressList check status OK I tried to set some MySQL configurations like below. SET GLOBAL max_connections=1500; SET GLOBAL sort_buffer_size=1024 * 1024 * 1024; But, the performance is not improved. I forget the MySQL configuration the first time it launches(I really regret it). Does anyone know what to do with it? Please, help me!
[ "\nIf a column cannot be NULL, then say NOT NULL\nNo PRIMARY KEY is specified, so one is generated for you.\nIf address were never NULL, then I strongly recommend PRIMARY KEY(address) and remove UNQIQUE(address)\n[potential design flaw] What kind of hashes are you using? Certain hashes do not want a \"ci\" collation -- they depend on \"A\" and \"a\" being different. Consider changing hashes to ascii_bin.\n[save lots of space] If the hashes are hex strings, consider converting to binary. For example, any standard UUID will shrink from 36 bytes (of ascii characters) to 16 bytes (of binary stuff).\n(If I understand the data), you have two very random values being indexed. Before continuing, let me discuss the ramification of that.\n\nEach index (including any UNIQUE and the hidden PK) is stored in a \"B+Tree\". This structure is well ordered, but by whatever is indexed.\nIf the INSERTs are performed approximately in chronological order, the index on TIMESTAMP will have all the activity at the \"end\" of the BTree. Such a 'hotspot' is easily cached. That is, it is very efficient and should never slow down, regardless of table size.\nIf firstTransactionHash is MD5 or SHAnnn or similar, then the values are very random. Caching of the blocks of its BTree are essentially useless. So, at some point, the 'next' block needed for the next INSERT is very unlikely to be in RAM. This necessitates an I/O. I/O is time-consuming.\nI don't know what address is like, but I suspect its index works like one of the above.\nThe \"randomness\" applies whether it is a varchar or binary.\nShrinking the size of the table is the main goal. But it is only a partial 'fix'. Eventually, your table will again be so big relative to the cache size that performance will decline. The cache size is controlled by MySQL's innodb_buffer_pool_size; what is the current value? That setting is constrained to a large fraction of the RAM available to MySQL; how much do you have? Check whether Docker is further constraining the \"ram\" under its control.\n" ]
[ 0 ]
[]
[]
[ "docker", "ethereum", "mysql", "node.js", "ubuntu_server" ]
stackoverflow_0074673086_docker_ethereum_mysql_node.js_ubuntu_server.txt
Q: Python Panda problems with group by and regularexpression A Table Sample like bellows- Product Price P1,Luxary product 2000 P2: Cosmetics product 1700 P1::Plastic product 600 P3/P1,Mobile phone 3300 P2:headphones 200 P3,Trimmer 150 P2,Camera 2200 P2/Airpods 250 P3;;phone case 100 P2/P1:Mirrors 800 Water Bottel P2 2011 60 From Product column, how can i extract hidden sings (- P1, P2 and P3) sometimes there is more than one signs it is okay if just extract the first sign. Then Group by them(Signs) with Price colums and Print from high price to low price ? Output: P2 - 5210 P3 - 3550 P1 - 2600 A: Assuming that your "hidden signs" always contain two characters, simply create new columns containing these prefixes: df['Prefix'] = df['Product'].str[:2] You may then group by prefix: df.groupby('Prefix').sum() A: Here is a proposition using pandas.Series.str.extract : out = ( df .assign(Signs= df["Product"].str.extract("(P\d)", expand=False)) .groupby("Signs", as_index=False)["Price"].sum() .sort_values(by="Price", ascending=False, ignore_index=True) ) # Output : print(out) Signs Price 0 P2 5210 1 P3 3550 2 P1 2600
Python Panda problems with group by and regularexpression
A Table Sample like bellows- Product Price P1,Luxary product 2000 P2: Cosmetics product 1700 P1::Plastic product 600 P3/P1,Mobile phone 3300 P2:headphones 200 P3,Trimmer 150 P2,Camera 2200 P2/Airpods 250 P3;;phone case 100 P2/P1:Mirrors 800 Water Bottel P2 2011 60 From Product column, how can i extract hidden sings (- P1, P2 and P3) sometimes there is more than one signs it is okay if just extract the first sign. Then Group by them(Signs) with Price colums and Print from high price to low price ? Output: P2 - 5210 P3 - 3550 P1 - 2600
[ "Assuming that your \"hidden signs\" always contain two characters, simply create new columns containing these prefixes:\ndf['Prefix'] = df['Product'].str[:2]\n\nYou may then group by prefix:\ndf.groupby('Prefix').sum()\n\n", "Here is a proposition using pandas.Series.str.extract :\nout = (\n df\n .assign(Signs= df[\"Product\"].str.extract(\"(P\\d)\", expand=False))\n .groupby(\"Signs\", as_index=False)[\"Price\"].sum()\n .sort_values(by=\"Price\", ascending=False, ignore_index=True)\n )\n\n# Output :\nprint(out)\n\n Signs Price\n0 P2 5210\n1 P3 3550\n2 P1 2600\n\n" ]
[ 0, 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074679857_group_by_pandas_python.txt
Q: call interval VBS or Batch I'm trying to code a simple chat program that runs from command line, which use a text file as the "database". And I'm stuck when trying to create an autoupdate function while still listening for user input. Is there a function to javascript's; setTimeout(functon(),int milliSec) in vbscript or batch? Here is the function i would like to call every second: Function read() Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile _ ("c:\chat.txt", 1) Do Until objTextFile.AtEndOfStream txtOutput = objTextFile.ReadLine Wscript.Echo txtOutput Loop objTextFile.Close End Function or in Batch: :read type c:\chat.txt how can I call these when the command line is listening for input? batch: set /p var="Say:" vbs: WScript.StdOut.Write("Say:") A: I ended up doing it VB.Net with a user interface instead. Works great now :) Thanks A: i know you asked this 9 years ago, but I've recently been doing this stuff, so if you do need this by any chance, give me a shout, because I also had this problem
call interval VBS or Batch
I'm trying to code a simple chat program that runs from command line, which use a text file as the "database". And I'm stuck when trying to create an autoupdate function while still listening for user input. Is there a function to javascript's; setTimeout(functon(),int milliSec) in vbscript or batch? Here is the function i would like to call every second: Function read() Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile _ ("c:\chat.txt", 1) Do Until objTextFile.AtEndOfStream txtOutput = objTextFile.ReadLine Wscript.Echo txtOutput Loop objTextFile.Close End Function or in Batch: :read type c:\chat.txt how can I call these when the command line is listening for input? batch: set /p var="Say:" vbs: WScript.StdOut.Write("Say:")
[ "I ended up doing it VB.Net with a user interface instead. Works great now :) Thanks\n", "i know you asked this 9 years ago, but I've recently been doing this stuff, so if you do need this by any chance, give me a shout, because I also had this problem\n" ]
[ 0, 0 ]
[]
[]
[ "batch_file", "command_line", "updates", "vbscript" ]
stackoverflow_0017746947_batch_file_command_line_updates_vbscript.txt
Q: Oauth implementation for graphql in Magento2 I have to implement OAuth for graphql API in Magento, I went through the documentation of Magento but I found that only we can authenticate by using username and password https://devdocs.magento.com/guides/v2.4/graphql/authorization-tokens.html https://devdocs.magento.com/guides/v2.4/graphql/mutations/generate-customer-token.html We are creating a PWA application and web application is going to use it directly Is there any other way to authenticate means any other authentication layer A: Including this below to this very old question, if in case some others coming across this question. Magento Graphql in the core implemented currently to handle more of frontend user request which will be in the form of either asking for some data that's either only to read or submit personal data (such as placing order with address) There are modules available with the support of Graphql to handle E2E ERP sync (products & order fulfillment) , OOTB does not support everything that you might able to do with the use of oAuth Integration token + REST API. You would want to determine the actual outcome or scope to decide on the authentication / authorization mode and then decide on the API layer medium. If in case of Integration token based approach is what decided for data / access security reasons then REST API will be easier option for the most of the OOTB functionalities.
Oauth implementation for graphql in Magento2
I have to implement OAuth for graphql API in Magento, I went through the documentation of Magento but I found that only we can authenticate by using username and password https://devdocs.magento.com/guides/v2.4/graphql/authorization-tokens.html https://devdocs.magento.com/guides/v2.4/graphql/mutations/generate-customer-token.html We are creating a PWA application and web application is going to use it directly Is there any other way to authenticate means any other authentication layer
[ "Including this below to this very old question, if in case some others coming across this question.\n\nMagento Graphql in the core implemented currently to handle more of frontend user request which will be in the form of either asking for some data that's either only to read or submit personal data (such as placing order with address)\nThere are modules available with the support of Graphql to handle E2E ERP sync (products & order fulfillment) , OOTB does not support everything that you might able to do with the use of oAuth Integration token + REST API.\n\nYou would want to determine the actual outcome or scope to decide on the authentication / authorization mode and then decide on the API layer medium. If in case of Integration token based approach is what decided for data / access security reasons then REST API will be easier option for the most of the OOTB functionalities.\n" ]
[ 0 ]
[]
[]
[ "adobe", "graphql", "magento", "magento2", "oauth" ]
stackoverflow_0071794827_adobe_graphql_magento_magento2_oauth.txt
Q: Delete all vowels from a string using a list-comprehension I'm trying to solve a challenge on Codewars. Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and return a new string with all vowels removed. For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!". Note: for this kata y isn't considered a vowel. This is working: def disemvowel(string): output = [] for char in string: if char not in "aeiouAEIOU": output.extend(char) return "".join(output) But I want to do it in one line with a list comprehension. I tried this: return "".join([[].extend(char) for char in string if char not in "aeiouAEIOU"]) ... but I'm getting TypeError: sequence item 0: expected str instance, NoneType found A: You're trying to make a list within your list-comprehension; you can just use the existing list: return "".join([char for char in x if char not in "aeiouAEIOU"]) Note that we could even omit the list comprehension and just use a generator expression (by omitting the square brackets), but join() works internally by converting the sequence to a list anyway, so in this case using a list-comprehension is actually quicker. A: def disemvowel(string_): vowels = 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' for a in vowels: string_ = string_.replace(a, '') return string_ A: I did in one liner but I don't know it's the correct way, although it is working and have passed all the tests. Any guidance is appreciated. Thanks. def disemvowel(string_): return string_.replace('a','').replace('e','').replace('i','').replace('o','').replace('u','').replace('A','').replace('E','').replace('I','').replace('O','').replace('U','')
Delete all vowels from a string using a list-comprehension
I'm trying to solve a challenge on Codewars. Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and return a new string with all vowels removed. For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!". Note: for this kata y isn't considered a vowel. This is working: def disemvowel(string): output = [] for char in string: if char not in "aeiouAEIOU": output.extend(char) return "".join(output) But I want to do it in one line with a list comprehension. I tried this: return "".join([[].extend(char) for char in string if char not in "aeiouAEIOU"]) ... but I'm getting TypeError: sequence item 0: expected str instance, NoneType found
[ "You're trying to make a list within your list-comprehension; you can just use the existing list:\nreturn \"\".join([char for char in x if char not in \"aeiouAEIOU\"])\n\nNote that we could even omit the list comprehension and just use a generator expression (by omitting the square brackets), but join() works internally by converting the sequence to a list anyway, so in this case using a list-comprehension is actually quicker.\n", "def disemvowel(string_):\n vowels = 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'\n for a in vowels:\n string_ = string_.replace(a, '')\n return string_\n\n", "I did in one liner but I don't know it's the correct way, although it is working and have passed all the tests. Any guidance is appreciated. Thanks.\ndef disemvowel(string_):\n return string_.replace('a','').replace('e','').replace('i','').replace('o','').replace('u','').replace('A','').replace('E','').replace('I','').replace('O','').replace('U','')\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "list", "list_comprehension", "python", "python_3.x", "string" ]
stackoverflow_0060169364_list_list_comprehension_python_python_3.x_string.txt