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: Excel VBA Selenium Basic ChromeDriver - Removing "Save Password" and "Restore Pages" popups? I have an Excel VBA script that uses Selenium Basic ChromeDriver to login and navigate a website. I'm trying to make it so that Chrome's popup prompts in the right corner asking either to "Save password" or "Restore Pages" don't appear. save password restore pages My attempt is below, but it isn't working for either case. `` ` Sub ChromeDriverTest() Dim bot2 As Selenium.ChromeDriver Set bot2 = New ChromeDriver bot2.SetCapability "goog:chromeOptions", "{""excludeSwitches"": [""enable-automation""], ""args"":[""--start-maximized"",""--hide-scrollbars"", ""user-data-dir=C:\\ChromeTest"",""--disable-notifications"",""--no-sandbox"",""--no-first-run"",""--no-service-autorun"",""--password-store=basic""]}" bot2.SetPreference "profile.default_content_setting_values.notifications", 2 bot2.SetPreference "credentials_enable_service", False bot2.SetPreference "profile.password_manager_enabled", False bot2.Timeouts.ImplicitWait = 2000 ` `` Unfortunately still always getting the "Save Password" prompt. And the "Restore pages?" prompt continues to happen after cases where ChromeDriver is stopped suddenly in the previous run. Any help is appreciated! A: Regarding the offer to restore pages, I don't know how to make it appear so I can't help with that. Regarding the offer to save the password: when I tried your code the offer did appear but when I used only this line: bot2.SetPreference "credentials_enable_service", False The offer stopped appearing Also, note that you must set preferences before calling the start method
Excel VBA Selenium Basic ChromeDriver - Removing "Save Password" and "Restore Pages" popups?
I have an Excel VBA script that uses Selenium Basic ChromeDriver to login and navigate a website. I'm trying to make it so that Chrome's popup prompts in the right corner asking either to "Save password" or "Restore Pages" don't appear. save password restore pages My attempt is below, but it isn't working for either case. `` ` Sub ChromeDriverTest() Dim bot2 As Selenium.ChromeDriver Set bot2 = New ChromeDriver bot2.SetCapability "goog:chromeOptions", "{""excludeSwitches"": [""enable-automation""], ""args"":[""--start-maximized"",""--hide-scrollbars"", ""user-data-dir=C:\\ChromeTest"",""--disable-notifications"",""--no-sandbox"",""--no-first-run"",""--no-service-autorun"",""--password-store=basic""]}" bot2.SetPreference "profile.default_content_setting_values.notifications", 2 bot2.SetPreference "credentials_enable_service", False bot2.SetPreference "profile.password_manager_enabled", False bot2.Timeouts.ImplicitWait = 2000 ` `` Unfortunately still always getting the "Save Password" prompt. And the "Restore pages?" prompt continues to happen after cases where ChromeDriver is stopped suddenly in the previous run. Any help is appreciated!
[ "Regarding the offer to restore pages, I don't know how to make it appear so I can't help with that.\nRegarding the offer to save the password: when I tried your code the offer did appear but when I used only this line:\nbot2.SetPreference \"credentials_enable_service\", False\n\nThe offer stopped appearing\nAlso, note that you must set preferences before calling the start method\n" ]
[ 0 ]
[]
[]
[ "excel", "selenium", "selenium_chromedriver", "vba" ]
stackoverflow_0074651290_excel_selenium_selenium_chromedriver_vba.txt
Q: Transform boundingBox according to angle and rotation I am trying to implement a plastic cards detector using Vision ML Model which was trained on a custom data set. I am drawing rectangles according to bounding boxes coordinates over the camera view and it works like a charm. BUT. It doesn't react to changes in the angle, or rotation. You can see this on the screens below. The ideal solution already exists in the same Vision library, but for rectangles detection. It has topLeft, topRight, bottomLeft, bottomRight with which I can draw whatever quadrilateral, but object detection has only bounding box property which actually is CGRect (ML model really required here for future changes). I found a lot of similar answers, but they had different contexts or language or the task itself. Maybe there is some way to do it with CGAffineTransform or configure model training better? Thanks! A: You can detect the object you need using object detector model and then use VNDetectRectanglesRequest. It may be a little bit slow, but this way you don't have to train anything :)
Transform boundingBox according to angle and rotation
I am trying to implement a plastic cards detector using Vision ML Model which was trained on a custom data set. I am drawing rectangles according to bounding boxes coordinates over the camera view and it works like a charm. BUT. It doesn't react to changes in the angle, or rotation. You can see this on the screens below. The ideal solution already exists in the same Vision library, but for rectangles detection. It has topLeft, topRight, bottomLeft, bottomRight with which I can draw whatever quadrilateral, but object detection has only bounding box property which actually is CGRect (ML model really required here for future changes). I found a lot of similar answers, but they had different contexts or language or the task itself. Maybe there is some way to do it with CGAffineTransform or configure model training better? Thanks!
[ "You can detect the object you need using object detector model and then use VNDetectRectanglesRequest. It may be a little bit slow, but this way you don't have to train anything :)\n" ]
[ 0 ]
[]
[]
[ "bounding_box", "machine_learning", "mlmodel", "swift", "visionkit" ]
stackoverflow_0074672499_bounding_box_machine_learning_mlmodel_swift_visionkit.txt
Q: How do I make an event listener with decorators in Python? I want to make an event listener like this: @some.event async def on_ready(some_info): print(some_info) @some.event async def on_error(err): print(err) So for when something is ready, or if a message is received in like WebSockets, using this for Discord since some info is only available for when the Bot is Identified or Ready I've seen something like: def add_listener(func, name): # ... def remove_listener(func, name): # ... But I don't really know how to use it or create one A: Quick example : ################################################################################ # the code for the "framework" event1_listeners = [] event2_listeners = [] def listen_event1(func): event1_listeners.append(func) return func def listen_event2(func): event2_listeners.append(func) return func def process_event(event): if event["type"] == 1: for func in event1_listeners: func(event) elif event["type"] == 2: for func in event2_listeners: func(event) else: raise NotImplementedError(f"{event['type']=!r}") ################################################################################ # your code @listen_event1 def handle_event1_v1(event): print(f"handle_event1_v1 : {event!r}") @listen_event1 def handle_event1_v2(event): print(f"handle_event1_v2 : {event!r}") @listen_event2 def handle_event2(event): print(f"handle_event2 : {event!r}") ################################################################################ # the events processed by the framework process_event({"type": 1, "msg": "hello"}) process_event({"type": 2, "msg": "world"}) handle_event1_v1 : {'type': 1, 'msg': 'hello'} handle_event1_v2 : {'type': 1, 'msg': 'hello'} handle_event2 : {'type': 2, 'msg': 'world'} Essentially, the decorators will store the function someplace, and when an event is received, the framework iterates over the functions registered for it. Removing a listener dynamically is basically just removing the func reference from the list. The decorator in this case is simply "sugar" to not having to do event1_listeners.append(func) yourself. A: Here's a simple class-based solution I quickly coded: class Event: def __init__(self): # Initialise a list of listeners self.__listeners = [] # Define a getter for the 'on' property which returns the decorator. @property def on(self): # A declorator to run addListener on the input function. def wrapper(func): self.addListener(func) return func return wrapper # Add and remove functions from the list of listeners. def addListener(self,func): if func in self.__listeners: return self.__listeners.append(func) def removeListener(self,func): if func not in self.__listeners: return self.__listeners.remove(func) # Trigger events. def trigger(self,args = []): # Run all the functions that are saved. for func in self.__listeners: func(*args) It allows you to create an Event that functions can 'subscribe' to: evn = Event() # Some code... evn.trigger(['arg x','arg y']) The functions can both subscribe to the event with decorators: @evn.on def some_function(x,y): pass Or with the addListener method: def some_function(x,y): pass evn.addListener(some_function) You can also remove listeners: evn.removeListener(some_function) To create something similar to what you asked for you can do something like this: # some.py from event import Event class SomeClass: def __init__(self): # Private event variable self.__event = Event() # Public event variable (decorator) self.event = self.__event.on some = SomeClass() And then use it like so: # main.py from some import some @some.event async def on_ready(some_info): print(some_info) @some.event async def on_error(err): print(err)
How do I make an event listener with decorators in Python?
I want to make an event listener like this: @some.event async def on_ready(some_info): print(some_info) @some.event async def on_error(err): print(err) So for when something is ready, or if a message is received in like WebSockets, using this for Discord since some info is only available for when the Bot is Identified or Ready I've seen something like: def add_listener(func, name): # ... def remove_listener(func, name): # ... But I don't really know how to use it or create one
[ "Quick example :\n################################################################################\n# the code for the \"framework\"\nevent1_listeners = []\nevent2_listeners = []\n\ndef listen_event1(func):\n event1_listeners.append(func)\n return func\n\ndef listen_event2(func):\n event2_listeners.append(func)\n return func\n\ndef process_event(event):\n if event[\"type\"] == 1:\n for func in event1_listeners:\n func(event)\n elif event[\"type\"] == 2:\n for func in event2_listeners:\n func(event)\n else:\n raise NotImplementedError(f\"{event['type']=!r}\")\n\n################################################################################\n# your code\n@listen_event1\ndef handle_event1_v1(event):\n print(f\"handle_event1_v1 : {event!r}\")\n\n@listen_event1\ndef handle_event1_v2(event):\n print(f\"handle_event1_v2 : {event!r}\")\n\n@listen_event2\ndef handle_event2(event):\n print(f\"handle_event2 : {event!r}\")\n\n################################################################################\n# the events processed by the framework\nprocess_event({\"type\": 1, \"msg\": \"hello\"})\nprocess_event({\"type\": 2, \"msg\": \"world\"})\n\nhandle_event1_v1 : {'type': 1, 'msg': 'hello'}\nhandle_event1_v2 : {'type': 1, 'msg': 'hello'}\nhandle_event2 : {'type': 2, 'msg': 'world'}\n\nEssentially, the decorators will store the function someplace, and when an event is received, the framework iterates over the functions registered for it.\nRemoving a listener dynamically is basically just removing the func reference from the list.\nThe decorator in this case is simply \"sugar\" to not having to do event1_listeners.append(func) yourself.\n", "Here's a simple class-based solution I quickly coded:\nclass Event:\n def __init__(self):\n # Initialise a list of listeners\n self.__listeners = []\n \n # Define a getter for the 'on' property which returns the decorator.\n @property\n def on(self):\n # A declorator to run addListener on the input function.\n def wrapper(func):\n self.addListener(func)\n return func\n return wrapper\n \n # Add and remove functions from the list of listeners.\n def addListener(self,func):\n if func in self.__listeners: return\n self.__listeners.append(func)\n \n def removeListener(self,func):\n if func not in self.__listeners: return\n self.__listeners.remove(func)\n \n # Trigger events.\n def trigger(self,args = []):\n # Run all the functions that are saved.\n for func in self.__listeners: func(*args)\n\nIt allows you to create an Event that functions can 'subscribe' to:\nevn = Event()\n\n# Some code...\n\nevn.trigger(['arg x','arg y'])\n\nThe functions can both subscribe to the event with decorators:\n@evn.on\ndef some_function(x,y): pass\n\nOr with the addListener method:\ndef some_function(x,y): pass\nevn.addListener(some_function)\n\nYou can also remove listeners:\nevn.removeListener(some_function)\n\nTo create something similar to what you asked for you can do something like this:\n# some.py\n\nfrom event import Event\n\nclass SomeClass:\n def __init__(self):\n # Private event variable\n self.__event = Event()\n # Public event variable (decorator)\n self.event = self.__event.on\n\nsome = SomeClass()\n\nAnd then use it like so:\n# main.py\n\nfrom some import some\n\n@some.event\nasync def on_ready(some_info):\n print(some_info)\n\n@some.event\nasync def on_error(err):\n print(err)\n\n" ]
[ 1, 0 ]
[]
[]
[ "decorator", "discord", "python" ]
stackoverflow_0070982565_decorator_discord_python.txt
Q: how to prerender multiple language in angular universal i am using angular universal for server side rendering and i cant figure out how to prerender multilingual routes prerender app being prerender only one language i tried to wrap whole routing into one lang parametr like en/tickets/.... but when i try to prerender i get result ✔ Prerendering routes to /Users/john/Desktop/project:name/dist/project:name/browser complete. nothing gets prerendered result angular universal 14. for translate i am using ngx-translate A: Angular Universal is a tool that allows Angular applications to be processed on the server side. This way, the pages of the application can be pre-processed and quickly displayed to the user. To pre-render multilingual routes, you can follow the steps below: Determine the routes you want to pre-render. For example, you may want to pre-process routes such as /en, /fr and /de. Open the server.ts file and add the following code snippet: app.get('/en', (req, res) => { res.render(indexHtml, { req, providers: [{ provide: 'serverUrl', useValue: ${req.protocol}://${req.get('host')} }] }); }); app.get('/fr', (req, res) => { res.render(indexHtml, { req, providers: [{ provide: 'serverUrl', useValue: ${req.protocol}://${req.get('host')} }] }); }); app.get('/de', (req, res) => { res.render(indexHtml, { req, providers: [{ provide: 'serverUrl', useValue: ${req.protocol}://${req.get('host')} }] }); }); This code snippet listens to the routes you have determined with the app.get() method and processes the requests received on these routes. We use the res.render() method to send the pre-rendered page. Open the package.json file and add the following line to the scripts section: "prerender": "ng run my-app:server:production && node dist/server.js" This line allows the Angular application to be run on the server side and pre-rendered pages to be generated. In the terminal, run the npm run prerender command to generate the pre-rendered pages. By following these steps, you can pre-render the multilingual routes of your Angular application and provide a better user experience.
how to prerender multiple language in angular universal
i am using angular universal for server side rendering and i cant figure out how to prerender multilingual routes prerender app being prerender only one language i tried to wrap whole routing into one lang parametr like en/tickets/.... but when i try to prerender i get result ✔ Prerendering routes to /Users/john/Desktop/project:name/dist/project:name/browser complete. nothing gets prerendered result angular universal 14. for translate i am using ngx-translate
[ "Angular Universal is a tool that allows Angular applications to be processed on the server side. This way, the pages of the application can be pre-processed and quickly displayed to the user. To pre-render multilingual routes, you can follow the steps below:\n\nDetermine the routes you want to pre-render. For example, you may want to pre-process routes such as /en, /fr and /de.\n\nOpen the server.ts file and add the following code snippet:\n\n\napp.get('/en', (req, res) => {\nres.render(indexHtml, { req, providers: [{ provide: 'serverUrl', useValue: ${req.protocol}://${req.get('host')} }] });\n});\napp.get('/fr', (req, res) => {\nres.render(indexHtml, { req, providers: [{ provide: 'serverUrl', useValue: ${req.protocol}://${req.get('host')} }] });\n});\napp.get('/de', (req, res) => {\nres.render(indexHtml, { req, providers: [{ provide: 'serverUrl', useValue: ${req.protocol}://${req.get('host')} }] });\n});\nThis code snippet listens to the routes you have determined with the app.get() method and processes the requests received on these routes. We use the res.render() method to send the pre-rendered page.\n\nOpen the package.json file and add the following line to the scripts section:\n\n\"prerender\": \"ng run my-app:server:production && node dist/server.js\"\nThis line allows the Angular application to be run on the server side and pre-rendered pages to be generated.\n\nIn the terminal, run the npm run prerender command to generate the pre-rendered pages.\nBy following these steps, you can pre-render the multilingual routes of your Angular application and provide a better user experience.\n\n" ]
[ 0 ]
[]
[]
[ "angular", "angular_universal", "prerender" ]
stackoverflow_0074678660_angular_angular_universal_prerender.txt
Q: Pre-cache List of videos uisng CacheDataSource.Factory( ) android I'm able to cache a playing video using the below code: ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory( new CacheDataSource.Factory() .setCache(SimpleMediaPlayer.simpleCache) .setUpstreamDataSourceFactory(new DefaultDataSource.Factory(this,new DefaultHttpDataSource.Factory())) .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR) ).createMediaSource(MediaItem.fromUri("https://xxxxxx.s3.us-north-2.amazonaws.com/xxxxxx.mp4")); playerView.setPlayer(player); player.setMediaSource(mediaSource); player.prepare(); But I want a list of videos to cache before playing. I want to do this in background threads something like using WorkManager or Services. I need an efficient way to do that. Please help me. A: You can use Workmanager to schedule background work for precache video data from URL refer this : https://www.section.io/engineering-education/preloading-and-buffering-videos-in-android-with-exoplayer/
Pre-cache List of videos uisng CacheDataSource.Factory( ) android
I'm able to cache a playing video using the below code: ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory( new CacheDataSource.Factory() .setCache(SimpleMediaPlayer.simpleCache) .setUpstreamDataSourceFactory(new DefaultDataSource.Factory(this,new DefaultHttpDataSource.Factory())) .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR) ).createMediaSource(MediaItem.fromUri("https://xxxxxx.s3.us-north-2.amazonaws.com/xxxxxx.mp4")); playerView.setPlayer(player); player.setMediaSource(mediaSource); player.prepare(); But I want a list of videos to cache before playing. I want to do this in background threads something like using WorkManager or Services. I need an efficient way to do that. Please help me.
[ "You can use Workmanager to schedule background work for precache video data from URL refer this :\nhttps://www.section.io/engineering-education/preloading-and-buffering-videos-in-android-with-exoplayer/\n" ]
[ 0 ]
[]
[]
[ "android", "cache_control", "caching", "exoplayer", "media_source" ]
stackoverflow_0074678504_android_cache_control_caching_exoplayer_media_source.txt
Q: SQL injection vulnerability? I have this simple website put together for learning purposes implementing a minor sanitization function ` def sqlescape(txt): return (str(txt).replace(";",";").replace("'","'")) def get_cipher(key): cipher = crypt.new(str.encode(salt+key)) return cipher def encode_body(body, key): if key == '': body = str.encode(body) else: cipher = get_cipher(key) body = cipher.encrypt(body) return base64.b64encode(body) def decode_body(body, key): body = (base64.b64decode(body)).decode() if not key == '': cipher = get_cipher(key) body = cipher.decrypt(body) body = body.decode() return body @app.route('/') def home(): return render_template('home.html') @app.route('/new') def new_task(): return render_template('new_task.html') @app.route('/addrec', methods=['POST', 'GET']) def addrec(): if request.method == 'POST': con = sql.connect(db) msg = "" try: title = request.form['title'] body = request.form['body'] key = request.form['password'] body = encode_body(body, key) cur = con.cursor() cur.executescript("INSERT INTO tasks (title,body) VALUES (" + html.unescape(sqlescape(title)) + "," + html.unescape(sqlescape(body.decode())) + ");") con.commit() msg = "Record successfully added" except: con.rollback() msg = "error in insert operation" finally: return render_template("result.html", msg=msg) con.close() @app.route('/task') def my_route(): taskid = request.args.get('id', default=1) con = sql.connect(db) con.row_factory = sql.Row cur = con.cursor() cur.execute("select title,body from tasks where id=?", taskid) (title, body) = cur.fetchone() return render_template( "task.html", title=title, body=body, # body.decode(), taskid=taskid) @app.route('/decrypt', methods=['POST', 'GET']) def decrypt(): if request.method == 'POST': taskid = request.form['id'] key = request.form['password'] con = sql.connect(db) con.row_factory = sql.Row cur = con.cursor() cur.execute("select title,body from tasks where id=?", taskid) (title, body) = cur.fetchone() body = decode_body(body, key) return render_template("decrypt.html", title=title, body=body) @app.route('/list') def list(): con = sql.connect(db) con.row_factory = sql.Row cur = con.cursor() cur.execute("select title,id from tasks") rows = cur.fetchall() return render_template("list.html", rows=rows) if not os.path.isfile(db): with sql.connect(db) as conn: conn.execute( 'CREATE TABLE tasks (id integer primary key, title TEXT, body TEXT)' ) ` Using bandit it still states there might be still be susceptible to SQL injection. I am looking for any potential ways a user might be to use SQL injection on it maybe with some examples as I haven been giving it a go myself to no avail as I am still new to this. Any pointers would be great. A: It looks like your code is vulnerable to SQL injection attacks in the addrec function. In particular, the following line of code concatenates user input directly into the SQL query string, which can allow an attacker to inject arbitrary SQL commands: cur.executescript("INSERT INTO tasks (title,body) VALUES (" + html.unescape(sqlescape(title)) + "," + html.unescape(sqlescape(body.decode())) + ");") For example, if an attacker were to provide the following input for the title field: '; DROP TABLE tasks; -- The resulting SQL query would be: INSERT INTO tasks (title,body) VALUES (''; DROP TABLE tasks; --','[base64-encoded body value]'); This query would first insert a new record with a title value of '; DROP TABLE tasks; --', and then execute a DROP statement to delete the entire tasks table. To protect against SQL injection attacks, you should use parameterized queries instead of concatenating user input into the query string. In Python, you can use the ? placeholder in your SQL query and pass the user input as a separate argument to the execute or executemany method. For example, the addrec function could be rewritten as follows: @app.route('/addrec', methods=['POST', 'GET']) def addrec(): if request.method == 'POST': con = sqlite3.connect(db) msg = "" try: # Get the user input title = request.form['title'] body = request.form['body'] key = request.form['password'] body = encode_body(body, key) # Use a parameterized query to insert the user input into the database cur = con.cursor() cur.execute("INSERT INTO tasks (title,body) VALUES (?, ?)", (title, body.decode())) # Commit the changes to the database con.commit() msg = "Record successfully added" except: con.rollback() msg = "error in insert operation" finally: return render_template("result.html", msg=msg) con.close()
SQL injection vulnerability?
I have this simple website put together for learning purposes implementing a minor sanitization function ` def sqlescape(txt): return (str(txt).replace(";",";").replace("'","'")) def get_cipher(key): cipher = crypt.new(str.encode(salt+key)) return cipher def encode_body(body, key): if key == '': body = str.encode(body) else: cipher = get_cipher(key) body = cipher.encrypt(body) return base64.b64encode(body) def decode_body(body, key): body = (base64.b64decode(body)).decode() if not key == '': cipher = get_cipher(key) body = cipher.decrypt(body) body = body.decode() return body @app.route('/') def home(): return render_template('home.html') @app.route('/new') def new_task(): return render_template('new_task.html') @app.route('/addrec', methods=['POST', 'GET']) def addrec(): if request.method == 'POST': con = sql.connect(db) msg = "" try: title = request.form['title'] body = request.form['body'] key = request.form['password'] body = encode_body(body, key) cur = con.cursor() cur.executescript("INSERT INTO tasks (title,body) VALUES (" + html.unescape(sqlescape(title)) + "," + html.unescape(sqlescape(body.decode())) + ");") con.commit() msg = "Record successfully added" except: con.rollback() msg = "error in insert operation" finally: return render_template("result.html", msg=msg) con.close() @app.route('/task') def my_route(): taskid = request.args.get('id', default=1) con = sql.connect(db) con.row_factory = sql.Row cur = con.cursor() cur.execute("select title,body from tasks where id=?", taskid) (title, body) = cur.fetchone() return render_template( "task.html", title=title, body=body, # body.decode(), taskid=taskid) @app.route('/decrypt', methods=['POST', 'GET']) def decrypt(): if request.method == 'POST': taskid = request.form['id'] key = request.form['password'] con = sql.connect(db) con.row_factory = sql.Row cur = con.cursor() cur.execute("select title,body from tasks where id=?", taskid) (title, body) = cur.fetchone() body = decode_body(body, key) return render_template("decrypt.html", title=title, body=body) @app.route('/list') def list(): con = sql.connect(db) con.row_factory = sql.Row cur = con.cursor() cur.execute("select title,id from tasks") rows = cur.fetchall() return render_template("list.html", rows=rows) if not os.path.isfile(db): with sql.connect(db) as conn: conn.execute( 'CREATE TABLE tasks (id integer primary key, title TEXT, body TEXT)' ) ` Using bandit it still states there might be still be susceptible to SQL injection. I am looking for any potential ways a user might be to use SQL injection on it maybe with some examples as I haven been giving it a go myself to no avail as I am still new to this. Any pointers would be great.
[ "It looks like your code is vulnerable to SQL injection attacks in the addrec function. In particular, the following line of code concatenates user input directly into the SQL query string, which can allow an attacker to inject arbitrary SQL commands:\ncur.executescript(\"INSERT INTO tasks (title,body) VALUES (\" +\n html.unescape(sqlescape(title)) + \",\" + html.unescape(sqlescape(body.decode())) +\n \");\")\n\nFor example, if an attacker were to provide the following input for the title field:\n'; DROP TABLE tasks; --\n\nThe resulting SQL query would be:\nINSERT INTO tasks (title,body) VALUES (''; DROP TABLE tasks; --','[base64-encoded body value]');\n\nThis query would first insert a new record with a title value of '; DROP TABLE tasks; --', and then execute a DROP statement to delete the entire tasks table.\nTo protect against SQL injection attacks, you should use parameterized queries instead of concatenating user input into the query string. In Python, you can use the ? placeholder in your SQL query and pass the user input as a separate argument to the execute or executemany method. For example, the addrec function could be rewritten as follows:\n @app.route('/addrec', methods=['POST', 'GET'])\ndef addrec():\n if request.method == 'POST':\n con = sqlite3.connect(db)\n msg = \"\"\n try:\n # Get the user input\n title = request.form['title']\n body = request.form['body']\n key = request.form['password']\n body = encode_body(body, key)\n\n # Use a parameterized query to insert the user input into the database\n cur = con.cursor()\n cur.execute(\"INSERT INTO tasks (title,body) VALUES (?, ?)\", (title, body.decode()))\n\n # Commit the changes to the database\n con.commit()\n msg = \"Record successfully added\"\n except:\n con.rollback()\n msg = \"error in insert operation\"\n\n finally:\n return render_template(\"result.html\", msg=msg)\n con.close()\n\n" ]
[ 1 ]
[]
[]
[ "python", "sql", "sql_injection" ]
stackoverflow_0074679347_python_sql_sql_injection.txt
Q: Can I add code/update my exported app in windows forms? So I made a Quick Notes app in Visual Studio using C# and the windows forms .NET Framework. I exported the program using the setup wizard which is part of the Microsoft visual studio installer projects extension. The app is completed but I forgot to add a bit of code. I can add it in visual studio since the project is still there but I'm not sure it will apply it to the exported app. Can anyone help? I don't want to break anything so I haven't written any new code. A: Any workflow that generates an installer (.msi, .msix, setup.exe) will need to be regenerated if code changes are made to the installed app. The installer version should be incremented and also a new ProductCode should be generated so that the newer installer has the information it needs to remove prior versions.
Can I add code/update my exported app in windows forms?
So I made a Quick Notes app in Visual Studio using C# and the windows forms .NET Framework. I exported the program using the setup wizard which is part of the Microsoft visual studio installer projects extension. The app is completed but I forgot to add a bit of code. I can add it in visual studio since the project is still there but I'm not sure it will apply it to the exported app. Can anyone help? I don't want to break anything so I haven't written any new code.
[ "Any workflow that generates an installer (.msi, .msix, setup.exe) will need to be regenerated if code changes are made to the installed app. The installer version should be incremented and also a new ProductCode should be generated so that the newer installer has the information it needs to remove prior versions.\n" ]
[ 0 ]
[]
[]
[ "c#", "forms", "setup_wizard", "windows", "winforms" ]
stackoverflow_0074678868_c#_forms_setup_wizard_windows_winforms.txt
Q: How to get the smallest texel that wraps a triangle Assume I have the UVs of the three vertices of a triangle. What is the fastest way to get the smallest texel that wraps this triangle? That is, the mip level and the UV coordinates of this texel. A: Let us use the following notation: Let p be the index of your points in the triangle, so p in {0,1,2} Let n(p) be a 2D vector function representing the normalized texcoords in [0,1] (per component), assigned to point index p Let t(p,l) nbe the unnormalized tex coords assiged to point p for mipmap level l This means t(p,l) = n(p) * vec2(width(l), height(l)). If we want to find the mipmap level, we can do this by calculating the size of the triangle in the base level t(p,0): Let: a = t(1,0) - t(0,0) b = t(2,0) - t(0,0) a and b represent the vectors of the edges of the triangle in texture space, at the base level. So let's find the maximum individually for each dimension: x_max = max(a.x,b.x) y_max = max(a.y,b.y) These two basically describe the size of an axis-aligned bounding-box around our triangle. So we can use the longest side to find the mipmap level: m = max(x_max,y_max). Finding the right mipmap level means finding the level l for which the size m would be <= 1 texel. By going up one mip level, the value of m would be halved. so we get (with the appropriate rounding): l = floor(log2(ceil(m))) What we have now is the level where the size of the triangle would fit in one texel. This is the lower bound of the actual level that fullfills your criteria. The triangle might intersect up to 2x2 texels at level n. However, just going up one more level might not do the trick, as it might still intersect different texel in the upper-next level. In the worst case, your triangle encloses the center point of your texture, in which case, only the upmost mip level sized 1x1 will ever completely enclose your triangle completely. So a naive algorithm could be start at level l as calculated above above calculate floor(t(p,l)) for all three points Compare them. If the are all identical, you are finished, l is the result. If not all three are identical, increase l by one and repeat at step 2. The resulting l will be the level you searched for. and the UV coordinates of this texel A texel doesn't have one UV coordinate, but represents a rectangle in UV space. So it is not clear what you want, but you might want some of the following the unnormalized integer texel coords, which are just thefloor(t(p,l)) you already calculated the unnormalized coordinates of the texel center, which is just floor(t(p,l)) + vec2(0.5) the unnormalized coordinates of the barycenter of the triangle, which is just (t(0,l) + t(1,l) + t(2,l))/3.0 the normalized variant of any of the above, which is just the value divided by the size of level l
How to get the smallest texel that wraps a triangle
Assume I have the UVs of the three vertices of a triangle. What is the fastest way to get the smallest texel that wraps this triangle? That is, the mip level and the UV coordinates of this texel.
[ "Let us use the following notation:\n\nLet p be the index of your points in the triangle, so p in {0,1,2}\nLet n(p) be a 2D vector function representing the normalized texcoords in [0,1] (per component), assigned to point index p\nLet t(p,l) nbe the unnormalized tex coords assiged to point p for mipmap level l\n\nThis means t(p,l) = n(p) * vec2(width(l), height(l)).\nIf we want to find the mipmap level, we can do this by calculating the size of the triangle in the base level t(p,0):\nLet:\n\na = t(1,0) - t(0,0)\n\nb = t(2,0) - t(0,0)\na and b represent the vectors of the edges of the triangle in texture space, at the base level. So let's find the maximum individually for each dimension:\n\nx_max = max(a.x,b.x)\n\ny_max = max(a.y,b.y)\n\n\nThese two basically describe the size of an axis-aligned bounding-box around our triangle. So we can use the longest side to find the mipmap level:\n\nm = max(x_max,y_max).\n\nFinding the right mipmap level means finding the level l for which the size m would be <= 1 texel. By going up one mip level, the value of m would be halved. so we get (with the appropriate rounding):\n\nl = floor(log2(ceil(m)))\n\nWhat we have now is the level where the size of the triangle would fit in one texel. This is the lower bound of the actual level that fullfills your criteria. The triangle might intersect up to 2x2 texels at level n. However, just going up one more level might not do the trick, as it might still intersect different texel in the upper-next level. In the worst case, your triangle encloses the center point of your texture, in which case, only the upmost mip level sized 1x1 will ever completely enclose your triangle completely.\nSo a naive algorithm could be\n\nstart at level l as calculated above above\ncalculate floor(t(p,l)) for all three points\nCompare them. If the are all identical, you are finished, l is the result. If not all three are identical, increase l by one and repeat at step 2.\n\nThe resulting l will be the level you searched for.\n\nand the UV coordinates of this texel\n\nA texel doesn't have one UV coordinate, but represents a rectangle in UV space. So it is not clear what you want, but you might want some of the following\n\nthe unnormalized integer texel coords, which are just thefloor(t(p,l)) you already calculated\nthe unnormalized coordinates of the texel center, which is just floor(t(p,l)) + vec2(0.5)\nthe unnormalized coordinates of the barycenter of the triangle, which is just (t(0,l) + t(1,l) + t(2,l))/3.0\nthe normalized variant of any of the above, which is just the value divided by the size of level l\n\n" ]
[ 0 ]
[]
[]
[ "glsl", "graphics", "opengl", "shader" ]
stackoverflow_0074671691_glsl_graphics_opengl_shader.txt
Q: How to remove all non alphanumeric characters from a string except period and space in excel? I need to remove all non alphanumeric characters from a string except period and space in Excel. A solution using VBA rather than pure excel functions be just fine. A: Insert this function into a new module in the Visual Basic Editor: Function AlphaNumericOnly(strSource As String) As String Dim i As Integer Dim strResult As String For i = 1 To Len(strSource) Select Case Asc(Mid(strSource, i, 1)) Case 48 To 57, 65 To 90, 97 To 122: 'include 32 if you want to include space strResult = strResult & Mid(strSource, i, 1) End Select Next AlphaNumericOnly = strResult End Function Now you can use this as a User Define Function, i.e. if your data is in cell A1, place this formula in an empty cell =AlphaNumericOnly(A1). If you want to convert a large range directly, i.e. replace all the non-alphanumeric characters without leaving the source, you can do this with another VBA routine: Sub CleanAll() Dim rng As Range For Each rng In Sheets("Sheet1").Range("A1:K1500").Cells 'adjust sheetname and range accordingly rng.Value = AlphaNumericOnly(rng.Value) Next End Sub Simply place this sub in the same module and execute it. Be aware though, that this will replace any formulas in the range. A: I was looking for a more elegant solution than the one I came up with. I was going to use ashleedawg's code above as it certainly is neater than my code. Ironically, mine ran 30% quicker. If speed is important (say you have a few million to do), try this: Public Function AlphaNumeric(str As String) As String Dim i As Long For i = 1 To Len(str) If InStr(1, "01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. ", Mid(str, i, 1)) Then AlphaNumeric = AlphaNumeric & Mid(str, i, 1) Next End Function There's a surprise around every corner with VBA. I'd never imagine this would be quicker... A: Here' an alternate method of removing "whatever characters you want" from a string using pattern matching. The example below removes everything except letters, numbers, spaces and periods ([A-Z.a-z 0-9]) For improved efficiency it also utilizes VBA's seamless conversion between Strings and Byte Arrays: cleanString Function: Function cleanString(str As String) As String Dim ch, bytes() As Byte: bytes = str For Each ch In bytes If Chr(ch) Like "[A-Z.a-z 0-9]" Then cleanString = cleanString & Chr(ch) Next ch End Function More Information: For more about creating patterns for the Like operator, see: VBA: Like Operator description better info in the VB.NET: Like Operator description More about how Byte Arrays and Strings are basically interchangeable A: I have written the following code and it works as far as I tested it, it consists of two functions. The first checks whether a string is alphanumeric and the second makes the replacement (it also removes spaces) Public Function Isalphanumeric(cadena As String) As Boolean Select Case Asc(UCase(cadena)) Case 65 To 90 'letras Isalphanumeric = True Case 48 To 57 'numeros Isalphanumeric = True Case Else Isalphanumeric = False End Select End Function And here goes the remove function Function RemoveSymbols_Enhanced(InputString As String) As String Dim InputString As String Dim CharactersArray() Dim i, arrayindex, longitud As Integer Dim item As Variant i = 1 arrayindex = 0 longitud = Len(InputString) 'We create an array with non alphanumeric characters For i = 1 To longitud If Isalphanumeric(Mid(InputString, i, 1)) = False Then ReDim Preserve CharactersArray(arrayindex) CharactersArray(arrayindex) = Mid(InputString, i, 1) arrayindex = arrayindex + 1 End If Next 'For each non alphanumeric character we do a replace For Each item In CharactersArray item = CStr(item) InputString = Replace(InputString, item, "") Next End Function A: Get alphanumeric characters including spaces, +- signs and (point)commata The tricky helper function getCodes() called by AlphaNum() groups each character into five categories, where category 4 corresponds to digits, 5 to any letters, not only from A-Z, but including even ►accented or ►diacritic ones. By looping to the returned codes array you are in the position to get only the relevant alphanum characters or allowed signs. Function AlphaNum(ByVal s As String, Optional info As Boolean = False) As String 'a) group characters into code categories Dim codes: codes = getCodes(s, info) 'b) check codes returning only alpha nums Dim i As Long, ii As Long For i = 1 To UBound(codes) Dim char As String: char = Mid$(s, i, 1) Dim okay As Boolean: okay = False Select Case codes(i) ' AlphaNum: 4=digits, 5=letters Case Is >= 4: okay = True ' other characters Case 2 ' allowing space, minus or comma If InStr(" ,-", char) <> 0 Then okay = True Case 3 ' allowing plus or point If InStr(".+", char) <> 0 Then okay = True End Select If okay Then ii = ii + 1: codes(ii) = char Next i ReDim Preserve codes(1 To ii) AlphaNum = Join(codes, vbNullString) End Function Helper functions Function Char2Arr(ByVal s As String) 'Purp.: assign single characters to array s = StrConv(s, vbUnicode) Char2Arr = Split(s, vbNullChar, Len(s) \ 2) End Function Function getCodes(s, Optional info As Boolean = False) 'Purp.: group characters into five categories Const CATEG As String = "' - . 0 A" Dim arr: arr = Char2Arr(s) Dim chars: chars = Split(CATEG) getCodes = Application.Match(arr, chars) 'No 3rd zero-argument!! 'optional display in immediate window If info Then Debug.Print Join(arr, "|") Debug.Print Join(getCodes, "|") End If End Function Example call Dim s As String s = "Alpha, -8.9 +äæçñöüéêëÿ'!$""#$%&()*/:;<=>?@|¶" Debug.Print "~~> " & AlphaNum(s, info:=True) Display in VB editor's immediate window A|l|p|h|a|,| |-|8|.|9| |+|ä|æ|ç|ñ|ö|ü|é|ê|ë|ÿ|'|!|$|"|#|$|%|&|(|)|*|/|:|;|<|=|>|?|@|||¶ 5|5|5|5|5|2|2|2|4|3|4|2|3|5|5|5|5|5|5|5|5|5|5|1|2|2|2|2|2|2|2|2|2|2|3|3|3|3|3|3|3|3|3|3 Alpha, -8.9 +äæçñöüéêëÿ
How to remove all non alphanumeric characters from a string except period and space in excel?
I need to remove all non alphanumeric characters from a string except period and space in Excel. A solution using VBA rather than pure excel functions be just fine.
[ "Insert this function into a new module in the Visual Basic Editor:\nFunction AlphaNumericOnly(strSource As String) As String\n Dim i As Integer\n Dim strResult As String\n\n For i = 1 To Len(strSource)\n Select Case Asc(Mid(strSource, i, 1))\n Case 48 To 57, 65 To 90, 97 To 122: 'include 32 if you want to include space\n strResult = strResult & Mid(strSource, i, 1)\n End Select\n Next\n AlphaNumericOnly = strResult\nEnd Function\n\nNow you can use this as a User Define Function, i.e. if your data is in cell A1, place this formula in an empty cell =AlphaNumericOnly(A1).\nIf you want to convert a large range directly, i.e. replace all the non-alphanumeric characters without leaving the source, you can do this with another VBA routine:\nSub CleanAll()\n Dim rng As Range\n\n For Each rng In Sheets(\"Sheet1\").Range(\"A1:K1500\").Cells 'adjust sheetname and range accordingly\n rng.Value = AlphaNumericOnly(rng.Value)\n Next\nEnd Sub\n\nSimply place this sub in the same module and execute it. Be aware though, that this will replace any formulas in the range.\n", "I was looking for a more elegant solution than the one I came up with. I was going to use ashleedawg's code above as it certainly is neater than my code. Ironically, mine ran 30% quicker. If speed is important (say you have a few million to do), try this:\nPublic Function AlphaNumeric(str As String) As String\n Dim i As Long\n \n For i = 1 To Len(str)\n If InStr(1, \"01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. \", Mid(str, i, 1)) Then AlphaNumeric = AlphaNumeric & Mid(str, i, 1)\n Next\nEnd Function\n\nThere's a surprise around every corner with VBA. I'd never imagine this would be quicker...\n", "Here' an alternate method of removing \"whatever characters you want\" from a string using pattern matching. \n\nThe example below removes everything except letters, numbers, spaces and periods ([A-Z.a-z 0-9]) \nFor improved efficiency it also utilizes VBA's seamless conversion between Strings and Byte Arrays:\n\n\ncleanString Function:\nFunction cleanString(str As String) As String\n Dim ch, bytes() As Byte: bytes = str\n For Each ch In bytes\n If Chr(ch) Like \"[A-Z.a-z 0-9]\" Then cleanString = cleanString & Chr(ch)\n Next ch\nEnd Function\n\n\n\nMore Information:\n\nFor more about creating patterns for the Like operator, see: \n\n\nVBA: Like Operator description \nbetter info in the VB.NET: Like Operator description \n\nMore about how Byte Arrays and Strings are basically interchangeable \n\n", "I have written the following code and it works as far as I tested it, it consists of two functions. The first checks whether a string is alphanumeric and the second makes the replacement (it also removes spaces)\nPublic Function Isalphanumeric(cadena As String) As Boolean\n\n Select Case Asc(UCase(cadena))\n Case 65 To 90 'letras\n Isalphanumeric = True\n Case 48 To 57 'numeros\n Isalphanumeric = True\n Case Else\n Isalphanumeric = False\n\n End Select\n\nEnd Function\n\nAnd here goes the remove function\nFunction RemoveSymbols_Enhanced(InputString As String) As String\n\n Dim InputString As String\n Dim CharactersArray()\n Dim i, arrayindex, longitud As Integer\n Dim item As Variant\n\n\n i = 1\n arrayindex = 0\n longitud = Len(InputString)\n\n'We create an array with non alphanumeric characters\n For i = 1 To longitud\n\n If Isalphanumeric(Mid(InputString, i, 1)) = False Then\n ReDim Preserve CharactersArray(arrayindex)\n CharactersArray(arrayindex) = Mid(InputString, i, 1)\n arrayindex = arrayindex + 1\n\n End If\n\n Next\n\n 'For each non alphanumeric character we do a replace\n For Each item In CharactersArray\n item = CStr(item)\n InputString = Replace(InputString, item, \"\")\n Next\n\n\nEnd Function\n\n", "Get alphanumeric characters including spaces, +- signs and (point)commata\nThe tricky helper function getCodes() called by AlphaNum() groups each character into five categories, where\n\ncategory 4 corresponds to digits,\n5 to any letters, not only from A-Z, but including even ►accented or ►diacritic ones.\n\nBy looping to the returned codes array you are in the position to get only the relevant alphanum characters\nor allowed signs.\nFunction AlphaNum(ByVal s As String, Optional info As Boolean = False) As String\n'a) group characters into code categories\n Dim codes: codes = getCodes(s, info)\n'b) check codes returning only alpha nums\n Dim i As Long, ii As Long\n For i = 1 To UBound(codes)\n Dim char As String: char = Mid$(s, i, 1)\n Dim okay As Boolean: okay = False\n Select Case codes(i)\n ' AlphaNum: 4=digits, 5=letters\n Case Is >= 4: okay = True\n ' other characters\n Case 2 ' allowing space, minus or comma\n If InStr(\" ,-\", char) <> 0 Then okay = True\n Case 3 ' allowing plus or point\n If InStr(\".+\", char) <> 0 Then okay = True\n End Select\n If okay Then ii = ii + 1: codes(ii) = char\n Next i\n ReDim Preserve codes(1 To ii)\n AlphaNum = Join(codes, vbNullString)\nEnd Function\n\nHelper functions\nFunction Char2Arr(ByVal s As String)\n'Purp.: assign single characters to array\n s = StrConv(s, vbUnicode)\n Char2Arr = Split(s, vbNullChar, Len(s) \\ 2)\nEnd Function\n\nFunction getCodes(s, Optional info As Boolean = False)\n'Purp.: group characters into five categories\n Const CATEG As String = \"' - . 0 A\"\n Dim arr: arr = Char2Arr(s)\n Dim chars: chars = Split(CATEG)\n getCodes = Application.Match(arr, chars) 'No 3rd zero-argument!!\n 'optional display in immediate window\n If info Then\n Debug.Print Join(arr, \"|\")\n Debug.Print Join(getCodes, \"|\")\n End If\nEnd Function\n\nExample call\n Dim s As String\n s = \"Alpha, -8.9 +äæçñöüéêëÿ'!$\"\"#$%&()*/:;<=>?@|¶\"\n\n Debug.Print \"~~> \" & AlphaNum(s, info:=True) \n\nDisplay in VB editor's immediate window\nA|l|p|h|a|,| |-|8|.|9| |+|ä|æ|ç|ñ|ö|ü|é|ê|ë|ÿ|'|!|$|\"|#|$|%|&|(|)|*|/|:|;|<|=|>|?|@|||¶ \n5|5|5|5|5|2|2|2|4|3|4|2|3|5|5|5|5|5|5|5|5|5|5|1|2|2|2|2|2|2|2|2|2|2|3|3|3|3|3|3|3|3|3|3\nAlpha, -8.9 +äæçñöüéêëÿ\n\n\n" ]
[ 44, 12, 10, 2, 0 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0015723672_excel_vba.txt
Q: `TypeError: 'str' object is not callable` when a decorator function is caleld I get a TypeError: 'str' object is not callable error when a decorator function is caleld. E.g. I call the function msgReturnAsList, which is actually meant to return a list and therefore I do not understand why is it throwing an error that a str object is not callable. I read at FreeCodeCamp that this TypeError occurs mainly in two occasions, neither of which has anything to do with my case: 1."If You Use str as a Variable Name in Python" 2. "If You Call a String Like a Function in Python" Can somebody clarify what is the logic behind this and how do I get msgReturnAsList to return the string converted to upper by wrapThis and then converted to a list by the problematic decorator function msgReturnAsList? def wrapThis(a): a = str(a).upper() return a @wrapThis def msgReturnAsList(msg): msg = list(msg) return msg b = "Convert to upper and output it as a list of letters." print(msgReturnAsList(b)) I tired changing the list to string, interestingly the error remains the same. A: A decorator method should return a method: def wrapThis(func): def wrapper_func(msg): msg = str(msg).upper() return func(msg) return wrapper_func @wrapThis def msgReturnAsList(msg): msg = list(msg) return msg b = "Convert to upper and output it as a list of letters." print(msgReturnAsList(b)) How to Create and Use Decorators in Python With Examples
`TypeError: 'str' object is not callable` when a decorator function is caleld
I get a TypeError: 'str' object is not callable error when a decorator function is caleld. E.g. I call the function msgReturnAsList, which is actually meant to return a list and therefore I do not understand why is it throwing an error that a str object is not callable. I read at FreeCodeCamp that this TypeError occurs mainly in two occasions, neither of which has anything to do with my case: 1."If You Use str as a Variable Name in Python" 2. "If You Call a String Like a Function in Python" Can somebody clarify what is the logic behind this and how do I get msgReturnAsList to return the string converted to upper by wrapThis and then converted to a list by the problematic decorator function msgReturnAsList? def wrapThis(a): a = str(a).upper() return a @wrapThis def msgReturnAsList(msg): msg = list(msg) return msg b = "Convert to upper and output it as a list of letters." print(msgReturnAsList(b)) I tired changing the list to string, interestingly the error remains the same.
[ "A decorator method should return a method:\ndef wrapThis(func):\n def wrapper_func(msg):\n msg = str(msg).upper()\n return func(msg)\n return wrapper_func\n\n@wrapThis\ndef msgReturnAsList(msg):\n msg = list(msg)\n return msg\n\nb = \"Convert to upper and output it as a list of letters.\"\nprint(msgReturnAsList(b))\n\nHow to Create and Use Decorators in Python With Examples\n" ]
[ 1 ]
[]
[]
[ "python", "python_decorators" ]
stackoverflow_0074679394_python_python_decorators.txt
Q: Debugging installed libraries I have installed mbedtls on my wsl Ubuntu: sudo apt-get install -y libmbedtls-dev But I would like to debug through library code. I have downloaded source files from git repository. But does it means I must build libraries with -g option which allows produce debugging information? A: Yes, you need to build the mbed TLS libraries with the -g flag to produce debugging symbols. This will allow you to use a debugger to step through the code and see what is happening at each step. To build mbed TLS with debugging information, you can use the -g option with the make command, i.e.: make CFLAGS=-g This will build the mbed TLS libraries with the -g option and produce debugging information. You can then use GDB to debug the code.
Debugging installed libraries
I have installed mbedtls on my wsl Ubuntu: sudo apt-get install -y libmbedtls-dev But I would like to debug through library code. I have downloaded source files from git repository. But does it means I must build libraries with -g option which allows produce debugging information?
[ "Yes, you need to build the mbed TLS libraries with the -g flag to produce debugging symbols. This will allow you to use a debugger to step through the code and see what is happening at each step. To build mbed TLS with debugging information, you can use the -g option with the make command, i.e.:\nmake CFLAGS=-g\n\nThis will build the mbed TLS libraries with the -g option and produce debugging information. You can then use GDB to debug the code.\n" ]
[ 0 ]
[]
[]
[ "c", "linux", "visual_studio_code" ]
stackoverflow_0074679169_c_linux_visual_studio_code.txt
Q: React hock useEvent TypeScript There is this code, it works on js but not on ts import { useCallback, useLayoutEffect, useRef } from 'react'; type callbackType = (...args: any[]) => any; export const useEvent = <TF extends callbackType>(callback: TF): TF => { const functionRef = useRef<TF>(callback); useLayoutEffect(() => { functionRef.current = callback; }); return useCallback((...args) => { const functionCall = functionRef.current; return functionCall(...args); }, []); }; error here: return useCallback((...args) => { TS2345: Argument of type '(...args: any[]) => any' is not assignable to parameter of type 'TF'.'(...args: any[]) => any' is assignable to the constraint of type 'TF', but 'TF' could be instantiated with a different subtype of constraint 'callbackType'. how to solve this problem without resorting to //@ts-ignore? A: I can't really explain why, but the issues seems to be with the ...args: any[] from callbackType, which could not be "respected". So I modified a bit callbackType to take two generics (one for the parameters and one for the result), and I added the constraint that the input should extend any[] (so it works well with the rest parameters), which seems to fix the issues. import { useCallback, useLayoutEffect, useRef } from "react"; type callbackType<A extends any[], R> = (...args: A) => R; export const useEvent = <A extends any[], R>( callback: callbackType<A, R> ): callbackType<A, R> => { const functionRef = useRef(callback); useLayoutEffect(() => { functionRef.current = callback; }); return useCallback((...args) => { const functionCall = functionRef.current; return functionCall(...args); }, []); }; function Component() { const cb = useEvent((x: number, y: string) => { return "Hello world"; }); cb(1, "test"); return null; } A: import {useRef, useLayoutEffect, useCallback} from 'react'; type callbackType = (...args: Array<any>) => any; interface useEventOverload { <TF extends callbackType>(callback: TF): TF; <TF extends callbackType>(callback: TF): any; } export const useEvent: useEventOverload = (callback) => { const callbackRef = useRef(callback); useLayoutEffect(() => { callbackRef.current = callback; }); return useCallback((...args: any) => { return callbackRef.current(...args); }, []); };
React hock useEvent TypeScript
There is this code, it works on js but not on ts import { useCallback, useLayoutEffect, useRef } from 'react'; type callbackType = (...args: any[]) => any; export const useEvent = <TF extends callbackType>(callback: TF): TF => { const functionRef = useRef<TF>(callback); useLayoutEffect(() => { functionRef.current = callback; }); return useCallback((...args) => { const functionCall = functionRef.current; return functionCall(...args); }, []); }; error here: return useCallback((...args) => { TS2345: Argument of type '(...args: any[]) => any' is not assignable to parameter of type 'TF'.'(...args: any[]) => any' is assignable to the constraint of type 'TF', but 'TF' could be instantiated with a different subtype of constraint 'callbackType'. how to solve this problem without resorting to //@ts-ignore?
[ "I can't really explain why, but the issues seems to be with the ...args: any[] from callbackType, which could not be \"respected\".\nSo I modified a bit callbackType to take two generics (one for the parameters and one for the result), and I added the constraint that the input should extend any[] (so it works well with the rest parameters), which seems to fix the issues.\nimport { useCallback, useLayoutEffect, useRef } from \"react\";\n\ntype callbackType<A extends any[], R> = (...args: A) => R;\n\nexport const useEvent = <A extends any[], R>(\n callback: callbackType<A, R>\n): callbackType<A, R> => {\n const functionRef = useRef(callback);\n\n useLayoutEffect(() => {\n functionRef.current = callback;\n });\n\n return useCallback((...args) => {\n const functionCall = functionRef.current;\n return functionCall(...args);\n }, []);\n};\n\nfunction Component() {\n const cb = useEvent((x: number, y: string) => {\n return \"Hello world\";\n });\n\n cb(1, \"test\");\n\n return null;\n}\n\n\n", "import {useRef, useLayoutEffect, useCallback} from 'react';\n\ntype callbackType = (...args: Array<any>) => any;\n\ninterface useEventOverload {\n <TF extends callbackType>(callback: TF): TF;\n <TF extends callbackType>(callback: TF): any;\n}\n\nexport const useEvent: useEventOverload = (callback) => {\n const callbackRef = useRef(callback);\n\n useLayoutEffect(() => {\n callbackRef.current = callback;\n });\n\n return useCallback((...args: any) => {\n return callbackRef.current(...args);\n }, []);\n};\n\n" ]
[ 2, 0 ]
[]
[]
[ "react_hooks", "reactjs", "typescript" ]
stackoverflow_0073101114_react_hooks_reactjs_typescript.txt
Q: How to use vue-toastification I just migrated my project created in vue 3 to nuxt 3. Previously I used the vue-toastification module but now I don't know how to import it correctly. My code using this module. import { useToast, POSITION } from 'vue-toastification' const toast = useToast() export default { methods: { copy(text) { toast.success('Copied!', { timeout: 2000, position: POSITION.BOTTOM_CENTER, }) navigator.clipboard.writeText(text) } } } In Vue I had to do app.use(Toast) but Nuxt does not have an index.js file. Adding modules: ['vue-toastification/nuxt'] in nuxt.config.js does not work because I get an error. A: If you want it to be available globally, you can install it as a Nuxt plugin as explained in the official docs or in this other answer. vue-toastification is probably a client-side only plugin, hence you would probably want to use it as /plugins/vue-toastificaton.client.js like this import { defineNuxtPlugin } from '#app' import Toast from "vue-toastification" import "vue-toastification/dist/index.css" // if needed export default defineNuxtPlugin(nuxtApp => { nuxtApp.vueApp.use(Toast) }) Then, you should be able to use it in your components with either Composition API or Options API (I think).
How to use vue-toastification
I just migrated my project created in vue 3 to nuxt 3. Previously I used the vue-toastification module but now I don't know how to import it correctly. My code using this module. import { useToast, POSITION } from 'vue-toastification' const toast = useToast() export default { methods: { copy(text) { toast.success('Copied!', { timeout: 2000, position: POSITION.BOTTOM_CENTER, }) navigator.clipboard.writeText(text) } } } In Vue I had to do app.use(Toast) but Nuxt does not have an index.js file. Adding modules: ['vue-toastification/nuxt'] in nuxt.config.js does not work because I get an error.
[ "If you want it to be available globally, you can install it as a Nuxt plugin as explained in the official docs or in this other answer.\nvue-toastification is probably a client-side only plugin, hence you would probably want to use it as\n/plugins/vue-toastificaton.client.js like this\nimport { defineNuxtPlugin } from '#app'\nimport Toast from \"vue-toastification\"\nimport \"vue-toastification/dist/index.css\" // if needed\n\nexport default defineNuxtPlugin(nuxtApp => {\n nuxtApp.vueApp.use(Toast)\n})\n\nThen, you should be able to use it in your components with either Composition API or Options API (I think).\n" ]
[ 0 ]
[]
[]
[ "javascript", "nuxt.js", "nuxtjs3" ]
stackoverflow_0074667905_javascript_nuxt.js_nuxtjs3.txt
Q: Query is not executing because it is not printing what is inside of the query I was expecting to have printed awake, asleepREM, asleepDeep, and asleepCore as well as startDate and endDate. When I run the program nothing prints. It seems like my query is not executing. I am not sure what I am doing wrong. Also I am getting an error when I put -7 for my startDate. Why query is not executing please? I don't know swift enough to know what is the problem. Can someone help me please? guard let startDate = Calendar.current.date(byAdding: DateComponents (day: -7), to: Date()) else { fatalError("*** Unable to create the start date ***") } let endDate = Date() if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis){ let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: []) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in if let result = tmpResult { // do something with my data for item in result { if let sample = item as? HKCategorySample { let startDate = sample.startDate let endDate = sample.endDate let awake = (sample.value == HKCategoryValueSleepAnalysis.awake.rawValue) ? "InBed" : "Awake" let asleepREM = (sample.value == HKCategoryValueSleepAnalysis.asleepREM.rawValue) ? "InBed" : "AsleepREM" let asleepDeep = (sample.value == HKCategoryValueSleepAnalysis.asleepDeep.rawValue) ? "InBed" : "AsleepDeep" let asleepCore = (sample.value == HKCategoryValueSleepAnalysis.asleepCore.rawValue) ? "InBed" : "AsleepCore"; print("Healthkit sleep: \(startDate) \(endDate) - value: \(awake), \(asleepREM), \(asleepDeep), \(asleepCore)") print("sleep: \(sample.startDate) \(sample.endDate) - source: \(sample.source.name)") let seconds = (sample.endDate.timeIntervalSince(sample.startDate)) let minutes = (seconds/60) let hours = (minutes/60) print("Hours: \(hours)") } } } healthStore.execute(query) } } A: It looks like there is a problem with the line where you create the startDate variable. The Calendar.current.date(byAdding:to:) method requires a DateComponents object as its first argument, but you are providing an integer (-7). This is causing the method to return nil, which triggers the fatalError() call and terminates the program. To fix this issue, you can create a DateComponents object with the desired number of days and pass it to the date(byAdding:to:) method instead of the integer. For example: let dateComponents = DateComponents(day: -7) guard let startDate = Calendar.current.date(byAdding: dateComponents, to: Date()) else { fatalError("*** Unable to create the start date ***") } This should create a Date object that is 7 days before the current date and assign it to the startDate variable. Additionally, it looks like you are not printing the values of the startDate and endDate variables, or the values of the sleepType object. To print these values, you can add some print() statements after you create the variables, like this: // Print the start and end dates print("Start date:", startDate) print("End date:", endDate) // Print the sleep type print("Sleep type:", sleepType) This should print the values of these variables to the console, which can help you verify that they are being created correctly. I hope this helps! Let me know if you have any other questions.
Query is not executing because it is not printing what is inside of the query
I was expecting to have printed awake, asleepREM, asleepDeep, and asleepCore as well as startDate and endDate. When I run the program nothing prints. It seems like my query is not executing. I am not sure what I am doing wrong. Also I am getting an error when I put -7 for my startDate. Why query is not executing please? I don't know swift enough to know what is the problem. Can someone help me please? guard let startDate = Calendar.current.date(byAdding: DateComponents (day: -7), to: Date()) else { fatalError("*** Unable to create the start date ***") } let endDate = Date() if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis){ let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: []) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in if let result = tmpResult { // do something with my data for item in result { if let sample = item as? HKCategorySample { let startDate = sample.startDate let endDate = sample.endDate let awake = (sample.value == HKCategoryValueSleepAnalysis.awake.rawValue) ? "InBed" : "Awake" let asleepREM = (sample.value == HKCategoryValueSleepAnalysis.asleepREM.rawValue) ? "InBed" : "AsleepREM" let asleepDeep = (sample.value == HKCategoryValueSleepAnalysis.asleepDeep.rawValue) ? "InBed" : "AsleepDeep" let asleepCore = (sample.value == HKCategoryValueSleepAnalysis.asleepCore.rawValue) ? "InBed" : "AsleepCore"; print("Healthkit sleep: \(startDate) \(endDate) - value: \(awake), \(asleepREM), \(asleepDeep), \(asleepCore)") print("sleep: \(sample.startDate) \(sample.endDate) - source: \(sample.source.name)") let seconds = (sample.endDate.timeIntervalSince(sample.startDate)) let minutes = (seconds/60) let hours = (minutes/60) print("Hours: \(hours)") } } } healthStore.execute(query) } }
[ "It looks like there is a problem with the line where you create the startDate variable. The Calendar.current.date(byAdding:to:) method requires a DateComponents object as its first argument, but you are providing an integer (-7). This is causing the method to return nil, which triggers the fatalError() call and terminates the program.\nTo fix this issue, you can create a DateComponents object with the desired number of days and pass it to the date(byAdding:to:) method instead of the integer. For example:\nlet dateComponents = DateComponents(day: -7)\nguard let startDate = Calendar.current.date(byAdding: dateComponents, to: Date()) else {\n fatalError(\"*** Unable to create the start date ***\")\n}\n\n\nThis should create a Date object that is 7 days before the current date and assign it to the startDate variable.\nAdditionally, it looks like you are not printing the values of the startDate and endDate variables, or the values of the sleepType object. To print these values, you can add some print() statements after you create the variables, like this:\n// Print the start and end dates\nprint(\"Start date:\", startDate)\nprint(\"End date:\", endDate)\n\n// Print the sleep type\nprint(\"Sleep type:\", sleepType)\n\n\nThis should print the values of these variables to the console, which can help you verify that they are being created correctly.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 0 ]
[]
[]
[ "swiftui" ]
stackoverflow_0074679404_swiftui.txt
Q: Error: Get config: Unable to establish a connection to query-engine-node-api library in Prisma and nextjs I use nextjs fresh project with Prisma and supabase database. I'm using ubuntu. No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 22.04 LTS Release: 22.04 Codename: jammy when I run Prisma push and generate command in my project. I face the same error with npm and yarn. I run all Prisma command. I start with a fresh supabase database. prisma migrate dev Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Error: Get config: Unable to establish a connection to query-engine-node-api library Prisma CLI Version : 3.15.2 npx prisma db push Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Error: Get config: Unable to establish a connection to query-engine-node-api library Prisma CLI Version : 3.15.2 prisma/schema.prisma file // This is your Prisma schema file, // learn more about it in the docs: https://pris.ly/d/prisma-schema generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url = env("DATABASE_URL") } model User { id Int @id @default(autoincrement()) email String @unique name String? } After I added the environment variable. DATABASE_URL="postgresql://postgres:EeVVG-password-wDiII@db.qpzh-url-opda.supabase.co:5432/postgres" I do not find why I'm facing errors with Prisma and supabase. I'm deleting the `node_modules` folder and creating one more project. but the problem is not solved. A: I had the same issue. Check if you're in a sandbox terminal. In my case, my anaconda environment was on and so, I couldn't initiate the migration. Open a fresh terminal without any environments or sandboxes. Also, Looking into other solutions, I found out that if your nodejs installation is done using snap, then also this error occurs. Try reinstalling nodejs using apt. A: I have faced the same error. Downgrading node from 18 to 16 solves this problem for me. I did't find better solution for this problem. Reference: prisma github comment. I don't recommend to downgrade though. But prisma works normally on node 16 lts.
Error: Get config: Unable to establish a connection to query-engine-node-api library in Prisma and nextjs
I use nextjs fresh project with Prisma and supabase database. I'm using ubuntu. No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 22.04 LTS Release: 22.04 Codename: jammy when I run Prisma push and generate command in my project. I face the same error with npm and yarn. I run all Prisma command. I start with a fresh supabase database. prisma migrate dev Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Error: Get config: Unable to establish a connection to query-engine-node-api library Prisma CLI Version : 3.15.2 npx prisma db push Environment variables loaded from .env Prisma schema loaded from prisma/schema.prisma Error: Get config: Unable to establish a connection to query-engine-node-api library Prisma CLI Version : 3.15.2 prisma/schema.prisma file // This is your Prisma schema file, // learn more about it in the docs: https://pris.ly/d/prisma-schema generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url = env("DATABASE_URL") } model User { id Int @id @default(autoincrement()) email String @unique name String? } After I added the environment variable. DATABASE_URL="postgresql://postgres:EeVVG-password-wDiII@db.qpzh-url-opda.supabase.co:5432/postgres" I do not find why I'm facing errors with Prisma and supabase. I'm deleting the `node_modules` folder and creating one more project. but the problem is not solved.
[ "I had the same issue. Check if you're in a sandbox terminal. In my case, my anaconda environment was on and so, I couldn't initiate the migration. Open a fresh terminal without any environments or sandboxes. Also, Looking into other solutions, I found out that if your nodejs installation is done using snap, then also this error occurs. Try reinstalling nodejs using apt.\n", "I have faced the same error.\nDowngrading node from 18 to 16 solves this problem for me. I did't find better solution for this problem. Reference: prisma github comment. I don't recommend to downgrade though.\nBut prisma works normally on node 16 lts.\n" ]
[ 1, 0 ]
[]
[]
[ "next.js", "postgresql", "prisma", "supabase", "supabase_database" ]
stackoverflow_0072774615_next.js_postgresql_prisma_supabase_supabase_database.txt
Q: How do I create a function that reverses an array in JavaScript? I tried with the following code but when I run it the function is not shown reversed although the number I chose is even: const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const number = 32; const myReversedArray = number => { if (number % 2 === 0) { return myArray.reverse(); } else { return myArray; } } console.log(myReversedArray()); I expected the function to be shown in reverse since the number I chose is even, but instead it is shown in the normal order (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). A: There are a few issues with the code. First, the number parameter in the myReversedArray function is not being used. It should be used to determine whether to reverse the array or not. Second, the myReversedArray function is not being called with any arguments, so the number parameter is not being set to anything. This can be fixed by passing the number variable as an argument when calling the function. Third, the myReversedArray function does not return anything if the number is not even, so it will always return undefined in that case. This can be fixed by adding a return statement that returns the original array if number is not even. const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const number = 32; const myReversedArray = number => { if (number % 2 === 0) { return myArray.reverse(); } else { return myArray; // Return the original array if number is not even } } console.log(myReversedArray(number)); // Pass the number variable as an argument
How do I create a function that reverses an array in JavaScript?
I tried with the following code but when I run it the function is not shown reversed although the number I chose is even: const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const number = 32; const myReversedArray = number => { if (number % 2 === 0) { return myArray.reverse(); } else { return myArray; } } console.log(myReversedArray()); I expected the function to be shown in reverse since the number I chose is even, but instead it is shown in the normal order (1, 2, 3, 4, 5, 6, 7, 8, 9, 10).
[ "There are a few issues with the code.\nFirst, the number parameter in the myReversedArray function is not being used. It should be used to determine whether to reverse the array or not.\nSecond, the myReversedArray function is not being called with any arguments, so the number parameter is not being set to anything. This can be fixed by passing the number variable as an argument when calling the function.\nThird, the myReversedArray function does not return anything if the number is not even, so it will always return undefined in that case. This can be fixed by adding a return statement that returns the original array if number is not even.\n\n\nconst myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nconst number = 32;\n\nconst myReversedArray = number => {\n if (number % 2 === 0) {\n return myArray.reverse();\n } else {\n return myArray; // Return the original array if number is not even\n }\n}\n\nconsole.log(myReversedArray(number)); // Pass the number variable as an argument\n\n\n\n" ]
[ 0 ]
[ "This should work:\nconst myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nconst number = 32;\n\nconst myReversedArray = (number) => {\n if (number % 2 === 0) {\n return myArray.reverse();\n } else {\n return myArray;\n }\n}\n\nconsole.log(myReversedArray(number)); // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n\n" ]
[ -1 ]
[ "function", "javascript" ]
stackoverflow_0074679365_function_javascript.txt
Q: How to click Recyclerview position with specific View Visible- Espresso I am writing UI Test for my App using Espresso. The screen shows a Recyclerview with list of shops that have status OPEN or CLOSED. Depending upon the data the openTextView or closedTextview is shown and are hidden by default. Below is my test case scenario: Check if screen is visible Check if Recyclerview is visible Check if Recyclerview has atleast one shop with OPEN status Click on first found OPEN shop Check if details screen shows up ISSUE: I tried to click the first OPEN status item but it is throwing Exception. Below is the code @Test fun openShopTest() { onView(withText(“Shops")).check(matches(isDisplayed())) onView(withId(R.id.rvShops)).check(matches(isDisplayed())) //There is at least one open shop visible onView(withId(R.id.rvShops)) .perform(RecyclerViewActions.scrollToHolder(first(withOpenText()))) //User clicks on open shop onView(allOf(withId(R.id.rvShops), isDisplayed())) .perform(actionOnItem<ListAdapter.ListViewHolder>(withChild(withText(“Open”)), click())) //Screen with details appear onView(withText("Details”)).check(matches(isDisplayed())) } fun withOpenText(): Matcher<RecyclerView.ViewHolder> { return object : BoundedMatcher<RecyclerView.ViewHolder, ListAdapter.ListViewHolder>( ListAdapter.ListViewHolder::class.java ) { override fun describeTo(description: Description) { description.appendText("No ViewHolder found with Open Status Visible") } override fun matchesSafely(item: ListAdapter.ListViewHolder): Boolean { val openTextView = item.itemView.findViewById(R.id.openTextView) as TextView return openTextView.isVisible } } } Below is the exception: androidx.test.espresso.PerformException: Error performing 'performing ViewAction: single click on item matching: holder with view: has child: with text: is "Open"' on view '(with id: mypackagename:id/rvShops and is displayed on the screen to the user)'. at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82) at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:79) at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:51) at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:312) at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:173) at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:114) at mypackagename.MyUITest.openShopTest(MyUITest.kt:77) ... 32 trimmed Caused by: androidx.test.espresso.PerformException: Error performing 'scroll RecyclerView to: holder with view: has child: with text: is "Open"' on view 'RecyclerView{id=2131231032, res-name=rvShops, visibility=VISIBLE, width=1080, height=2047, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@295fec9, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=12}'. at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82) at androidx.test.espresso.contrib.RecyclerViewActions$ScrollToViewAction.perform(RecyclerViewActions.java:381) at androidx.test.espresso.contrib.RecyclerViewActions$ActionOnItemViewAction.perform(RecyclerViewActions.java:221) at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:356) at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:248) at androidx.test.espresso.ViewInteraction.access$100(ViewInteraction.java:63) at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:153) at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:150) at java.util.concurrent.FutureTask.run(FutureTask.java:264) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8751) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.RuntimeException: Found 0 items matching holder with view: has child: with text: is "Open", but position -1 was requested. at androidx.test.espresso.contrib.RecyclerViewActions$ScrollToViewAction.perform(RecyclerViewActions.java:361) What i have tried? I had an idea that maybe openTextView or closedTextview are not always visible so that might be causing the problem. I tried by making both always visible as well. I followed the steps mentioned in answers of this question but the same excpetion shows up. What is required? Click on Recyclerview row where openTextView is visible Get position of row where openTextView is visible; so that i can use atPosition function and click the row. Can somebody please help me out with this? Any help will be appreciated. Thanks A: The idea is to custom the View action of Espresso. object MyViewAction { fun clickChildViewWithIdAndText(id: Int, text: String): ViewAction { return object: ViewAction { override fun getConstraints(): Matcher<View> { return withText(text) } override fun getDescription(): String { return "Click on a child view with specified id and text" } override fun perform(uiController: UiController?, view: View) { val v: View = view.findViewById(id) v.performClick() } } } } onView(withId(R.id.rv_home)).perform( RecyclerViewActions.actionOnItemAtPosition<ListAdapter.ListViewHolder>( 0, MyViewAction.clickChildViewWithIdAndText(R.id.tv_id, "OPEN") ) ); By the way, you can use some powerful testing libraries which are built on top of Espresso such as Barista or Kakao. It helps your testing code to be much more readable and elegant. For example, you can assert the item displayed at position x with text y in the list view with just one line of code import com.adevinta.android.barista.assertion.BaristaListAssertions.assertDisplayedAtPosition assertDisplayedAtPosition(R.id.rv_list, x, R.id.tv_id, y) A: It looks like the issue is with the withOpenText() method that you are using to find the viewholder with the "Open" text. This method is returning a Matcher object that matches a RecyclerView.ViewHolder that has a child TextView with the text "Open" and is visible. However, in your test case, you are using the withChild() matcher to find a RecyclerView.ViewHolder that has a child with the text "Open" and then trying to perform a click action on that viewholder. In order for this to work, you will need to modify the withOpenText() method to return a ViewAction that can be performed on the matched viewholder, instead of a Matcher object. You can do this by using the ViewActions.click() method to create a ViewAction that will click on the matched viewholder. Here is an example of how you can modify the withOpenText() method to return a ViewAction instead of a Matcher: fun withOpenText(): ViewAction { return object : ViewAction { override fun getConstraints(): Matcher<View> { return allOf( isDescendantOfA(withId(R.id.rvShops)), withChild(withText("Open")) ) } override fun getDescription(): String { return "Click on ViewHolder with Open Status Visible" } override fun perform(uiController: UiController, view: View) { val openTextView = view.findViewById(R.id.openTextView) as TextView if (openTextView.isVisible) { ViewActions.click().perform(uiController, view) } } } } Then, you can use the withOpenText() method in your test case like this: @Test fun openShopTest() { onView(withText(“Shops")).check(matches(isDisplayed())) onView(withId(R.id.rvShops)).check(matches(isDisplayed())) //There is at least one open shop visible onView(withId(R.id.rvShops)) .perform(RecyclerViewActions.scrollToHolder(first(withOpenText()))) //Screen with details appear onView(withText("Details”)).check(matches(isDisplayed())) } This should fix the issue and allow you to click on the first open shop in the recyclerview.
How to click Recyclerview position with specific View Visible- Espresso
I am writing UI Test for my App using Espresso. The screen shows a Recyclerview with list of shops that have status OPEN or CLOSED. Depending upon the data the openTextView or closedTextview is shown and are hidden by default. Below is my test case scenario: Check if screen is visible Check if Recyclerview is visible Check if Recyclerview has atleast one shop with OPEN status Click on first found OPEN shop Check if details screen shows up ISSUE: I tried to click the first OPEN status item but it is throwing Exception. Below is the code @Test fun openShopTest() { onView(withText(“Shops")).check(matches(isDisplayed())) onView(withId(R.id.rvShops)).check(matches(isDisplayed())) //There is at least one open shop visible onView(withId(R.id.rvShops)) .perform(RecyclerViewActions.scrollToHolder(first(withOpenText()))) //User clicks on open shop onView(allOf(withId(R.id.rvShops), isDisplayed())) .perform(actionOnItem<ListAdapter.ListViewHolder>(withChild(withText(“Open”)), click())) //Screen with details appear onView(withText("Details”)).check(matches(isDisplayed())) } fun withOpenText(): Matcher<RecyclerView.ViewHolder> { return object : BoundedMatcher<RecyclerView.ViewHolder, ListAdapter.ListViewHolder>( ListAdapter.ListViewHolder::class.java ) { override fun describeTo(description: Description) { description.appendText("No ViewHolder found with Open Status Visible") } override fun matchesSafely(item: ListAdapter.ListViewHolder): Boolean { val openTextView = item.itemView.findViewById(R.id.openTextView) as TextView return openTextView.isVisible } } } Below is the exception: androidx.test.espresso.PerformException: Error performing 'performing ViewAction: single click on item matching: holder with view: has child: with text: is "Open"' on view '(with id: mypackagename:id/rvShops and is displayed on the screen to the user)'. at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82) at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:79) at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:51) at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:312) at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:173) at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:114) at mypackagename.MyUITest.openShopTest(MyUITest.kt:77) ... 32 trimmed Caused by: androidx.test.espresso.PerformException: Error performing 'scroll RecyclerView to: holder with view: has child: with text: is "Open"' on view 'RecyclerView{id=2131231032, res-name=rvShops, visibility=VISIBLE, width=1080, height=2047, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@295fec9, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=12}'. at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82) at androidx.test.espresso.contrib.RecyclerViewActions$ScrollToViewAction.perform(RecyclerViewActions.java:381) at androidx.test.espresso.contrib.RecyclerViewActions$ActionOnItemViewAction.perform(RecyclerViewActions.java:221) at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:356) at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:248) at androidx.test.espresso.ViewInteraction.access$100(ViewInteraction.java:63) at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:153) at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:150) at java.util.concurrent.FutureTask.run(FutureTask.java:264) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8751) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.RuntimeException: Found 0 items matching holder with view: has child: with text: is "Open", but position -1 was requested. at androidx.test.espresso.contrib.RecyclerViewActions$ScrollToViewAction.perform(RecyclerViewActions.java:361) What i have tried? I had an idea that maybe openTextView or closedTextview are not always visible so that might be causing the problem. I tried by making both always visible as well. I followed the steps mentioned in answers of this question but the same excpetion shows up. What is required? Click on Recyclerview row where openTextView is visible Get position of row where openTextView is visible; so that i can use atPosition function and click the row. Can somebody please help me out with this? Any help will be appreciated. Thanks
[ "The idea is to custom the View action of Espresso.\nobject MyViewAction {\n fun clickChildViewWithIdAndText(id: Int, text: String): ViewAction {\n return object: ViewAction {\n override fun getConstraints(): Matcher<View> {\n return withText(text)\n }\n\n override fun getDescription(): String {\n return \"Click on a child view with specified id and text\"\n }\n\n override fun perform(uiController: UiController?, view: View) {\n val v: View = view.findViewById(id)\n v.performClick()\n }\n }\n }\n}\n\nonView(withId(R.id.rv_home)).perform(\n RecyclerViewActions.actionOnItemAtPosition<ListAdapter.ListViewHolder>(\n 0,\n MyViewAction.clickChildViewWithIdAndText(R.id.tv_id, \"OPEN\")\n )\n);\n\nBy the way, you can use some powerful testing libraries which are built on top of Espresso such as Barista or Kakao. It helps your testing code to be much more readable and elegant.\nFor example, you can assert the item displayed at position x with text y in the list view with just one line of code\nimport com.adevinta.android.barista.assertion.BaristaListAssertions.assertDisplayedAtPosition\n\nassertDisplayedAtPosition(R.id.rv_list, x, R.id.tv_id, y)\n\n", "It looks like the issue is with the withOpenText() method that you are using to find the viewholder with the \"Open\" text. This method is returning a Matcher object that matches a RecyclerView.ViewHolder that has a child TextView with the text \"Open\" and is visible. However, in your test case, you are using the withChild() matcher to find a RecyclerView.ViewHolder that has a child with the text \"Open\" and then trying to perform a click action on that viewholder.\nIn order for this to work, you will need to modify the withOpenText() method to return a ViewAction that can be performed on the matched viewholder, instead of a Matcher object. You can do this by using the ViewActions.click() method to create a ViewAction that will click on the matched viewholder.\nHere is an example of how you can modify the withOpenText() method to return a ViewAction instead of a Matcher:\nfun withOpenText(): ViewAction {\n return object :\n ViewAction {\n\n override fun getConstraints(): Matcher<View> {\n return allOf(\n isDescendantOfA(withId(R.id.rvShops)),\n withChild(withText(\"Open\"))\n )\n }\n\n override fun getDescription(): String {\n return \"Click on ViewHolder with Open Status Visible\"\n }\n\n override fun perform(uiController: UiController, view: View) {\n val openTextView = view.findViewById(R.id.openTextView) as TextView\n if (openTextView.isVisible) {\n ViewActions.click().perform(uiController, view)\n }\n }\n}\n}\n\nThen, you can use the withOpenText() method in your test case like this:\n@Test\nfun openShopTest() {\n\n onView(withText(“Shops\")).check(matches(isDisplayed()))\n\n onView(withId(R.id.rvShops)).check(matches(isDisplayed()))\n\n //There is at least one open shop visible\n\n onView(withId(R.id.rvShops))\n .perform(RecyclerViewActions.scrollToHolder(first(withOpenText())))\n\n //Screen with details appear\n\n onView(withText(\"Details”)).check(matches(isDisplayed()))\n}\n\nThis should fix the issue and allow you to click on the first open shop in the recyclerview.\n" ]
[ 0, 0 ]
[]
[]
[ "android", "android_espresso", "android_recyclerview", "android_testing", "gui_testing" ]
stackoverflow_0074552594_android_android_espresso_android_recyclerview_android_testing_gui_testing.txt
Q: Github remote permission denied I'm trying to upload my repo on github and go through all the steps upto: git push -u origin master at that point it gives me the following error: remote: Permission to samrao2/manager-4.git denied to samrao1. fatal: unable to access 'https://github.com/samrao2/manager-4.git/': The requested URL returned error: 403 I think the issue is that i was logged into another Git account before "samrao1" and now i am trying to push to "samrao2". Can someone help me reset this to where i can successfully push to "samrao2". I am assuming i will be prompted for my password the first time i try to do it. A: Unable to access https means: this has nothing to do with SSH (and switching to SSH, while possible, does not explain the original issue) This has to do with credential caching, meaning Git will be default provide the credentials (GitHub account and password PAT Personal Access Token) of the old account while you are trying to push to the new account. Reminder, most Git repository hosting service uses token as password, not your actual user account password. For instance, GitHub no longer accept password since Aug. 2021. See if you have a credential helper that would have cached your (old account) credentials (username/password) used to authentication you. git config credential.helper On Mac, as commented by Arpit J, just goto/open your keychain access->search for github.com related file->and edit credentials there. See "Updating credentials from the OSX Keychain" On Windows (And, in 2021, possibly Linux or even Mac), that would be the Windows Credential Managers GCMC: Git Credential Manager. Open the Windows Credential Store, and see if the first user is registered there: delete that entry, and you will be able to authenticate with the second user. (Here is an example for BitBucket) In command-line (see git credential), for a manager core credential helper: Get the old password or token: printf "protocol=https\nhost=github.com\nusername=<me>" | \ git credential-manager-core get # output: protocol=https host=github.com username=<me> password=<old_password_or_token> Remove the old password: printf "protocol=https\nhost=github.com\nusername=<me>" | \ git credential-manager-core erase (Replace <me> by your GitHub user account name) A: Resolved this error by updating my username and credentials: git config user.name "new name" git config credential.username "new name" A: I'm not sure what the issue is, but since you mentioned not knowing what having the "right keys installed" means, I'm going to assume you have not set up your computer to authenticate to your Github repository via SSH. This guide should show you how to do that: Adding a new SSH key to your Github account Also, I would suggesting using 'git://github.com/samrao2/manager-4.git/' for your remote URL rather than 'https://github.com/samrao2/manager-4.git/'. The latter requires you to enter a password each time, whereas the former will authenticate via SSH, which is far less irritating. You can change the remote URL in your repository to use the git protocol, instead of https, by typing: git remote set-url origin git://github.com/samrao2/manager-4.git from within your project directory. A: If you are using MacOS, you can go to KeyChain Access, Search for "GitHub", then when then result "github.com" pops up, change the account or password to your new account, and save. Then you are all set! A: Here 403 (error) means credentials errors or that you don’t have permission to push. Solution For Windows click on window button > credential manager > Windows credentials > Generic credentials Next, remove or edit the Github keys. For Mac 1-In Finder, search for the Keychain Access app. 2In Keychain Access, search for github.com. 3-Find the "internet password" entry for github.com. 4-Edit or delete the entry accordingly. A: Appreciating VonC's answer. To simplify and add into it, one can follow below simple steps: Remove all GitHub entries from (Windows) Credential Manager Set useHttpPath = true in Git global configuration git config --global credential.useHttpPath true You can validate this by checking git config --global -e This will create a different entry for each user account. A: I had a similar issue and what found out its two things you need to verify: The key chain issue that has adequately been discussed above; Git recently stopped using passwords, you need to instead generate a personal access token. NOTE THIS IS IMPORTANT and the source of the problem I had, on the creation of token ensure permission are granted to the token on Github under developer option. A: Multiple users generate their own ssh key, Generating a new SSH key and adding it to the ssh-agent Adding a new SSH key to your GitHub account Alice Repository, git bash: git config user.name "Alice" git config user.email "alice@email.com" eval $(ssh-agent -s), ssh-add ~/.ssh/alice.private ssh -T git@github.com, Testing your SSH connection Git other operations Bob Repository, git bash: git config user.name "Bob" git config user.email "bob@email.com" eval $(ssh-agent -s), ssh-add ~/.ssh/bob.private ssh -T git@github.com, Testing your SSH connection Git other operations A: I was facing the same issue I have resolved using below command git config --global credential.useHttpPath true A: The problem is you are trying to push into new github account using old github account's ssh key, so generate a new SSH key for the new github account using this link https://help.github.com/en/github/authenticating-to-github/error-permission-to-userrepo-denied-to-userother-repo and then add it your github account. After this try to push, it works A: I have one personal account and one business account at Github. I commit and push changes to both accounts at the same time. What I did was 1) to run personal and business projects at separate sessions; 2) to set the URL for one account with an SSH link, and leave the URL as normal (HTTPS) for another account. A: You can solve this issue by revoking the access of 2nd account "samrao1" from that specific repo that you have previously connected. A: just go to Control Panel\User Accounts\Credential Manager\Edit Generic Credential and update your git Credential A: if you are still having problems with the same, uninstall git and re-install again. That worked for me . thanks A: Check your personal access token. Edit the scopes in your token. I checked all the access options in the token. Doing this, the error did not come. https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token A: ONLY IF you've used git cli BEFORE on your machine Then simply open the credential manager on your system by pressing start button and type "Credential Manager" and switch to the "Windows Credentials" tab. Delete the existing saved account associated with https://github.com like following: Now try pushing code again, this time an authentication prompt will be popped up, authenticate your github account and congratulations, your code is hosted onto the given branch of desired repository. A: I faced same problem and then removed the git credential from windows credential manager A: Important: Remember to set your token permissions correctly. I had the same problem until I changed the permissions to allow full repo access: A: If you're using git credentials helper open the ~/.git-credentials file and change your token if it is expired, check also your GitHub username if it's correct!
Github remote permission denied
I'm trying to upload my repo on github and go through all the steps upto: git push -u origin master at that point it gives me the following error: remote: Permission to samrao2/manager-4.git denied to samrao1. fatal: unable to access 'https://github.com/samrao2/manager-4.git/': The requested URL returned error: 403 I think the issue is that i was logged into another Git account before "samrao1" and now i am trying to push to "samrao2". Can someone help me reset this to where i can successfully push to "samrao2". I am assuming i will be prompted for my password the first time i try to do it.
[ "Unable to access https means: this has nothing to do with SSH (and switching to SSH, while possible, does not explain the original issue)\nThis has to do with credential caching, meaning Git will be default provide the credentials (GitHub account and password PAT Personal Access Token) of the old account while you are trying to push to the new account.\n\nReminder, most Git repository hosting service uses token as password, not your actual user account password.\nFor instance, GitHub no longer accept password since Aug. 2021.\n\nSee if you have a credential helper that would have cached your (old account) credentials (username/password) used to authentication you.\ngit config credential.helper \n\nOn Mac, as commented by Arpit J, just goto/open your keychain access->search for github.com related file->and edit credentials there.\n\nSee \"Updating credentials from the OSX Keychain\"\nOn Windows (And, in 2021, possibly Linux or even Mac), that would be the Windows Credential Managers GCMC: Git Credential Manager.\nOpen the Windows Credential Store, and see if the first user is registered there: delete that entry, and you will be able to authenticate with the second user.\n(Here is an example for BitBucket)\n\n\nIn command-line (see git credential), for a manager core credential helper:\n\nGet the old password or token:\nprintf \"protocol=https\\nhost=github.com\\nusername=<me>\" | \\\n git credential-manager-core get\n\n# output:\nprotocol=https\nhost=github.com\nusername=<me>\npassword=<old_password_or_token>\n\n\nRemove the old password:\nprintf \"protocol=https\\nhost=github.com\\nusername=<me>\" | \\\n git credential-manager-core erase\n\n\n\n(Replace <me> by your GitHub user account name)\n", "Resolved this error by updating my username and credentials:\ngit config user.name \"new name\"\ngit config credential.username \"new name\"\n\n", "I'm not sure what the issue is, but since you mentioned not knowing what having the \"right keys installed\" means, I'm going to assume you have not set up your computer to authenticate to your Github repository via SSH.\nThis guide should show you how to do that: Adding a new SSH key to your Github account\nAlso, I would suggesting using 'git://github.com/samrao2/manager-4.git/' for your remote URL rather than 'https://github.com/samrao2/manager-4.git/'. The latter requires you to enter a password each time, whereas the former will authenticate via SSH, which is far less irritating. You can change the remote URL in your repository to use the git protocol, instead of https, by typing:\ngit remote set-url origin git://github.com/samrao2/manager-4.git\n\nfrom within your project directory.\n", "If you are using MacOS, you can\n\ngo to KeyChain Access, \nSearch for \"GitHub\", \nthen when then result \"github.com\" pops up, change the account or password to your new account, and save.\n\nThen you are all set!\n", "Here 403 (error) means credentials errors or that you don’t have permission to push.\nSolution\nFor Windows\nclick on window button > credential manager > Windows credentials > Generic credentials\nNext, remove or edit the Github keys.\nFor Mac \n1-In Finder, search for the Keychain Access app.\n2In Keychain Access, search for github.com.\n3-Find the \"internet password\" entry for github.com.\n4-Edit or delete the entry accordingly.\n", "Appreciating VonC's answer.\nTo simplify and add into it, one can follow below simple steps:\n\nRemove all GitHub entries from (Windows) Credential Manager\nSet useHttpPath = true in Git global configuration\n\n\ngit config --global credential.useHttpPath true\n\nYou can validate this by checking\n\ngit config --global -e\n\nThis will create a different entry for each user account.\n", "I had a similar issue and what found out its two things you need to verify:\n\nThe key chain issue that has adequately been discussed above;\nGit recently stopped using passwords, you need to instead generate a personal access token. NOTE THIS IS IMPORTANT and the source of the problem I had, on the creation of token ensure permission are granted to the token on Github under developer option.\n\n\n", "\nMultiple users generate their own ssh key, Generating a new SSH key and adding it to the ssh-agent\nAdding a new SSH key to your GitHub account\nAlice Repository, git bash:\n\ngit config user.name \"Alice\"\ngit config user.email \"alice@email.com\"\neval $(ssh-agent -s), \nssh-add ~/.ssh/alice.private\nssh -T git@github.com, Testing your SSH connection\nGit other operations\n\nBob Repository, git bash:\n\ngit config user.name \"Bob\"\ngit config user.email \"bob@email.com\"\neval $(ssh-agent -s), \nssh-add ~/.ssh/bob.private\nssh -T git@github.com, Testing your SSH connection\nGit other operations\n\n\n", "I was facing the same issue I have resolved using below command\ngit config --global credential.useHttpPath true\n", "The problem is you are trying to push into new github account using old github account's ssh key, so generate a new SSH key for the new github account using this link https://help.github.com/en/github/authenticating-to-github/error-permission-to-userrepo-denied-to-userother-repo and then add it your github account. After this try to push, it works \n", "I have one personal account and one business account at Github. I commit and push changes to both accounts at the same time.\nWhat I did was 1) to run personal and business projects at separate sessions; 2) to set the URL for one account with an SSH link, and leave the URL as normal (HTTPS) for another account.\n", "You can solve this issue by revoking the access of 2nd account \"samrao1\" from that specific repo that you have previously connected.\n", "just go to Control Panel\\User Accounts\\Credential Manager\\Edit Generic Credential\n\nand update your git Credential\n", "if you are still having problems with the same, uninstall git and re-install again. That worked for me . thanks\n", "Check your personal access token. Edit the scopes in your token. I checked all the access options in the token. Doing this, the error did not come.\nhttps://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token\n", "ONLY IF you've used git cli BEFORE on your machine\nThen simply open the credential manager on your system by pressing start button and type \"Credential Manager\" and switch to the \"Windows Credentials\" tab.\nDelete the existing saved account associated with https://github.com like following:\nNow try pushing code again, this time an authentication prompt will be popped up, authenticate your github account and congratulations, your code is hosted onto the given branch of desired repository.\n", "I faced same problem and then removed the git credential from windows credential manager\n", "Important: Remember to set your token permissions correctly.\nI had the same problem until I changed the permissions to allow full repo access:\n\n", "If you're using git credentials helper\nopen the ~/.git-credentials file and change your token if it is expired,\ncheck also your GitHub username if it's correct!\n" ]
[ 170, 21, 8, 8, 8, 8, 6, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "Removing the .git folder from the project directory, and then again pushing them from the beginning worked for me.\n" ]
[ -5 ]
[ "git", "github" ]
stackoverflow_0047465644_git_github.txt
Q: Loop a Map Type after call an async method i have this method inside a class Map<String, String> value = {}; bool isReady = false; void getData() async { try { Map<String, String> data = await CustomerData().getService(selectedService); isReady = true; setState(() { value = data; }); } catch (e) { print(e); } } i'd like to loop the results inside a widget so: @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Customer'), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ value.forEach((key, value) { Text('$key: $value'), }) ], ), ); } the only solution that i found is this but i don't like it @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Customer'), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text(isReady ? 'Service: value["deliver"]' : '?'), Text(isReady ? 'Status: value["status"]' : '?'), Text(isReady ? 'Note: value["note"]' : '?'), ], ), ); } is possible loop a Map type that comes from a method async inside a Widget? A: To loop through a Map in a Widget, you can use a ListView.builder widget. The ListView.builder widget allows you to build a list of items on-demand. This is useful when the number of items in your list is not known beforehand, or when your list is very large. To use the ListView.builder widget, you need to provide a builder function that returns a Widget for each item in the Map. Inside the builder function, you can access the key and value of each item in the Map using the index parameter. Here's an example of how you can use the ListView.builder widget to loop through a Map: @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Customer'), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ // Use a ListView.builder widget to loop through the Map ListView.builder( // The number of items in the list is the number of items in the Map itemCount: value.length, // The builder function returns a widget for each item in the Map itemBuilder: (context, index) { // Access the key and value of each item in the Map using the index var key = value.keys.elementAt(index); var val = value.values.elementAt(index); // Return a Text widget with the key and value of the Map item return Text('$key: $val'); }, ), ], ), ); } Note that you need to make sure that the Map is initialized before you try to access its items in the build method. You can do this by using the isReady variable that you defined in your code. You can check if the Map is ready by checking if the isReady variable is true. If the Map is not ready, you A: Use FutureBuilder to get future and then Listview.builder in the same way @haris told you. A: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: value.entries.map((e) => Text('${e.key}: ${e.value}')).toList(), ),
Loop a Map Type after call an async method
i have this method inside a class Map<String, String> value = {}; bool isReady = false; void getData() async { try { Map<String, String> data = await CustomerData().getService(selectedService); isReady = true; setState(() { value = data; }); } catch (e) { print(e); } } i'd like to loop the results inside a widget so: @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Customer'), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ value.forEach((key, value) { Text('$key: $value'), }) ], ), ); } the only solution that i found is this but i don't like it @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Customer'), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text(isReady ? 'Service: value["deliver"]' : '?'), Text(isReady ? 'Status: value["status"]' : '?'), Text(isReady ? 'Note: value["note"]' : '?'), ], ), ); } is possible loop a Map type that comes from a method async inside a Widget?
[ "To loop through a Map in a Widget, you can use a ListView.builder widget. The ListView.builder widget allows you to build a list of items on-demand. This is useful when the number of items in your list is not known beforehand, or when your list is very large.\nTo use the ListView.builder widget, you need to provide a builder function that returns a Widget for each item in the Map. Inside the builder function, you can access the key and value of each item in the Map using the index parameter. Here's an example of how you can use the ListView.builder widget to loop through a Map:\n@override\nWidget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text('Customer'),\n ),\n body: Column(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n crossAxisAlignment: CrossAxisAlignment.stretch,\n children: <Widget>[\n // Use a ListView.builder widget to loop through the Map\n ListView.builder(\n // The number of items in the list is the number of items in the Map\n itemCount: value.length,\n // The builder function returns a widget for each item in the Map\n itemBuilder: (context, index) {\n // Access the key and value of each item in the Map using the index\n var key = value.keys.elementAt(index);\n var val = value.values.elementAt(index);\n // Return a Text widget with the key and value of the Map item\n return Text('$key: $val');\n },\n ),\n ],\n ),\n );\n}\n\nNote that you need to make sure that the Map is initialized before you try to access its items in the build method. You can do this by using the isReady variable that you defined in your code. You can check if the Map is ready by checking if the isReady variable is true. If the Map is not ready, you\n", "Use FutureBuilder to get future and then Listview.builder in the same way @haris told you.\n", "Column(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n crossAxisAlignment: CrossAxisAlignment.stretch,\n children: value.entries.map((e) => Text('${e.key}: ${e.value}')).toList(),\n),\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "async_await", "asynchronous", "dart", "flutter", "widget" ]
stackoverflow_0074679290_async_await_asynchronous_dart_flutter_widget.txt
Q: How to flutter sdk upgrade in specific version I want to upgrade flutter specific version. How to do , i don't want to upgrade latest sdk version. I want tp upgrade specific sdk version A: There is an issue about your question on Github. I think it is not possible yet.
How to flutter sdk upgrade in specific version
I want to upgrade flutter specific version. How to do , i don't want to upgrade latest sdk version. I want tp upgrade specific sdk version
[ "There is an issue about your question on Github. I think it is not possible yet.\n" ]
[ 0 ]
[]
[]
[ "dart", "flutter" ]
stackoverflow_0074679285_dart_flutter.txt
Q: Array is not changed after filter on javascript I'm trying yo filter the numeric values of an array with this code: function getNumerics(toFilter) { toFilter = toFilter.filter( element => !isNaN(element)); console.log(toFilter); } var toFilter = [1, 'z', '4', 2, 6]; getNumerics(toFilter); console.log(toFilter); The console.log inside the function shows a correct result but but the last console.log show the array with all the values but if I pass the array to the function why is not change? in javascript all parameters are passed are reference , aren't it? A: Your function should return the filtered Array: function getNumerics(toFilter) { return toFilter.filter( element => !isNaN(element)); } var toFilter = [1, 'z', '4', 2, 6]; toFilter = getNumerics(toFilter); console.log(toFilter);
Array is not changed after filter on javascript
I'm trying yo filter the numeric values of an array with this code: function getNumerics(toFilter) { toFilter = toFilter.filter( element => !isNaN(element)); console.log(toFilter); } var toFilter = [1, 'z', '4', 2, 6]; getNumerics(toFilter); console.log(toFilter); The console.log inside the function shows a correct result but but the last console.log show the array with all the values but if I pass the array to the function why is not change? in javascript all parameters are passed are reference , aren't it?
[ "Your function should return the filtered Array:\n\n\nfunction getNumerics(toFilter) {\n return toFilter.filter( element => !isNaN(element));\n}\n \nvar toFilter = [1, 'z', '4', 2, 6];\ntoFilter = getNumerics(toFilter);\nconsole.log(toFilter);\n\n\n\n" ]
[ 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074679435_javascript.txt
Q: RabbitMQ same message to each consumer I have implemented the example from the RabbitMQ website: RabbitMQ Example I have expanded it to have an application with a button to send a message. Now I started two consumer on two different computers. When I send the message the first message is sent to computer1, then the second message is sent to computer2, the thrid to computer1 and so on. Why is this, and how can I change the behavior to send each message to each consumer? A: Why is this As noted by Yazan, messages are consumed from a single queue in a round-robin manner. The behavior your are seeing is by design, making it easy to scale up the number of consumers for a given queue. how can I change the behavior to send each message to each consumer? To have each consumer receive the same message, you need to create a queue for each consumer and deliver the same message to each queue. The easiest way to do this is to use a fanout exchange. This will send every message to every queue that is bound to the exchange, completely ignoring the routing key. If you need more control over the routing, you can use a topic or direct exchange and manage the routing keys. Whatever type of exchange you choose, though, you will need to have a queue per consumer and have each message routed to each queue. A: you can't it's controlled by the server check Round-robin dispatching section It decides which consumer turn is. i'm not sure if there is a set of algorithms you can pick from, but at the end server will control this (i think round robin algorithm is default) unless you want to use routing keys and exchanges A: I would see this more as a design question. Ideally, producers should create the exchanges and the consumers create the queues and each consumer can create its own queue and hook it up to an exchange. This makes sure every consumer gets its message with its private queue. A: What youre doing is essentially 'worker queues' model which is used to distribute tasks among worker nodes. Since each task needs to be performed only once, the message is sent to only one node. If you want to send a message to all the nodes, you need a different model called 'pub-sub' where each message is broadcasted to all the subscribers. The following link shows a simple pub-sub tutorial https://www.rabbitmq.com/tutorials/tutorial-three-python.html
RabbitMQ same message to each consumer
I have implemented the example from the RabbitMQ website: RabbitMQ Example I have expanded it to have an application with a button to send a message. Now I started two consumer on two different computers. When I send the message the first message is sent to computer1, then the second message is sent to computer2, the thrid to computer1 and so on. Why is this, and how can I change the behavior to send each message to each consumer?
[ "\nWhy is this\n\nAs noted by Yazan, messages are consumed from a single queue in a round-robin manner. The behavior your are seeing is by design, making it easy to scale up the number of consumers for a given queue. \n\nhow can I change the behavior to send each message to each consumer?\n\nTo have each consumer receive the same message, you need to create a queue for each consumer and deliver the same message to each queue. \nThe easiest way to do this is to use a fanout exchange. This will send every message to every queue that is bound to the exchange, completely ignoring the routing key.\nIf you need more control over the routing, you can use a topic or direct exchange and manage the routing keys.\nWhatever type of exchange you choose, though, you will need to have a queue per consumer and have each message routed to each queue.\n", "you can't it's controlled by the server check Round-robin dispatching section\nIt decides which consumer turn is. i'm not sure if there is a set of algorithms you can pick from, but at the end server will control this (i think round robin algorithm is default)\nunless you want to use routing keys and exchanges\n", "I would see this more as a design question. Ideally, producers should create the exchanges and the consumers create the queues and each consumer can create its own queue and hook it up to an exchange. This makes sure every consumer gets its message with its private queue.\n", "What youre doing is essentially 'worker queues' model which is used to distribute tasks among worker nodes. Since each task needs to be performed only once, the message is sent to only one node. If you want to send a message to all the nodes, you need a different model called 'pub-sub' where each message is broadcasted to all the subscribers. The following link shows a simple pub-sub tutorial\nhttps://www.rabbitmq.com/tutorials/tutorial-three-python.html\n" ]
[ 30, 3, 0, 0 ]
[]
[]
[ "rabbitmq" ]
stackoverflow_0041160585_rabbitmq.txt
Q: include external files in processmaker 4 php scripts I am using processmaker 4 comunity, I need to run a PHP script that needs to include some external files with classes I defined. Since the php executor runs in a container it does not have access to the file system in my computer, how can I make the included files available in the executor container? I understand that one of the option would be to create a new executor with a dockerfile that will copy the required php files in the docker's executor image, but that means rebuilding the image each time I make a change on the included files. It would be great if I could mount a directory of my local host to the executors container, but have not figurer out if I can do that in processmaker. Any suggestions or information on how to work arround this? A: It is not possible to mount a directory from your local host to the executor container in ProcessMaker. However, there are a few options you can consider to make your PHP files available in the executor container. One option is to include the PHP files directly in your PHP script using the include or require statements. This way, you can specify the path to the PHP file relative to the location of your PHP script, and the executor container will be able to access it. For example: include "./path/to/file.php"; Another option is to package the PHP files into a ZIP archive and use the pm.downloadFile function in ProcessMaker to download the ZIP file to the executor container. You can then extract the ZIP file and access the PHP files as needed. Finally, you can build a custom executor image that includes the PHP files you need. This will require rebuilding the image each time you make changes to the PHP files, but it will allow you to easily access the files in the executor container without having to download or include them in your PHP script. A: In order to do this, you will need to ensure that the PHP executor has access to the files. One option would be to build a new PHP executor image that includes the necessary PHP files. This would involve creating a Dockerfile that installs the necessary dependencies and copies the PHP files into the image. Then, you can use this image as the PHP executor in ProcessMaker. Another option would be to mount a local directory from your host machine to the PHP executor container. This would allow you to access the local PHP files from within the container. To do this, you will need to use the -v flag when running the PHP executor container. For example: docker run -v /path/to/local/php/files:/path/to/php/files \ -e PM_PHP_EXECUTOR_IMAGE=php:7.4-cli \ processmaker/pm4-php-executor:4.0.23 This will mount the local directory /path/to/local/php/files from your host machine to the /path/to/php/files directory in the PHP executor container. You can then use the PHP files in the mounted directory from within your workflow. It's worth noting that using a mounted directory like this can make it easier to update the PHP files, since you don't need to rebuild the PHP executor image each time you make a change. However, there are some potential drawbacks to this approach, such as increased complexity and potential security concerns. I hope this helps!
include external files in processmaker 4 php scripts
I am using processmaker 4 comunity, I need to run a PHP script that needs to include some external files with classes I defined. Since the php executor runs in a container it does not have access to the file system in my computer, how can I make the included files available in the executor container? I understand that one of the option would be to create a new executor with a dockerfile that will copy the required php files in the docker's executor image, but that means rebuilding the image each time I make a change on the included files. It would be great if I could mount a directory of my local host to the executors container, but have not figurer out if I can do that in processmaker. Any suggestions or information on how to work arround this?
[ "It is not possible to mount a directory from your local host to the executor container in ProcessMaker. However, there are a few options you can consider to make your PHP files available in the executor container.\nOne option is to include the PHP files directly in your PHP script using the include or require statements. This way, you can specify the path to the PHP file relative to the location of your PHP script, and the executor container will be able to access it.\nFor example:\ninclude \"./path/to/file.php\";\nAnother option is to package the PHP files into a ZIP archive and use the pm.downloadFile function in ProcessMaker to download the ZIP file to the executor container. You can then extract the ZIP file and access the PHP files as needed.\nFinally, you can build a custom executor image that includes the PHP files you need. This will require rebuilding the image each time you make changes to the PHP files, but it will allow you to easily access the files in the executor container without having to download or include them in your PHP script.\n", "In order to do this, you will need to ensure that the PHP executor has access to the files.\nOne option would be to build a new PHP executor image that includes the necessary PHP files. This would involve creating a Dockerfile that installs the necessary dependencies and copies the PHP files into the image. Then, you can use this image as the PHP executor in ProcessMaker.\nAnother option would be to mount a local directory from your host machine to the PHP executor container. This would allow you to access the local PHP files from within the container. To do this, you will need to use the -v flag when running the PHP executor container. For example:\ndocker run -v /path/to/local/php/files:/path/to/php/files \\\n -e PM_PHP_EXECUTOR_IMAGE=php:7.4-cli \\\n processmaker/pm4-php-executor:4.0.23\n\nThis will mount the local directory /path/to/local/php/files from your host machine to the /path/to/php/files directory in the PHP executor container. You can then use the PHP files in the mounted directory from within your workflow.\nIt's worth noting that using a mounted directory like this can make it easier to update the PHP files, since you don't need to rebuild the PHP executor image each time you make a change. However, there are some potential drawbacks to this approach, such as increased complexity and potential security concerns.\nI hope this helps!\n" ]
[ 0, 0 ]
[]
[]
[ "processmaker" ]
stackoverflow_0074070932_processmaker.txt
Q: Create individual hover text with background color over circle photo grid elements, CSS/HTML I have been struggling to create hover text and circular background color elements that appear over my circular image grid on my website. This requires some combination of the HTML and CSS I have I imagine. I think this is difficult for me due to the way I have the grid and positioning setup. So it is hard to position the overlap hover element properly...`Below is my HTML and corresponding CSS code. Thanks!! #page-container { position: relative; min-height: 100vh; } #content-wrap { padding-bottom: 2.5rem; /* Footer height */ } .title { font-family: 'Helvetica', 'Arial', sans-serif; font-size: 6vw/*550%90px*/ ; color: #aa5129; margin-left: 11.75%/*205px*/ ; padding-top: .5%/*10px*/ ; padding-left: 4.25%; } .subtitle { font-family: 'Helvetica', 'Arial', sans-serif; font-size: 2.666666667vw/*40px*/ ; color: rgb(120, 120, 120); margin-left: 11.75%/*205px*/ ; padding-top: .5%/*10px*/ ; padding-left: 6.75%; } body { margin: 0; } .galleryhome { width: 75%; height: 100%; margin-top: 1%; margin-left: 18%/*300px*/ ; margin-right: auto; margin-bottom: 1%; } .galleryhome img { transition: 1s; padding: 1%; width: 20%/*250px*/ ; border-radius: 50%; } .galleryhome img:hover { color: #3d5d7a; transition: 0.2s; opacity: 0.75; transform: scale(1.07); } .side3 { height: 100%; width: 18%/*300px*/ ; position: fixed; z-index: 1; top: 0; left: 0; overflow-x: hidden; padding-top: .5%/*20px*/ ; /*padding-top: .5%20px;*/ /* tweaked from https://creative.colorado.edu/~jogr5195/web/Portfolio/index.html */ } .side3 a { font-family: 'Helvetica', 'Arial', sans-serif; padding: 6px 0px 20px 30px; text-decoration: none; font-size: 22px; color: rgb(120, 120, 120); display: block; padding-top: 1.2vw; /*padding-top: 20px;*/ /* tweaked from https://creative.colorado.edu/~jogr5195/web/Portfolio/index.html */ } <div id="page-container"> <div id="content-wrap"> <div class="title">name</div> <div class="subtitle">home</div> <div class="galleryhome"> <a href="index.html"><img class="img h1" src="media/home/about.png" alt="" /></a> <a href="photog_pages/index.html"><img class="img h1" src="media/home/photo.jpg" alt="" /></a> <a href="Photography.html"><img class="img h1" src="media/home/photoproj.jpg" alt="" /></a> <a href="SoftwareProjects.html"><img class="img h1" src="media/home/software.png" alt="" /></a> <a href="GraphicDesign.html"><img class="img h1" src="media/home/art.png" alt="" /></a> <a href="HardwareProjects.html"><img class="img h1" src="media/home/hardware.png" alt="" /></a> <!--<a href="Travel.html"><img class="img h1" src="media/home/travel.png" alt=""/></a>--> <a href="Contact.html"><img class="img h1" src="media/home/contact.png" alt="" /></a> </div> <div class="side3"> <a href="home.html"><img src="media/about_page/logo.png" alt="cornerLogo" width=87%></a> </div> </div> </div> Here is an example of what I want to do below. Thanks! This is my desired result if the image in the middle top image is hovered over.: This is the normal state with no images being hovered over.: This is some of the code I tried to experiment with but the positioning I couldn't get. .galleryhome .overlay { transition: 1s; padding: 1%; width: /*12%*/ 20% /*200px*/; border-radius: 50%; opacity: 0; } .galleryhome:hover .overlay { opacity: 1; } .hover-text { color: black; font-size: 3em; font-family: Ubuntu; font-weight: bold; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); text-align: center; } .bio-photo { border-radius:50%; border: 20px solid #1565C0; display: block; width: var(--width); height: auto; } .img-hover { position: relative; width: 100%; } .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: var(--width); opacity: 0; transition: .5s ease; background: rgba(0,0,0,0.25); border-radius:50%; border: 20px solid #1565C0; } .img-hover:hover .overlay { opacity: 1; } .hover-text { color: black; font-size: 3em; font-family: Ubuntu; font-weight: bold; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); text-align: center; } A: I had to do a bit of refactoring to your original code, and I have marked the new code areas with a /* new line of code */ or /* new block of code begin */ and /* new block of code end */. I hope this is what you are looking for: #page-container { position: relative; min-height: 100vh; } #content-wrap { padding-bottom: 2.5rem; } .title { font-family: 'Helvetica', 'Arial', sans-serif; font-size: 6vw; color: #aa5129; margin-left: 11.75%; padding-top: 0.5%; padding-left: 4.25%; } .subtitle { font-family: 'Helvetica', 'Arial', sans-serif; font-size: 2.666666667vw; color: rgb(120, 120, 120); margin-left: 11.75%; padding-top: 0.5%; padding-left: 6.75%; } body { margin: 0; } .galleryhome { display: grid; /* new line of code */ grid-template-columns: repeat(3, 1fr); /* new line of code */ gap: 50px; /* new line of code */ width: 75%; height: 100%; margin-top: 1%; margin-left: 18%; margin-right: auto; margin-bottom: 1%; } /* new block of code begin */ .galleryhome a { width: 100%; position: relative; } /* new block of code end */ .galleryhome a > img { transition: 1s; padding: 1%; width: inherit; height: inherit; border-radius: 50%; } /* new block of code begin */ .galleryhome a > .details { width: 100%; display: grid; position: absolute; top: 0; right: 0; bottom: 0; left: 0; justify-content: center; align-content: center; opacity: 0; transition: 1s; } .galleryhome a:hover { color: #3d5d7a; } .galleryhome a:hover img { opacity: 0.75; transform: scale(1.07); } .galleryhome a:hover .details { opacity: 1; } /* new block of code end */ .side3 { height: 100%; width: 18%; position: fixed; z-index: 1; top: 0; left: 0; overflow-x: hidden; padding-top: 0.5%; } .side3 a { font-family: 'Helvetica', 'Arial', sans-serif; padding: 6px 0px 20px 30px; text-decoration: none; font-size: 22px; color: rgb(120, 120, 120); display: block; padding-top: 1.2vw; } <div id="page-container"> <div id="content-wrap"> <div class="title">name</div> <div class="subtitle">home</div> <div class="galleryhome"> <a href="index.html"> <img class="img h1" src="https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg" alt="" /> <span class="details">Image 1</span> </a> <a href="photog_pages/index.html"> <img class="img h1" src="https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg" alt="" /> <span class="details">Image 2</span> </a> <a href="Photography.html"> <img class="img h1" src="https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg" alt="" /> <span class="details">Image 3</span> </a> <a href="SoftwareProjects.html"> <img class="img h1" src="https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg" alt="" /> <span class="details">Image 4</span> </a> <a href="GraphicDesign.html"> <img class="img h1" src="https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg" alt="" /> <span class="details">Image 5</span> </a> <a href="HardwareProjects.html"> <img class="img h1" src="https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg" alt="" /> <span class="details">Image 6</span> </a> <!--<a href="Travel.html"><img class="img h1" src="media/home/travel.png" alt=""/></a>--> <a href="Contact.html"> <img class="img h1" src="https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg" alt="" /> <span class="details">Image 7</span> </a> </div> <div class="side3"> <a href="home.html"><img src="https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg" alt="cornerLogo" width=87%></a> </div> </div> </div> Link to JS Fiddle Text on hover image
Create individual hover text with background color over circle photo grid elements, CSS/HTML
I have been struggling to create hover text and circular background color elements that appear over my circular image grid on my website. This requires some combination of the HTML and CSS I have I imagine. I think this is difficult for me due to the way I have the grid and positioning setup. So it is hard to position the overlap hover element properly...`Below is my HTML and corresponding CSS code. Thanks!! #page-container { position: relative; min-height: 100vh; } #content-wrap { padding-bottom: 2.5rem; /* Footer height */ } .title { font-family: 'Helvetica', 'Arial', sans-serif; font-size: 6vw/*550%90px*/ ; color: #aa5129; margin-left: 11.75%/*205px*/ ; padding-top: .5%/*10px*/ ; padding-left: 4.25%; } .subtitle { font-family: 'Helvetica', 'Arial', sans-serif; font-size: 2.666666667vw/*40px*/ ; color: rgb(120, 120, 120); margin-left: 11.75%/*205px*/ ; padding-top: .5%/*10px*/ ; padding-left: 6.75%; } body { margin: 0; } .galleryhome { width: 75%; height: 100%; margin-top: 1%; margin-left: 18%/*300px*/ ; margin-right: auto; margin-bottom: 1%; } .galleryhome img { transition: 1s; padding: 1%; width: 20%/*250px*/ ; border-radius: 50%; } .galleryhome img:hover { color: #3d5d7a; transition: 0.2s; opacity: 0.75; transform: scale(1.07); } .side3 { height: 100%; width: 18%/*300px*/ ; position: fixed; z-index: 1; top: 0; left: 0; overflow-x: hidden; padding-top: .5%/*20px*/ ; /*padding-top: .5%20px;*/ /* tweaked from https://creative.colorado.edu/~jogr5195/web/Portfolio/index.html */ } .side3 a { font-family: 'Helvetica', 'Arial', sans-serif; padding: 6px 0px 20px 30px; text-decoration: none; font-size: 22px; color: rgb(120, 120, 120); display: block; padding-top: 1.2vw; /*padding-top: 20px;*/ /* tweaked from https://creative.colorado.edu/~jogr5195/web/Portfolio/index.html */ } <div id="page-container"> <div id="content-wrap"> <div class="title">name</div> <div class="subtitle">home</div> <div class="galleryhome"> <a href="index.html"><img class="img h1" src="media/home/about.png" alt="" /></a> <a href="photog_pages/index.html"><img class="img h1" src="media/home/photo.jpg" alt="" /></a> <a href="Photography.html"><img class="img h1" src="media/home/photoproj.jpg" alt="" /></a> <a href="SoftwareProjects.html"><img class="img h1" src="media/home/software.png" alt="" /></a> <a href="GraphicDesign.html"><img class="img h1" src="media/home/art.png" alt="" /></a> <a href="HardwareProjects.html"><img class="img h1" src="media/home/hardware.png" alt="" /></a> <!--<a href="Travel.html"><img class="img h1" src="media/home/travel.png" alt=""/></a>--> <a href="Contact.html"><img class="img h1" src="media/home/contact.png" alt="" /></a> </div> <div class="side3"> <a href="home.html"><img src="media/about_page/logo.png" alt="cornerLogo" width=87%></a> </div> </div> </div> Here is an example of what I want to do below. Thanks! This is my desired result if the image in the middle top image is hovered over.: This is the normal state with no images being hovered over.: This is some of the code I tried to experiment with but the positioning I couldn't get. .galleryhome .overlay { transition: 1s; padding: 1%; width: /*12%*/ 20% /*200px*/; border-radius: 50%; opacity: 0; } .galleryhome:hover .overlay { opacity: 1; } .hover-text { color: black; font-size: 3em; font-family: Ubuntu; font-weight: bold; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); text-align: center; } .bio-photo { border-radius:50%; border: 20px solid #1565C0; display: block; width: var(--width); height: auto; } .img-hover { position: relative; width: 100%; } .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: var(--width); opacity: 0; transition: .5s ease; background: rgba(0,0,0,0.25); border-radius:50%; border: 20px solid #1565C0; } .img-hover:hover .overlay { opacity: 1; } .hover-text { color: black; font-size: 3em; font-family: Ubuntu; font-weight: bold; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); text-align: center; }
[ "I had to do a bit of refactoring to your original code, and I have marked the new code areas with a /* new line of code */ or /* new block of code begin */ and /* new block of code end */. I hope this is what you are looking for:\n\n\n#page-container {\n position: relative;\n min-height: 100vh;\n}\n\n#content-wrap {\n padding-bottom: 2.5rem;\n}\n\n.title {\n font-family: 'Helvetica', 'Arial', sans-serif;\n font-size: 6vw;\n color: #aa5129;\n margin-left: 11.75%;\n padding-top: 0.5%;\n padding-left: 4.25%;\n}\n\n.subtitle {\n font-family: 'Helvetica', 'Arial', sans-serif;\n font-size: 2.666666667vw;\n color: rgb(120, 120, 120);\n margin-left: 11.75%;\n padding-top: 0.5%;\n padding-left: 6.75%;\n}\n\nbody {\n margin: 0;\n}\n\n.galleryhome {\n display: grid; /* new line of code */\n grid-template-columns: repeat(3, 1fr); /* new line of code */\n gap: 50px; /* new line of code */\n width: 75%;\n height: 100%;\n margin-top: 1%;\n margin-left: 18%;\n margin-right: auto;\n margin-bottom: 1%;\n}\n\n/* new block of code begin */\n.galleryhome a {\n width: 100%;\n position: relative;\n}\n\n/* new block of code end */\n\n.galleryhome a > img {\n transition: 1s;\n padding: 1%;\n width: inherit;\n height: inherit;\n border-radius: 50%;\n}\n\n\n/* new block of code begin */\n.galleryhome a > .details {\n width: 100%;\n display: grid;\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n justify-content: center;\n align-content: center;\n opacity: 0;\n transition: 1s;\n}\n\n.galleryhome a:hover {\n color: #3d5d7a;\n}\n\n.galleryhome a:hover img {\n opacity: 0.75;\n transform: scale(1.07);\n}\n\n.galleryhome a:hover .details {\n opacity: 1;\n}\n\n/* new block of code end */\n\n.side3 {\n height: 100%;\n width: 18%;\n position: fixed;\n z-index: 1;\n top: 0;\n left: 0;\n overflow-x: hidden;\n padding-top: 0.5%;\n}\n\n.side3 a {\n font-family: 'Helvetica', 'Arial', sans-serif;\n padding: 6px 0px 20px 30px;\n text-decoration: none;\n font-size: 22px;\n color: rgb(120, 120, 120);\n display: block;\n padding-top: 1.2vw;\n}\n<div id=\"page-container\">\n <div id=\"content-wrap\">\n\n <div class=\"title\">name</div>\n <div class=\"subtitle\">home</div>\n\n <div class=\"galleryhome\">\n <a href=\"index.html\">\n <img class=\"img h1\" src=\"https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg\" alt=\"\" />\n <span class=\"details\">Image 1</span>\n </a>\n\n <a href=\"photog_pages/index.html\">\n <img class=\"img h1\" src=\"https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg\" alt=\"\" />\n <span class=\"details\">Image 2</span>\n </a>\n\n <a href=\"Photography.html\">\n <img class=\"img h1\" src=\"https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg\" alt=\"\" />\n <span class=\"details\">Image 3</span>\n </a>\n\n <a href=\"SoftwareProjects.html\">\n <img class=\"img h1\" src=\"https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg\" alt=\"\" />\n <span class=\"details\">Image 4</span>\n </a>\n\n <a href=\"GraphicDesign.html\">\n <img class=\"img h1\" src=\"https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg\" alt=\"\" />\n <span class=\"details\">Image 5</span>\n </a>\n\n <a href=\"HardwareProjects.html\">\n <img class=\"img h1\" src=\"https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg\" alt=\"\" />\n <span class=\"details\">Image 6</span>\n </a>\n\n <!--<a href=\"Travel.html\"><img class=\"img h1\" src=\"media/home/travel.png\" alt=\"\"/></a>-->\n\n <a href=\"Contact.html\">\n <img class=\"img h1\" src=\"https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg\" alt=\"\" />\n <span class=\"details\">Image 7</span>\n </a>\n </div>\n <div class=\"side3\">\n <a href=\"home.html\"><img src=\"https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg\" alt=\"cornerLogo\" width=87%></a>\n </div>\n </div>\n</div>\n\n\n\nLink to JS Fiddle Text on hover image\n" ]
[ 0 ]
[]
[]
[ "css", "hover", "html", "image", "text" ]
stackoverflow_0074675447_css_hover_html_image_text.txt
Q: Apache Kafka in kraft mode fails frequently We have created a 3 node kafka-3.3.1 cluster in kraft mode. This is based on bitnami-kafka image. Basic configuration for all nodes are (port number is different for each and other changes as required) KAFKA_ENABLE_KRAFT: 'yes' KAFKA_KRAFT_CLUSTER_ID: xxyyddjjjddkk1234 KAFKA_CFG_PROCESS_ROLES: broker,controller KAFKA_CFG_CONTROLLER_LISTENER_NAMES: CONTROLLER KAFKA_CFG_LISTENERS: CONTROLLER://:9093,INSIDE://:9092,EXTERNAL://:9094 KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,INSIDE:PLAINTEXT,EXTERNAL:PLAINTEXT KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: 1@dpkafka01:9093,2@dpkafka02:9093,3@dpkafka03:9093 KAFKA_CFG_ADVERTISED_LISTENERS: INSIDE://dpkafka02:9092,EXTERNAL://_{HOSTIP}:9098 KAFKA_BROKER_ID: 2 KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE KAFKA_HEAP_OPTS: "-Xmx1G -Xms256m" KAFKA_LOG_DIRS: /bitnami/kafka/kafka-logs KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false' KAFKA_LOG_RETENTION_MS: 7200000 KAFKA_LOG_SEGMENT_MS: 86400000 KAFKA_LOG_DELETE_RETENTION_MS: 7200000 KAFKA_LOG_RETENTION_CHECK_INTERVAL_MS: 60000 KAFKA_LOG_CLEANUP_POLICY: "compact,delete" KAFKA_CFG_GROUP_INITIAL_REBALANCE_DELAY_MS: 12000 KAFKA_CFG_NUM_RECOVERY_THREADS_PER_DATA_DIR: 4 KAFKA_CFG_OFFSETS_TOPIC_REPLICATION_FACTOR: 2 KAFKA_CFG_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 2 KAFKA_CFG_TRANSACTION_STATE_LOG_MIN_ISR: 2 ALLOW_PLAINTEXT_LISTENER: 'yes' BITNAMI_DEBUG: 'true' KAFKA_OPTS: -javaagent:/opt/bitnami/kafka/libs/jmx_prometheus_javaagent.jar=7072:/opt/bitnami/kafka/libs/prom-jmx-agent-config.yml While the cluster works for a while, one or two of them shuts down very frequently. Logs are not very helpful to identify the root cause. Some relevant logs we see before the state changes to shutdown are: [2022-12-04 08:35:16,928] INFO [RaftManager nodeId=2] Become candidate due to fetch timeout (org.apache.kafka.raft.KafkaRaftClient) [2022-12-04 08:35:17,414] INFO [RaftManager nodeId=2] Disconnecting from node 3 due to request timeout. (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:17,414] INFO [RaftManager nodeId=2] Cancelled in-flight FETCH request with correlation id 73082 due to node 3 being disconnected (elapsed time since creation: 2471ms, elapsed time since send: 2471ms, request timeout: 2000ms) (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:27,508] INFO [RaftManager nodeId=2] Completed transition to CandidateState(localId=2, epoch=31047, retries=1, electionTimeoutMs=1697) (org.apache.kafka.raft.QuorumState) [2022-12-04 08:35:27,508] INFO [Controller 2] In the new epoch 31047, the leader is (none). (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:27,802] INFO [RaftManager nodeId=2] Completed transition to Unattached(epoch=31048, voters=[1, 2, 3], electionTimeoutMs=0) (org.apache.kafka.raft.QuorumState) [2022-12-04 08:35:27,802] INFO [Controller 2] In the new epoch 31048, the leader is (none). (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:27,815] INFO [BrokerToControllerChannelManager broker=2 name=heartbeat] Client requested disconnect from node 3 (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:27,815] INFO [BrokerLifecycleManager id=2] Unable to send a heartbeat because the RPC got timed out before it could be sent. (kafka.server.BrokerLifecycleManager) [2022-12-04 08:35:27,830] INFO [RaftManager nodeId=2] Completed transition to Voted(epoch=31048, votedId=1, voters=[1, 2, 3], electionTimeoutMs=1014) (org.apache.kafka.raft.QuorumState) ..... [2022-12-04 08:35:32,210] INFO [Broker id=2] Stopped fetchers as part of become-follower for 479 partitions (state.change.logger) [2022-12-04 08:35:32,211] INFO [Broker id=2] Started fetchers as part of become-follower for 479 partitions (state.change.logger) [2022-12-04 08:35:32,232] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Shutting down (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,232] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Client requested connection close from node 1 (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:32,233] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Cancelled in-flight FETCH request with correlation id 675913 due to node 1 being disconnected (elapsed time since creation: 4394ms, elapsed time since send: 4394ms, request timeout: 30000ms) (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:32,233] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Error sending fetch request (sessionId=1961820001, epoch=181722) to node 1: (org.apache.kafka.clients.FetchSessionHandler) java.io.IOException: Client was shutdown before response was read at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:108) at kafka.server.BrokerBlockingSender.sendRequest(BrokerBlockingSender.scala:113) at kafka.server.RemoteLeaderEndPoint.fetch(RemoteLeaderEndPoint.scala:78) at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:309) at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:124) at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:123) at scala.Option.foreach(Option.scala:407) at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:123) at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:106) at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96) [2022-12-04 08:35:32,234] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Stopped (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,234] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Shutdown completed (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,237] INFO [ReplicaFetcher replicaId=2, leaderId=3, fetcherId=0] Shutting down (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,237] INFO [ReplicaFetcher replicaId=2, leaderId=3, fetcherId=0] Shutdown completed (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,237] INFO [ReplicaFetcher replicaId=2, leaderId=3, fetcherId=0] Stopped (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,245] INFO [GroupCoordinator 2]: Resigned as the group coordinator for partition 13 in epoch Some(3200) (kafka.coordinator.group.GroupCoordinator) .... [2022-12-04 08:35:48,229] INFO [Controller 2] Unfenced broker: 2 (org.apache.kafka.controller.ClusterControlManager) [2022-12-04 08:35:48,254] INFO [RaftManager nodeId=2] Completed transition to Unattached(epoch=31055, voters=[1, 2, 3], electionTimeoutMs=1607) (org.apache.kafka.raft.QuorumState) [2022-12-04 08:35:48,254] INFO [RaftManager nodeId=2] Vote request VoteRequestData(clusterId='<redacted>', topics=[TopicData(topicName='__cluster_metadata', partitions=[PartitionData(partitionIndex=0, candidateEpoch=31055, candidateId=3, lastOffsetEpoch=31052, lastOffset=6552512)])]) with epoch 31055 is rejected (org.apache.kafka.raft.KafkaRaftClient) [2022-12-04 08:35:48,254] WARN [Controller 2] Renouncing the leadership due to a metadata log event. We were the leader at epoch 31052, but in the new epoch 31055, the leader is (none). Reverting to last committed offset 6552511. (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 8243762 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] alterPartition: failed with NotControllerException in 8005283 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 7743806 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 7243753 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] processBrokerHeartbeat: failed with NotControllerException in 7151815 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] processBrokerHeartbeat: failed with NotControllerException in 7151616 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 6743693 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 6243134 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 5742969 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 5242852 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 4742694 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 4242529 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 3742380 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 3242258 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 2741822 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 2241677 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 1741549 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 1241369 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 741246 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] maybeFenceReplicas: failed with NotControllerException in 244485 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 241049 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] maybeFenceReplicas: failed with NotControllerException in 196629 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] processBrokerHeartbeat: failed with NotControllerException in 27063 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,255] INFO [BrokerToControllerChannelManager broker=2 name=heartbeat] Client requested disconnect from node 2 (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:48,255] ERROR Encountered fatal fault: exception while renouncing leadership (org.apache.kafka.server.fault.ProcessExitingFaultHandler) java.lang.NullPointerException at org.apache.kafka.timeline.SnapshottableHashTable$HashTier.mergeFrom(SnapshottableHashTable.java:125) at org.apache.kafka.timeline.Snapshot.mergeFrom(Snapshot.java:68) at org.apache.kafka.timeline.SnapshotRegistry.deleteSnapshot(SnapshotRegistry.java:236) at org.apache.kafka.timeline.SnapshotRegistry$SnapshotIterator.remove(SnapshotRegistry.java:67) at org.apache.kafka.timeline.SnapshotRegistry.revertToSnapshot(SnapshotRegistry.java:214) at org.apache.kafka.controller.QuorumController.renounce(QuorumController.java:1232) at org.apache.kafka.controller.QuorumController.access$3300(QuorumController.java:150) at org.apache.kafka.controller.QuorumController$QuorumMetaLogListener.lambda$handleLeaderChange$3(QuorumController.java:1076) at org.apache.kafka.controller.QuorumController$QuorumMetaLogListener.lambda$appendRaftEvent$4(QuorumController.java:1101) at org.apache.kafka.controller.QuorumController$ControlEvent.run(QuorumController.java:496) at org.apache.kafka.queue.KafkaEventQueue$EventContext.run(KafkaEventQueue.java:121) at org.apache.kafka.queue.KafkaEventQueue$EventHandler.handleEvents(KafkaEventQueue.java:200) at org.apache.kafka.queue.KafkaEventQueue$EventHandler.run(KafkaEventQueue.java:173) at java.base/java.lang.Thread.run(Thread.java:829) [2022-12-04 08:35:48,259] INFO [BrokerServer id=2] Transition from STARTED to SHUTTING_DOWN (kafka.server.BrokerServer) [2022-12-04 08:35:48,259] INFO [BrokerServer id=2] shutting down (kafka.server.BrokerServer) [2022-12-04 08:35:48,261] INFO [BrokerLifecycleManager id=2] Beginning controlled shutdown. (kafka.server.BrokerLifecycleManager) [2022-12-04 08:35:48,277] INFO [RaftManager nodeId=2] Completed transition to FollowerState(fetchTimeoutMs=2000, epoch=31055, leaderId=3, voters=[1, 2, 3], highWatermark=Optional[LogOffsetMetadata(offset=6552512, metadata=Optional[(segmentBaseOffset=6497886,relativePositionInSegment=3821894)])], fetchingSnapshot=Optional.empty) (org.apache.kafka.raft.QuorumState) [2022-12-04 08:35:48,355] INFO [BrokerToControllerChannelManager broker=2 name=heartbeat]: Recorded new controller, from now on will use broker dpkafka03:9093 (id: 3 rack: null) (kafka.server.BrokerToControllerRequestThread) Appreciate if anyone experienced with Kraft mode Kafka cluster can provide some guidance to debug this issue. Other problem is that the container doesn't exit after the error which makes the services to fail. Container will be restarted by our orchestration layer if it exits. (this is a different problem that as we use Bitnami images) I also didn't find many production examples out there that uses kraft mode. Are we missing some configuration or do we need to change any default configuration values such as request timeout in Kraft mode? A: It looks like your Kafka cluster is having issues with its Raft-based state management. The KAFKA_ENABLE_KRAFT configuration parameter indicates that your cluster is using Raft for state management, and the log messages indicate that one of the nodes is timing out when trying to fetch state from another node. This can happen if the network connection between the nodes is unstable, or if one of the nodes is running on a machine with inadequate resources (e.g. not enough memory or CPU). I would recommend checking the network connectivity between the nodes to make sure there are no issues there. You can also try increasing the KAFKA_CFG_CONTROLLER_QUORUM_VOTERS configuration parameter to ensure that a quorum of nodes is always available for state management, which can help prevent these kinds of timeouts. Additionally, you may want to monitor the resources (e.g. memory, CPU) available on the machines running your Kafka nodes to make sure they are not being overloaded.
Apache Kafka in kraft mode fails frequently
We have created a 3 node kafka-3.3.1 cluster in kraft mode. This is based on bitnami-kafka image. Basic configuration for all nodes are (port number is different for each and other changes as required) KAFKA_ENABLE_KRAFT: 'yes' KAFKA_KRAFT_CLUSTER_ID: xxyyddjjjddkk1234 KAFKA_CFG_PROCESS_ROLES: broker,controller KAFKA_CFG_CONTROLLER_LISTENER_NAMES: CONTROLLER KAFKA_CFG_LISTENERS: CONTROLLER://:9093,INSIDE://:9092,EXTERNAL://:9094 KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,INSIDE:PLAINTEXT,EXTERNAL:PLAINTEXT KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: 1@dpkafka01:9093,2@dpkafka02:9093,3@dpkafka03:9093 KAFKA_CFG_ADVERTISED_LISTENERS: INSIDE://dpkafka02:9092,EXTERNAL://_{HOSTIP}:9098 KAFKA_BROKER_ID: 2 KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE KAFKA_HEAP_OPTS: "-Xmx1G -Xms256m" KAFKA_LOG_DIRS: /bitnami/kafka/kafka-logs KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false' KAFKA_LOG_RETENTION_MS: 7200000 KAFKA_LOG_SEGMENT_MS: 86400000 KAFKA_LOG_DELETE_RETENTION_MS: 7200000 KAFKA_LOG_RETENTION_CHECK_INTERVAL_MS: 60000 KAFKA_LOG_CLEANUP_POLICY: "compact,delete" KAFKA_CFG_GROUP_INITIAL_REBALANCE_DELAY_MS: 12000 KAFKA_CFG_NUM_RECOVERY_THREADS_PER_DATA_DIR: 4 KAFKA_CFG_OFFSETS_TOPIC_REPLICATION_FACTOR: 2 KAFKA_CFG_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 2 KAFKA_CFG_TRANSACTION_STATE_LOG_MIN_ISR: 2 ALLOW_PLAINTEXT_LISTENER: 'yes' BITNAMI_DEBUG: 'true' KAFKA_OPTS: -javaagent:/opt/bitnami/kafka/libs/jmx_prometheus_javaagent.jar=7072:/opt/bitnami/kafka/libs/prom-jmx-agent-config.yml While the cluster works for a while, one or two of them shuts down very frequently. Logs are not very helpful to identify the root cause. Some relevant logs we see before the state changes to shutdown are: [2022-12-04 08:35:16,928] INFO [RaftManager nodeId=2] Become candidate due to fetch timeout (org.apache.kafka.raft.KafkaRaftClient) [2022-12-04 08:35:17,414] INFO [RaftManager nodeId=2] Disconnecting from node 3 due to request timeout. (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:17,414] INFO [RaftManager nodeId=2] Cancelled in-flight FETCH request with correlation id 73082 due to node 3 being disconnected (elapsed time since creation: 2471ms, elapsed time since send: 2471ms, request timeout: 2000ms) (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:27,508] INFO [RaftManager nodeId=2] Completed transition to CandidateState(localId=2, epoch=31047, retries=1, electionTimeoutMs=1697) (org.apache.kafka.raft.QuorumState) [2022-12-04 08:35:27,508] INFO [Controller 2] In the new epoch 31047, the leader is (none). (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:27,802] INFO [RaftManager nodeId=2] Completed transition to Unattached(epoch=31048, voters=[1, 2, 3], electionTimeoutMs=0) (org.apache.kafka.raft.QuorumState) [2022-12-04 08:35:27,802] INFO [Controller 2] In the new epoch 31048, the leader is (none). (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:27,815] INFO [BrokerToControllerChannelManager broker=2 name=heartbeat] Client requested disconnect from node 3 (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:27,815] INFO [BrokerLifecycleManager id=2] Unable to send a heartbeat because the RPC got timed out before it could be sent. (kafka.server.BrokerLifecycleManager) [2022-12-04 08:35:27,830] INFO [RaftManager nodeId=2] Completed transition to Voted(epoch=31048, votedId=1, voters=[1, 2, 3], electionTimeoutMs=1014) (org.apache.kafka.raft.QuorumState) ..... [2022-12-04 08:35:32,210] INFO [Broker id=2] Stopped fetchers as part of become-follower for 479 partitions (state.change.logger) [2022-12-04 08:35:32,211] INFO [Broker id=2] Started fetchers as part of become-follower for 479 partitions (state.change.logger) [2022-12-04 08:35:32,232] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Shutting down (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,232] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Client requested connection close from node 1 (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:32,233] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Cancelled in-flight FETCH request with correlation id 675913 due to node 1 being disconnected (elapsed time since creation: 4394ms, elapsed time since send: 4394ms, request timeout: 30000ms) (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:32,233] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Error sending fetch request (sessionId=1961820001, epoch=181722) to node 1: (org.apache.kafka.clients.FetchSessionHandler) java.io.IOException: Client was shutdown before response was read at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:108) at kafka.server.BrokerBlockingSender.sendRequest(BrokerBlockingSender.scala:113) at kafka.server.RemoteLeaderEndPoint.fetch(RemoteLeaderEndPoint.scala:78) at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:309) at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:124) at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:123) at scala.Option.foreach(Option.scala:407) at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:123) at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:106) at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96) [2022-12-04 08:35:32,234] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Stopped (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,234] INFO [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Shutdown completed (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,237] INFO [ReplicaFetcher replicaId=2, leaderId=3, fetcherId=0] Shutting down (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,237] INFO [ReplicaFetcher replicaId=2, leaderId=3, fetcherId=0] Shutdown completed (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,237] INFO [ReplicaFetcher replicaId=2, leaderId=3, fetcherId=0] Stopped (kafka.server.ReplicaFetcherThread) [2022-12-04 08:35:32,245] INFO [GroupCoordinator 2]: Resigned as the group coordinator for partition 13 in epoch Some(3200) (kafka.coordinator.group.GroupCoordinator) .... [2022-12-04 08:35:48,229] INFO [Controller 2] Unfenced broker: 2 (org.apache.kafka.controller.ClusterControlManager) [2022-12-04 08:35:48,254] INFO [RaftManager nodeId=2] Completed transition to Unattached(epoch=31055, voters=[1, 2, 3], electionTimeoutMs=1607) (org.apache.kafka.raft.QuorumState) [2022-12-04 08:35:48,254] INFO [RaftManager nodeId=2] Vote request VoteRequestData(clusterId='<redacted>', topics=[TopicData(topicName='__cluster_metadata', partitions=[PartitionData(partitionIndex=0, candidateEpoch=31055, candidateId=3, lastOffsetEpoch=31052, lastOffset=6552512)])]) with epoch 31055 is rejected (org.apache.kafka.raft.KafkaRaftClient) [2022-12-04 08:35:48,254] WARN [Controller 2] Renouncing the leadership due to a metadata log event. We were the leader at epoch 31052, but in the new epoch 31055, the leader is (none). Reverting to last committed offset 6552511. (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 8243762 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] alterPartition: failed with NotControllerException in 8005283 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 7743806 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 7243753 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] processBrokerHeartbeat: failed with NotControllerException in 7151815 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] processBrokerHeartbeat: failed with NotControllerException in 7151616 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 6743693 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 6243134 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 5742969 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 5242852 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 4742694 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 4242529 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 3742380 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 3242258 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 2741822 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 2241677 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 1741549 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 1241369 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 741246 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] maybeFenceReplicas: failed with NotControllerException in 244485 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] writeNoOpRecord: failed with NotControllerException in 241049 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] maybeFenceReplicas: failed with NotControllerException in 196629 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,254] INFO [Controller 2] processBrokerHeartbeat: failed with NotControllerException in 27063 us (org.apache.kafka.controller.QuorumController) [2022-12-04 08:35:48,255] INFO [BrokerToControllerChannelManager broker=2 name=heartbeat] Client requested disconnect from node 2 (org.apache.kafka.clients.NetworkClient) [2022-12-04 08:35:48,255] ERROR Encountered fatal fault: exception while renouncing leadership (org.apache.kafka.server.fault.ProcessExitingFaultHandler) java.lang.NullPointerException at org.apache.kafka.timeline.SnapshottableHashTable$HashTier.mergeFrom(SnapshottableHashTable.java:125) at org.apache.kafka.timeline.Snapshot.mergeFrom(Snapshot.java:68) at org.apache.kafka.timeline.SnapshotRegistry.deleteSnapshot(SnapshotRegistry.java:236) at org.apache.kafka.timeline.SnapshotRegistry$SnapshotIterator.remove(SnapshotRegistry.java:67) at org.apache.kafka.timeline.SnapshotRegistry.revertToSnapshot(SnapshotRegistry.java:214) at org.apache.kafka.controller.QuorumController.renounce(QuorumController.java:1232) at org.apache.kafka.controller.QuorumController.access$3300(QuorumController.java:150) at org.apache.kafka.controller.QuorumController$QuorumMetaLogListener.lambda$handleLeaderChange$3(QuorumController.java:1076) at org.apache.kafka.controller.QuorumController$QuorumMetaLogListener.lambda$appendRaftEvent$4(QuorumController.java:1101) at org.apache.kafka.controller.QuorumController$ControlEvent.run(QuorumController.java:496) at org.apache.kafka.queue.KafkaEventQueue$EventContext.run(KafkaEventQueue.java:121) at org.apache.kafka.queue.KafkaEventQueue$EventHandler.handleEvents(KafkaEventQueue.java:200) at org.apache.kafka.queue.KafkaEventQueue$EventHandler.run(KafkaEventQueue.java:173) at java.base/java.lang.Thread.run(Thread.java:829) [2022-12-04 08:35:48,259] INFO [BrokerServer id=2] Transition from STARTED to SHUTTING_DOWN (kafka.server.BrokerServer) [2022-12-04 08:35:48,259] INFO [BrokerServer id=2] shutting down (kafka.server.BrokerServer) [2022-12-04 08:35:48,261] INFO [BrokerLifecycleManager id=2] Beginning controlled shutdown. (kafka.server.BrokerLifecycleManager) [2022-12-04 08:35:48,277] INFO [RaftManager nodeId=2] Completed transition to FollowerState(fetchTimeoutMs=2000, epoch=31055, leaderId=3, voters=[1, 2, 3], highWatermark=Optional[LogOffsetMetadata(offset=6552512, metadata=Optional[(segmentBaseOffset=6497886,relativePositionInSegment=3821894)])], fetchingSnapshot=Optional.empty) (org.apache.kafka.raft.QuorumState) [2022-12-04 08:35:48,355] INFO [BrokerToControllerChannelManager broker=2 name=heartbeat]: Recorded new controller, from now on will use broker dpkafka03:9093 (id: 3 rack: null) (kafka.server.BrokerToControllerRequestThread) Appreciate if anyone experienced with Kraft mode Kafka cluster can provide some guidance to debug this issue. Other problem is that the container doesn't exit after the error which makes the services to fail. Container will be restarted by our orchestration layer if it exits. (this is a different problem that as we use Bitnami images) I also didn't find many production examples out there that uses kraft mode. Are we missing some configuration or do we need to change any default configuration values such as request timeout in Kraft mode?
[ "It looks like your Kafka cluster is having issues with its Raft-based state management. The KAFKA_ENABLE_KRAFT configuration parameter indicates that your cluster is using Raft for state management, and the log messages indicate that one of the nodes is timing out when trying to fetch state from another node. This can happen if the network connection between the nodes is unstable, or if one of the nodes is running on a machine with inadequate resources (e.g. not enough memory or CPU).\nI would recommend checking the network connectivity between the nodes to make sure there are no issues there. You can also try increasing the KAFKA_CFG_CONTROLLER_QUORUM_VOTERS configuration parameter to ensure that a quorum of nodes is always available for state management, which can help prevent these kinds of timeouts. Additionally, you may want to monitor the resources (e.g. memory, CPU) available on the machines running your Kafka nodes to make sure they are not being overloaded.\n" ]
[ 0 ]
[]
[]
[ "apache_kafka", "bitnami", "bitnami_kafka", "kraft" ]
stackoverflow_0074679400_apache_kafka_bitnami_bitnami_kafka_kraft.txt
Q: Plot one series for one column with Polars dataframe and Plotly I can't find how to plot these two series A and B with time on X. from numpy import linspace import polars as pl import plotly.express as px import plotly.io as pio pio.renderers.default = 'browser' times = linspace(1, 6, 10) df = pl.DataFrame({ 'time': times, 'A': times**2, 'B': times**3, }) fig = px.line(df) fig.show() Data keep showing as 10 series with 3 points, instead of 2 series with 10 points and the first column as X values. Edit: This line: fig = px.line(df, x='time', y=['A', 'B']) produces this error: ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] but received: time Using polars 0.15.0 and plotly 5.11.0 A: You use Polars Dataframe instead of Pandas dataframe and indexing is a little different here and what is why you have this error. In order to plot it, one way to do it is to convert the dataframe from Polars to Pandas on the fly by using to_pandas(): fig = px.line(df.to_pandas(),x='time', y=['A', 'B']) Output You can also use this way: fig = px.line(x=df['time'], y=[df["A"],df["B"]]) A: In your code, you can use the line() function to plot the A and B columns from your DataFrame, which contain the time-series data for the two series. You can then set the x and y parameters of the line() function to specify which column should be used for the X-axis and which columns should be used for the Y-axis. Here's an example of how you can use the line() function to plot the A and B columns from your DataFrame with time on the X-axis: # Import the necessary modules from numpy import linspace import plotly.express as px # Create a DataFrame with time-series data for two series times = linspace(1, 6, 10) df = pl.DataFrame({ 'time': times, 'A': times**2, 'B': times**3, }) # Use the line() function to plot the A and B columns from the DataFrame fig = px.line(df, x='time', y=['A', 'B']) # Show the plot fig.show() This will create a line chart with the A and B columns from your DataFrame as the data series, and the time column as the X-axis. The resulting plot should show the two series with time on the X-axis.
Plot one series for one column with Polars dataframe and Plotly
I can't find how to plot these two series A and B with time on X. from numpy import linspace import polars as pl import plotly.express as px import plotly.io as pio pio.renderers.default = 'browser' times = linspace(1, 6, 10) df = pl.DataFrame({ 'time': times, 'A': times**2, 'B': times**3, }) fig = px.line(df) fig.show() Data keep showing as 10 series with 3 points, instead of 2 series with 10 points and the first column as X values. Edit: This line: fig = px.line(df, x='time', y=['A', 'B']) produces this error: ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] but received: time Using polars 0.15.0 and plotly 5.11.0
[ "You use Polars Dataframe instead of Pandas dataframe and indexing is a little different here and what is why you have this error. In order to plot it, one way to do it is to convert the dataframe from Polars to Pandas on the fly by using to_pandas():\nfig = px.line(df.to_pandas(),x='time', y=['A', 'B'])\n\nOutput\n\nYou can also use this way:\nfig = px.line(x=df['time'], y=[df[\"A\"],df[\"B\"]])\n\n", "In your code, you can use the line() function to plot the A and B columns from your DataFrame, which contain the time-series data for the two series. You can then set the x and y parameters of the line() function to specify which column should be used for the X-axis and which columns should be used for the Y-axis.\nHere's an example of how you can use the line() function to plot the A and B columns from your DataFrame with time on the X-axis:\n# Import the necessary modules\nfrom numpy import linspace\nimport plotly.express as px\n\n# Create a DataFrame with time-series data for two series\ntimes = linspace(1, 6, 10)\ndf = pl.DataFrame({\n 'time': times,\n 'A': times**2,\n 'B': times**3,\n})\n\n# Use the line() function to plot the A and B columns from the DataFrame\nfig = px.line(df, x='time', y=['A', 'B'])\n\n# Show the plot\nfig.show()\n\nThis will create a line chart with the A and B columns from your DataFrame as the data series, and the time column as the X-axis. The resulting plot should show the two series with time on the X-axis.\n" ]
[ 1, 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074678281_plotly_python.txt
Q: Can I interrogate a PySpark DataFrame to get the list of referenced columns? Given a PySpark DataFrame is it possible to obtain a list of source columns that are being referenced by the DataFrame? Perhaps a more concrete example might help explain what I'm after. Say I have a DataFrame defined as: import pyspark.sql.functions as func from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() source_df = spark.createDataFrame( [("pru", 23, "finance"), ("paul", 26, "HR"), ("noel", 20, "HR")], ["name", "age", "department"], ) source_df.createOrReplaceTempView("people") sqlDF = spark.sql("SELECT name, age, department FROM people") df = sqlDF.groupBy("department").agg(func.max("age").alias("max_age")) df.show() which returns: +----------+--------+ |department|max_age | +----------+--------+ | finance| 23| | HR| 26| +----------+--------+ The columns that are referenced by df are [department, age]. Is it possible to get that list of referenced columns programatically? Thanks to Capturing the result of explain() in pyspark I know I can extract the plan as a string: df._sc._jvm.PythonSQLUtils.explainString(df._jdf.queryExecution(), "formatted") which returns: == Physical Plan == AdaptiveSparkPlan (6) +- HashAggregate (5) +- Exchange (4) +- HashAggregate (3) +- Project (2) +- Scan ExistingRDD (1) (1) Scan ExistingRDD Output [3]: [name#0, age#1L, department#2] Arguments: [name#0, age#1L, department#2], MapPartitionsRDD[4] at applySchemaToPythonRDD at NativeMethodAccessorImpl.java:0, ExistingRDD, UnknownPartitioning(0) (2) Project Output [2]: [age#1L, department#2] Input [3]: [name#0, age#1L, department#2] (3) HashAggregate Input [2]: [age#1L, department#2] Keys [1]: [department#2] Functions [1]: [partial_max(age#1L)] Aggregate Attributes [1]: [max#22L] Results [2]: [department#2, max#23L] (4) Exchange Input [2]: [department#2, max#23L] Arguments: hashpartitioning(department#2, 200), ENSURE_REQUIREMENTS, [plan_id=60] (5) HashAggregate Input [2]: [department#2, max#23L] Keys [1]: [department#2] Functions [1]: [max(age#1L)] Aggregate Attributes [1]: [max(age#1L)#12L] Results [2]: [department#2, max(age#1L)#12L AS max_age#13L] (6) AdaptiveSparkPlan Output [2]: [department#2, max_age#13L] Arguments: isFinalPlan=false which is useful, however its not what I need. I need a list of the referenced columns. Is this possible? Perhaps another way of asking the question is... is there a way to obtain the explain plan as an object that I can iterate over/explore? A: There is an object for that unfortunately its a java object, and not translated to pyspark. You can still access it with Spark constucts: >>> df._jdf.queryExecution().executedPlan().apply(0).output().apply(0).toString() u'department#1621' >>> df._jdf.queryExecution().executedPlan().apply(0).output().apply(1).toString() u'max_age#1632L' You could loop through both the above apply to get the information you are looking for with something like: plan = df._jdf.queryExecution().executedPlan() steps = [ plan.apply(i).toString() for i in range(1,100) if not isinstance(plan.apply(i), type(None)) ] Bit of a hack but apparently size doesn't work. A: Yes, it is possible to obtain a list of source columns that are being referenced by a PySpark DataFrame. To do this, you can use the DataFrame's df.columns attribute, which returns a list of the column names in the DataFrame. In your example, this would be df.columns which would return ['department', 'max_age']. Alternatively, you can also use the df.dtypes attribute, which returns a list of tuples containing the column names and their data types. For example, df.dtypes would return [('department', 'string'), ('max_age', 'bigint')].
Can I interrogate a PySpark DataFrame to get the list of referenced columns?
Given a PySpark DataFrame is it possible to obtain a list of source columns that are being referenced by the DataFrame? Perhaps a more concrete example might help explain what I'm after. Say I have a DataFrame defined as: import pyspark.sql.functions as func from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() source_df = spark.createDataFrame( [("pru", 23, "finance"), ("paul", 26, "HR"), ("noel", 20, "HR")], ["name", "age", "department"], ) source_df.createOrReplaceTempView("people") sqlDF = spark.sql("SELECT name, age, department FROM people") df = sqlDF.groupBy("department").agg(func.max("age").alias("max_age")) df.show() which returns: +----------+--------+ |department|max_age | +----------+--------+ | finance| 23| | HR| 26| +----------+--------+ The columns that are referenced by df are [department, age]. Is it possible to get that list of referenced columns programatically? Thanks to Capturing the result of explain() in pyspark I know I can extract the plan as a string: df._sc._jvm.PythonSQLUtils.explainString(df._jdf.queryExecution(), "formatted") which returns: == Physical Plan == AdaptiveSparkPlan (6) +- HashAggregate (5) +- Exchange (4) +- HashAggregate (3) +- Project (2) +- Scan ExistingRDD (1) (1) Scan ExistingRDD Output [3]: [name#0, age#1L, department#2] Arguments: [name#0, age#1L, department#2], MapPartitionsRDD[4] at applySchemaToPythonRDD at NativeMethodAccessorImpl.java:0, ExistingRDD, UnknownPartitioning(0) (2) Project Output [2]: [age#1L, department#2] Input [3]: [name#0, age#1L, department#2] (3) HashAggregate Input [2]: [age#1L, department#2] Keys [1]: [department#2] Functions [1]: [partial_max(age#1L)] Aggregate Attributes [1]: [max#22L] Results [2]: [department#2, max#23L] (4) Exchange Input [2]: [department#2, max#23L] Arguments: hashpartitioning(department#2, 200), ENSURE_REQUIREMENTS, [plan_id=60] (5) HashAggregate Input [2]: [department#2, max#23L] Keys [1]: [department#2] Functions [1]: [max(age#1L)] Aggregate Attributes [1]: [max(age#1L)#12L] Results [2]: [department#2, max(age#1L)#12L AS max_age#13L] (6) AdaptiveSparkPlan Output [2]: [department#2, max_age#13L] Arguments: isFinalPlan=false which is useful, however its not what I need. I need a list of the referenced columns. Is this possible? Perhaps another way of asking the question is... is there a way to obtain the explain plan as an object that I can iterate over/explore?
[ "There is an object for that unfortunately its a java object, and not translated to pyspark.\nYou can still access it with Spark constucts:\n>>> df._jdf.queryExecution().executedPlan().apply(0).output().apply(0).toString()\nu'department#1621'\n>>> df._jdf.queryExecution().executedPlan().apply(0).output().apply(1).toString()\nu'max_age#1632L'\n\nYou could loop through both the above apply to get the information you are looking for with something like:\nplan = df._jdf.queryExecution().executedPlan()\nsteps = [ plan.apply(i).toString() for i in range(1,100) if not isinstance(plan.apply(i), type(None)) ]\n\nBit of a hack but apparently size doesn't work.\n", "Yes, it is possible to obtain a list of source columns that are being referenced by a PySpark DataFrame. To do this, you can use the DataFrame's df.columns attribute, which returns a list of the column names in the DataFrame. In your example, this would be df.columns which would return ['department', 'max_age'].\nAlternatively, you can also use the df.dtypes attribute, which returns a list of tuples containing the column names and their data types. For example, df.dtypes would return [('department', 'string'), ('max_age', 'bigint')].\n" ]
[ 4, 0 ]
[ "You can try the below codes, this will give you a column list and its data type in the data frame.\nfor field in df.schema.fields:\n print(field.name +\" , \"+str(field.dataType))\n\n" ]
[ -1 ]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0074598689_apache_spark_pyspark_python.txt
Q: Is there any article with all LeanTween operations on Internet? Soo, I am working on my little game and I have been using LeanTween Engine for some UI elements. But there is a problem, I don't know all operations that I can use with LeanTween. So I am asking if there is any working article that could help me? I know that there was one article with information that I need but it is taken down from internet... Help pls. Much love. A: As of writing, the official LeanTween API website appears to be down. Nevertheless, the web archive has a snapshot of the index page, which captures all of the available methods:
Is there any article with all LeanTween operations on Internet?
Soo, I am working on my little game and I have been using LeanTween Engine for some UI elements. But there is a problem, I don't know all operations that I can use with LeanTween. So I am asking if there is any working article that could help me? I know that there was one article with information that I need but it is taken down from internet... Help pls. Much love.
[ "As of writing, the official LeanTween API website appears to be down. Nevertheless, the web archive has a snapshot of the index page, which captures all of the available methods:\n\n" ]
[ 0 ]
[]
[]
[ "unity3d" ]
stackoverflow_0074679233_unity3d.txt
Q: How do I copy all folder contents from one location to another location in Python? I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL things ... i need solution to this problem. A: Here is one way to do this using the shutil module in Python: import shutil # Replace the source and destination paths with the appropriate paths on your system src_dir = "C:\\source\\folder" dst_dir = "C:\\destination\\folder" # Use the shutil.copytree function to copy everything from the source directory to the destination directory shutil.copytree(src_dir, dst_dir) This will copy all files and subdirectories from src_dir to dst_dir. Note that dst_dir must not already exist, otherwise the copytree function will raise an error. You can also use the copy function from the shutil module to copy individual files. For example: import shutil # Replace the source and destination paths with the appropriate paths on your system src_file = "C:\\source\\folder\\file.txt" dst_file = "C:\\destination\\folder\\file.txt" # Use the shutil.copy function to copy the file shutil.copy(src_file, dst_file) This will copy the file at src_file to the destination at dst_file. If dst_file already exists, it will be overwritten. You can use these functions in a loop to iterate over all files in a directory and copy them to the destination directory. Here is an example: import os import shutil # Replace the source and destination paths with the appropriate paths on your system src_dir = "C:\\source\\folder" dst_dir = "C:\\destination\\folder" # Create the destination directory if it does not already exist if not os.path.exists(dst_dir): os.makedirs(dst_dir) # Iterate over all files in the source directory for filename in os.listdir(src_dir): # Construct the full paths for the source and destination files src_file = os.path.join(src_dir, filename) dst_file = os.path.join(dst_dir, filename) # Use the shutil.copy function to copy the file shutil.copy(src_file, dst_file) A: import shutil import os # Path to the directory source = 'C:/path/to/source/folder' # Path to the destination directory destination = 'C:/path/to/destination/folder' # Copy contents from source to destination shutil.copytree(source, destination) # List all the files in source directory source_files = os.listdir(source) # Iterate over all the files in source directory for file_name in source_files: # Create full path of file in source directory full_file_name = os.path.join(source, file_name) # If file is a directory, create corresponding directory in destination # directory if os.path.isdir(full_file_name): shutil.copytree(full_file_name, os.path.join(destination, file_name)) else: # Copy the file from source to destination shutil.copy2(full_file_name, destination)
How do I copy all folder contents from one location to another location in Python?
I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL things ... i need solution to this problem.
[ "Here is one way to do this using the shutil module in Python:\nimport shutil\n\n# Replace the source and destination paths with the appropriate paths on your system\nsrc_dir = \"C:\\\\source\\\\folder\"\ndst_dir = \"C:\\\\destination\\\\folder\"\n\n# Use the shutil.copytree function to copy everything from the source directory to the destination directory\nshutil.copytree(src_dir, dst_dir)\n\nThis will copy all files and subdirectories from src_dir to dst_dir. Note that dst_dir must not already exist, otherwise the copytree function will raise an error.\nYou can also use the copy function from the shutil module to copy individual files. For example:\nimport shutil\n\n# Replace the source and destination paths with the appropriate paths on your system\nsrc_file = \"C:\\\\source\\\\folder\\\\file.txt\"\ndst_file = \"C:\\\\destination\\\\folder\\\\file.txt\"\n\n# Use the shutil.copy function to copy the file\nshutil.copy(src_file, dst_file)\n\nThis will copy the file at src_file to the destination at dst_file. If dst_file already exists, it will be overwritten.\nYou can use these functions in a loop to iterate over all files in a directory and copy them to the destination directory. Here is an example:\nimport os\nimport shutil\n\n# Replace the source and destination paths with the appropriate paths on your system\nsrc_dir = \"C:\\\\source\\\\folder\"\ndst_dir = \"C:\\\\destination\\\\folder\"\n\n# Create the destination directory if it does not already exist\nif not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n\n# Iterate over all files in the source directory\nfor filename in os.listdir(src_dir):\n # Construct the full paths for the source and destination files\n src_file = os.path.join(src_dir, filename)\n dst_file = os.path.join(dst_dir, filename)\n \n # Use the shutil.copy function to copy the file\n shutil.copy(src_file, dst_file)\n\n", "import shutil\nimport os\n\n# Path to the directory\nsource = 'C:/path/to/source/folder'\n\n# Path to the destination directory\ndestination = 'C:/path/to/destination/folder'\n\n# Copy contents from source to destination\nshutil.copytree(source, destination)\n\n# List all the files in source directory\nsource_files = os.listdir(source)\n\n# Iterate over all the files in source directory\nfor file_name in source_files:\n # Create full path of file in source directory\n full_file_name = os.path.join(source, file_name)\n # If file is a directory, create corresponding directory in destination\n # directory\n if os.path.isdir(full_file_name):\n shutil.copytree(full_file_name, os.path.join(destination, file_name))\n else:\n # Copy the file from source to destination\n shutil.copy2(full_file_name, destination)\n\n" ]
[ 0, 0 ]
[]
[]
[ "coding_style", "copy", "paste", "python", "windows" ]
stackoverflow_0074679356_coding_style_copy_paste_python_windows.txt
Q: The problem of not being able to change the background color, thickness and position of the texts in the Streamlit Multiple Page App's Side Bar Streamlit Version: 1.13.0 in Homepage.py: import streamlit as st st.set_page_config( page_title= "Multipage App", page_icon="") st.title("Main Page") st.markdown('<style>div[class="css-6qob1r e1fqkh3o3"] {color:black; font-weight: 900; background: url("https://media2.giphy.com/media/46hpy8xB3MiHfruixn/giphy.gif");background-repeat: no-repeat;background-size:350%;} </style>', unsafe_allow_html=True) st.markdown('<style>div[class="css-y3drt2 e1fqkh3o5"] {color:red; } </style>', unsafe_allow_html=True)#NOT WORKING------------------------------------------- I want to change the color, font, and position of the Homepage, Application, and Contact texts. How do I do this? A: You can do this via inline CSS and st.markdown, although it's admittedly hacky. def _set_block_container_style( max_width: int = 1200, max_width_100_percent: bool = False, padding_top: int = 1, padding_right: int = 1, padding_left: int = 1, padding_bottom: int = 1, ): if max_width_100_percent: max_width_str = f"max-width: 100%;" else: max_width_str = f"max-width: {max_width}px;" styl = f""" <style> .reportview-container .main .block-container{{ {max_width_str} padding-top: {padding_top}rem; padding-right: {padding_right}rem; padding-left: {padding_left}rem; padding-bottom: {padding_bottom}rem; }} }} </style> A: You have to pay close attention to the classes to get the right class and also making sure you wrap the css in a valid format in order to get it working. This is a work around which I think should solve your problem. But I am not really sure if there are change in class names in deferent versions of streamlit. st.markdown(""" <style> ul[class="css-wjbhl0 e1fqkh3o9"]{ position: relative; padding-top: 2rem; display: flex; justify-content: center; flex-direction: column; align-items: center; } .css-17lntkn { font-weight: bold; font-size: 20px; color: yellow; } .css-pkbazv { font-weight: bold; font-size: 20px; } </style>""", unsafe_allow_html=True)
The problem of not being able to change the background color, thickness and position of the texts in the Streamlit Multiple Page App's Side Bar
Streamlit Version: 1.13.0 in Homepage.py: import streamlit as st st.set_page_config( page_title= "Multipage App", page_icon="") st.title("Main Page") st.markdown('<style>div[class="css-6qob1r e1fqkh3o3"] {color:black; font-weight: 900; background: url("https://media2.giphy.com/media/46hpy8xB3MiHfruixn/giphy.gif");background-repeat: no-repeat;background-size:350%;} </style>', unsafe_allow_html=True) st.markdown('<style>div[class="css-y3drt2 e1fqkh3o5"] {color:red; } </style>', unsafe_allow_html=True)#NOT WORKING------------------------------------------- I want to change the color, font, and position of the Homepage, Application, and Contact texts. How do I do this?
[ "You can do this via inline CSS and st.markdown, although it's admittedly hacky.\ndef _set_block_container_style(\n max_width: int = 1200,\n max_width_100_percent: bool = False,\n padding_top: int = 1,\n padding_right: int = 1,\n padding_left: int = 1,\n padding_bottom: int = 1,\n):\n\nif max_width_100_percent:\n max_width_str = f\"max-width: 100%;\"\nelse:\n max_width_str = f\"max-width: {max_width}px;\"\n \nstyl = f\"\"\"\n <style>\n .reportview-container .main .block-container{{\n {max_width_str}\n padding-top: {padding_top}rem;\n padding-right: {padding_right}rem;\n padding-left: {padding_left}rem;\n padding-bottom: {padding_bottom}rem;\n }}\n }}\n </style>\n\n", "You have to pay close attention to the classes to get the right class and also making sure you wrap the css in a valid format in order to get it working.\nThis is a work around which I think should solve your problem. But I am not really sure if there are change in class names in deferent versions of streamlit.\nst.markdown(\"\"\"\n <style>\n ul[class=\"css-wjbhl0 e1fqkh3o9\"]{\n position: relative;\n padding-top: 2rem;\n display: flex;\n justify-content: center;\n flex-direction: column;\n align-items: center;\n }\n \n .css-17lntkn {\n font-weight: bold;\n font-size: 20px;\n color: yellow;\n }\n \n .css-pkbazv {\n font-weight: bold;\n font-size: 20px;\n }\n </style>\"\"\", unsafe_allow_html=True)\n\n" ]
[ 0, 0 ]
[]
[]
[ "css", "html", "python", "python_3.x", "streamlit" ]
stackoverflow_0074551058_css_html_python_python_3.x_streamlit.txt
Q: Cant find a path to java.exe to start SonarQube Here is the path to StartSonar batch file: C:\sonarqube\sonarqube-9.7.1.62043\bin\windows-x86-64>StartSonar.bat And here is my JAVA_HOME environment variable path: C:\Program Files\Java\jdk1.8.0_291\bin I use the same path to setup SONAR_JAVA_PATH environment variable but all I get is: Starting SonarQube... '"C:\Program Files\Java\jdk1.8.0_291\bin"' is not recognized as an internal or external command, operable program or batch file. I experimented with different paths to java.exe file, but nothing was working. Here is the directory content of bin file in JAVA_HOME path: 13.10.2021. 10:56 20.224 appletviewer.exe 13.10.2021. 10:56 20.224 extcheck.exe 13.10.2021. 10:56 20.224 idlj.exe 13.10.2021. 10:56 41.216 jabswitch.exe 13.10.2021. 10:56 20.224 jar.exe 13.10.2021. 10:56 20.224 jarsigner.exe 13.10.2021. 10:56 20.224 java-rmi.exe 13.10.2021. 10:56 276.224 java.exe 13.10.2021. 10:56 20.224 javac.exe 13.10.2021. 10:56 20.224 javadoc.exe 13.10.2021. 10:56 157.440 javafxpackager.exe 13.10.2021. 10:56 20.224 javah.exe 13.10.2021. 10:56 20.224 javap.exe //other exe files related to jdk You see that there is java.exe file here, so I really don't know where to go from here. I did restart cmd after setting env variable. As requested, here is the output from this commandline, @For %G In (java StartSonar.bat) Do @Echo %~$PATH:G, entered within my working Command Prompt window: StartSonar.bat was unexpected at this time. The output of commandline Path: PATH=C:\Program Files\Eclipse Adoptium\jdk-17.0.5.8-hotspot\bin;C:\Program Files\Java\jdk1.8.0_291\bin;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\PostgreSQL\14\bin;C:\Program Files\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Azure Data Studio\bin;C:\Program Files\dotnet\;C:\msys64\mingw64\bin;C:\Users\pk\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Azure Data Studio\bin;C:\Users\pk\.dotnet\tools;C:\Users\pk\AppData\Local\GitHubDesktop\bin A: This is a temporary post, not an answer. I have submitted it, only to assist you to fix your PATH environment variable. Open the GUI for your environment variables, starting with the System environment, delete everything in the box. Now repopulate it with the following, exactly as below, in the same order. %SystemRoot%\System32 %SystemRoot% %SystemRoot%\System32\Wbem %SystemRoot%\System32\WindowsPowerShell\v1.0 %SystemRoot%\System32\OpenSSH %ProgramFiles%\NVIDIA Corporation\NVIDIA NvDLISR %SystemDrive%\msys64\mingw64\bin %ProgramFiles%\nodejs %ProgramFiles%\dotnet %ProgramFiles%\Java\jdk1.8.0_291\bin %ProgramFiles%\Git\cmd %ProgramFiles%\Azure Data Studio\bin %ProgramFiles%\PostgreSQL\14\bin %ProgramFiles%\Eclipse Adoptium\jdk-17.0.5.8-hotspot\bin %ProgramFiles%\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn %ProgramFiles%\Microsoft SQL Server\150\Tools\Binn %ProgramFiles(x86)%\Microsoft SQL Server\150\Tools\Binn %ProgramFiles%\Microsoft SQL Server\150\DTS\Binn %ProgramFiles(x86)%\Microsoft SQL Server\150\DTS\Binn Now switch to the User environment, delete everything in the box, then repopulate it with the following, exactly as below, in the same order. %LocalAppData%\Microsoft\WindowsApps %LocalAppData%\Programs\Microsoft VS Code\bin %UserProfile%\.dotnet\tools %LocalAppData%\GitHubDesktop\bin Now, in your new cmd.exe instances, you should have your environment uncorrupted, and containing the correct/wanted paths.
Cant find a path to java.exe to start SonarQube
Here is the path to StartSonar batch file: C:\sonarqube\sonarqube-9.7.1.62043\bin\windows-x86-64>StartSonar.bat And here is my JAVA_HOME environment variable path: C:\Program Files\Java\jdk1.8.0_291\bin I use the same path to setup SONAR_JAVA_PATH environment variable but all I get is: Starting SonarQube... '"C:\Program Files\Java\jdk1.8.0_291\bin"' is not recognized as an internal or external command, operable program or batch file. I experimented with different paths to java.exe file, but nothing was working. Here is the directory content of bin file in JAVA_HOME path: 13.10.2021. 10:56 20.224 appletviewer.exe 13.10.2021. 10:56 20.224 extcheck.exe 13.10.2021. 10:56 20.224 idlj.exe 13.10.2021. 10:56 41.216 jabswitch.exe 13.10.2021. 10:56 20.224 jar.exe 13.10.2021. 10:56 20.224 jarsigner.exe 13.10.2021. 10:56 20.224 java-rmi.exe 13.10.2021. 10:56 276.224 java.exe 13.10.2021. 10:56 20.224 javac.exe 13.10.2021. 10:56 20.224 javadoc.exe 13.10.2021. 10:56 157.440 javafxpackager.exe 13.10.2021. 10:56 20.224 javah.exe 13.10.2021. 10:56 20.224 javap.exe //other exe files related to jdk You see that there is java.exe file here, so I really don't know where to go from here. I did restart cmd after setting env variable. As requested, here is the output from this commandline, @For %G In (java StartSonar.bat) Do @Echo %~$PATH:G, entered within my working Command Prompt window: StartSonar.bat was unexpected at this time. The output of commandline Path: PATH=C:\Program Files\Eclipse Adoptium\jdk-17.0.5.8-hotspot\bin;C:\Program Files\Java\jdk1.8.0_291\bin;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\PostgreSQL\14\bin;C:\Program Files\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\Tools\Binn\;C:\Program Files\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files\Azure Data Studio\bin;C:\Program Files\dotnet\;C:\msys64\mingw64\bin;C:\Users\pk\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Azure Data Studio\bin;C:\Users\pk\.dotnet\tools;C:\Users\pk\AppData\Local\GitHubDesktop\bin
[ "This is a temporary post, not an answer. I have submitted it, only to assist you to fix your PATH environment variable.\nOpen the GUI for your environment variables, starting with the System environment, delete everything in the box. Now repopulate it with the following, exactly as below, in the same order.\n%SystemRoot%\\System32\n%SystemRoot%\n%SystemRoot%\\System32\\Wbem\n%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\n%SystemRoot%\\System32\\OpenSSH\n%ProgramFiles%\\NVIDIA Corporation\\NVIDIA NvDLISR\n%SystemDrive%\\msys64\\mingw64\\bin\n%ProgramFiles%\\nodejs\n%ProgramFiles%\\dotnet\n%ProgramFiles%\\Java\\jdk1.8.0_291\\bin\n%ProgramFiles%\\Git\\cmd\n%ProgramFiles%\\Azure Data Studio\\bin\n%ProgramFiles%\\PostgreSQL\\14\\bin\n%ProgramFiles%\\Eclipse Adoptium\\jdk-17.0.5.8-hotspot\\bin\n%ProgramFiles%\\Microsoft SQL Server\\Client SDK\\ODBC\\170\\Tools\\Binn\n%ProgramFiles%\\Microsoft SQL Server\\150\\Tools\\Binn\n%ProgramFiles(x86)%\\Microsoft SQL Server\\150\\Tools\\Binn\n%ProgramFiles%\\Microsoft SQL Server\\150\\DTS\\Binn\n%ProgramFiles(x86)%\\Microsoft SQL Server\\150\\DTS\\Binn\n\nNow switch to the User environment, delete everything in the box, then repopulate it with the following, exactly as below, in the same order.\n%LocalAppData%\\Microsoft\\WindowsApps\n%LocalAppData%\\Programs\\Microsoft VS Code\\bin\n%UserProfile%\\.dotnet\\tools\n%LocalAppData%\\GitHubDesktop\\bin\n\nNow, in your new cmd.exe instances, you should have your environment uncorrupted, and containing the correct/wanted paths.\n" ]
[ 0 ]
[]
[]
[ "batch_file", "cmd", "sonarqube", "windows" ]
stackoverflow_0074677538_batch_file_cmd_sonarqube_windows.txt
Q: RESOLVED - Spring Boot Starter Mail - failed to access class com.sun.activation.registries.LogSupport from class javax.activation.MimetypesFileTypeMap I want to share the solution for above issue when using Spring Boot Starter Mail and attempt to create instance of MimeMessageHelper results in exception: failed to access class com.sun.activation.registries.LogSupport from class javax.activation.MimetypesFileTypeMap The issue is behind the jaxb-core dependency in version 4.0.0 which brings angus-activation library dependency. The library if loaded first doesn't have a public class of LogSupport. The correct source of LogSupport is from com.sun.activation:jakarta.activation library. Solution is to exclude the following in jaxb-core dependency: <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>4.0.0</version> <exclusions> <exclusion> <groupId>org.eclipse.angus</groupId> <artifactId>angus-activation</artifactId> </exclusion> </exclusions> </dependency> At the same time the following dependency should be available: <dependency> <groupId>com.sun.activation</groupId> <artifactId>jakarta.activation</artifactId> <version>2.0.1</version> </dependency> A: add <dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> A: Downgrade jaxws-rt to version 2.3.1 solve the problem for me A: I ran into this error when I used spring boot 3.0.0. Downgrading to 2.7.5 solved the problem by itself
RESOLVED - Spring Boot Starter Mail - failed to access class com.sun.activation.registries.LogSupport from class javax.activation.MimetypesFileTypeMap
I want to share the solution for above issue when using Spring Boot Starter Mail and attempt to create instance of MimeMessageHelper results in exception: failed to access class com.sun.activation.registries.LogSupport from class javax.activation.MimetypesFileTypeMap The issue is behind the jaxb-core dependency in version 4.0.0 which brings angus-activation library dependency. The library if loaded first doesn't have a public class of LogSupport. The correct source of LogSupport is from com.sun.activation:jakarta.activation library. Solution is to exclude the following in jaxb-core dependency: <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>4.0.0</version> <exclusions> <exclusion> <groupId>org.eclipse.angus</groupId> <artifactId>angus-activation</artifactId> </exclusion> </exclusions> </dependency> At the same time the following dependency should be available: <dependency> <groupId>com.sun.activation</groupId> <artifactId>jakarta.activation</artifactId> <version>2.0.1</version> </dependency>
[ "add\n<dependency>\n <groupId>jakarta.xml.bind</groupId>\n <artifactId>jakarta.xml.bind-api</artifactId>\n <version>4.0.0</version>\n</dependency>\n\n<dependency>\n <groupId>javax.xml.bind</groupId>\n <artifactId>jaxb-api</artifactId>\n <version>2.3.1</version>\n</dependency>\n\n", "Downgrade jaxws-rt to version 2.3.1 solve the problem for me\n", "I ran into this error when I used spring boot 3.0.0. Downgrading to 2.7.5 solved the problem by itself\n" ]
[ 0, 0, 0 ]
[]
[]
[ "jaxb", "spring_boot" ]
stackoverflow_0073034101_jaxb_spring_boot.txt
Q: Casting `std::unique_ptr` Is there any problem in performing dynamic casting via the following function? template<typename Base, typename Derived> requires std::is_convertible_v<Derived&, Base&> && std::is_polymorphic_v<Base> inline std::unique_ptr<Derived> cast_to(std::unique_ptr<Base>&& ptr) { return std::unique_ptr<Derived>(dynamic_cast<Derived*>(ptr.release())); } A: Yes, your function can easily leak memory if the cast fails. Consider the following: struct Base { virtual ~Base() = default; }; struct Derived1 : Base {}; struct Derived2 : Base {}; int main() { std::unique_ptr<Base> bp = std::make_unique<Derived1>(); // bp does not point to a Derived2, so this cast will fail auto d2p = cast_to<Base, Derived2>(std::move(bp)); std::cout << bp.get() << '\n'; // 0 std::cout << d2p.get() << '\n'; // also 0; object was leaked } Demo From this snippet you can also see another small issue: because of the order of the template parameters you have to supply them both. You can't let the compiler deduce Base because it comes before Derived. With both of those issues in mind, the following would be a better implementation: template<typename Derived, typename Base> // swap the order of template parameters requires std::is_convertible_v<Derived&, Base&> && std::is_polymorphic_v<Base> inline std::unique_ptr<Derived> cast_to(std::unique_ptr<Base>&& ptr) { Derived* d = dynamic_cast<Derived*>(ptr.get()); if (d) { ptr.release(); return std::unique_ptr<Derived>(d); } return nullptr; // object is still owned by ptr } This fixes both of the above issues: int main() { std::unique_ptr<Base> bp = std::make_unique<Derived1>(); // No need to explicitly specify Base; the compiler can deduce that itself auto d2p = cast_to<Derived2>(std::move(bp)); std::cout << bp.get() << '\n'; // not 0; no leak std::cout << d2p.get() << '\n'; // 0 } Demo
Casting `std::unique_ptr`
Is there any problem in performing dynamic casting via the following function? template<typename Base, typename Derived> requires std::is_convertible_v<Derived&, Base&> && std::is_polymorphic_v<Base> inline std::unique_ptr<Derived> cast_to(std::unique_ptr<Base>&& ptr) { return std::unique_ptr<Derived>(dynamic_cast<Derived*>(ptr.release())); }
[ "Yes, your function can easily leak memory if the cast fails. Consider the following:\nstruct Base\n{\n virtual ~Base() = default;\n};\n\nstruct Derived1 : Base {};\nstruct Derived2 : Base {};\n\nint main()\n{\n std::unique_ptr<Base> bp = std::make_unique<Derived1>();\n\n // bp does not point to a Derived2, so this cast will fail\n auto d2p = cast_to<Base, Derived2>(std::move(bp));\n std::cout << bp.get() << '\\n'; // 0\n std::cout << d2p.get() << '\\n'; // also 0; object was leaked\n}\n\nDemo\nFrom this snippet you can also see another small issue: because of the order of the template parameters you have to supply them both. You can't let the compiler deduce Base because it comes before Derived.\n\nWith both of those issues in mind, the following would be a better implementation:\ntemplate<typename Derived, typename Base> // swap the order of template parameters\n requires std::is_convertible_v<Derived&, Base&> &&\n std::is_polymorphic_v<Base>\ninline std::unique_ptr<Derived> cast_to(std::unique_ptr<Base>&& ptr)\n{\n Derived* d = dynamic_cast<Derived*>(ptr.get());\n if (d) {\n ptr.release();\n return std::unique_ptr<Derived>(d);\n }\n return nullptr; // object is still owned by ptr\n}\n\nThis fixes both of the above issues:\nint main()\n{\n std::unique_ptr<Base> bp = std::make_unique<Derived1>();\n\n // No need to explicitly specify Base; the compiler can deduce that itself\n auto d2p = cast_to<Derived2>(std::move(bp));\n std::cout << bp.get() << '\\n'; // not 0; no leak\n std::cout << d2p.get() << '\\n'; // 0\n}\n\nDemo\n" ]
[ 2 ]
[]
[]
[ "c++", "casting", "dynamic_cast", "unique_ptr" ]
stackoverflow_0074679162_c++_casting_dynamic_cast_unique_ptr.txt
Q: Outlook Security, interop NET reference? I am attempting to create a standalone application that accesses Outlook email details. Specifically the Subject, Sender, and Body of the MailItem. I cannot for the life of me figure out why sometimes Outlook will prompt the user to allow access (as in, getting the "A program is trying to access email address information....Allow Access for x Minutes message box) and sometimes NOT. This irregularity is across different attempts at making an application over the weeks, so I am thinking that maybe there is something different with the references I am adding or object use? I have installed the Microsoft Office 2010 interop assemblies and adding the .NET reference of Microsoft.Office.Interop.Outlook version 14.0.0.0 Here is a very basic snippet of code that does cause the diaglog: using System; <br/> using System.Collections.Generic; <br/> using System.Linq; <br/> using System.Text; <br/> using Microsoft.Office.Interop.Outlook; <br/> namespace OutlookTest { class Program { static void Main(string[] args) { Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace olNS = olApp.GetNamespace("MAPI"); MAPIFolder oFolder = olNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox); foreach (object item in oFolder.Items) { if (item is MailItem) { MailItem i = (MailItem)item; Console.WriteLine("{0}", i.Body); } } Console.ReadLine(); } } } What am I doing wrong here? A: You dont do anything wrong, this is outlook security alert which is good for user/company. I had similar issue previous year. Options I remember so far: You can create a trusted microsoft addin as Remou mentioned or you can add yourself as trusted publisher or you can add a visual basic script into Outlook which you can call from your application. A: In the past, if Outlook did not detect an antivirus solution installed on the host machine, you would get the "Security Confirmation Prompt" on every code run. You would get it less if you had a commercial solution. This prompt still comes up today in Office 365, but you can suppress it by changing the "Programmatic Access Security" settings. Below is a before and after. Before, no "commercial" antivirus solution was installed on the host, initially we got the prompt on every code run. The prompt ceased to surface after we set Programmatic Access Security to "Never warn me about..." Once the commercial Antivirus Solution was installed the "Antivirus Status" showed up as "Valid".
Outlook Security, interop NET reference?
I am attempting to create a standalone application that accesses Outlook email details. Specifically the Subject, Sender, and Body of the MailItem. I cannot for the life of me figure out why sometimes Outlook will prompt the user to allow access (as in, getting the "A program is trying to access email address information....Allow Access for x Minutes message box) and sometimes NOT. This irregularity is across different attempts at making an application over the weeks, so I am thinking that maybe there is something different with the references I am adding or object use? I have installed the Microsoft Office 2010 interop assemblies and adding the .NET reference of Microsoft.Office.Interop.Outlook version 14.0.0.0 Here is a very basic snippet of code that does cause the diaglog: using System; <br/> using System.Collections.Generic; <br/> using System.Linq; <br/> using System.Text; <br/> using Microsoft.Office.Interop.Outlook; <br/> namespace OutlookTest { class Program { static void Main(string[] args) { Microsoft.Office.Interop.Outlook.Application olApp = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.NameSpace olNS = olApp.GetNamespace("MAPI"); MAPIFolder oFolder = olNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox); foreach (object item in oFolder.Items) { if (item is MailItem) { MailItem i = (MailItem)item; Console.WriteLine("{0}", i.Body); } } Console.ReadLine(); } } } What am I doing wrong here?
[ "You dont do anything wrong, this is outlook security alert which is good for user/company. I had similar issue previous year. Options I remember so far: \nYou can create a trusted microsoft addin as Remou mentioned or you can add yourself as trusted publisher or you can add a visual basic script into Outlook which you can call from your application.\n", "In the past, if Outlook did not detect an antivirus solution installed on the host machine, you would get the \"Security Confirmation Prompt\" on every code run. You would get it less if you had a commercial solution.\nThis prompt still comes up today in Office 365, but you can suppress it by changing the \"Programmatic Access Security\" settings. Below is a before and after.\nBefore, no \"commercial\" antivirus solution was installed on the host, initially we got the prompt on every code run. The prompt ceased to surface after we set Programmatic Access Security to \"Never warn me about...\"\n\nOnce the commercial Antivirus Solution was installed the \"Antivirus Status\" showed up as \"Valid\".\n\n" ]
[ 0, 0 ]
[]
[]
[ "interop", "outlook" ]
stackoverflow_0011892884_interop_outlook.txt
Q: Plotly imshow reversing y labels reverses the image I'd like to visualize a 20x20 matrix, where top left point is (-10, 9) and lower right point is (9, -10). So the x is increasing from left to right and y is decreasing from top to bottom. So my idea was to pass x labels as a list: [-10, -9 ... 9, 9] and y labels as [9, 8 ... -9, -10]. This worked as intended in seaborn (matplotlib), however doing so in plotly just reverses the image vertically. Here's the code: import numpy as np import plotly.express as px img = np.arange(20**2).reshape((20, 20)) fig = px.imshow(img, x=list(range(-10, 10)), y=list(range(-10, 10)), ) fig.show() import numpy as np import plotly.express as px img = np.arange(20**2).reshape((20, 20)) fig = px.imshow(img, x=list(range(-10, 10)), y=list(reversed(range(-10, 10))), ) fig.show() Why is this happening and how can I fix it? EDIT: Adding seaborn code to see the difference. As you can see, reversing the range for labels only changes the labels and has no effect on the image whatsoever, this is the effect I want in plotly. import seaborn as sns import numpy as np img = np.arange(20**2).reshape((20, 20)) sns.heatmap(img, xticklabels=list(range(-10, 10)), yticklabels=list(range(-10, 10)) ) import seaborn as sns import numpy as np img = np.arange(20**2).reshape((20, 20)) sns.heatmap(img, xticklabels=list(range(-10, 10)), yticklabels=list(reversed(range(-10, 10))) ) A: To get the desired visualization in plotly, you will need to specify the x and y values manually. Instead of passing in the labels as a list, you should specify the x and y values as a list of tuples, like so: x = [(-10, 9), (-9, 8), ... (9, -10)] y = [(-10, 9), (-9, 8), ... (9, -10)] This should produce the desired visualization. A: As I mentioned in my comment, the internal representation of px.imshow() is a heatmap. I coded your objective with a heatmap in a graph object. I didn't change this for any clear reason, I just took a different approach because I couldn't achieve it with px.imshow(). import plotly.graph_objects as go img = np.arange(20**2).reshape((20, 20)) fig = go.Figure(data=go.Heatmap(z=img.tolist()[::-1])) fig.update_yaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)]) fig.update_xaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)]) fig.update_layout(autosize=False, height=500, width=500) fig.show() A: It looks like the issue is that the y values in the px.imshow() function are being interpreted as the actual y-values for the data points in your matrix, rather than labels for the y-axis. Therefore, when you provide y=list(reversed(range(-10, 10))), the y-values of your data points are being reversed, resulting in the vertical reversal of the image. One way to fix this is to use the yaxis_title argument in the px.imshow() function to specify the title for the y-axis, and then use the tickvals and ticktext arguments to specify the values and labels for the y-axis ticks, respectively. For example: import numpy as np import plotly.express as px img = np.arange(20**2).reshape((20, 20)) y_values = list(range(-10, 10)) fig = px.imshow(img, x=list(range(-10, 10)), yaxis_title="y-axis", tickvals=y_values, ticktext=reversed(y_values), ) fig.show() This should produce an image where the y-axis labels are in the correct order, without reversing the image.
Plotly imshow reversing y labels reverses the image
I'd like to visualize a 20x20 matrix, where top left point is (-10, 9) and lower right point is (9, -10). So the x is increasing from left to right and y is decreasing from top to bottom. So my idea was to pass x labels as a list: [-10, -9 ... 9, 9] and y labels as [9, 8 ... -9, -10]. This worked as intended in seaborn (matplotlib), however doing so in plotly just reverses the image vertically. Here's the code: import numpy as np import plotly.express as px img = np.arange(20**2).reshape((20, 20)) fig = px.imshow(img, x=list(range(-10, 10)), y=list(range(-10, 10)), ) fig.show() import numpy as np import plotly.express as px img = np.arange(20**2).reshape((20, 20)) fig = px.imshow(img, x=list(range(-10, 10)), y=list(reversed(range(-10, 10))), ) fig.show() Why is this happening and how can I fix it? EDIT: Adding seaborn code to see the difference. As you can see, reversing the range for labels only changes the labels and has no effect on the image whatsoever, this is the effect I want in plotly. import seaborn as sns import numpy as np img = np.arange(20**2).reshape((20, 20)) sns.heatmap(img, xticklabels=list(range(-10, 10)), yticklabels=list(range(-10, 10)) ) import seaborn as sns import numpy as np img = np.arange(20**2).reshape((20, 20)) sns.heatmap(img, xticklabels=list(range(-10, 10)), yticklabels=list(reversed(range(-10, 10))) )
[ "To get the desired visualization in plotly, you will need to specify the x and y values manually. Instead of passing in the labels as a list, you should specify the x and y values as a list of tuples, like so:\nx = [(-10, 9), (-9, 8), ... (9, -10)]\ny = [(-10, 9), (-9, 8), ... (9, -10)]\n\nThis should produce the desired visualization.\n", "As I mentioned in my comment, the internal representation of px.imshow() is a heatmap. I coded your objective with a heatmap in a graph object. I didn't change this for any clear reason, I just took a different approach because I couldn't achieve it with px.imshow().\nimport plotly.graph_objects as go\n\nimg = np.arange(20**2).reshape((20, 20))\n\nfig = go.Figure(data=go.Heatmap(z=img.tolist()[::-1]))\n\nfig.update_yaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_xaxes(tickvals=np.arange(0, 20, 1), ticktext=[str(x) for x in np.arange(-10, 10, 1)])\nfig.update_layout(autosize=False, height=500, width=500)\nfig.show()\n\n\n", "It looks like the issue is that the y values in the px.imshow() function are being interpreted as the actual y-values for the data points in your matrix, rather than labels for the y-axis. Therefore, when you provide y=list(reversed(range(-10, 10))), the y-values of your data points are being reversed, resulting in the vertical reversal of the image.\nOne way to fix this is to use the yaxis_title argument in the px.imshow() function to specify the title for the y-axis, and then use the tickvals and ticktext arguments to specify the values and labels for the y-axis ticks, respectively.\nFor example:\nimport numpy as np\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\n\ny_values = list(range(-10, 10))\n\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n yaxis_title=\"y-axis\",\n tickvals=y_values,\n ticktext=reversed(y_values),\n )\nfig.show()\n\nThis should produce an image where the y-axis labels are in the correct order, without reversing the image.\n" ]
[ 2, 2, 0 ]
[ "import plotly.graph_objects as go\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n y=list(range(10, 30, 1)),\n)\n\nfig.show()\n\nOutput:\n\n" ]
[ -1 ]
[ "plotly", "plotly_python", "python" ]
stackoverflow_0074601283_plotly_plotly_python_python.txt
Q: Unuderstanding testbenching of Lattice Semiconductor IP verilog modules - MIPI CSI2-DPHY module My development environment is from Lattice Semiconductor EDA (Radiant Software). I have included an IP implementing CSI2-DPHY interface. When I generate the module only verilog files are generated. The generated files include: RTL file CSI2-DPHY.v which is the main module. This has the port list, but then it is encrypted; Testbench files tb_top.v, csi2_model.v, dsi_model.v, clck_driver.v, bus_driver.v Constraint file CSI2_DPHY.ldc Configuration file CSI2_DPHY.cfg When I testbench the file I use ModelSim but it must be called from within the Radiant Software otherwise simulation fails to load the IP design (it gives some error about the missing GSR module within the tb_top.v module). I successfully tested the testbench file and I got the signals I was expecting, like the clock and data signals, the header and footer packets, the pixels themselves, etc... However, I did not understand how the main module is instantiated within the top_level.v. This is the CSI_DPHY port list: module CSI2_DPHY //port list (sync_clk_i, sync_rst_i, clk_byte_o, clk_byte_hs_o, clk_lp_ctrl_i, clk_byte_fr_i, reset_n_i, reset_lp_n_i, reset_byte_n_i, reset_byte_fr_n_i, clk_p_io, clk_n_io, d_p_io, d_n_io, bd_o, payload_en_o, payload_o, dt_o, vc_o, wc_o, ecc_o, ref_dt_i, tx_rdy_i, pd_dphy_i, sp_en_o, lp_en_o, lp_av_en_o) ; //port declaration input sync_clk_i ; input sync_rst_i ; output clk_byte_o ; output clk_byte_hs_o ; input clk_lp_ctrl_i ; input clk_byte_fr_i ; input reset_n_i ; input reset_lp_n_i ; input reset_byte_n_i ; input reset_byte_fr_n_i ; inout clk_p_io ; inout clk_n_io ; inout [0:0] d_p_io ; inout [0:0] d_n_io ; output [7:0] bd_o ; output payload_en_o ; output [7:0] payload_o ; output [5:0] dt_o ; output [1:0] vc_o ; output [15:0] wc_o ; output [7:0] ecc_o ; input [5:0] ref_dt_i ; input tx_rdy_i ; input pd_dphy_i ; output sp_en_o ; output lp_en_o ; output lp_av_en_o ; None of the testbench modules(tb_top.v, csi2_model, etc...) have trace of any CSI2-DPHY instantiation. So it's mysterious to me how the CSI2-DPHY module is actually included in the simulation enviornment. I would be very glad if somebody reading this can help me out at understanding this. A: i'm working currently with the ip core v1.5 in lattice diamond and the testbench instantiates the module with the line `include"dut_inst.v" of the testbench and the file dut_inst.v contains the instantiation. keep in mind, that you have to pay for the ip core in radiant. it's only free to use in diamond. -> https://www.latticesemi.com/en/Products/DesignSoftwareAndIP/IntellectualProperty/IPCore/IPCores04/CSI2DSIDPHYTransmitter
Unuderstanding testbenching of Lattice Semiconductor IP verilog modules - MIPI CSI2-DPHY module
My development environment is from Lattice Semiconductor EDA (Radiant Software). I have included an IP implementing CSI2-DPHY interface. When I generate the module only verilog files are generated. The generated files include: RTL file CSI2-DPHY.v which is the main module. This has the port list, but then it is encrypted; Testbench files tb_top.v, csi2_model.v, dsi_model.v, clck_driver.v, bus_driver.v Constraint file CSI2_DPHY.ldc Configuration file CSI2_DPHY.cfg When I testbench the file I use ModelSim but it must be called from within the Radiant Software otherwise simulation fails to load the IP design (it gives some error about the missing GSR module within the tb_top.v module). I successfully tested the testbench file and I got the signals I was expecting, like the clock and data signals, the header and footer packets, the pixels themselves, etc... However, I did not understand how the main module is instantiated within the top_level.v. This is the CSI_DPHY port list: module CSI2_DPHY //port list (sync_clk_i, sync_rst_i, clk_byte_o, clk_byte_hs_o, clk_lp_ctrl_i, clk_byte_fr_i, reset_n_i, reset_lp_n_i, reset_byte_n_i, reset_byte_fr_n_i, clk_p_io, clk_n_io, d_p_io, d_n_io, bd_o, payload_en_o, payload_o, dt_o, vc_o, wc_o, ecc_o, ref_dt_i, tx_rdy_i, pd_dphy_i, sp_en_o, lp_en_o, lp_av_en_o) ; //port declaration input sync_clk_i ; input sync_rst_i ; output clk_byte_o ; output clk_byte_hs_o ; input clk_lp_ctrl_i ; input clk_byte_fr_i ; input reset_n_i ; input reset_lp_n_i ; input reset_byte_n_i ; input reset_byte_fr_n_i ; inout clk_p_io ; inout clk_n_io ; inout [0:0] d_p_io ; inout [0:0] d_n_io ; output [7:0] bd_o ; output payload_en_o ; output [7:0] payload_o ; output [5:0] dt_o ; output [1:0] vc_o ; output [15:0] wc_o ; output [7:0] ecc_o ; input [5:0] ref_dt_i ; input tx_rdy_i ; input pd_dphy_i ; output sp_en_o ; output lp_en_o ; output lp_av_en_o ; None of the testbench modules(tb_top.v, csi2_model, etc...) have trace of any CSI2-DPHY instantiation. So it's mysterious to me how the CSI2-DPHY module is actually included in the simulation enviornment. I would be very glad if somebody reading this can help me out at understanding this.
[ "i'm working currently with the ip core v1.5 in lattice diamond and the testbench instantiates the module with the line `include\"dut_inst.v\" of the testbench and the file dut_inst.v contains the instantiation.\nkeep in mind, that you have to pay for the ip core in radiant. it's only free to use in diamond. -> https://www.latticesemi.com/en/Products/DesignSoftwareAndIP/IntellectualProperty/IPCore/IPCores04/CSI2DSIDPHYTransmitter\n" ]
[ 0 ]
[]
[]
[ "fpga", "image_processing", "verilog" ]
stackoverflow_0074536144_fpga_image_processing_verilog.txt
Q: Throttling threads in C# I have a situation where I am doing WebAPI calls to a service which sometimes cannot keep up with the load. I'm keeping track of how long the WebAPI takes to respond and how many active threads I have, and when the WebAPI is taking long to respond I want to limit the number of concurrent calls to a specific number (which I'd save in a config). What I was thinking was of using SemaphoreSlim but the problem would be that at that time the number of concurrent threads would most likely be greater than the number I'm limiting to. Is there a neat way of tackling this problem that wouldn't involve reinventing the wheel? A: I have created a library that does just that. It's called SemaphoreSlimThrottling and is available on GitHub and NuGet. Suppose you had 11 concurrent threads and wanted to limit them to 10. SemaphoreSlim doesn't allow you to initialize with an initialCount of -1 (i.e. you need to release 2 before a new one can enter), but with SemaphoreSlimThrottle you can. var mySemaphore = new SemaphoreSlimThrottle(-1, 10); A: One way to solve this problem is to use a SemaphoreSlim object to limit the number of concurrent threads that can access a critical section of code. When a thread wants to enter the critical section, it can call the Wait() method on the SemaphoreSlim object. If the number of threads that are currently in the critical section is less than the maximum number allowed, the thread will be granted access to the critical section and the SemaphoreSlim's internal count will be decremented by 1. Otherwise, the thread will be blocked until another thread leaves the critical section and the SemaphoreSlim's count is incremented. When a thread leaves the critical section, it should call the Release() method on the SemaphoreSlim object to increment the count and potentially unblock another thread that is waiting to enter the critical section. Here is an example of how you could use a SemaphoreSlim object to limit the number of concurrent threads that can access a critical section of code: // Create a SemaphoreSlim object with a maximum count of 10. // This means that at most 10 threads can be in the critical section at the same time. SemaphoreSlim semaphore = new SemaphoreSlim(10); // This is the critical section of code that we want to limit access to. void MakeWebApiCall() { // Acquire a lock on the semaphore. // If the number of threads in the critical section is already at the maximum allowed, // this thread will be blocked until another thread leaves the critical section. semaphore.Wait(); try { // Make the WebAPI call here. // Note that only 10 threads can be in this section of code at the same time. } finally { // Release the lock on the semaphore. // This will increment the semaphore's count and potentially unblock another thread // that is waiting to enter the critical section. semaphore.Release(); } }
Throttling threads in C#
I have a situation where I am doing WebAPI calls to a service which sometimes cannot keep up with the load. I'm keeping track of how long the WebAPI takes to respond and how many active threads I have, and when the WebAPI is taking long to respond I want to limit the number of concurrent calls to a specific number (which I'd save in a config). What I was thinking was of using SemaphoreSlim but the problem would be that at that time the number of concurrent threads would most likely be greater than the number I'm limiting to. Is there a neat way of tackling this problem that wouldn't involve reinventing the wheel?
[ "I have created a library that does just that. It's called SemaphoreSlimThrottling and is available on GitHub and NuGet. Suppose you had 11 concurrent threads and wanted to limit them to 10. SemaphoreSlim doesn't allow you to initialize with an initialCount of -1 (i.e. you need to release 2 before a new one can enter), but with SemaphoreSlimThrottle you can.\nvar mySemaphore = new SemaphoreSlimThrottle(-1, 10);\n\n", "One way to solve this problem is to use a SemaphoreSlim object to limit the number of concurrent threads that can access a critical section of code. When a thread wants to enter the critical section, it can call the Wait() method on the SemaphoreSlim object. If the number of threads that are currently in the critical section is less than the maximum number allowed, the thread will be granted access to the critical section and the SemaphoreSlim's internal count will be decremented by 1. Otherwise, the thread will be blocked until another thread leaves the critical section and the SemaphoreSlim's count is incremented.\nWhen a thread leaves the critical section, it should call the Release() method on the SemaphoreSlim object to increment the count and potentially unblock another thread that is waiting to enter the critical section.\nHere is an example of how you could use a SemaphoreSlim object to limit the number of concurrent threads that can access a critical section of code:\n// Create a SemaphoreSlim object with a maximum count of 10.\n// This means that at most 10 threads can be in the critical section at the same time.\nSemaphoreSlim semaphore = new SemaphoreSlim(10);\n\n// This is the critical section of code that we want to limit access to.\nvoid MakeWebApiCall()\n{\n // Acquire a lock on the semaphore.\n // If the number of threads in the critical section is already at the maximum allowed,\n // this thread will be blocked until another thread leaves the critical section.\n semaphore.Wait();\n\n try\n {\n // Make the WebAPI call here.\n // Note that only 10 threads can be in this section of code at the same time.\n }\n finally\n {\n // Release the lock on the semaphore.\n // This will increment the semaphore's count and potentially unblock another thread\n // that is waiting to enter the critical section.\n semaphore.Release();\n }\n}\n\n" ]
[ 2, 0 ]
[]
[]
[ "api_throttling", "c#", "semaphore", "throttling" ]
stackoverflow_0074679349_api_throttling_c#_semaphore_throttling.txt
Q: Restrict typescript to insure reference to 'any' object's properties is checked I have a JS object myObject, which is of type any (I can't change the type, since it comes from a library). If I try to access a property from myObject I get no errors from typescript, since its type is any. But myObject could be undefined, and cause a crash. Is it possible to get typescript to give an error in this case? For example: console.log(myObject.myProperty) // <-- if myObject is undefined, this will crash. What I would like: console.log(myObject.myProperty) // <-- typescript gives error console.log(myObject?.myProperty) // <-- typescript gives no error Is there a tsconfig for changing this behavior? I am not looking for a solution using type unknown. A: No, TypeScript does not have support for a stricter interpretation of the any type in which member access is disallowed unless it is known to be safe. Nor have I found any existing request for this particular feature. There was a proposal for a --strictAny, which would have been different, but this was eventually closed in microsoft/TypeScript#24737 saying, among other things, that extra complexity around any really didn't seem to be worth it, especially because there are many places in real world code where any is intentionally used as a way to turn off type checking. So it is unlikely that TypeScript will add such functionality. Instead, you could use a linter, like TypeScript ESLint. There is a no-unsafe-member-access rule which "disallows member access on any variable that is typed as any". This will cause the desired error to appear, but it will also cause undesired errors where you have done the proper type check. That is, it is more restrictive than you want: declare const myObject: any; myObject.myProperty // warning: unsafe access myObject?.myProperty // warning: unsafe access ☹ It doesn't look like there's any "perfect" way to proceed. I'd recommend that you copy the value to a variable of a non-any type: type MyAny = { [k: string]: any } | undefined | null; const _myObject: MyAny = myObject _myObject.myProperty; // error _myObject?.myProperty; // okay Or write a type checking function that narrows any to more safely indexable type: function nonNullish(x: any): x is { [k: string]: any } { return x != null; } if (nonNullish(myObject)) { myObject.myProperty // okay } Or maybe even push back on the typings provider for the library and say that any is too loose of a type if the value might really be undefined or null at runtime. (If it can't, then the other option is to just stop worrying about it until and unless it does happen.) TS-ESLint Playground link to code
Restrict typescript to insure reference to 'any' object's properties is checked
I have a JS object myObject, which is of type any (I can't change the type, since it comes from a library). If I try to access a property from myObject I get no errors from typescript, since its type is any. But myObject could be undefined, and cause a crash. Is it possible to get typescript to give an error in this case? For example: console.log(myObject.myProperty) // <-- if myObject is undefined, this will crash. What I would like: console.log(myObject.myProperty) // <-- typescript gives error console.log(myObject?.myProperty) // <-- typescript gives no error Is there a tsconfig for changing this behavior? I am not looking for a solution using type unknown.
[ "No, TypeScript does not have support for a stricter interpretation of the any type in which member access is disallowed unless it is known to be safe. Nor have I found any existing request for this particular feature. There was a proposal for a --strictAny, which would have been different, but this was eventually closed in microsoft/TypeScript#24737 saying, among other things, that extra complexity around any really didn't seem to be worth it, especially because there are many places in real world code where any is intentionally used as a way to turn off type checking. So it is unlikely that TypeScript will add such functionality.\nInstead, you could use a linter, like TypeScript ESLint. There is a no-unsafe-member-access rule which \"disallows member access on any variable that is typed as any\". This will cause the desired error to appear, but it will also cause undesired errors where you have done the proper type check. That is, it is more restrictive than you want:\ndeclare const myObject: any;\nmyObject.myProperty // warning: unsafe access \nmyObject?.myProperty // warning: unsafe access ☹\n\nIt doesn't look like there's any \"perfect\" way to proceed. I'd recommend that you copy the value to a variable of a non-any type:\ntype MyAny = { [k: string]: any } | undefined | null;\nconst _myObject: MyAny = myObject\n_myObject.myProperty; // error\n_myObject?.myProperty; // okay\n\nOr write a type checking function that narrows any to more safely indexable type:\nfunction nonNullish(x: any): x is { [k: string]: any } {\n return x != null;\n}\nif (nonNullish(myObject)) {\n myObject.myProperty // okay\n}\n\nOr maybe even push back on the typings provider for the library and say that any is too loose of a type if the value might really be undefined or null at runtime. (If it can't, then the other option is to just stop worrying about it until and unless it does happen.)\nTS-ESLint Playground link to code\n" ]
[ 0 ]
[]
[]
[ "any", "object", "typescript" ]
stackoverflow_0074678765_any_object_typescript.txt
Q: Why are some properties of my Firebase database undefined? When my character card component loads I receive the below error. TypeError: Cannot read properties of undefined (reading 'attack') The main thing that confuses me is that the character name(userData.name) and profile image(userData.icon) are not undefined. All properties are stored in the same Firebase database. I can't figure out why 2 out of the 4 properties I'm trying to access are undefined. I get the same error if trying to access the defense level. I'm following the Firebase docs for accessing the database under the read data section: https://firebase.google.com/docs/database/web/read-and-write Here is my component code: import { Card, Container, Row, Col } from "react-bootstrap"; import { auth } from "../../components/Utils/firebase"; import { getDatabase, onValue, ref } from "firebase/database"; import { useState, useEffect } from "react"; import classes from "./charCard.module.css"; const CharCard = () => { const userId = auth.currentUser.uid; const db = getDatabase(); const [userData, setUserData] = useState([]); //acceses Firebase useEffect(() => { const userRef = ref(db, "/Users/" + userId); onValue(userRef, (snapshot) => { const data = snapshot.val(); setUserData(data); console.log(data); }); }, []); return ( <Card className={classes.charCard}> <h2 className={classes.charName}>{userData.name}</h2> <Container> <Row> <Col> <img className={classes.charIcon} src={userData.icon} /> </Col> <Col> <Col className={classes.stats}> Attack: {userData.skills.attack.level} </Col> <Col className={classes.stats}> Defense: {userData.skills.defense.level} </Col> </Col> </Row> </Container> </Card> ); }; export default CharCard; Here is the layout of the Firebase Database "Users": { "fAzbjOaHflTTos45CDRu1ITrZs23": { "icon": "crossedswords.png", "name": "Waffle", "skills": { "attack": { "level": 1, "name": "Attack" }, If I comment out the below and let the page load first, and then un-comment it pulls the correct value of "1". <Col className={classes.stats}> Attack: {userData.skills.attack.level} </Col> I've also tried re-writing how I access the Firebase database to not use useEffect, but that hasn't changed anything. I have a feeling that I'm missing something pretty basic. Repo is public at https://github.com/nschroder26/idleWeb if more context is needed. A: I read your code. There are 3 problems with your code. The initial value of userData should be an empty object not an array. You should check if userData is set and then render your UI. You wrote your onValue function in useEffect without any dependency. It means that it runs only once. At that time, auth.currentUser is undefined so userId is undefined too. So you get null for the user data. In order to fix the issue, you should write your logic inside onAuthStateChanged. This will fix your problem: import { Fragment, useState, useEffect } from "react"; import { auth } from "../../components/Utils/firebase"; import { getDatabase, onValue, ref } from "firebase/database"; import CharCard from "../../components/CharCard/charCard"; import { onAuthStateChanged } from "firebase/auth"; const Character = () => { const db = getDatabase(); const [userData, setUserData] = useState({}); //caputures current user from firebase db useEffect(() => { onAuthStateChanged(auth, (currentUser) => { if(currentUser) { const userId = currentUser.uid; const userRef = ref(db, "/Users/" + userId); onValue(userRef, (snapshot) => { const data = snapshot.val(); setUserData(data); console.log(data) }); } }) }, []); return ( <Fragment> <CharCard name={userData?.name} icon={userData?.icon} attack={userData?.skills?.attack?.level} defense={userData?.skills?.defense?.level} /> </Fragment> ); }; export default Character;
Why are some properties of my Firebase database undefined?
When my character card component loads I receive the below error. TypeError: Cannot read properties of undefined (reading 'attack') The main thing that confuses me is that the character name(userData.name) and profile image(userData.icon) are not undefined. All properties are stored in the same Firebase database. I can't figure out why 2 out of the 4 properties I'm trying to access are undefined. I get the same error if trying to access the defense level. I'm following the Firebase docs for accessing the database under the read data section: https://firebase.google.com/docs/database/web/read-and-write Here is my component code: import { Card, Container, Row, Col } from "react-bootstrap"; import { auth } from "../../components/Utils/firebase"; import { getDatabase, onValue, ref } from "firebase/database"; import { useState, useEffect } from "react"; import classes from "./charCard.module.css"; const CharCard = () => { const userId = auth.currentUser.uid; const db = getDatabase(); const [userData, setUserData] = useState([]); //acceses Firebase useEffect(() => { const userRef = ref(db, "/Users/" + userId); onValue(userRef, (snapshot) => { const data = snapshot.val(); setUserData(data); console.log(data); }); }, []); return ( <Card className={classes.charCard}> <h2 className={classes.charName}>{userData.name}</h2> <Container> <Row> <Col> <img className={classes.charIcon} src={userData.icon} /> </Col> <Col> <Col className={classes.stats}> Attack: {userData.skills.attack.level} </Col> <Col className={classes.stats}> Defense: {userData.skills.defense.level} </Col> </Col> </Row> </Container> </Card> ); }; export default CharCard; Here is the layout of the Firebase Database "Users": { "fAzbjOaHflTTos45CDRu1ITrZs23": { "icon": "crossedswords.png", "name": "Waffle", "skills": { "attack": { "level": 1, "name": "Attack" }, If I comment out the below and let the page load first, and then un-comment it pulls the correct value of "1". <Col className={classes.stats}> Attack: {userData.skills.attack.level} </Col> I've also tried re-writing how I access the Firebase database to not use useEffect, but that hasn't changed anything. I have a feeling that I'm missing something pretty basic. Repo is public at https://github.com/nschroder26/idleWeb if more context is needed.
[ "I read your code.\nThere are 3 problems with your code.\n\nThe initial value of userData should be an empty object not an array.\n\nYou should check if userData is set and then render your UI.\n\nYou wrote your onValue function in useEffect without any dependency. It means that it runs only once. At that time, auth.currentUser is undefined so userId is undefined too. So you get null for the user data.\n\n\nIn order to fix the issue, you should write your logic inside onAuthStateChanged.\nThis will fix your problem:\nimport { Fragment, useState, useEffect } from \"react\";\nimport { auth } from \"../../components/Utils/firebase\";\nimport { getDatabase, onValue, ref } from \"firebase/database\";\nimport CharCard from \"../../components/CharCard/charCard\";\nimport { onAuthStateChanged } from \"firebase/auth\";\n\nconst Character = () => {\n const db = getDatabase();\n const [userData, setUserData] = useState({});\n\n //caputures current user from firebase db\n useEffect(() => {\n onAuthStateChanged(auth, (currentUser) => {\n if(currentUser) {\n const userId = currentUser.uid;\n const userRef = ref(db, \"/Users/\" + userId);\n onValue(userRef, (snapshot) => {\n const data = snapshot.val();\n setUserData(data);\n console.log(data)\n });\n }\n })\n }, []);\n\n return (\n <Fragment>\n <CharCard\n name={userData?.name}\n icon={userData?.icon}\n attack={userData?.skills?.attack?.level}\n defense={userData?.skills?.defense?.level}\n />\n </Fragment>\n );\n};\n\nexport default Character;\n\n" ]
[ 2 ]
[]
[]
[ "firebase", "firebase_realtime_database", "reactjs" ]
stackoverflow_0074679306_firebase_firebase_realtime_database_reactjs.txt
Q: Where the .env keys get stored after the nom build command in react? Hello guys I build a react application using Django as the backend and having many keys at.env file. Now when I build the react app with the ‘npm run build’ command it builds the index file with CSS in the build folder. But where it stores all the keys of the .env file which were used in some components. Or its gets build with all the components A: On a client-rendered application (like a standard React app), the build process will embed the actual environment variable values in your bundled code, making it available when serving the build to a hosting server. Reference from the "Create React App" documentation WARNING: Do not store any secrets (such as private API keys) in your React app! Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files. A: when you run npm run build The environment variables are embedded and you can read them at runtime. by loading HTML into memory on the server and replacing placeholders in runtime . check docs for more information
Where the .env keys get stored after the nom build command in react?
Hello guys I build a react application using Django as the backend and having many keys at.env file. Now when I build the react app with the ‘npm run build’ command it builds the index file with CSS in the build folder. But where it stores all the keys of the .env file which were used in some components. Or its gets build with all the components
[ "On a client-rendered application (like a standard React app), the build process will embed the actual environment variable values in your bundled code, making it available when serving the build to a hosting server.\nReference from the \"Create React App\" documentation\n\nWARNING: Do not store any secrets (such as private API keys) in your React app!\n\n\nEnvironment variables are embedded into the build, meaning anyone can\nview them by inspecting your app's files.\n\n", "when you run npm run build The environment variables are embedded and you can read them at runtime. by loading HTML into memory on the server and replacing placeholders in runtime . check docs for more information\n" ]
[ 0, 0 ]
[]
[]
[ "django", "environment_variables", "reactjs", "webpack" ]
stackoverflow_0074678694_django_environment_variables_reactjs_webpack.txt
Q: Unable to connect to the server: dial tcp: lookup MasterIP on 127.0.0.53:53: server misbehaving I am trying to start Kubernetes with 'kubectl apply -f redis.yaml' and I am getting Unable to connect to the server: dial tcp: lookup MasterIP on 127.0.0.53:53: server misbehaving Before, I was receiving The connection to the server localhost:8080 was refused - did you specify the right host or port? This error. I was searching for the solution and someone said trying to use this command export KUBERNETES_MASTER=http://MasterIP:8080 After that, I am receiving the error above? How can I fix this? kubectl cluster-info Kubernetes master is running at 192.168.219.107:6443 KubeDNS is running at 192.168.219.107:6443/api/v1/namespaces/kube-system/services/ my ./kube/config apiVersion: v1 clusters: - cluster: certificate-authority-data: server: https://****:6443 name: kubernetes contexts: - context: cluster: kubernetes user: kubernetes-admin name: kubernetes-admin@kubernetes current-context: kubernetes-admin@kubernetes kind: Config preferences: {} users: - name: kubernetes-admin user: client-certificate-data: client-key-data: A: export KUBERNETES_MASTER=http://MasterIP:8080 is not correct because the port should be 6443 and protocol should be https for external connection coming to Kubernetes API Server. export KUBERNETES_MASTER=https://MasterIP:6443` You seem to have a valid kubeconfig file and so you really don't need to export KUBERNETES_MASTER environment variable. Make sure that the file is located at .kube/config path in your home directory. otherwise point KUBECONFIG environment variable to the path where the kubeconfig file is located. A: i got same issu.. use this one kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
Unable to connect to the server: dial tcp: lookup MasterIP on 127.0.0.53:53: server misbehaving
I am trying to start Kubernetes with 'kubectl apply -f redis.yaml' and I am getting Unable to connect to the server: dial tcp: lookup MasterIP on 127.0.0.53:53: server misbehaving Before, I was receiving The connection to the server localhost:8080 was refused - did you specify the right host or port? This error. I was searching for the solution and someone said trying to use this command export KUBERNETES_MASTER=http://MasterIP:8080 After that, I am receiving the error above? How can I fix this? kubectl cluster-info Kubernetes master is running at 192.168.219.107:6443 KubeDNS is running at 192.168.219.107:6443/api/v1/namespaces/kube-system/services/ my ./kube/config apiVersion: v1 clusters: - cluster: certificate-authority-data: server: https://****:6443 name: kubernetes contexts: - context: cluster: kubernetes user: kubernetes-admin name: kubernetes-admin@kubernetes current-context: kubernetes-admin@kubernetes kind: Config preferences: {} users: - name: kubernetes-admin user: client-certificate-data: client-key-data:
[ "export KUBERNETES_MASTER=http://MasterIP:8080 is not correct because the port should be 6443 and protocol should be https for external connection coming to Kubernetes API Server.\nexport KUBERNETES_MASTER=https://MasterIP:6443`\n\nYou seem to have a valid kubeconfig file and so you really don't need to export KUBERNETES_MASTER environment variable.\nMake sure that the file is located at .kube/config path in your home directory. otherwise point KUBECONFIG environment variable to the path where the kubeconfig file is located.\n", "i got same issu.. use this one kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml\n" ]
[ 2, 0 ]
[]
[]
[ "kubernetes", "ubuntu" ]
stackoverflow_0063326973_kubernetes_ubuntu.txt
Q: Why does this code bit work in clion but doesn't in VS Hi I copied the following code from my linux machine with clion running. But in VS on Windows it seems to cause problems entry_t* find_entry( char* n ) { // TODO (2) int x = strlen(n); char str[x]; for (size_t i = 0; i < strlen(str); i++) { str[i] = toupper(n[i]); } n = &str; for (size_t i = 0; i < list_length; i++) { if (strcmp(n, name_list[i].name) == 0) { return &name_list[i]; } } } VS underlines the x in char str[x]; before the statement do find x was in the brackets of str. I thought finding the length first in another variable would solve the problem VS give the following error Schweregrad Code Beschreibung Projekt Datei Zeile Unterdrückungszustand Fehler (aktiv) E0028 Der Ausdruck muss einen Konstantenwert aufweisen. Names.exe - x64-Debug C:\Users\Eyüp\source\repos\09\main.c 102 trying my best to translate it -> Error(active) E0028 Statement needs to be a constant value A: Your code invokes undefined behaviour: as you do not null terminate the string you call strlen on not null terminated (and initially not initialized string) The logic is also wrong. entry_t* find_entry( const char* n ) { // TODO (2) size_t x = strlen(n); char str[x + 1]; for (size_t i = 0; i <= x; i++) { str[i] = toupper((unsigned char)n[i]); } str[x] = 0; for (size_t i = 0; i < list_length; i++) { if (strcmp(str, name_list[i].name) == 0) { return &name_list[i]; } } return NULL; } You need to return something if the sting was not found. To use VLAs in VS How to use Visual Studio as an IDE with variable length array(VLA) working? A: Variable-length arrays (i.e. arrays whose size is not known at compile-time) are not supported in MSVC because they don't care. Hence you need to use malloc and friends instead. However that is not the only problem in your code: it has multiple undefined behaviours. Here is a suggested fix: entry_t* find_entry( char* n ) { // return value of strlen is of type size_t, not int size_t x = strlen(n); // [x] was wrong, it needs to be [x + 1] for the null terminator! char *str = malloc(x + 1); // do not use strlen again in the loop. In worst case it does need // to go through the entire string looking for the null terminator every time. // You must copy the null terminator, hence i <= x or i < x + 1 for (size_t i = 0; i <= x; i++) { // the argument of toupper needs to be *unsigned char* str[i] = toupper((unsigned char)n[i]); } // why this did even exist? And it has type error anyway // n = &str; for (size_t i = 0; i < list_length; i++) { if (strcmp(str, name_list[i].name) == 0) { // need to free the str... free(str); return &name_list[i]; } } // in both paths... free(str); // add default return value return NULL; }
Why does this code bit work in clion but doesn't in VS
Hi I copied the following code from my linux machine with clion running. But in VS on Windows it seems to cause problems entry_t* find_entry( char* n ) { // TODO (2) int x = strlen(n); char str[x]; for (size_t i = 0; i < strlen(str); i++) { str[i] = toupper(n[i]); } n = &str; for (size_t i = 0; i < list_length; i++) { if (strcmp(n, name_list[i].name) == 0) { return &name_list[i]; } } } VS underlines the x in char str[x]; before the statement do find x was in the brackets of str. I thought finding the length first in another variable would solve the problem VS give the following error Schweregrad Code Beschreibung Projekt Datei Zeile Unterdrückungszustand Fehler (aktiv) E0028 Der Ausdruck muss einen Konstantenwert aufweisen. Names.exe - x64-Debug C:\Users\Eyüp\source\repos\09\main.c 102 trying my best to translate it -> Error(active) E0028 Statement needs to be a constant value
[ "Your code invokes undefined behaviour:\n\nas you do not null terminate the string\nyou call strlen on not null terminated (and initially not initialized string)\n\nThe logic is also wrong.\nentry_t* find_entry( const char* n ) \n{\n // TODO (2)\n size_t x = strlen(n);\n char str[x + 1];\n\n for (size_t i = 0; i <= x; i++)\n {\n str[i] = toupper((unsigned char)n[i]);\n }\n str[x] = 0;\n\n for (size_t i = 0; i < list_length; i++)\n {\n if (strcmp(str, name_list[i].name) == 0)\n {\n return &name_list[i];\n }\n }\n return NULL;\n}\n\nYou need to return something if the sting was not found.\nTo use VLAs in VS How to use Visual Studio as an IDE with variable length array(VLA) working?\n", "Variable-length arrays (i.e. arrays whose size is not known at compile-time) are not supported in MSVC because they don't care. Hence you need to use malloc and friends instead.\nHowever that is not the only problem in your code: it has multiple undefined behaviours. Here is a suggested fix:\nentry_t* find_entry( char* n ) \n{\n // return value of strlen is of type size_t, not int\n size_t x = strlen(n);\n\n // [x] was wrong, it needs to be [x + 1] for the null terminator!\n char *str = malloc(x + 1);\n\n // do not use strlen again in the loop. In worst case it does need \n // to go through the entire string looking for the null terminator every time.\n // You must copy the null terminator, hence i <= x or i < x + 1\n for (size_t i = 0; i <= x; i++)\n {\n // the argument of toupper needs to be *unsigned char*\n str[i] = toupper((unsigned char)n[i]);\n }\n\n // why this did even exist? And it has type error anyway\n // n = &str;\n\n for (size_t i = 0; i < list_length; i++)\n {\n if (strcmp(str, name_list[i].name) == 0)\n {\n // need to free the str...\n free(str);\n return &name_list[i];\n }\n }\n\n // in both paths...\n free(str);\n\n // add default return value\n return NULL;\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "c", "clion", "linux", "visual_studio", "windows" ]
stackoverflow_0074679337_c_clion_linux_visual_studio_windows.txt
Q: Merge corresponding elements from multiple arrays I have below inputs input 1: [{ "id": "3857" }, { "id": "57" }] input 2: [{ "Date": "2022-11-30", "name": "salesorder", "brand": "Apple", "Requests": "111", "price": "917.65" }, { "Date": "2022-11-13", "name": "orders", "brand": "TV", "Requests": "11", "price": "91.60" }] input 3: [{ "count": "3" }, { "count": "4" }] input 4: [{ "stock": "21", "sold": "112" }, { "stock": "2", "sold": "12" }] Desired Output: [{ "id": "3857", "Date": "2022-11-30", "name": "salesorder", "brand": "Apple", "Requests": "111", "price": "917.65", "count": "3", "stock": "21", "sold": "112" }, { "id": "57", "Date": "2022-11-13", "name": "orders", "brand": "TV", "Requests": "11", "price": "91.60", "count": "4", "stock": "2", "sold": "12" } ] A: Assuming that all arrays have the same size you can map each element of the concatenation of the key-values from each item using the index number of each element being mapped ($$ by default). %dw 2.0 output application/json var input1=[{"id": "3857"},{"id": "57"}] var input2=[{"Date": "2022-11-30","name": "salesorder","brand": "Apple","Requests": "111","price":"917.65"},{"Date": "2022-11-13","name": "orders","brand": "TV","Requests": "11","price": "91.60"}] var input3=[{"count": "3" },{"count": "4" }] var input4=[{"stock": "21","sold": "112"},{"stock": "2","sold": "12"}] --- input1 map (input1[$$] ++ input2[$$] ++ input3[$$] ++ input4[$$]) Output: [ { "id": "3857", "Date": "2022-11-30", "name": "salesorder", "brand": "Apple", "Requests": "111", "price": "917.65", "count": "3", "stock": "21", "sold": "112" }, { "id": "57", "Date": "2022-11-13", "name": "orders", "brand": "TV", "Requests": "11", "price": "91.60", "count": "4", "stock": "2", "sold": "12" } ] A: Use the zip function to combine the arrays together, and then the ++ operator to merge the objects together: (input1 zip input2) // produces an array of two element arrays map ($[0] ++ $[1]) // combines the two elements into a single object
Merge corresponding elements from multiple arrays
I have below inputs input 1: [{ "id": "3857" }, { "id": "57" }] input 2: [{ "Date": "2022-11-30", "name": "salesorder", "brand": "Apple", "Requests": "111", "price": "917.65" }, { "Date": "2022-11-13", "name": "orders", "brand": "TV", "Requests": "11", "price": "91.60" }] input 3: [{ "count": "3" }, { "count": "4" }] input 4: [{ "stock": "21", "sold": "112" }, { "stock": "2", "sold": "12" }] Desired Output: [{ "id": "3857", "Date": "2022-11-30", "name": "salesorder", "brand": "Apple", "Requests": "111", "price": "917.65", "count": "3", "stock": "21", "sold": "112" }, { "id": "57", "Date": "2022-11-13", "name": "orders", "brand": "TV", "Requests": "11", "price": "91.60", "count": "4", "stock": "2", "sold": "12" } ]
[ "Assuming that all arrays have the same size you can map each element of the concatenation of the key-values from each item using the index number of each element being mapped ($$ by default).\n%dw 2.0\noutput application/json\nvar input1=[{\"id\": \"3857\"},{\"id\": \"57\"}]\nvar input2=[{\"Date\": \"2022-11-30\",\"name\": \"salesorder\",\"brand\": \"Apple\",\"Requests\": \"111\",\"price\":\"917.65\"},{\"Date\": \"2022-11-13\",\"name\": \"orders\",\"brand\": \"TV\",\"Requests\": \"11\",\"price\": \"91.60\"}] \nvar input3=[{\"count\": \"3\" },{\"count\": \"4\" }]\nvar input4=[{\"stock\": \"21\",\"sold\": \"112\"},{\"stock\": \"2\",\"sold\": \"12\"}]\n---\ninput1 map (input1[$$] ++ input2[$$] ++ input3[$$] ++ input4[$$])\n\nOutput:\n[\n {\n \"id\": \"3857\",\n \"Date\": \"2022-11-30\",\n \"name\": \"salesorder\",\n \"brand\": \"Apple\",\n \"Requests\": \"111\",\n \"price\": \"917.65\",\n \"count\": \"3\",\n \"stock\": \"21\",\n \"sold\": \"112\"\n },\n {\n \"id\": \"57\",\n \"Date\": \"2022-11-13\",\n \"name\": \"orders\",\n \"brand\": \"TV\",\n \"Requests\": \"11\",\n \"price\": \"91.60\",\n \"count\": \"4\",\n \"stock\": \"2\",\n \"sold\": \"12\"\n }\n]\n\n", "Use the zip function to combine the arrays together, and then the ++ operator to merge the objects together:\n(input1 zip input2) // produces an array of two element arrays\n map ($[0] ++ $[1]) // combines the two elements into a single object\n\n" ]
[ 1, 0 ]
[]
[]
[ "dataweave", "mule4", "mulesoft" ]
stackoverflow_0074660990_dataweave_mule4_mulesoft.txt
Q: How to I assign values to letters that come from a csv file? I am calculating the gpa of a given curriculum. I want to multiply the number of credits by the grade that the student achieved. I want to make the program know that A in the csv file is equal to 4, B is equal to 3 and so on. enter image description here I tried telling the program that the letters on the slice of data equal a number, but it didn't work I have written this so far: def over_gpa(data): total_cred = np.sum(data[:,3]) messi = np.unique(data[:,3:]) for k in messi: value = [] y = data[:,3] f = data[:,4] x = y * f value.append(x) m = np.sum(value) total_gpa = m/total_cred print(total_gpa) over_gpa(data) A: I'd initialize a dict that maps letters to grades and then apply it to a new column. vals = { "A" : 4, "B" : 3, "C" : 2, "D" : 1, "F" : 0 } df['Grade number'] = df['Grade'].apply(lambda x: vals.get(x))
How to I assign values to letters that come from a csv file?
I am calculating the gpa of a given curriculum. I want to multiply the number of credits by the grade that the student achieved. I want to make the program know that A in the csv file is equal to 4, B is equal to 3 and so on. enter image description here I tried telling the program that the letters on the slice of data equal a number, but it didn't work I have written this so far: def over_gpa(data): total_cred = np.sum(data[:,3]) messi = np.unique(data[:,3:]) for k in messi: value = [] y = data[:,3] f = data[:,4] x = y * f value.append(x) m = np.sum(value) total_gpa = m/total_cred print(total_gpa) over_gpa(data)
[ "I'd initialize a dict that maps letters to grades and then apply it to a new column.\nvals = { \"A\" : 4, \"B\" : 3, \"C\" : 2, \"D\" : 1, \"F\" : 0 }\ndf['Grade number'] = df['Grade'].apply(lambda x: vals.get(x))\n\n" ]
[ 0 ]
[]
[]
[ "assign", "python" ]
stackoverflow_0074679411_assign_python.txt
Q: Reverse string using .as_bytes() I'm trying to reverse a string. I use the solution of this post and it works. But I would like to try with bytes instead of grapheme clusters as shown below: pub fn reverse2(input: &str) -> String { let s: String = input .as_bytes() .iter() .rev() .collect(); return s; } Unfortunately, I can't run the function collect() after rev(). I don't know which method to use. How would you do it ? A: As you explicitly ask about not using chars(), you have to restrict yourself to ASCII strings. pub fn reverse2(input: &str) -> String { // Reversing on byte-level only works with ASCII strings. assert!(input.is_ascii()); let reversed_bytes: Vec<u8> = input.as_bytes().iter().copied().rev().collect(); let reversed_string = unsafe { // SAFETY: This is guaranteed to be a valid UTF8 string, because: // - the input string is a valid ASCII string // - a reversed ASCII string is still a valid ASCII string // - an ASCII string is a valid UTF8 string String::from_utf8_unchecked(reversed_bytes) }; return reversed_string; } You can also use the checked version, if you don't like the unsafe, but it comes with a little bit of overhead: pub fn reverse2(input: &str) -> String { // Reversing on byte-level only works with ASCII strings. assert!(input.is_ascii()); let reversed_bytes: Vec<u8> = input.as_bytes().iter().copied().rev().collect(); let reversed_string = String::from_utf8(reversed_bytes).unwrap(); return reversed_string; } Optimization: Checking is_ascii() is some overhead. It is not strictly required, however. UTF-8 has one special property: every non-ASCII byte is valued 128 and above. So technically it is enough to just simply filter out all values equal to or above 128: pub fn reverse2(input: &str) -> String { let reversed_bytes: Vec<u8> = input .as_bytes() .iter() .rev() .map(|&val| { if val < 128 { val } else { 0x1a // replacement char } }) .collect(); let reversed_string = unsafe { // SAFETY: This is guaranteed to be a valid UTF8 string, because: // - `reversed_bytes` is guaranteed to be an ASCII string // - an ASCII string is a valid UTF8 string String::from_utf8_unchecked(reversed_bytes) }; return reversed_string; } fn main() { let s = "abcdefghij"; println!("{:?}", s.as_bytes()); let reversed = reverse2(s); println!("{}", reversed); println!("{:?}", reversed.as_bytes()); } [97, 98, 99, 100, 101, 240, 159, 152, 131, 102, 103, 104, 105, 106] jihgfedcba [106, 105, 104, 103, 102, 26, 26, 26, 26, 101, 100, 99, 98, 97] Additional remark: Consider using .bytes() instead of .as_bytes().iter(). A: To fix this code, you can use the .chars() method on the input string to return an iterator of the characters in the string instead of the bytes. Then you can use the .collect() method to create a new string with the reversed characters: pub fn reverse2(input: &str) -> String { let s: String = input .chars() .rev() .collect(); return s; } This will properly reverse the characters in the input string and return the new reversed string. A: Well, firstly you should use .bytes() instead of .as_bytes().iter(). Secondly, you need to reverse characters, not bytes, cuz a &str may contain UTF-8, so use .chars() instead of .bytes(). Thirdly, you don’t need to collect it into a variable and return a variable, just return the result of collecting. Fourthly, you don’t need explicit return. Let’s sum all the stuff i said: pub fn reverse2(input: &str) -> String { input.chars() .rev() .collect() } A: Here is a solution that converts the input string into a byte vector ─ so the reverse function of Vec can be used: pub fn reverse2(input: &str) -> String { let v = &mut input.to_string().into_bytes(); v.reverse(); std::str::from_utf8(v).unwrap().to_string() } The input string may only contain ASCII characters. Playground
Reverse string using .as_bytes()
I'm trying to reverse a string. I use the solution of this post and it works. But I would like to try with bytes instead of grapheme clusters as shown below: pub fn reverse2(input: &str) -> String { let s: String = input .as_bytes() .iter() .rev() .collect(); return s; } Unfortunately, I can't run the function collect() after rev(). I don't know which method to use. How would you do it ?
[ "As you explicitly ask about not using chars(), you have to restrict yourself to ASCII strings.\npub fn reverse2(input: &str) -> String {\n // Reversing on byte-level only works with ASCII strings.\n assert!(input.is_ascii());\n\n let reversed_bytes: Vec<u8> = input.as_bytes().iter().copied().rev().collect();\n let reversed_string = unsafe {\n // SAFETY: This is guaranteed to be a valid UTF8 string, because:\n // - the input string is a valid ASCII string\n // - a reversed ASCII string is still a valid ASCII string\n // - an ASCII string is a valid UTF8 string\n String::from_utf8_unchecked(reversed_bytes)\n };\n\n return reversed_string;\n}\n\nYou can also use the checked version, if you don't like the unsafe, but it comes with a little bit of overhead:\npub fn reverse2(input: &str) -> String {\n // Reversing on byte-level only works with ASCII strings.\n assert!(input.is_ascii());\n\n let reversed_bytes: Vec<u8> = input.as_bytes().iter().copied().rev().collect();\n let reversed_string = String::from_utf8(reversed_bytes).unwrap();\n\n return reversed_string;\n}\n\n\nOptimization:\nChecking is_ascii() is some overhead. It is not strictly required, however.\nUTF-8 has one special property: every non-ASCII byte is valued 128 and above. So technically it is enough to just simply filter out all values equal to or above 128:\npub fn reverse2(input: &str) -> String {\n let reversed_bytes: Vec<u8> = input\n .as_bytes()\n .iter()\n .rev()\n .map(|&val| {\n if val < 128 {\n val\n } else {\n 0x1a // replacement char\n }\n })\n .collect();\n\n let reversed_string = unsafe {\n // SAFETY: This is guaranteed to be a valid UTF8 string, because:\n // - `reversed_bytes` is guaranteed to be an ASCII string\n // - an ASCII string is a valid UTF8 string\n String::from_utf8_unchecked(reversed_bytes)\n };\n\n return reversed_string;\n}\n\nfn main() {\n let s = \"abcdefghij\";\n println!(\"{:?}\", s.as_bytes());\n\n let reversed = reverse2(s);\n println!(\"{}\", reversed);\n println!(\"{:?}\", reversed.as_bytes());\n}\n\n[97, 98, 99, 100, 101, 240, 159, 152, 131, 102, 103, 104, 105, 106]\njihgfedcba\n[106, 105, 104, 103, 102, 26, 26, 26, 26, 101, 100, 99, 98, 97]\n\n\nAdditional remark:\nConsider using .bytes() instead of .as_bytes().iter().\n", "To fix this code, you can use the .chars() method on the input string to return an iterator of the characters in the string instead of the bytes. Then you can use the .collect() method to create a new string with the reversed characters:\npub fn reverse2(input: &str) -> String {\n let s: String = input\n .chars()\n .rev()\n .collect();\n return s;\n}\n\nThis will properly reverse the characters in the input string and return the new reversed string.\n", "Well, firstly you should use .bytes() instead of .as_bytes().iter(). Secondly, you need to reverse characters, not bytes, cuz a &str may contain UTF-8, so use .chars() instead of .bytes(). Thirdly, you don’t need to collect it into a variable and return a variable, just return the result of collecting. Fourthly, you don’t need explicit return.\nLet’s sum all the stuff i said:\npub fn reverse2(input: &str) -> String {\n input.chars()\n .rev()\n .collect()\n}\n\n", "Here is a solution that converts the input string into a byte vector ─ so the reverse function of Vec can be used:\npub fn reverse2(input: &str) -> String {\n let v = &mut input.to_string().into_bytes();\n v.reverse();\n std::str::from_utf8(v).unwrap().to_string()\n}\n\nThe input string may only contain ASCII characters.\nPlayground\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "rust", "string" ]
stackoverflow_0074674328_rust_string.txt
Q: Getting "Another exception was thrown: Instance of 'minified:bV'" while running flutter app on web (localhost) I am working on a flutter application. Recently I have enabled this application for web and its running fine if I run it from Android Studio by clicking on Run button. The problem is when I run it on localhost or I build it for release it gives en error that is Another exception was thrown: Instance of 'minified:bV<void> and the page appears blank in gray color. In the page that is broken, I have used flower kind of layout. I have modified this library. It was working fine on localhost too before but, its breaking now. Please suggest. Below are the details: Flutter Version - v1.14.6 (Beta) Commands: I use below commands to run the app on localhost. cd build/web flutter build web -t lib/main_web.dart flutter pub global activate dhttpd flutter pub global run dhttpd Thanks in advance. A: My console displayed a similar error message to yours, as well as a blank grey screen. After searching for few days, I found out that the error could be due to an expanded or flexible widget. solution: just try to remove or replace Expanded widget, it worked for me Thank you A: For me, it meant I had a null value somewhere. After searching deeper, it was .env_prod files that work for web on local builds in Chrome, but not once published. i had to use "dotenv_prod" for my variable files. A: I had the same error. I don't know enough flutter on a technical level but what fixed it for me was changing the root widget of the web page to a Scaffold . A: I had the same issue using FlutterFlow.io and using a Custom Widget on a page. FlutterFlow exposes a widget property: "Enforce width & Height". When this property is set, FlutterFlow generates the code for a new Container and places the Custom Widget in that container. Which means that Custom Widget I was using was causing a lot of screen overflow errors w/o this new Container. So it seems that this error is caused by Flutter not being able to figure out how to bound the widget (?). Add a container and see...
Getting "Another exception was thrown: Instance of 'minified:bV'" while running flutter app on web (localhost)
I am working on a flutter application. Recently I have enabled this application for web and its running fine if I run it from Android Studio by clicking on Run button. The problem is when I run it on localhost or I build it for release it gives en error that is Another exception was thrown: Instance of 'minified:bV<void> and the page appears blank in gray color. In the page that is broken, I have used flower kind of layout. I have modified this library. It was working fine on localhost too before but, its breaking now. Please suggest. Below are the details: Flutter Version - v1.14.6 (Beta) Commands: I use below commands to run the app on localhost. cd build/web flutter build web -t lib/main_web.dart flutter pub global activate dhttpd flutter pub global run dhttpd Thanks in advance.
[ "My console displayed a similar error message to yours, as well as a blank grey screen. After searching for few days, I found out that the error could be due to an expanded or flexible widget.\nsolution:\njust try to remove or replace Expanded widget, it worked for me\nThank you\n", "For me, it meant I had a null value somewhere. After searching deeper, it was .env_prod files that work for web on local builds in Chrome, but not once published. i had to use \"dotenv_prod\" for my variable files.\n", "I had the same error. I don't know enough flutter on a technical level but what fixed it for me was changing the root widget of the web page to a Scaffold .\n", "I had the same issue using FlutterFlow.io and using a Custom Widget on a page. FlutterFlow exposes a widget property: \"Enforce width & Height\". When this property is set, FlutterFlow generates the code for a new Container and places the Custom Widget in that container.\nWhich means that Custom Widget I was using was causing a lot of screen overflow errors w/o this new Container.\nSo it seems that this error is caused by Flutter not being able to figure out how to bound the widget (?).\nAdd a container and see...\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "flutter_web" ]
stackoverflow_0061005758_flutter_web.txt
Q: How to get the type of inner function for the return type of outer function? It would be convenient to not have to change the return type of fn0 each time I modify the type of fn1. Is there any way to do this in TypeScript? export function fn0(): typeof fn1 { return function fn1(): any { } } A: Remove the typeof fn1: export function fn0() { return function fn1(): any { } } This is automatic type inference.
How to get the type of inner function for the return type of outer function?
It would be convenient to not have to change the return type of fn0 each time I modify the type of fn1. Is there any way to do this in TypeScript? export function fn0(): typeof fn1 { return function fn1(): any { } }
[ "Remove the typeof fn1:\nexport function fn0() {\n\n return function fn1(): any {\n }\n}\n\nThis is automatic type inference.\n" ]
[ 0 ]
[]
[]
[ "typescript" ]
stackoverflow_0074679263_typescript.txt
Q: HAProxy SSL termination: how to resolve certificate error only experienced by WAN clients? My HAProxy SSL termination setup works exactly as expected for LAN clients, but if I use a WAN client (e.g. Tor Browser) I get a certificate error. Yet, they can bypass my 80->443 redirect and access my server on port 80 if I provide a firewall rule allowing access to port 80. How can I ensure WAN clients connect with HTTPS? My front end is configured to use my wildcard certificate, *.example.com, with a rule which routes requests to the correct backend server. I also have a frontend redirect from port 80 to 443. The system work exactly as I expect for clients on my home network: when visiting subdomain.example.com in a browser: all subdomain.example.com:80 requests are forwarded to subdomain.example.com443 HAproxy frontend performs SSL offloading the client is connected to the backend server 192.168.1.50:80 via HTTPS as I expected. However, when I try to connect to my subdomain from outside my local network, e.g. subdomain.example.com:443 using TOR browser, I receive a "Secure Connection Failed" message, with "Error code: SSL_ERROR_RX_RECORD_TOO_LONG". If I create a firewall rule allowing access to port 192.168.1.50:80, I can change the Tor Browser to HTTP mode and then connect to my backend server in an unsecured way. But, I don't understand how this is possible. I expect at least that the http redirect I created in the HAProxy frontend would be respected. How could an outside client can bypass my HAProxy front end redirect? I assume whatever is happening here is also related to the outside client not establishing a secure connection with my HAProxy front end. A: I've solved my issue. Here is what I did: Create a virtual IP (Firewall --> Virtual IPs --> Add)\ IP Alias --> WAN --> Single Address (I picked an address that wasn't in use, like 192.168.1.XXX) Saved with description "HAProxy Frontend Virtual IP" Opened port 443 in the Firewall, specifying access to 192.168.1.XXX Services --> HAProxy. Here I duplicated my front end, and under "Listen Address" I changed from "WAN" to 192.168.1.XXX (HAProxy Frontend Virtual IP) Now I can access my server via a Tor connection (or any other external client) without issue. I still don't understand exactly what was happening before and what is happening now. I assume there was some conflict since HAProxy was listening on the same address as pfSense (my WAN IP address).
HAProxy SSL termination: how to resolve certificate error only experienced by WAN clients?
My HAProxy SSL termination setup works exactly as expected for LAN clients, but if I use a WAN client (e.g. Tor Browser) I get a certificate error. Yet, they can bypass my 80->443 redirect and access my server on port 80 if I provide a firewall rule allowing access to port 80. How can I ensure WAN clients connect with HTTPS? My front end is configured to use my wildcard certificate, *.example.com, with a rule which routes requests to the correct backend server. I also have a frontend redirect from port 80 to 443. The system work exactly as I expect for clients on my home network: when visiting subdomain.example.com in a browser: all subdomain.example.com:80 requests are forwarded to subdomain.example.com443 HAproxy frontend performs SSL offloading the client is connected to the backend server 192.168.1.50:80 via HTTPS as I expected. However, when I try to connect to my subdomain from outside my local network, e.g. subdomain.example.com:443 using TOR browser, I receive a "Secure Connection Failed" message, with "Error code: SSL_ERROR_RX_RECORD_TOO_LONG". If I create a firewall rule allowing access to port 192.168.1.50:80, I can change the Tor Browser to HTTP mode and then connect to my backend server in an unsecured way. But, I don't understand how this is possible. I expect at least that the http redirect I created in the HAProxy frontend would be respected. How could an outside client can bypass my HAProxy front end redirect? I assume whatever is happening here is also related to the outside client not establishing a secure connection with my HAProxy front end.
[ "I've solved my issue. Here is what I did:\n\nCreate a virtual IP (Firewall --> Virtual IPs --> Add)\\\nIP Alias --> WAN --> Single Address (I picked an address that wasn't in use, like 192.168.1.XXX)\nSaved with description \"HAProxy Frontend Virtual IP\"\nOpened port 443 in the Firewall, specifying access to 192.168.1.XXX\nServices --> HAProxy. Here I duplicated my front end, and under \"Listen Address\" I changed from \"WAN\" to 192.168.1.XXX (HAProxy Frontend Virtual IP)\n\nNow I can access my server via a Tor connection (or any other external client) without issue.\nI still don't understand exactly what was happening before and what is happening now. I assume there was some conflict since HAProxy was listening on the same address as pfSense (my WAN IP address).\n" ]
[ 0 ]
[]
[]
[ "haproxy", "http", "https", "offloading", "pfsense" ]
stackoverflow_0074660845_haproxy_http_https_offloading_pfsense.txt
Q: How can I make the movement faster if I press the key? I'm making a Tetris game now. I want to implement it so that if I press the down key , the block falls quickly, and if I press the left and right keys, the block moves quickly. Pressing the key used the pygame.key.get_pressed() function and used pygame.time.set_timer() function to make speed change. The game speed was set to 600 for the interval of pygame.time.set_timer(), but if I press the down key, the block drops quickly because the interval was set to 150 to speed up the game so that the block drops quickly. The problem is to implement the function on the left and right direction keys. It is also possible to move the left and right keys quickly if I change the interval. The problem is that the pygame.time.set_timer() function changes the speed of the entire game, so the block falls quickly as well as the left and right movements of the block. Is there a way to speed up left and right movements without touching the speed of other things? I'd appreciate it if you let me know, thanks! code elif start: for event in pygame.event.get(): attack_stack = 0 pos = pygame.mouse.get_pos() if event.type == QUIT: done = True elif event.type == USEREVENT: # Set speed if not game_over: keys_pressed = pygame.key.get_pressed() # Soft drop if keys_pressed[K_DOWN]: pygame.time.set_timer(pygame.USEREVENT, 100) elif keys_pressed[K_RIGHT]: pygame.time.set_timer(pygame.USEREVENT, 100) if not is_rightedge1(dx, dy, mino_en, rotation, matrix): ui_variables.move_sound.play() dx += 1 elif keys_pressed[K_LEFT]: pygame.time.set_timer(pygame.USEREVENT, 100) if not is_leftedge1(dx, dy, mino_en, rotation, matrix): ui_variables.move_sound.play() dx -= 1 else: pygame.time.set_timer(pygame.USEREVENT, 600) A: It looks to me that the reason your piece is dropping faster when you press a button is because if the user doesn't press a button the timer is set to 600ms. If they do press a button then the timer is set to 100ms. As for how to fix this, you'll need to decouple the downward piece movement and user-input movement. I'd suggest making another event that only handles downward movement. DROPEVENT = pygame.USEREVENT + 1 elif event.Type == DROPEVENT: pygame.time.set_timer(DROPEVENT, 600) # Your piece drop logic. This snippet is not complete nor tested at all, but I hope it get the idea across. You don't seem to have posted the logic that handles dropping the piece, but you would need to move this into the new event. A: Waiting a long time (100 ms is already long) before reacting to user input feels bad, so you don’t want to wait a full piece-movement time before checking for input again just because there is none at the moment you check. Instead, poll for input at a steady pace of (say) 30 Hz; for simplicity, the usual approach is to just run the whole game at that frequency even if nothing needs to change on the screen for some (or even most) frames. (This technique also naturally allows smooth animations of or between piece movements.) The usual implementation of “nothing” on a frame is to adjust the piece’s position every frame but integer-divide that position by some constant before using it for anything other than keeping track of its progress toward the next movement (like drawing it or checking for collisions). You might use pixels as the “invisible unit” when movement must be by whole tiles; games where sprites can be drawn at any pixel divide each into some convenient number of subpixels in the same fashion.
How can I make the movement faster if I press the key?
I'm making a Tetris game now. I want to implement it so that if I press the down key , the block falls quickly, and if I press the left and right keys, the block moves quickly. Pressing the key used the pygame.key.get_pressed() function and used pygame.time.set_timer() function to make speed change. The game speed was set to 600 for the interval of pygame.time.set_timer(), but if I press the down key, the block drops quickly because the interval was set to 150 to speed up the game so that the block drops quickly. The problem is to implement the function on the left and right direction keys. It is also possible to move the left and right keys quickly if I change the interval. The problem is that the pygame.time.set_timer() function changes the speed of the entire game, so the block falls quickly as well as the left and right movements of the block. Is there a way to speed up left and right movements without touching the speed of other things? I'd appreciate it if you let me know, thanks! code elif start: for event in pygame.event.get(): attack_stack = 0 pos = pygame.mouse.get_pos() if event.type == QUIT: done = True elif event.type == USEREVENT: # Set speed if not game_over: keys_pressed = pygame.key.get_pressed() # Soft drop if keys_pressed[K_DOWN]: pygame.time.set_timer(pygame.USEREVENT, 100) elif keys_pressed[K_RIGHT]: pygame.time.set_timer(pygame.USEREVENT, 100) if not is_rightedge1(dx, dy, mino_en, rotation, matrix): ui_variables.move_sound.play() dx += 1 elif keys_pressed[K_LEFT]: pygame.time.set_timer(pygame.USEREVENT, 100) if not is_leftedge1(dx, dy, mino_en, rotation, matrix): ui_variables.move_sound.play() dx -= 1 else: pygame.time.set_timer(pygame.USEREVENT, 600)
[ "It looks to me that the reason your piece is dropping faster when you press a button is because if the user doesn't press a button the timer is set to 600ms. If they do press a button then the timer is set to 100ms.\nAs for how to fix this, you'll need to decouple the downward piece movement and user-input movement. I'd suggest making another event that only handles downward movement.\nDROPEVENT = pygame.USEREVENT + 1\n\nelif event.Type == DROPEVENT:\n pygame.time.set_timer(DROPEVENT, 600)\n # Your piece drop logic.\n\nThis snippet is not complete nor tested at all, but I hope it get the idea across. You don't seem to have posted the logic that handles dropping the piece, but you would need to move this into the new event.\n", "Waiting a long time (100 ms is already long) before reacting to user input feels bad, so you don’t want to wait a full piece-movement time before checking for input again just because there is none at the moment you check. Instead, poll for input at a steady pace of (say) 30 Hz; for simplicity, the usual approach is to just run the whole game at that frequency even if nothing needs to change on the screen for some (or even most) frames. (This technique also naturally allows smooth animations of or between piece movements.)\nThe usual implementation of “nothing” on a frame is to adjust the piece’s position every frame but integer-divide that position by some constant before using it for anything other than keeping track of its progress toward the next movement (like drawing it or checking for collisions). You might use pixels as the “invisible unit” when movement must be by whole tiles; games where sprites can be drawn at any pixel divide each into some convenient number of subpixels in the same fashion.\n" ]
[ 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074673028_pygame_python.txt
Q: React/JS: Click on a btn without triggering div click not working as expected codesandbox: https://codesandbox.io/s/currying-breeze-depdc9?file=/package.json I have a Card component that has 4 potential states: "active", "selected", "discarded", "complete". Depending on the state, I need to display a different css class. The states are set by clicking on specific parts of the card and each part is a "toggle" (one click sets it, another click "unsets" it): default state is active, if the user click anywhere on the card, it gets "selected" and two buttons appear inside the card ("back", "discard"). if the user clicks on "back", I need to toggle the state bac to "active". if the user clicks on "discard" I need to set the state to "discarted" The state is stored at the "App" level and I am passing it to the component through props. This means that for updating the states I am passing some "handler" from the app to the component (SelectCard, DiscardCard) Here below is my code. I am able to toggle the "active"-->"select"-->"active" through the function SelectCard. However, I am doing something wrong since I can't manage to get the click on "discard" to actually call the DiscardCard function. My feeling is that it has something to do with the fact that the btn is inside the div and I have an "onClic" for the div that calls SelectCard so when I click on the "discard btn" it's like I am clicking into the div as well and things don't work out. But maybe it's something else. Not sure. import { useState } from 'react' import reactLogo from './assets/react.svg' import Card from './components/Card' import data from "./assets/data.json" import {nanoid} from "nanoid" function App() { const [people, setPeople] = useState(data['people'].map( el=>{ return { ...el, 'key' : nanoid(), } } )) const [myCard, setMyCard] = useState( { "name":"Name and Surname", "img":"https://i.picsum.photos/id/1070/200/300.jpg?hmac=dJNTYlLwT_0RupxbJNbw5Wj-q2cCTB4Xh-GqWRofIIc", "description": "This is a silly descriptionhis is a silly descriptionhis is a silly description", 'key' : nanoid(), "selected":false, "active":true, } ) function SelectCard(CardKey){ console.log('SelectCard') setPeople(oldPeople=>{ return oldPeople.map(el=>{ return el.key === CardKey ? { ...el, 'state': el.state === 'active'?'selected': 'active'} : { ...el, 'state':'active'} }) }) } function DiscardCard(CardKey){ console.log('DiscardCard') setPeople(oldPeople=>{ return oldPeople.map(el=>{ return el.key === CardKey ? { ...el, 'state': el.state === 'discarded'?'active': 'discarded'} : { ...el} }) }) } const cards = people.map(el=>{ return <Card key = {el.key} item={el} onPress={()=>SelectCard(el.key)} onDiscard={()=>DiscardCard(el.key)} /> }) return ( <div className="App"> <div className='container'> <div className='left'> <div className='cards'> {cards} </div> </div> <div className = 'right'> <h4>You are: </h4> <Card key = {myCard.key} item={myCard}/> </div> </div> </div> ) } export default App import { useState } from 'react' function Card(props) { //const [count, setCount] = useState(0) function getClassName(state) { switch (state) { case "active": return ""; case "selected": return "overlay-selected"; case "discarded": return "overlay-discarded"; case "complete": return "overlay-complete"; default: return ""; } } const className = `card ${getClassName(props.item.state)}` return ( <div className={className} onClick={(event)=>{ props.onPress()}}> <img className='card-img' alt='Card Image' src={props.item.img} /> <h3 className='card-title'>{props.item.name} </h3> { props.item.state === 'selected' ? <div className='card-cta'> <button className='btn btn-back' onClick={ props.item.selected ? (event)=> { props.onPress //event.stopPropagation() } : ()=>{}} >Back</button> <button className='btn btn-discard' onClick={ (event) =>{ //event.stopPropagation() props.onDiscard } } >Discard</button> </div> : <p className='card-description'>{props.item.description} </p> } </div> ) } export default Card A: For stopping the event from bubling up to other handlers, you need to call stopPropagation on the event. Then, as mentioned in the other question, you need to actually run the handler you passed. And in order to call a handler in a block of code you need to add () after its name. So for the Back you need onClick={ props.item.selected ? (e) => { e.stopPropagation(); props.onPress(); } : undefined } and for Discard you want onClick={(e) => { e.stopPropagation(); props.onDiscard(); }} Demo at https://codesandbox.io/s/competent-swartz-d05x9y
React/JS: Click on a btn without triggering div click not working as expected
codesandbox: https://codesandbox.io/s/currying-breeze-depdc9?file=/package.json I have a Card component that has 4 potential states: "active", "selected", "discarded", "complete". Depending on the state, I need to display a different css class. The states are set by clicking on specific parts of the card and each part is a "toggle" (one click sets it, another click "unsets" it): default state is active, if the user click anywhere on the card, it gets "selected" and two buttons appear inside the card ("back", "discard"). if the user clicks on "back", I need to toggle the state bac to "active". if the user clicks on "discard" I need to set the state to "discarted" The state is stored at the "App" level and I am passing it to the component through props. This means that for updating the states I am passing some "handler" from the app to the component (SelectCard, DiscardCard) Here below is my code. I am able to toggle the "active"-->"select"-->"active" through the function SelectCard. However, I am doing something wrong since I can't manage to get the click on "discard" to actually call the DiscardCard function. My feeling is that it has something to do with the fact that the btn is inside the div and I have an "onClic" for the div that calls SelectCard so when I click on the "discard btn" it's like I am clicking into the div as well and things don't work out. But maybe it's something else. Not sure. import { useState } from 'react' import reactLogo from './assets/react.svg' import Card from './components/Card' import data from "./assets/data.json" import {nanoid} from "nanoid" function App() { const [people, setPeople] = useState(data['people'].map( el=>{ return { ...el, 'key' : nanoid(), } } )) const [myCard, setMyCard] = useState( { "name":"Name and Surname", "img":"https://i.picsum.photos/id/1070/200/300.jpg?hmac=dJNTYlLwT_0RupxbJNbw5Wj-q2cCTB4Xh-GqWRofIIc", "description": "This is a silly descriptionhis is a silly descriptionhis is a silly description", 'key' : nanoid(), "selected":false, "active":true, } ) function SelectCard(CardKey){ console.log('SelectCard') setPeople(oldPeople=>{ return oldPeople.map(el=>{ return el.key === CardKey ? { ...el, 'state': el.state === 'active'?'selected': 'active'} : { ...el, 'state':'active'} }) }) } function DiscardCard(CardKey){ console.log('DiscardCard') setPeople(oldPeople=>{ return oldPeople.map(el=>{ return el.key === CardKey ? { ...el, 'state': el.state === 'discarded'?'active': 'discarded'} : { ...el} }) }) } const cards = people.map(el=>{ return <Card key = {el.key} item={el} onPress={()=>SelectCard(el.key)} onDiscard={()=>DiscardCard(el.key)} /> }) return ( <div className="App"> <div className='container'> <div className='left'> <div className='cards'> {cards} </div> </div> <div className = 'right'> <h4>You are: </h4> <Card key = {myCard.key} item={myCard}/> </div> </div> </div> ) } export default App import { useState } from 'react' function Card(props) { //const [count, setCount] = useState(0) function getClassName(state) { switch (state) { case "active": return ""; case "selected": return "overlay-selected"; case "discarded": return "overlay-discarded"; case "complete": return "overlay-complete"; default: return ""; } } const className = `card ${getClassName(props.item.state)}` return ( <div className={className} onClick={(event)=>{ props.onPress()}}> <img className='card-img' alt='Card Image' src={props.item.img} /> <h3 className='card-title'>{props.item.name} </h3> { props.item.state === 'selected' ? <div className='card-cta'> <button className='btn btn-back' onClick={ props.item.selected ? (event)=> { props.onPress //event.stopPropagation() } : ()=>{}} >Back</button> <button className='btn btn-discard' onClick={ (event) =>{ //event.stopPropagation() props.onDiscard } } >Discard</button> </div> : <p className='card-description'>{props.item.description} </p> } </div> ) } export default Card
[ "For stopping the event from bubling up to other handlers, you need to call stopPropagation on the event.\nThen, as mentioned in the other question, you need to actually run the handler you passed. And in order to call a handler in a block of code you need to add () after its name.\nSo for the Back you need\nonClick={\n props.item.selected\n ? (e) => {\n e.stopPropagation();\n props.onPress();\n }\n : undefined\n}\n\nand for Discard you want\nonClick={(e) => {\n e.stopPropagation();\n props.onDiscard();\n}}\n\nDemo at https://codesandbox.io/s/competent-swartz-d05x9y\n" ]
[ 0 ]
[]
[]
[ "javascript", "reactjs" ]
stackoverflow_0074670677_javascript_reactjs.txt
Q: How do i make VBS scrip with "Yes" and "No", and if you press "Yes", it runs other file? I don't know how to make VBScript "Yes, No" which when you press "Yes" it runs file. How do I do that? I need quick help because im making a program. I was trying to do that on many possible ideas, and I don't know how to compile these, can you give me it scripted fully, with vbInformation, vbYes and vbNo? (Remember, if yes is pressed, it runs file, and if no is pressed, it closes it) You can still give me that scripted, even in other file extension. A: Try this : result = MsgBox ("Yes or No?", vbYesNo, "Yes No Example") Select Case result Case vbYes MsgBox("You chose Yes") Dim objShell Set objShell = Wscript.CreateObject("WScript.Shell") objShell.Run "TestScript.vbs" Set objShell = Nothing Case vbNo MsgBox("You chose No") End Select
How do i make VBS scrip with "Yes" and "No", and if you press "Yes", it runs other file?
I don't know how to make VBScript "Yes, No" which when you press "Yes" it runs file. How do I do that? I need quick help because im making a program. I was trying to do that on many possible ideas, and I don't know how to compile these, can you give me it scripted fully, with vbInformation, vbYes and vbNo? (Remember, if yes is pressed, it runs file, and if no is pressed, it closes it) You can still give me that scripted, even in other file extension.
[ "Try this :\nresult = MsgBox (\"Yes or No?\", vbYesNo, \"Yes No Example\")\n\nSelect Case result\nCase vbYes\n MsgBox(\"You chose Yes\")\n Dim objShell\n Set objShell = Wscript.CreateObject(\"WScript.Shell\")\n objShell.Run \"TestScript.vbs\" \n Set objShell = Nothing\nCase vbNo\n MsgBox(\"You chose No\")\nEnd Select\n\n" ]
[ 0 ]
[]
[]
[ "vbscript" ]
stackoverflow_0074679447_vbscript.txt
Q: Typescript enum index object iterate over object I have the following enum enum FunnelStage { LOGIN } then I have the following object const overall = { [FunnelStage.LOGIN]: {count: 1} } overall[FunnelStage.Login].count = 2 and later I want to iterate over the overall object like so for (let funnelStage in overall) { console.log(overall[funnelStage].count) } this gives me an error - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<FunnalStage, { count: number; }>'. No index signature with a parameter of type 'string' was found on type 'Record<FunnalStage, { count: number; }>' How do I achieve my loop ? I tried also like this but it gives me the same error for (let funnelStageKey in Object.keys(overall) as Array<keyof typeof FunnalStage>) { const count = overall[funnelStageKey].count; console.log(count); } LINK TO PLAYGROUND A: You can use the Object.entries method to iterate over the properties of the overall object. You can then destructure the key/value pairs in the for-of loop and use the key to access the corresponding enum value: for (const [key, value] of Object.entries(overall)) { console.log(FunnelStage[key], value.count); } Or, you can use the Object.keys method to get an array of keys, and then use the map method to create a new array of FunnelStage values: const keys = Object.keys(overall); const funnelStages = keys.map(key => FunnelStage[key]); You can then iterate over the funnelStages array and use the values to access the corresponding properties in the overall object: for (const funnelStage of funnelStages) { console.log(funnelStage, overall[funnelStage].count); }
Typescript enum index object iterate over object
I have the following enum enum FunnelStage { LOGIN } then I have the following object const overall = { [FunnelStage.LOGIN]: {count: 1} } overall[FunnelStage.Login].count = 2 and later I want to iterate over the overall object like so for (let funnelStage in overall) { console.log(overall[funnelStage].count) } this gives me an error - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<FunnalStage, { count: number; }>'. No index signature with a parameter of type 'string' was found on type 'Record<FunnalStage, { count: number; }>' How do I achieve my loop ? I tried also like this but it gives me the same error for (let funnelStageKey in Object.keys(overall) as Array<keyof typeof FunnalStage>) { const count = overall[funnelStageKey].count; console.log(count); } LINK TO PLAYGROUND
[ "You can use the Object.entries method to iterate over the properties of the overall object. You can then destructure the key/value pairs in the for-of loop and use the key to access the corresponding enum value:\nfor (const [key, value] of Object.entries(overall)) {\n console.log(FunnelStage[key], value.count);\n}\n\nOr, you can use the Object.keys method to get an array of keys, and then use the map method to create a new array of FunnelStage values:\nconst keys = Object.keys(overall);\nconst funnelStages = keys.map(key => FunnelStage[key]);\n\nYou can then iterate over the funnelStages array and use the values to access the corresponding properties in the overall object:\nfor (const funnelStage of funnelStages) {\n console.log(funnelStage, overall[funnelStage].count);\n}\n\n" ]
[ 0 ]
[]
[]
[ "enums", "typescript" ]
stackoverflow_0074679386_enums_typescript.txt
Q: Why do I get "Pickle - EOFError: Ran out of input" reading an empty file? I am getting an interesting error while trying to use Unpickler.load(), here is the source code: open(target, 'a').close() scores = {}; with open(target, "rb") as file: unpickler = pickle.Unpickler(file); scores = unpickler.load(); if not isinstance(scores, dict): scores = {}; Here is the traceback: Traceback (most recent call last): File "G:\python\pendu\user_test.py", line 3, in <module>: save_user_points("Magix", 30); File "G:\python\pendu\user.py", line 22, in save_user_points: scores = unpickler.load(); EOFError: Ran out of input The file I am trying to read is empty. How can I avoid getting this error, and get an empty variable instead? A: Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not. However, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could have over-written the file. for example: filename = 'cd.pkl' with open(filename, 'wb') as f: classification_dict = pickle.load(f) This will over-write the pickled file. You might have done this by mistake before using: ... open(filename, 'rb') as f: And then got the EOFError because the previous block of code over-wrote the cd.pkl file. When working in Jupyter, or in the console (Spyder) I usually write a wrapper over the reading/writing code, and call the wrapper subsequently. This avoids common read-write mistakes, and saves a bit of time if you're going to be reading the same file multiple times through your travails A: I would check that the file is not empty first: import os scores = {} # scores is an empty dict already if os.path.getsize(target) > 0: with open(target, "rb") as f: unpickler = pickle.Unpickler(f) # if file is not empty scores will be equal # to the value unpickled scores = unpickler.load() Also open(target, 'a').close() is doing nothing in your code and you don't need to use ;. A: It is very likely that the pickled file is empty. It is surprisingly easy to overwrite a pickle file if you're copying and pasting code. For example the following writes a pickle file: pickle.dump(df,open('df.p','wb')) And if you copied this code to reopen it, but forgot to change 'wb' to 'rb' then you would overwrite the file: df=pickle.load(open('df.p','wb')) The correct syntax is df=pickle.load(open('df.p','rb')) A: As you see, that's actually a natural error .. A typical construct for reading from an Unpickler object would be like this .. try: data = unpickler.load() except EOFError: data = list() # or whatever you want EOFError is simply raised, because it was reading an empty file, it just meant End of File .. A: You can catch that exception and return whatever you want from there. open(target, 'a').close() scores = {}; try: with open(target, "rb") as file: unpickler = pickle.Unpickler(file); scores = unpickler.load(); if not isinstance(scores, dict): scores = {}; except EOFError: return {} A: if path.exists(Score_file): try : with open(Score_file , "rb") as prev_Scr: return Unpickler(prev_Scr).load() except EOFError : return dict() A: I have encountered this error many times and it always occurs because after writing into the file, I didn't close it. If we don't close the file the content stays in the buffer and the file stays empty. To save the content into the file, either file should be closed or file_object should go out of scope. That's why at the time of loading it's giving the ran out of input error because the file is empty. So you have two options : file_object.close() file_object.flush(): if you don't wanna close your file in between the program, you can use the flush() function as it will forcefully move the content from the buffer to the file. A: Had the same issue. It turns out when I was writing to my pickle file I had not used the file.close(). Inserted that line in and the error was no more. A: Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting. pointer = open('makeaafile.txt', 'ab+') tes = pickle.load(pointer, encoding='utf-8') A: temp_model = os.path.join(models_dir, train_type + '_' + part + '_' + str(pc)) # print(type(temp_model)) # <class 'str'> filehandler = open(temp_model, "rb") # print(type(filehandler)) # <class '_io.BufferedReader'> try: pdm_temp = pickle.load(filehandler) except UnicodeDecodeError: pdm_temp = pickle.load(filehandler, fix_imports=True, encoding="latin1") A: This error comes when your pickle file is empty (0 Bytes). You need to check the size of your pickle file first. This was the scenario in my case. Hope this helps!
Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?
I am getting an interesting error while trying to use Unpickler.load(), here is the source code: open(target, 'a').close() scores = {}; with open(target, "rb") as file: unpickler = pickle.Unpickler(file); scores = unpickler.load(); if not isinstance(scores, dict): scores = {}; Here is the traceback: Traceback (most recent call last): File "G:\python\pendu\user_test.py", line 3, in <module>: save_user_points("Magix", 30); File "G:\python\pendu\user.py", line 22, in save_user_points: scores = unpickler.load(); EOFError: Ran out of input The file I am trying to read is empty. How can I avoid getting this error, and get an empty variable instead?
[ "Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not.\nHowever, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could have over-written the file.\nfor example:\nfilename = 'cd.pkl'\nwith open(filename, 'wb') as f:\n classification_dict = pickle.load(f)\n\nThis will over-write the pickled file. You might have done this by mistake before using:\n...\nopen(filename, 'rb') as f:\n\nAnd then got the EOFError because the previous block of code over-wrote the cd.pkl file. \nWhen working in Jupyter, or in the console (Spyder) I usually write a wrapper over the reading/writing code, and call the wrapper subsequently. This avoids common read-write mistakes, and saves a bit of time if you're going to be reading the same file multiple times through your travails \n", "I would check that the file is not empty first:\nimport os\n\nscores = {} # scores is an empty dict already\n\nif os.path.getsize(target) > 0: \n with open(target, \"rb\") as f:\n unpickler = pickle.Unpickler(f)\n # if file is not empty scores will be equal\n # to the value unpickled\n scores = unpickler.load()\n\nAlso open(target, 'a').close() is doing nothing in your code and you don't need to use ;.\n", "It is very likely that the pickled file is empty.\nIt is surprisingly easy to overwrite a pickle file if you're copying and pasting code.\nFor example the following writes a pickle file:\npickle.dump(df,open('df.p','wb'))\n\nAnd if you copied this code to reopen it, but forgot to change 'wb' to 'rb' then you would overwrite the file:\ndf=pickle.load(open('df.p','wb'))\n\nThe correct syntax is\ndf=pickle.load(open('df.p','rb'))\n\n", "As you see, that's actually a natural error ..\nA typical construct for reading from an Unpickler object would be like this ..\ntry:\n data = unpickler.load()\nexcept EOFError:\n data = list() # or whatever you want\n\nEOFError is simply raised, because it was reading an empty file, it just meant End of File ..\n", "You can catch that exception and return whatever you want from there. \nopen(target, 'a').close()\nscores = {};\ntry:\n with open(target, \"rb\") as file:\n unpickler = pickle.Unpickler(file);\n scores = unpickler.load();\n if not isinstance(scores, dict):\n scores = {};\nexcept EOFError:\n return {}\n\n", "if path.exists(Score_file):\n try : \n with open(Score_file , \"rb\") as prev_Scr:\n\n return Unpickler(prev_Scr).load()\n\n except EOFError : \n\n return dict() \n\n", "I have encountered this error many times and it always occurs because after writing into the file, I didn't close it. If we don't close the file the content stays in the buffer and the file stays empty.\nTo save the content into the file, either file should be closed or file_object should go out of scope.\nThat's why at the time of loading it's giving the ran out of input error because the file is empty. So you have two options :\n\nfile_object.close()\nfile_object.flush(): if you don't wanna close your file in between the program, you can use the flush() function as it will forcefully move the content from the buffer to the file.\n\n", "Had the same issue. It turns out when I was writing to my pickle file I had not used the file.close(). Inserted that line in and the error was no more.\n", "Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.\npointer = open('makeaafile.txt', 'ab+')\ntes = pickle.load(pointer, encoding='utf-8')\n\n", "temp_model = os.path.join(models_dir, train_type + '_' + part + '_' + str(pc))\n# print(type(temp_model)) # <class 'str'>\nfilehandler = open(temp_model, \"rb\")\n# print(type(filehandler)) # <class '_io.BufferedReader'>\ntry:\n pdm_temp = pickle.load(filehandler)\nexcept UnicodeDecodeError:\n pdm_temp = pickle.load(filehandler, fix_imports=True, encoding=\"latin1\")\n\n", "This error comes when your pickle file is empty (0 Bytes). You need to check the size of your pickle file first. This was the scenario in my case. Hope this helps!\n" ]
[ 297, 176, 27, 11, 3, 2, 1, 1, 0, 0, 0 ]
[ "from os.path import getsize as size\nfrom pickle import *\nif size(target)>0:\n with open(target,'rb') as f:\n scores={i:j for i,j in enumerate(load(f))}\nelse: scores={}\n\n#line 1.\nwe importing Function 'getsize' from Library 'OS' sublibrary 'path' and we rename it with command 'as' for shorter style of writing. Important is hier that we loading only one single Func that we need and not whole Library!\nline 2.\nSame Idea, but when we dont know wich modul we will use in code at the begining, we can import all library using a command '*'.\nline 3.\nConditional Statement... if size of your file >0 ( means obj is not an empty). 'target' is variable that schould be a bit earlier predefined.\njust an Example : target=(r'd:\\dir1\\dir.2..\\YourDataFile.bin')\nLine 4.\n'With open(target) as file:' an open construction for any file, u dont need then to use file.close(). it helps to avoid some typical Errors such as \"Run out of input\" or Permissions rights.\n'rb' mod means 'rea binary' that u can only read(load) the data from your binary file but u cant modify/rewrite it.\nLine5.\nList comprehension method in applying to a Dictionary..\nline 6. Case your datafile is empty, it will not raise an any Error msg, but return just an empty dictionary.\n" ]
[ -1 ]
[ "file", "pickle", "python" ]
stackoverflow_0024791987_file_pickle_python.txt
Q: Accessing variable template using decltype A minimized example of my code showing the problem: #include <cassert> #include <iostream> #include <map> #include <string> template <typename T> const std::map<std::string, T> smap; template <> const std::map<std::string, bool> smap<bool>{{"a", false}}; int main() { std::map<bool, std::string> rmap{{false, "x"}}; for (const auto& [key, val] : rmap) { std::cerr << typeid(bool).hash_code() << "\n"; std::cerr << typeid(decltype(key)).hash_code() << "\n"; std::cerr << smap<bool>.size() << "\n"; std::cerr << smap<decltype(key)>.size() << "\n"; assert((std::is_same_v<bool, decltype(key)>)); } return 0; } Godbolt It gives the output: 10838281452030117757 10838281452030117757 1 0 example.cpp:22: int main(): Assertion `(std::is_same_v<bool, decltype(key)>)' failed. Why is it that I can't access the variable template using decltype when it's referring to the same type (bool)? For the record I also tried to not use structured binding and using decltype on first in the pair with the same result. However if I create an actual bool variable, like so ... bool b; std::cerr << settings_map<decltype(b)>.size() << "\n"; ... it's working. A: the value_type is std::pair<const Key, T>, so decltype(key) is const bool, not bool and you capture it by const auto& so it's const anyway typeid remove all cvref qualifiers, that's why you get same hash_code as a side note, hash_code is a hash and no guaranteed on they would not collide, you can use operator== to check type equality. A: Keys are const so you'll need to remove it to make the assertion pass. assert((std::is_same_v<bool, std::remove_cv_t<decltype(key)>>)); A: decltype(key) is const bool, not bool. And typeid strips const qualifiers, so the two have the same (runtime) representation. If the type of type or expression is cv-qualified, the result of the typeid refers to a std::type_info object representing the cv-unqualified type (that is, typeid(const T) == typeid(T)). So while typeid treats the two types as equivalent, template expansion (and is_same_v) does not, and you get two different maps: one for bool and one for const bool. Note that the assertion assert((std::is_same_v<const bool, decltype(key)>)); succeeeds if put in place of the one in your code. To remove cv-qualifiers, use remove_cv_t. std::cerr << settings_map<std::remove_cv_t<decltype(key)>>.size() << "\n"; In your last snippet bool b; std::cerr << settings_map<decltype(b)>.size() << "\n"; The b is not constant, so decltype(b) is actually bool, not const bool.
Accessing variable template using decltype
A minimized example of my code showing the problem: #include <cassert> #include <iostream> #include <map> #include <string> template <typename T> const std::map<std::string, T> smap; template <> const std::map<std::string, bool> smap<bool>{{"a", false}}; int main() { std::map<bool, std::string> rmap{{false, "x"}}; for (const auto& [key, val] : rmap) { std::cerr << typeid(bool).hash_code() << "\n"; std::cerr << typeid(decltype(key)).hash_code() << "\n"; std::cerr << smap<bool>.size() << "\n"; std::cerr << smap<decltype(key)>.size() << "\n"; assert((std::is_same_v<bool, decltype(key)>)); } return 0; } Godbolt It gives the output: 10838281452030117757 10838281452030117757 1 0 example.cpp:22: int main(): Assertion `(std::is_same_v<bool, decltype(key)>)' failed. Why is it that I can't access the variable template using decltype when it's referring to the same type (bool)? For the record I also tried to not use structured binding and using decltype on first in the pair with the same result. However if I create an actual bool variable, like so ... bool b; std::cerr << settings_map<decltype(b)>.size() << "\n"; ... it's working.
[ "the value_type is std::pair<const Key, T>, so decltype(key) is const bool, not bool\nand you capture it by const auto& so it's const anyway\n\n\ntypeid remove all cvref qualifiers, that's why you get same hash_code\nas a side note, hash_code is a hash and no guaranteed on they would not collide, you can use operator== to check type equality.\n", "Keys are const so you'll need to remove it to make the assertion pass.\nassert((std::is_same_v<bool, std::remove_cv_t<decltype(key)>>));\n\n", "decltype(key) is const bool, not bool. And typeid strips const qualifiers, so the two have the same (runtime) representation.\n\nIf the type of type or expression is cv-qualified, the result of the typeid refers to a std::type_info object representing the cv-unqualified type (that is, typeid(const T) == typeid(T)).\n\nSo while typeid treats the two types as equivalent, template expansion (and is_same_v) does not, and you get two different maps: one for bool and one for const bool. Note that the assertion\nassert((std::is_same_v<const bool, decltype(key)>));\n\nsucceeeds if put in place of the one in your code. To remove cv-qualifiers, use remove_cv_t.\nstd::cerr << settings_map<std::remove_cv_t<decltype(key)>>.size() << \"\\n\";\n\nIn your last snippet\nbool b;\nstd::cerr << settings_map<decltype(b)>.size() << \"\\n\";\n\nThe b is not constant, so decltype(b) is actually bool, not const bool.\n" ]
[ 2, 2, 2 ]
[]
[]
[ "c++", "decltype", "templates" ]
stackoverflow_0074679452_c++_decltype_templates.txt
Q: Summing column values based on time period Date | Cost 1-1-22 | $5 1/1/22 | $10 1/1/22 | $8 2/5-22 | $9 2/5/22 | $10 3/5/22 | $5 3/7/22 | $10 ... 2019 2018 How would I add total costs for a single month, quarterly, and annually? Tried this below --- But it is giving me a lot of NA values for by year and quarter for a large dataset tempDF <- tempDF %>% mutate( Date = lubridate::dmy(Date), Month = lubridate::month(Date), Year = lubridate::year(Date) ) %>% left_join(quarters, by='Month') tempDF %>% group_by(Year) %>% summarise(total = sum(Cost)) # A tibble: 1 × 2 # Year total # <dbl> <dbl> # 1 2022 57 tempDF %>% group_by(Quarter) %>% summarise(total = sum(Cost)) # A tibble: 3 × 2 # Quarter total # <chr> <dbl> # 1 Q1 23 # 2 Q2 24 # 3 Q3 10 tempDF %>% group_by(Month) %>% summarise(total = sum(Cost)) # A tibble: 3 × 2 # Month total # <dbl> <dbl> # 1 1 23 # 2 5 24 # 3 7 10 A: Assuming the data shown reproducibly in the Note at the end what is wanted is the sum of the Cost column by year/month, year/quarter and year that any NA's are to be removed before summing then first clean it up (change - to / in Date and convert Date to Date class, remove $ in Cost and convert Cost to numeric) giving DF2 and then group by yearmon, yearqtr and year and summarize: Presumably the NA's you got are either from not cleaning up the data or if there are NA's in the data then by not using sum(..., na.rm = TRUE) . library(dplyr) library(zoo) DF2 <- DF %>% mutate(Date = as.Date(gsub("-", "/", Date), "%m/%d/%y"), Cost = as.numeric(sub("\\$", "", Cost))) DF2 %>% group_by(yearmon = as.yearmon(Date)) %>% summarize(Cost = sum(Cost, na.rm = TRUE)) ## # A tibble: 3 × 2 ## yearmon Cost ## <yearmon> <dbl> ## 1 Jan 2022 23 ## 2 Feb 2022 19 ## 3 Mar 2022 15 DF2 %>% group_by(yearqtr = as.yearqtr(Date)) %>% summarize(Cost = sum(Cost, na.rm = TRUE)) ## # A tibble: 1 × 2 ## yearqtr Cost ## <yearqtr> <dbl> ## 1 2022 Q1 57 DF2 %>% group_by(year = as.integer(as.yearmon(Date))) %>% summarize(Cost = sum(Cost, na.rm = TRUE)) ## # A tibble: 1 × 2 ## year Cost ## <int> <dbl> ## 1 2022 57 Note Lines <- "Date | Cost 1-1-22 | $5 1/1/22 | $10 1/1/22 | $8 2/5/22 | $9 2/5/22 | $10 3/5/22 | $5 3/7/22 | $10" DF <- read.table(text = Lines, header = TRUE, sep = "|", strip.white = TRUE)
Summing column values based on time period
Date | Cost 1-1-22 | $5 1/1/22 | $10 1/1/22 | $8 2/5-22 | $9 2/5/22 | $10 3/5/22 | $5 3/7/22 | $10 ... 2019 2018 How would I add total costs for a single month, quarterly, and annually? Tried this below --- But it is giving me a lot of NA values for by year and quarter for a large dataset tempDF <- tempDF %>% mutate( Date = lubridate::dmy(Date), Month = lubridate::month(Date), Year = lubridate::year(Date) ) %>% left_join(quarters, by='Month') tempDF %>% group_by(Year) %>% summarise(total = sum(Cost)) # A tibble: 1 × 2 # Year total # <dbl> <dbl> # 1 2022 57 tempDF %>% group_by(Quarter) %>% summarise(total = sum(Cost)) # A tibble: 3 × 2 # Quarter total # <chr> <dbl> # 1 Q1 23 # 2 Q2 24 # 3 Q3 10 tempDF %>% group_by(Month) %>% summarise(total = sum(Cost)) # A tibble: 3 × 2 # Month total # <dbl> <dbl> # 1 1 23 # 2 5 24 # 3 7 10
[ "Assuming\n\nthe data shown reproducibly in the Note at the end\nwhat is wanted is the sum of the Cost column by year/month, year/quarter and year\nthat any NA's are to be removed before summing\n\nthen first clean it up (change - to / in Date and convert Date to Date class, remove $ in Cost and convert Cost to numeric) giving DF2 and then group by yearmon, yearqtr and year and summarize:\nPresumably the NA's you got are either from not cleaning up the data or if there are NA's in the data then by not using sum(..., na.rm = TRUE) .\nlibrary(dplyr)\nlibrary(zoo)\n \nDF2 <- DF %>%\n mutate(Date = as.Date(gsub(\"-\", \"/\", Date), \"%m/%d/%y\"),\n Cost = as.numeric(sub(\"\\\\$\", \"\", Cost)))\n\nDF2 %>%\n group_by(yearmon = as.yearmon(Date)) %>%\n summarize(Cost = sum(Cost, na.rm = TRUE))\n## # A tibble: 3 × 2\n## yearmon Cost\n## <yearmon> <dbl>\n## 1 Jan 2022 23\n## 2 Feb 2022 19\n## 3 Mar 2022 15\n\nDF2 %>%\n group_by(yearqtr = as.yearqtr(Date)) %>%\n summarize(Cost = sum(Cost, na.rm = TRUE))\n## # A tibble: 1 × 2\n## yearqtr Cost\n## <yearqtr> <dbl>\n## 1 2022 Q1 57\n\nDF2 %>%\n group_by(year = as.integer(as.yearmon(Date))) %>%\n summarize(Cost = sum(Cost, na.rm = TRUE))\n## # A tibble: 1 × 2\n## year Cost\n## <int> <dbl>\n## 1 2022 57\n\nNote\nLines <- \"Date | Cost\n1-1-22 | $5\n1/1/22 | $10\n1/1/22 | $8\n2/5/22 | $9\n2/5/22 | $10\n3/5/22 | $5\n3/7/22 | $10\"\nDF <- read.table(text = Lines, header = TRUE, sep = \"|\", strip.white = TRUE)\n\n" ]
[ 0 ]
[]
[]
[ "r" ]
stackoverflow_0074673059_r.txt
Q: Update only the chunks that have changed with Webpack.watch()? I have a webpack build that utilizes the watch() method to continuously rebuild my javascript as I work. I also have a watcher that uploads changed JS files to a remote server. Right now when I change ANY file, it recompiles ALL files. So even if one chunk changed, it will update everything, including my vendor file and other unrelated bundles, chunks, etc. Is there a way in Webpack to only recompile the files that changed and have dependencies that were changed? Here's an example of my webpack build code: var compiler = webpack(require('./webpack.config.js')); compiler.watch({ aggregateTimeout: 300, // wait so long for more changes poll: true }, function(err, stats) { console.log(stats); }); A: Yes, can do this by using the optimization.moduleIds option in your webpack configuration. The optimization.moduleIds option allows you to specify the method that webpack should use to generate module IDs for module identification in the generated code. By default, webpack uses the natural module ID generation method, which assigns a unique ID to each module based on its location in the file system. This means that whenever the file system structure changes, all module IDs will be regenerated, even if the module content has not changed. If you want to only recompile the changed modules and their dependencies, you can use the named or hashed module ID generation methods. These methods generate module IDs based on the module name or the module content hash, respectively, so they will not change unless the module content itself changes. Here is an example of how you can configure webpack to use the named module ID generation method: module.exports = { // ... optimization: { moduleIds: 'named' } }; With this configuration, webpack will only recompile the changed modules and their dependencies when you use the watch method.
Update only the chunks that have changed with Webpack.watch()?
I have a webpack build that utilizes the watch() method to continuously rebuild my javascript as I work. I also have a watcher that uploads changed JS files to a remote server. Right now when I change ANY file, it recompiles ALL files. So even if one chunk changed, it will update everything, including my vendor file and other unrelated bundles, chunks, etc. Is there a way in Webpack to only recompile the files that changed and have dependencies that were changed? Here's an example of my webpack build code: var compiler = webpack(require('./webpack.config.js')); compiler.watch({ aggregateTimeout: 300, // wait so long for more changes poll: true }, function(err, stats) { console.log(stats); });
[ "Yes, can do this by using the optimization.moduleIds option in your webpack configuration.\nThe optimization.moduleIds option allows you to specify the method that webpack should use to generate module IDs for module identification in the generated code. By default, webpack uses the natural module ID generation method, which assigns a unique ID to each module based on its location in the file system. This means that whenever the file system structure changes, all module IDs will be regenerated, even if the module content has not changed.\nIf you want to only recompile the changed modules and their dependencies, you can use the named or hashed module ID generation methods. These methods generate module IDs based on the module name or the module content hash, respectively, so they will not change unless the module content itself changes.\nHere is an example of how you can configure webpack to use the named module ID generation method:\nmodule.exports = {\n // ...\n optimization: {\n moduleIds: 'named'\n }\n};\n\nWith this configuration, webpack will only recompile the changed modules and their dependencies when you use the watch method.\n" ]
[ 0 ]
[]
[]
[ "build", "gulp", "javascript", "webpack" ]
stackoverflow_0034729163_build_gulp_javascript_webpack.txt
Q: How to save an OpenGL rendering to disk I'm using this library in order to render an STL: How do we convert this STL into a BITMAP or IMAGE? This method is responsible for generating the STL: private void ReadSelectedFile(string fileName) { STLReader stlReader = new STLReader(fileName); TriangleMesh[] meshArray = stlReader.ReadFile(); modelVAO = new Batu_GL.VAO_TRIANGLES(); modelVAO.parameterArray = STLExport.Get_Mesh_Vertices(meshArray); modelVAO.normalArray = STLExport.Get_Mesh_Normals(meshArray); modelVAO.color = Color.Crimson; minPos = stlReader.GetMinMeshPosition(meshArray); maxPos = stlReader.GetMaxMeshPosition(meshArray); orb.Reset_Orientation(); orb.Reset_Pan(); orb.Reset_Scale(); if (stlReader.Get_Process_Error()) { modelVAO = null; /* if there is an error, deinitialize the gl monitor to clear the screen */ Batu_GL.Configure(GL_Monitor, Batu_GL.Ortho_Mode.CENTER); GL_Monitor.SwapBuffers(); } } How do generate an image/bitmap and save it? I've stumbled upon this, specifically this method: // Returns a System.Drawing.Bitmap with the contents of the current framebuffer public static Bitmap GrabScreenshot() { if (GraphicsContext.CurrentContext == null) throw new GraphicsContextMissingException(); Bitmap bmp = new Bitmap(this.ClientSize.Width, this.ClientSize.Height); System.Drawing.Imaging.BitmapData data = bmp.LockBits(this.ClientRectangle, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); GL.ReadPixels(0, 0, this.ClientSize.Width, this.ClientSize.Height, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0); bmp.UnlockBits(data); bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); return bmp; } However, I'm getting this issue: System.Runtime.InteropServices.ExternalException HResult=0x80004005 Message=A generic error occurred in GDI+. Source=System.Drawing StackTrace: at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(String filename, ImageFormat format) at System.Drawing.Image.Save(String filename) at STLViewer.AppMainForm.ReadSelectedFile(String fileName) in C:\Users\alexg\Source\Repos\STL-Viewer\STL-Viewer\AppMainForm.cs:line 152 at STLViewer.AppMainForm.FileMenuImportBt_Click(Object sender, EventArgs e) in C:\Users\alexg\Source\Repos\STL-Viewer\STL-Viewer\AppMainForm.cs:line 162 at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e) at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e) at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e) at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e) at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met) at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met) at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea) at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ToolStrip.WndProc(Message& m) at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at STLViewer.Program.Main() in C:\Users\alexg\Source\Repos\STL-Viewer\STL-Viewer\Program.cs:line 19 A: OK I just busted up small C++/OpenGL/VCL example of this: void gl_save_bmp(AnsiString name,int xs,int ys) { int hnd; // header extracted from 24bit uncompressed BMP image DWORD hdr[54>>2]={0x3ACE4D42,0x0,0x360000,0x280000,0x640000,0x320000,0x10000,0x18,0x3A980000,0x0,0x0,0x0,0x0}; // chnage resolution ((DWORD*)(((BYTE*)hdr)+0x12))[0]=xs; ((DWORD*)(((BYTE*)hdr)+0x16))[0]=ys; // read pixel data from OpenGL into memory BYTE *dat=new BYTE[xs*ys*3]; glReadPixels(0,0,xs,ys,GL_BGR,GL_UNSIGNED_BYTE,dat); // save header hnd=FileCreate(name); FileWrite(hnd,hdr,54); // save pixel data FileWrite(hnd,dat,xs*ys*3); // free up stuff FileClose(hnd); delete[] dat; } simply call it after you render your scene providing out filename and resolution of your OpenGL window ... Just port it to C# and change the file access to whatever you got at disposal. The header was extracted from 24bit BMP created in MS Paint (win7 x64) ... and just changed the resolution according to BMP format specs Here sample output it produced: just beware that for resolutions not divisible by 4 it might need some align tweaking (I am too lazy to check it)...
How to save an OpenGL rendering to disk
I'm using this library in order to render an STL: How do we convert this STL into a BITMAP or IMAGE? This method is responsible for generating the STL: private void ReadSelectedFile(string fileName) { STLReader stlReader = new STLReader(fileName); TriangleMesh[] meshArray = stlReader.ReadFile(); modelVAO = new Batu_GL.VAO_TRIANGLES(); modelVAO.parameterArray = STLExport.Get_Mesh_Vertices(meshArray); modelVAO.normalArray = STLExport.Get_Mesh_Normals(meshArray); modelVAO.color = Color.Crimson; minPos = stlReader.GetMinMeshPosition(meshArray); maxPos = stlReader.GetMaxMeshPosition(meshArray); orb.Reset_Orientation(); orb.Reset_Pan(); orb.Reset_Scale(); if (stlReader.Get_Process_Error()) { modelVAO = null; /* if there is an error, deinitialize the gl monitor to clear the screen */ Batu_GL.Configure(GL_Monitor, Batu_GL.Ortho_Mode.CENTER); GL_Monitor.SwapBuffers(); } } How do generate an image/bitmap and save it? I've stumbled upon this, specifically this method: // Returns a System.Drawing.Bitmap with the contents of the current framebuffer public static Bitmap GrabScreenshot() { if (GraphicsContext.CurrentContext == null) throw new GraphicsContextMissingException(); Bitmap bmp = new Bitmap(this.ClientSize.Width, this.ClientSize.Height); System.Drawing.Imaging.BitmapData data = bmp.LockBits(this.ClientRectangle, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); GL.ReadPixels(0, 0, this.ClientSize.Width, this.ClientSize.Height, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0); bmp.UnlockBits(data); bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); return bmp; } However, I'm getting this issue: System.Runtime.InteropServices.ExternalException HResult=0x80004005 Message=A generic error occurred in GDI+. Source=System.Drawing StackTrace: at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(String filename, ImageFormat format) at System.Drawing.Image.Save(String filename) at STLViewer.AppMainForm.ReadSelectedFile(String fileName) in C:\Users\alexg\Source\Repos\STL-Viewer\STL-Viewer\AppMainForm.cs:line 152 at STLViewer.AppMainForm.FileMenuImportBt_Click(Object sender, EventArgs e) in C:\Users\alexg\Source\Repos\STL-Viewer\STL-Viewer\AppMainForm.cs:line 162 at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e) at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e) at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e) at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e) at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met) at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met) at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea) at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ToolStrip.WndProc(Message& m) at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at STLViewer.Program.Main() in C:\Users\alexg\Source\Repos\STL-Viewer\STL-Viewer\Program.cs:line 19
[ "OK I just busted up small C++/OpenGL/VCL example of this:\nvoid gl_save_bmp(AnsiString name,int xs,int ys)\n {\n int hnd;\n // header extracted from 24bit uncompressed BMP image\n DWORD hdr[54>>2]={0x3ACE4D42,0x0,0x360000,0x280000,0x640000,0x320000,0x10000,0x18,0x3A980000,0x0,0x0,0x0,0x0};\n // chnage resolution\n ((DWORD*)(((BYTE*)hdr)+0x12))[0]=xs;\n ((DWORD*)(((BYTE*)hdr)+0x16))[0]=ys;\n // read pixel data from OpenGL into memory\n BYTE *dat=new BYTE[xs*ys*3];\n glReadPixels(0,0,xs,ys,GL_BGR,GL_UNSIGNED_BYTE,dat);\n // save header\n hnd=FileCreate(name);\n FileWrite(hnd,hdr,54);\n // save pixel data\n FileWrite(hnd,dat,xs*ys*3);\n // free up stuff\n FileClose(hnd);\n delete[] dat;\n }\n\nsimply call it after you render your scene providing out filename and resolution of your OpenGL window ...\nJust port it to C# and change the file access to whatever you got at disposal. The header was extracted from 24bit BMP created in MS Paint (win7 x64) ... and just changed the resolution according to BMP format specs\nHere sample output it produced:\n\njust beware that for resolutions not divisible by 4 it might need some align tweaking (I am too lazy to check it)...\n" ]
[ 0 ]
[]
[]
[ "c#", "opengl", "opentk", "screenshot", "stl_format" ]
stackoverflow_0074660393_c#_opengl_opentk_screenshot_stl_format.txt
Q: Converting a BigInteger to a string in some base: speed issue (Kotlin) I want to convert large positive BigIntegers (up to many thousands of digits) to strings in Kotlin, using number bases up to 100 (and possibly higher). For bases ≤36, there is of course toString(base), but for larger bases, I wrote this extension function: fun BigInteger.toStringX(base: Int): String { if (base <= 36) return toString(base) // improve speed if base <= 36 val bigBase = base.toBigInteger() var n = this val stringBuilder = StringBuilder() while (n > ZERO) { val div = n.divideAndRemainder(bigBase) stringBuilder.append(DIGITS[div[1].toInt()]) n = div[0] } return stringBuilder.reverse().toString() } where DIGITS is a string containing the list of digits. Now the native toString is faster by about an order of magnitude than my function – e.g. 60 ms for about 10,000 digits vs. 500 ms. Why is my function so slow? Any help improving on its speed (while maintinaing the ability to convert to bases > 36) would be appreciated. (By the way, replacing append() with insert() and losing reverse() in the last line doesn't change much.) A: Looking at the source code for the built-in toString, it seems to call this private toString, which implements a divide-and-conquer algorithm. /** * Converts the specified BigInteger to a string and appends to * {@code sb}. This implements the recursive Schoenhage algorithm * for base conversions. This method can only be called for non-negative * numbers. * <p> * See Knuth, Donald, _The Art of Computer Programming_, Vol. 2, * Answers to Exercises (4.4) Question 14. * * @param u The number to convert to a string. * @param sb The StringBuilder that will be appended to in place. * @param radix The base to convert to. * @param digits The minimum number of digits to pad to. */ private static void toString(BigInteger u, StringBuilder sb, int radix, int digits) { ... results = u.divideAndRemainder(v); int expectedDigits = 1 << n; // Now recursively build the two halves of each number. toString(results[0], sb, radix, digits - expectedDigits); toString(results[1], sb, radix, expectedDigits); } This means that there is only O(log(N)) divisions, for an N-bit number. Compare this to your algorithm, which does O(N) divisions. So for large numbers, you can implement this algorithm too - "split" the number up into smaller ones, then use your O(N) algorithm when they are small enough, all the while passing the string builder along, so the digits are appended.
Converting a BigInteger to a string in some base: speed issue (Kotlin)
I want to convert large positive BigIntegers (up to many thousands of digits) to strings in Kotlin, using number bases up to 100 (and possibly higher). For bases ≤36, there is of course toString(base), but for larger bases, I wrote this extension function: fun BigInteger.toStringX(base: Int): String { if (base <= 36) return toString(base) // improve speed if base <= 36 val bigBase = base.toBigInteger() var n = this val stringBuilder = StringBuilder() while (n > ZERO) { val div = n.divideAndRemainder(bigBase) stringBuilder.append(DIGITS[div[1].toInt()]) n = div[0] } return stringBuilder.reverse().toString() } where DIGITS is a string containing the list of digits. Now the native toString is faster by about an order of magnitude than my function – e.g. 60 ms for about 10,000 digits vs. 500 ms. Why is my function so slow? Any help improving on its speed (while maintinaing the ability to convert to bases > 36) would be appreciated. (By the way, replacing append() with insert() and losing reverse() in the last line doesn't change much.)
[ "Looking at the source code for the built-in toString, it seems to call this private toString, which implements a divide-and-conquer algorithm.\n/**\n * Converts the specified BigInteger to a string and appends to\n * {@code sb}. This implements the recursive Schoenhage algorithm\n * for base conversions. This method can only be called for non-negative\n * numbers.\n * <p>\n * See Knuth, Donald, _The Art of Computer Programming_, Vol. 2,\n * Answers to Exercises (4.4) Question 14.\n *\n * @param u The number to convert to a string.\n * @param sb The StringBuilder that will be appended to in place.\n * @param radix The base to convert to.\n * @param digits The minimum number of digits to pad to.\n */\nprivate static void toString(BigInteger u, StringBuilder sb,\n int radix, int digits) {\n\n ...\n\n results = u.divideAndRemainder(v);\n\n int expectedDigits = 1 << n;\n\n // Now recursively build the two halves of each number.\n toString(results[0], sb, radix, digits - expectedDigits);\n toString(results[1], sb, radix, expectedDigits);\n\n}\n\nThis means that there is only O(log(N)) divisions, for an N-bit number. Compare this to your algorithm, which does O(N) divisions.\nSo for large numbers, you can implement this algorithm too - \"split\" the number up into smaller ones, then use your O(N) algorithm when they are small enough, all the while passing the string builder along, so the digits are appended.\n" ]
[ 0 ]
[]
[]
[ "base_conversion", "kotlin" ]
stackoverflow_0074679019_base_conversion_kotlin.txt
Q: Laravel Filter Query results based on URL Parameters The issue: How do I pass the following values to the URL. It would also need to have the ability to pass both, the date option and category to the URL, so I can handle it in the controller with the $request->query('') I cannot figure out how to do this? I have the following Controller: public function allCoursesList(Request $request) { if (empty($request->query())) { return view('pages.all-events', [ 'events' => Events::query() ->where('start', '>', now()) // add pagination ->paginate(15) ]); } else { return view('pages.all-events', [ 'events' => Events::query() ->where('category', $request->query('category')) ->where('start', '>', now()) // add pagination ->paginate(15) ]); } } and I have my filter blade: <form class="container"> <div class="bg-custom-gray p-6 rounded-lg"> <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <div class="mb-3">Kategorie</div> <select class="w-full p-3 rounded-lg"> <option value="0">Lorem Impsum</option> <option value="1">Lorem Impsum</option> <option value="2">Lorem Impsum</option> <option value="3">Lorem Impsum</option> <option value="4">Lorem Impsum</option> <option value="5">Lorem Impsum</option> <option value="6">Lorem Impsum</option> <option value="7">Lorem Impsum</option> <option value="8">Lorem Impsum</option> </select> </div> <div> <div class="mb-3">Zeitbereich</div> <select class="w-full p-3 rounded-lg"> <option>Anstehend</option> <option>Heute</option> <option>Morgen</option> <option>Diese Woche</option> <option>Dieses Wochenende</option> <option>Nächste Woche</option> <option>Nächster Monat</option> </select> </div> </div> <x-button type="submit" class="mt-6 w-full">Suchen</x-button> </div> </form> based on the controller I can pass my category to the query with e.g. example.com/loremimpsum?category=1 A: This issue was caused because the <select> was missing a name value. So by adding name="category" <select name="category" class="w-full p-3 rounded-lg"> <option value="0">Lorem Impsum</option> <option value="1">Lorem Impsum</option> <option value="2">Lorem Impsum</option> <option value="3">Lorem Impsum</option> <option value="4">Lorem Impsum</option> <option value="5">Lorem Impsum</option> <option value="6">Lorem Impsum</option> <option value="7">Lorem Impsum</option> <option value="8">Lorem Impsum</option> </select> I get the wanted URL parameter for the controller. Thank you very much for this info @lagbox
Laravel Filter Query results based on URL Parameters
The issue: How do I pass the following values to the URL. It would also need to have the ability to pass both, the date option and category to the URL, so I can handle it in the controller with the $request->query('') I cannot figure out how to do this? I have the following Controller: public function allCoursesList(Request $request) { if (empty($request->query())) { return view('pages.all-events', [ 'events' => Events::query() ->where('start', '>', now()) // add pagination ->paginate(15) ]); } else { return view('pages.all-events', [ 'events' => Events::query() ->where('category', $request->query('category')) ->where('start', '>', now()) // add pagination ->paginate(15) ]); } } and I have my filter blade: <form class="container"> <div class="bg-custom-gray p-6 rounded-lg"> <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <div class="mb-3">Kategorie</div> <select class="w-full p-3 rounded-lg"> <option value="0">Lorem Impsum</option> <option value="1">Lorem Impsum</option> <option value="2">Lorem Impsum</option> <option value="3">Lorem Impsum</option> <option value="4">Lorem Impsum</option> <option value="5">Lorem Impsum</option> <option value="6">Lorem Impsum</option> <option value="7">Lorem Impsum</option> <option value="8">Lorem Impsum</option> </select> </div> <div> <div class="mb-3">Zeitbereich</div> <select class="w-full p-3 rounded-lg"> <option>Anstehend</option> <option>Heute</option> <option>Morgen</option> <option>Diese Woche</option> <option>Dieses Wochenende</option> <option>Nächste Woche</option> <option>Nächster Monat</option> </select> </div> </div> <x-button type="submit" class="mt-6 w-full">Suchen</x-button> </div> </form> based on the controller I can pass my category to the query with e.g. example.com/loremimpsum?category=1
[ "This issue was caused because the <select> was missing a name value.\nSo by adding name=\"category\"\n<select name=\"category\" class=\"w-full p-3 rounded-lg\">\n <option value=\"0\">Lorem Impsum</option>\n <option value=\"1\">Lorem Impsum</option>\n <option value=\"2\">Lorem Impsum</option>\n <option value=\"3\">Lorem Impsum</option>\n <option value=\"4\">Lorem Impsum</option>\n <option value=\"5\">Lorem Impsum</option>\n <option value=\"6\">Lorem Impsum</option>\n <option value=\"7\">Lorem Impsum</option>\n <option value=\"8\">Lorem Impsum</option>\n</select>\n\nI get the wanted URL parameter for the controller. Thank you very much for this info @lagbox\n" ]
[ 0 ]
[]
[]
[ "forms", "html", "laravel", "php" ]
stackoverflow_0074678837_forms_html_laravel_php.txt
Q: SCNScene initialization from file crashes on macOS Ventura This is pretty unusual, because I'm unable to replicate the issue on macOS Monterey. I have a SCNScene object that is initialized in viewDidLoad as such: scene = SCNScene(named: "art.scnassets/preview.scn")! And as you can see below, the file exists in my project's Resources under the appropriate path: As previously mentioned, the crash does not occur in builds created under macOS Monterey. Did something change in the resource file path's API? So far I have tried to initialize using a different way of creating the URL, like so: scene = try! SCNScene(url: Bundle.main.url(forResource: "art.scnassets/preview", withExtension: "scn")!) A: 1. Reset the path to Command Line Tools To fix this issue, install the latest version of Command_Line_Tools for Xcode 14.1 and then execute these two commands in zsh Terminal (password is required): sudo xcode-select --reset sudo xcode-select -switch /Library/Developer/CommandLineTools Restart your Mac. 2. Renaming process Rename the art.scnassets to artist.scnassets if the above steps still do not help.
SCNScene initialization from file crashes on macOS Ventura
This is pretty unusual, because I'm unable to replicate the issue on macOS Monterey. I have a SCNScene object that is initialized in viewDidLoad as such: scene = SCNScene(named: "art.scnassets/preview.scn")! And as you can see below, the file exists in my project's Resources under the appropriate path: As previously mentioned, the crash does not occur in builds created under macOS Monterey. Did something change in the resource file path's API? So far I have tried to initialize using a different way of creating the URL, like so: scene = try! SCNScene(url: Bundle.main.url(forResource: "art.scnassets/preview", withExtension: "scn")!)
[ "1. Reset the path to Command Line Tools\nTo fix this issue, install the latest version of Command_Line_Tools for Xcode 14.1 and then execute these two commands in zsh Terminal (password is required):\nsudo xcode-select --reset\n\n\nsudo xcode-select -switch /Library/Developer/CommandLineTools\n\nRestart your Mac.\n\n2. Renaming process\nRename the art.scnassets to artist.scnassets if the above steps still do not help.\n" ]
[ 0 ]
[]
[]
[ "crash", "macos_ventura", "scenekit" ]
stackoverflow_0074320169_crash_macos_ventura_scenekit.txt
Q: How to Exclude a column in a row of data in sqlalchemy and fastapi I am trying to load only AuthUser.id and AuthUser.username from the below result statement = select(func.count(UserCountry.id).label("uid"), AuthUser.id,AuthUser.username).\ join(CountryTool, CountryTool.id == UserCountry.country_tool_id).\ join(Country, Country.id == CountryTool.country_id).\ join(Tool, Tool.id == CountryTool.tool_id).\ join(AuthUser, AuthUser.id == UserCountry.user_id).\ where(CountryTool.id == country_tool_id).\ group_by(AuthUser.id,AuthUser.username) current json response is { "uid": 1, "id": 1, "username": "ross" }, { "uid": 1, "id": 2, "username": "harvey" } response that I need is { "id": 1, "username": "ross" }, { "id": 2, "username": "harvey" } A: You can do it like this: result = statement.all() response = [] for r in result: response.append({ "id": r[1], "username": r[2] }) This code will iterate over the query result, and create a dictionary object with only the id and username fields, and append it to the response list. You can then return the response list as the JSON response.
How to Exclude a column in a row of data in sqlalchemy and fastapi
I am trying to load only AuthUser.id and AuthUser.username from the below result statement = select(func.count(UserCountry.id).label("uid"), AuthUser.id,AuthUser.username).\ join(CountryTool, CountryTool.id == UserCountry.country_tool_id).\ join(Country, Country.id == CountryTool.country_id).\ join(Tool, Tool.id == CountryTool.tool_id).\ join(AuthUser, AuthUser.id == UserCountry.user_id).\ where(CountryTool.id == country_tool_id).\ group_by(AuthUser.id,AuthUser.username) current json response is { "uid": 1, "id": 1, "username": "ross" }, { "uid": 1, "id": 2, "username": "harvey" } response that I need is { "id": 1, "username": "ross" }, { "id": 2, "username": "harvey" }
[ "You can do it like this:\nresult = statement.all()\nresponse = []\n\nfor r in result:\n\n response.append({\n \"id\": r[1],\n \"username\": r[2]\n })\n\nThis code will iterate over the query result, and create a dictionary object with only the id and username fields, and append it to the response list. You can then return the response list as the JSON response.\n" ]
[ 0 ]
[]
[]
[ "fastapi", "python", "python_3.x", "sqlalchemy" ]
stackoverflow_0074679473_fastapi_python_python_3.x_sqlalchemy.txt
Q: Create New rows from a multiple columns of lists I am scraping a website:- https://spfpharmacy.com/ I have successfully scraped this using selenium using the below code. test_list = [] test_list = list(string.ascii_uppercase) med_url = [] for i in tqdm(test_ list): driver.get(f'https://spfpharmacy.com/search/?drugName={i}') for i in driver.find_elements(By.XPATH,"//a[@class='rxrequired default']"): med_url.append(i.get_attribute("href")) data = [] for i in tqdm(med_url): driver.get(i) time.sleep(1) try: med_name = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div[@class='product-name']"): med_name.append(i.text) except: med_name.append(None) try: manuf_name = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div//span[@class='manufactured-name']"): manuf_name.append(i.text) except: manuf_name.append(i.text) try: country = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div//span[@class='product-country']"): country.append(i.text) except: country.append(None) try: pres_req = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div//span[@class='product-prescription']"): pres_req.append(i.text) except: pres_req.append(None) str_price = [] try: for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div//span[@class='product-dose-text']"): for j in driver.find_elements(By.XPATH,f"//div[@id='brand_dose']//div//select//option[@data-str='{i.text}']"): str_price.append({i.text, j.text}) except: str_price.append(None) data.append({ 'Medicine_name':med_name, 'Manufacture_name':manuf_name, 'Product_Counry':country, 'Prescription_Required':pres_req, 'Product_Details':str_price}) where test_list is a list of alphabets in uppercase which completes the URL like:- https://spfpharmacy.com/search/?drugName=A which gives the details of all the medicines with A. After scraping the data I am getting results as shown below:- But I want to get the name of each medicine in a single row and all details associated with that medicine under different columns. Something like this. I tried using explode, and transform and also searched over the internet and stack overflow but was unable to convert this into the expected format. A: It looks like you are appending the values to the list within the try block, which means that if an exception occurs, the list will not be updated. Instead, you should append the values to the list outside of the try block, and use a default value within the except block. For example, instead of this: try: med_name = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div[@class='product-name']"): med_name.append(i.text) except: med_name.append(None) You can do this: med_name = [] try: for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div[@class='product-name']"): med_name.append(i.text) except: med_name.append(None) This way, the med_name list will always be updated, whether or not an exception occurs. To achieve the expected output, you can simply use the extend method to add the elements of the lists to the data list, instead of creating a dictionary and appending that to the data list. For example, instead of this: data.append({ 'Medicine_name':med_name, 'Manufacture_name':manuf_name, 'Product_Counry':country, 'Prescription_Required':pres_req, 'Product_Details':str_price}) You can do this: data.extend(zip(med_name, manuf_name, country, pres_req, str_price)) This will create a list of tuples, where each tuple contains the values of the corresponding elements from the med_name, manuf_name, country, pres_req, and str_price lists. This will give you the desired output, where each medicine's details are on a separate row.
Create New rows from a multiple columns of lists
I am scraping a website:- https://spfpharmacy.com/ I have successfully scraped this using selenium using the below code. test_list = [] test_list = list(string.ascii_uppercase) med_url = [] for i in tqdm(test_ list): driver.get(f'https://spfpharmacy.com/search/?drugName={i}') for i in driver.find_elements(By.XPATH,"//a[@class='rxrequired default']"): med_url.append(i.get_attribute("href")) data = [] for i in tqdm(med_url): driver.get(i) time.sleep(1) try: med_name = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div[@class='product-name']"): med_name.append(i.text) except: med_name.append(None) try: manuf_name = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div//span[@class='manufactured-name']"): manuf_name.append(i.text) except: manuf_name.append(i.text) try: country = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div//span[@class='product-country']"): country.append(i.text) except: country.append(None) try: pres_req = [] for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div//span[@class='product-prescription']"): pres_req.append(i.text) except: pres_req.append(None) str_price = [] try: for i in driver.find_elements(By.XPATH,"//div[@id='brand_dose']//div//span[@class='product-dose-text']"): for j in driver.find_elements(By.XPATH,f"//div[@id='brand_dose']//div//select//option[@data-str='{i.text}']"): str_price.append({i.text, j.text}) except: str_price.append(None) data.append({ 'Medicine_name':med_name, 'Manufacture_name':manuf_name, 'Product_Counry':country, 'Prescription_Required':pres_req, 'Product_Details':str_price}) where test_list is a list of alphabets in uppercase which completes the URL like:- https://spfpharmacy.com/search/?drugName=A which gives the details of all the medicines with A. After scraping the data I am getting results as shown below:- But I want to get the name of each medicine in a single row and all details associated with that medicine under different columns. Something like this. I tried using explode, and transform and also searched over the internet and stack overflow but was unable to convert this into the expected format.
[ "It looks like you are appending the values to the list within the try block, which means that if an exception occurs, the list will not be updated. Instead, you should append the values to the list outside of the try block, and use a default value within the except block. For example, instead of this:\ntry:\n med_name = []\n for i in driver.find_elements(By.XPATH,\"//div[@id='brand_dose']//div[@class='product-name']\"):\n med_name.append(i.text)\nexcept:\n med_name.append(None)\n\nYou can do this:\nmed_name = []\ntry:\n for i in driver.find_elements(By.XPATH,\"//div[@id='brand_dose']//div[@class='product-name']\"):\n med_name.append(i.text)\nexcept:\n med_name.append(None)\n\nThis way, the med_name list will always be updated, whether or not an exception occurs.\nTo achieve the expected output, you can simply use the extend method to add the elements of the lists to the data list, instead of creating a dictionary and appending that to the data list. For example, instead of this:\ndata.append({\n 'Medicine_name':med_name,\n 'Manufacture_name':manuf_name,\n 'Product_Counry':country,\n 'Prescription_Required':pres_req,\n 'Product_Details':str_price})\n\nYou can do this:\ndata.extend(zip(med_name, manuf_name, country, pres_req, str_price))\n\nThis will create a list of tuples, where each tuple contains the values of the corresponding elements from the med_name, manuf_name, country, pres_req, and str_price lists. This will give you the desired output, where each medicine's details are on a separate row.\n" ]
[ 0 ]
[]
[]
[ "data_preprocessing", "dataframe", "pandas", "python", "selenium" ]
stackoverflow_0074679389_data_preprocessing_dataframe_pandas_python_selenium.txt
Q: Springboot not reading external Property file Trying to read property in SpringBoot application through external property file. @SpringBootApplication @Configuration @PropertySource({"file:${DOCUMENT_CONVERTER_PROPERTIES}"}) public class ConverterApplication { public static void main(String[] args) { SpringApplication.run(ConverterApplication.class, args); } } here, DOCUMENT_CONVERTER_PROPERTIES is the place holder for file F:\PROPPERTIES\converter\documentConverter.properties added in evironment variable. ConverterService.java @Service public class ConverterService { @Autowired private Environment environment; String tempPDFPath = environment.getProperty(Constants.TEMP_PDF_PATH); String tempDocxPath = environment.getProperty(Constants.TEMP_DOCX_PATH); ConverterServiceTest.java @SpringBootTest @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SpringExtension.class) //@TestPropertySource("classpath:/") public class ConverterServiceTest { @Autowired private ConverterService service; private byte[] bytes = null; @Test void testConvertDocxToPDF(){ createFile("<path>/myFile.docx"); //put this file at given location service.convertDocxToPDF(bytes); } what missing here, any help is appreciated Thanks in advance !! A: The problem is building URIs in Windows. Your PropertySource results in file:F:\PROPPERTIES\converter\documentConverter.properties. I think the correct format is file:///F:/PROPPERTIES/converter/documentConverter.properties Backslashes in the path may work, but the slashes at the start (file:///) are mandatory...
Springboot not reading external Property file
Trying to read property in SpringBoot application through external property file. @SpringBootApplication @Configuration @PropertySource({"file:${DOCUMENT_CONVERTER_PROPERTIES}"}) public class ConverterApplication { public static void main(String[] args) { SpringApplication.run(ConverterApplication.class, args); } } here, DOCUMENT_CONVERTER_PROPERTIES is the place holder for file F:\PROPPERTIES\converter\documentConverter.properties added in evironment variable. ConverterService.java @Service public class ConverterService { @Autowired private Environment environment; String tempPDFPath = environment.getProperty(Constants.TEMP_PDF_PATH); String tempDocxPath = environment.getProperty(Constants.TEMP_DOCX_PATH); ConverterServiceTest.java @SpringBootTest @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SpringExtension.class) //@TestPropertySource("classpath:/") public class ConverterServiceTest { @Autowired private ConverterService service; private byte[] bytes = null; @Test void testConvertDocxToPDF(){ createFile("<path>/myFile.docx"); //put this file at given location service.convertDocxToPDF(bytes); } what missing here, any help is appreciated Thanks in advance !!
[ "The problem is building URIs in Windows.\nYour PropertySource results in\nfile:F:\\PROPPERTIES\\converter\\documentConverter.properties.\nI think the correct format is\nfile:///F:/PROPPERTIES/converter/documentConverter.properties\nBackslashes in the path may work, but the slashes at the start (file:///) are mandatory...\n" ]
[ 0 ]
[]
[]
[ "environment_variables", "java", "properties_file", "spring_boot" ]
stackoverflow_0074675202_environment_variables_java_properties_file_spring_boot.txt
Q: Timeseries - group data by specific time period slices I am working with a csv file that has a dataset of 13 years worth of 5m time intervals. I am trying to slice sections of this dataset into specific time periods. example time_period = (df['time'] >= '01:00:00') & (df['time']<='5:00:00') time_period_df = df.loc[time_period] I would expect an output of only the time between 1-5 to be included in this time period, however, I am getting all 24hrs in the output I would like the output to print only time in between and including 1:00:00 and 5:00:00. A: It looks like you are using the comparison operators >= and <= to try and specify the time range you want to include in your time period dataframe. However, these comparison operators will not work as expected on string values like the ones you have in your time column. Instead of using these operators, you can use the str.slice() method to extract the hour portion of the time strings and then use the comparison operators on those numeric values to specify your time range. Here is an example of how you could do this: # First, extract the hour portion of the time strings df['hour'] = df['time'].str.slice(0, 2) # Next, create a boolean mask using the comparison operators on the 'hour' column time_period = (df['hour'] >= '01') & (df['hour'] <= '05') # Finally, use this boolean mask to create your time period dataframe time_period_df = df.loc[time_period] This should give you a dataframe that includes only the rows with time values between and including 1:00:00 and 5:00:00. Note that this solution assumes that the time strings in your time column are in the format 'HH:MM:SS'. If the time strings are in a different format, you will need to adjust the str.slice() call accordingly.
Timeseries - group data by specific time period slices
I am working with a csv file that has a dataset of 13 years worth of 5m time intervals. I am trying to slice sections of this dataset into specific time periods. example time_period = (df['time'] >= '01:00:00') & (df['time']<='5:00:00') time_period_df = df.loc[time_period] I would expect an output of only the time between 1-5 to be included in this time period, however, I am getting all 24hrs in the output I would like the output to print only time in between and including 1:00:00 and 5:00:00.
[ "It looks like you are using the comparison operators >= and <= to try and specify the time range you want to include in your time period dataframe. However, these comparison operators will not work as expected on string values like the ones you have in your time column. Instead of using these operators, you can use the str.slice() method to extract the hour portion of the time strings and then use the comparison operators on those numeric values to specify your time range.\nHere is an example of how you could do this:\n# First, extract the hour portion of the time strings\ndf['hour'] = df['time'].str.slice(0, 2)\n\n# Next, create a boolean mask using the comparison operators on the 'hour' column\ntime_period = (df['hour'] >= '01') & (df['hour'] <= '05')\n\n# Finally, use this boolean mask to create your time period dataframe\ntime_period_df = df.loc[time_period]\n\nThis should give you a dataframe that includes only the rows with time values between and including 1:00:00 and 5:00:00.\nNote that this solution assumes that the time strings in your time column are in the format 'HH:MM:SS'. If the time strings are in a different format, you will need to adjust the str.slice() call accordingly.\n" ]
[ 0 ]
[]
[]
[ "group_by", "pandas", "python", "python_datetime", "time_series" ]
stackoverflow_0074679543_group_by_pandas_python_python_datetime_time_series.txt
Q: What's the point of conforming to an empty protocol in Swift I'm just working on a codebase where the most classes conform to an empty protocol. Is there any point of doing so? Actually conforming that protocol does nothing. Edit as reaction to @vacawama's helpful comment : the protocol is only used once import Foundation protocol myUrlRequestConfig {} extension myUrlRequest: myUrlRequestConfig { public static func configGetAppConfig() -> URLRequest { let request = .... return request } } A: An empty protocol can be useful if you want to create an easy way to add static functions or variables to several different classes. Of course, this only makes sense if the static functionality is the same for all classes conforming to the protocol. Here is an example: I have a protocol sizeable. Every class that conforms to Sizeable is extended with the static variable stride and size. protocol Sizeable { } extension Sizeable { static var size: Int { return MemoryLayout<Self>.size } static var stride: Int { return MemoryLayout<Self>.stride } } class Foo: Sizeable {} class Baa: Sizeable {} Foo.size Baa.size A: Our app has three perfectly legitimate uses for an empty protocol: The protocol has an extension with method definitions. The implementation in the extension is automatically injected into any type that adopts the protocol. The protocol has other protocols that adopt it. This allows multiple protocols to be unified under a single head. The protocol marks the adopter as wanting some other type to behave in a certain way. Code can always is whether an object is ThisEmptyProtocol and if it is, can behave differently than if it isn't.
What's the point of conforming to an empty protocol in Swift
I'm just working on a codebase where the most classes conform to an empty protocol. Is there any point of doing so? Actually conforming that protocol does nothing. Edit as reaction to @vacawama's helpful comment : the protocol is only used once import Foundation protocol myUrlRequestConfig {} extension myUrlRequest: myUrlRequestConfig { public static func configGetAppConfig() -> URLRequest { let request = .... return request } }
[ "An empty protocol can be useful if you want to create an easy way to add static functions or variables to several different classes. Of course, this only makes sense if the static functionality is the same for all classes conforming to the protocol. \nHere is an example: I have a protocol sizeable. Every class that conforms to Sizeable is extended with the static variable stride and size. \nprotocol Sizeable { }\n\nextension Sizeable {\n static var size: Int {\n return MemoryLayout<Self>.size\n }\n\n static var stride: Int {\n return MemoryLayout<Self>.stride\n }\n}\n\nclass Foo: Sizeable {}\n\nclass Baa: Sizeable {}\n\nFoo.size\nBaa.size \n\n", "Our app has three perfectly legitimate uses for an empty protocol:\n\nThe protocol has an extension with method definitions. The implementation in the extension is automatically injected into any type that adopts the protocol.\n\nThe protocol has other protocols that adopt it. This allows multiple protocols to be unified under a single head.\n\nThe protocol marks the adopter as wanting some other type to behave in a certain way. Code can always is whether an object is ThisEmptyProtocol and if it is, can behave differently than if it isn't.\n\n\n" ]
[ 3, 0 ]
[]
[]
[ "swift", "swift_protocols" ]
stackoverflow_0060476700_swift_swift_protocols.txt
Q: Find rows with overlapping ranges in R dplyr I have 3 large data frames that look like this: library(tibble) df1 <- tibble(peak=c("peak1","peak2","peak3"), coord1=c(100,500,1000), coord2=c(250,700,1250)) df2 <- tibble(peak=c("peak5","peak6","peak7"), coord1=c(120,280,900), coord2=c(300,400,1850)) df3 <- tibble(peak=c("peak8","peak9","peak10"), coord1=c(900,3000,5600), coord2=c(2000,3400,5850)) df1 #> # A tibble: 3 × 3 #> peak coord1 coord2 #> <chr> <dbl> <dbl> #> 1 peak1 100 250 #> 2 peak2 500 700 #> 3 peak3 1000 1250 df2 #> # A tibble: 3 × 3 #> peak coord1 coord2 #> <chr> <dbl> <dbl> #> 1 peak5 120 300 #> 2 peak6 280 400 #> 3 peak7 900 1850 df3 #> # A tibble: 3 × 3 #> peak coord1 coord2 #> <chr> <dbl> <dbl> #> 1 peak8 900 2000 #> 2 peak9 3000 3400 #> 3 peak10 5600 5850 I am relative new to R and I am trying to find the overlapping area within coordinates (coord1, coord2) that are unique to each data frame, overlap between two data frames, and overlap within all data frames. I want these data frames as an ouptut. At the moment Its hard for me to find how to specify in R, dplyr that I want to filter based on the overlapping ranges. There is a command that I am missing unique the ranges of these peaks do not overlap with the ranges of peaks of other data frames > unique peak coord1 coord2 peak6 280 400 peak9 3000 3400 peak10 5600 5850 common between df1-df2 >df1df2 peak coord1 coord2 peak1 100 250 peak5 120 300 peak3 1000 1250 peak7 900 1850 common between df1-df3 peak coord1 coord2 peak3 1000 1250 peak8 900 2000 and then common between df1-df2-df3 A: To be honest, I don't understand which is the final goal of your search. At any rate, there is a solution that uses tidyverse approach and functions from ivs package in order to check vectors' intervals. It is not an elegant solution, and it does not consider overlapping vectors within the same data frame. # load packages library(tidyverse) library(ivs) Your data df1 <- tibble(peak=c("peak1","peak2","peak3"), coord1 = c(100, 500, 1000), coord2 = c(250, 700, 1250)) df2 <- tibble(peak=c("peak5","peak6","peak7"), coord1 = c(120, 280, 900), coord2 = c(300, 400, 1850)) df3 <- tibble(peak=c("peak8","peak9","peak10"), coord1 = c(900, 3000, 5600), coord2 = c(2000, 3400, 5850)) Use of function iv_overlaps in order to create intervals check_df1_df2 <- df1 %>% mutate(any_overlap = iv_overlaps(range, df2$range), check = "df1-df2") check_df1_df3 <- df1 %>% mutate(any_overlap = iv_overlaps(range, df3$range), check = "df1-df3") check_df2_df1 <- df2 %>% mutate(any_overlap = iv_overlaps(range, df1$range), check = "df2-df1") check_df2_df3 <- df2 %>% mutate(any_overlap = iv_overlaps(range, df3$range), check = "df2-df3") check_df3_df1 <- df3 %>% mutate(any_overlap = iv_overlaps(range, df1$range), check = "df3-df1") check_df3_df2 <- df3 %>% mutate(any_overlap = iv_overlaps(range, df2$range), check = "df3-df2") Bind dataframes final_conclusion <- bind_rows(check_df1_df2, check_df1_df3, check_df2_df1, check_df2_df3, check_df3_df1, check_df3_df2, .id = "df_check") %>% group_by(peak) %>% mutate(overlapping_sum = sum(any_overlap)) Check overlapping intervals between dataframes overlapping <- final_conclusion %>% filter(overlapping_sum > 0) %>% pivot_wider(id_cols = peak, names_from = check, values_from = range) > overlapping # A tibble: 5 × 7 # Groups: peak [5] peak `df1-df2` `df1-df3` `df2-df1` `df2-df3` `df3-df1` `df3-df2` <chr> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> 1 peak1 [100, 250) [100, 250) [NA, NA) [NA, NA) [NA, NA) [NA, NA) 2 peak3 [1000, 1250) [1000, 1250) [NA, NA) [NA, NA) [NA, NA) [NA, NA) 3 peak5 [NA, NA) [NA, NA) [120, 300) [120, 300) [NA, NA) [NA, NA) 4 peak7 [NA, NA) [NA, NA) [900, 1850) [900, 1850) [NA, NA) [NA, NA) 5 peak8 [NA, NA) [NA, NA) [NA, NA) [NA, NA) [900, 2000) [900, 2000) Check non overlapping interval between dataframes not_overlapping <- final_conclusion %>% filter(overlapping_sum == 0) %>% pivot_wider(id_cols = peak, names_from = check, values_from = range) > not_overlapping # A tibble: 4 × 7 # Groups: peak [4] peak `df1-df2` `df1-df3` `df2-df1` `df2-df3` `df3-df1` `df3-df2` <chr> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> 1 peak2 [500, 700) [500, 700) [NA, NA) [NA, NA) [NA, NA) [NA, NA) 2 peak6 [NA, NA) [NA, NA) [280, 400) [280, 400) [NA, NA) [NA, NA) 3 peak9 [NA, NA) [NA, NA) [NA, NA) [NA, NA) [3000, 3400) [3000, 3400) 4 peak10 [NA, NA) [NA, NA) [NA, NA) [NA, NA) [5600, 5850) [5600, 5850)
Find rows with overlapping ranges in R dplyr
I have 3 large data frames that look like this: library(tibble) df1 <- tibble(peak=c("peak1","peak2","peak3"), coord1=c(100,500,1000), coord2=c(250,700,1250)) df2 <- tibble(peak=c("peak5","peak6","peak7"), coord1=c(120,280,900), coord2=c(300,400,1850)) df3 <- tibble(peak=c("peak8","peak9","peak10"), coord1=c(900,3000,5600), coord2=c(2000,3400,5850)) df1 #> # A tibble: 3 × 3 #> peak coord1 coord2 #> <chr> <dbl> <dbl> #> 1 peak1 100 250 #> 2 peak2 500 700 #> 3 peak3 1000 1250 df2 #> # A tibble: 3 × 3 #> peak coord1 coord2 #> <chr> <dbl> <dbl> #> 1 peak5 120 300 #> 2 peak6 280 400 #> 3 peak7 900 1850 df3 #> # A tibble: 3 × 3 #> peak coord1 coord2 #> <chr> <dbl> <dbl> #> 1 peak8 900 2000 #> 2 peak9 3000 3400 #> 3 peak10 5600 5850 I am relative new to R and I am trying to find the overlapping area within coordinates (coord1, coord2) that are unique to each data frame, overlap between two data frames, and overlap within all data frames. I want these data frames as an ouptut. At the moment Its hard for me to find how to specify in R, dplyr that I want to filter based on the overlapping ranges. There is a command that I am missing unique the ranges of these peaks do not overlap with the ranges of peaks of other data frames > unique peak coord1 coord2 peak6 280 400 peak9 3000 3400 peak10 5600 5850 common between df1-df2 >df1df2 peak coord1 coord2 peak1 100 250 peak5 120 300 peak3 1000 1250 peak7 900 1850 common between df1-df3 peak coord1 coord2 peak3 1000 1250 peak8 900 2000 and then common between df1-df2-df3
[ "To be honest, I don't understand which is the final goal of your search.\nAt any rate, there is a solution that uses tidyverse approach and functions from ivs package in order to check vectors' intervals. It is not an elegant solution, and it does not consider overlapping vectors within the same data frame.\n# load packages\nlibrary(tidyverse)\nlibrary(ivs)\n\nYour data\ndf1 <- tibble(peak=c(\"peak1\",\"peak2\",\"peak3\"), \n coord1 = c(100, 500, 1000),\n coord2 = c(250, 700, 1250))\n\n\ndf2 <- tibble(peak=c(\"peak5\",\"peak6\",\"peak7\"), \n coord1 = c(120, 280, 900),\n coord2 = c(300, 400, 1850))\n\n\ndf3 <- tibble(peak=c(\"peak8\",\"peak9\",\"peak10\"), \n coord1 = c(900, 3000, 5600),\n coord2 = c(2000, 3400, 5850))\n\nUse of function iv_overlaps in order to create intervals\ncheck_df1_df2 <- df1 %>%\n mutate(any_overlap = iv_overlaps(range, df2$range),\n check = \"df1-df2\")\n\ncheck_df1_df3 <- df1 %>%\n mutate(any_overlap = iv_overlaps(range, df3$range),\n check = \"df1-df3\")\n\ncheck_df2_df1 <- df2 %>%\n mutate(any_overlap = iv_overlaps(range, df1$range),\n check = \"df2-df1\")\n\ncheck_df2_df3 <- df2 %>%\n mutate(any_overlap = iv_overlaps(range, df3$range),\n check = \"df2-df3\")\n\ncheck_df3_df1 <- df3 %>%\n mutate(any_overlap = iv_overlaps(range, df1$range),\n check = \"df3-df1\")\n\ncheck_df3_df2 <- df3 %>%\n mutate(any_overlap = iv_overlaps(range, df2$range),\n check = \"df3-df2\")\n\nBind dataframes\nfinal_conclusion <- bind_rows(check_df1_df2, check_df1_df3, check_df2_df1, check_df2_df3, check_df3_df1, check_df3_df2, .id = \"df_check\") %>% \n group_by(peak) %>% \n mutate(overlapping_sum = sum(any_overlap))\n\nCheck overlapping intervals between dataframes\noverlapping <- final_conclusion %>% \n filter(overlapping_sum > 0) %>% \n pivot_wider(id_cols = peak, names_from = check, values_from = range)\n\n> overlapping\n\n# A tibble: 5 × 7\n# Groups: peak [5]\n peak `df1-df2` `df1-df3` `df2-df1` `df2-df3` `df3-df1` `df3-df2`\n <chr> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>>\n1 peak1 [100, 250) [100, 250) [NA, NA) [NA, NA) [NA, NA) [NA, NA)\n2 peak3 [1000, 1250) [1000, 1250) [NA, NA) [NA, NA) [NA, NA) [NA, NA)\n3 peak5 [NA, NA) [NA, NA) [120, 300) [120, 300) [NA, NA) [NA, NA)\n4 peak7 [NA, NA) [NA, NA) [900, 1850) [900, 1850) [NA, NA) [NA, NA)\n5 peak8 [NA, NA) [NA, NA) [NA, NA) [NA, NA) [900, 2000) [900, 2000)\n\nCheck non overlapping interval between dataframes\nnot_overlapping <- final_conclusion %>% \n filter(overlapping_sum == 0) %>% \n pivot_wider(id_cols = peak, names_from = check, values_from = range)\n\n> not_overlapping\n# A tibble: 4 × 7\n# Groups: peak [4]\n peak `df1-df2` `df1-df3` `df2-df1` `df2-df3` `df3-df1` `df3-df2`\n <chr> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>> <iv<dbl>>\n1 peak2 [500, 700) [500, 700) [NA, NA) [NA, NA) [NA, NA) [NA, NA)\n2 peak6 [NA, NA) [NA, NA) [280, 400) [280, 400) [NA, NA) [NA, NA)\n3 peak9 [NA, NA) [NA, NA) [NA, NA) [NA, NA) [3000, 3400) [3000, 3400)\n4 peak10 [NA, NA) [NA, NA) [NA, NA) [NA, NA) [5600, 5850) [5600, 5850)\n\n" ]
[ 0 ]
[]
[]
[ "dplyr", "r", "tidyr" ]
stackoverflow_0074674069_dplyr_r_tidyr.txt
Q: How to write a cobol code to read master file and retrieve pm-h-apl field, How to write a cobol code to read master file and retrieve pm-h-apl field, IF this apl indicator field will be spaces move 'N' to pm-h-apl field How to write a cobol code to read master file and retrieve pm-h-apl field, IF this apl indicator field will be spaces move 'N' to pm-h-apl field. A: You can use the READ statement to read from the master file and the MOVE statement to move values to the pm-h-apl field. The following code demonstrates how this can be done: MOVE SPACES TO pm-h-apl READ master-file AT END MOVE 'N' TO pm-h-apl NOT AT END IF pm-h-apl = SPACES MOVE 'N' TO pm-h-apl END-READ Here, we first initialize the pm-h-apl field with spaces using the MOVE statement. Then, we use the READ statement to read from the master file. If the end of the file is reached (indicated by the AT END clause), we move 'N' to the pm-h-apl field. If the end of the file is not reached (indicated by the NOT AT END clause), we check if the pm-h-apl field is equal to spaces, and if it is, we move 'N' to the pm-h-apl field. The END-READ statement marks the end of the READ block.
How to write a cobol code to read master file and retrieve pm-h-apl field,
How to write a cobol code to read master file and retrieve pm-h-apl field, IF this apl indicator field will be spaces move 'N' to pm-h-apl field How to write a cobol code to read master file and retrieve pm-h-apl field, IF this apl indicator field will be spaces move 'N' to pm-h-apl field.
[ "You can use the READ statement to read from the master file and the MOVE statement to move values to the pm-h-apl field. The following code demonstrates how this can be done:\nMOVE SPACES TO pm-h-apl\n\nREAD master-file\n AT END\n MOVE 'N' TO pm-h-apl\n NOT AT END\n IF pm-h-apl = SPACES\n MOVE 'N' TO pm-h-apl\nEND-READ\n\nHere, we first initialize the pm-h-apl field with spaces using the MOVE statement. Then, we use the READ statement to read from the master file. If the end of the file is reached (indicated by the AT END clause), we move 'N' to the pm-h-apl field. If the end of the file is not reached (indicated by the NOT AT END clause), we check if the pm-h-apl field is equal to spaces, and if it is, we move 'N' to the pm-h-apl field. The END-READ statement marks the end of the READ block.\n" ]
[ 0 ]
[]
[]
[ "cobol" ]
stackoverflow_0074679545_cobol.txt
Q: how i can add an object to a nested array in reducer? const initState = { questions:[ { id: uuidv4(), answers:[ {answerid: uuidv4()}, {answerid: uuidv4()} ] }, ], } this is the state i wanna function to add object in the answers array so the state will be after add like that: const initState = { questions:[ { id: uuidv4(), answers:[ {answerid: uuidv4()}, {answerid: uuidv4()}, {answerid: uuidv4()} ] }, ], } A: you can use a library like Immer for deeply nested objects update, My try as below const initState = { questions: [ { id: 1, answers: [ { answerid: 34, }, { answerid: 12, }, ], }, ], }; const newState = { ...initState, questions: initState.questions.map((q) => { const newq = { ...q, answers: [ ...q.answers, { a: "b", }, ], }; return newq; }), }; newState.questions[0].id = 2; // to test it doesn't mutate original object console.log({initState, newState});
how i can add an object to a nested array in reducer?
const initState = { questions:[ { id: uuidv4(), answers:[ {answerid: uuidv4()}, {answerid: uuidv4()} ] }, ], } this is the state i wanna function to add object in the answers array so the state will be after add like that: const initState = { questions:[ { id: uuidv4(), answers:[ {answerid: uuidv4()}, {answerid: uuidv4()}, {answerid: uuidv4()} ] }, ], }
[ "you can use a library like Immer for deeply nested objects update,\nMy try as below\n\n\nconst initState = {\n questions: [\n {\n id: 1,\n answers: [\n {\n answerid: 34,\n },\n {\n answerid: 12,\n },\n ],\n },\n ],\n};\n\nconst newState = {\n ...initState,\n questions: initState.questions.map((q) => {\n const newq = {\n ...q,\n answers: [\n ...q.answers,\n {\n a: \"b\",\n },\n ],\n };\n return newq;\n }),\n};\n\nnewState.questions[0].id = 2; // to test it doesn't mutate original object\n\nconsole.log({initState, newState});\n\n\n\n" ]
[ 0 ]
[]
[]
[ "react_redux", "reactjs" ]
stackoverflow_0074679129_react_redux_reactjs.txt
Q: Why is My HTML code printing root in the username input field? I am a newbie in programming world so if i am asking something silly, really for the same. The problem i am facing is that while using the below mentioned code it prints root automatically in the username input field. I have no clue why its doing so, can anyone please help. <form role="form" action="registration.php" method="post" id="login-form"> <div class="form-group"> <label for="username" class="sr-only">username</label> <input type="text" name="username" id="username" class="form-control" placeholder="Enter Desired Username" value="<?php echo isset($username)? $username : '' ?>" autocomplete="on"> <p><?php echo isset($error['username']) ? $error['username'] : '' ?></p> </div> A: I am trying to reply, I hope it will support you to do what you want or help you to think about how to do. On Login page( the page you are showing us): <?php if(isset($_POST['username'])){ $username = $_POST['username']; }else{ $username = ""; } ?> <html> <body> <form role="form" action="registration.php" method="post" id="login-form"> <div class="form-group"> <label for="username" class="sr-only">username</label> <input type="text" name="username" id="username" class="form-control" placeholder="Enter Desired Username" value="<?php echo isset($username)? $username : '' ?>" autocomplete="on"> <p><?php echo isset($error['username']) ? $error['username'] : '' ?></p> <button type="submit">Login</button </div> </form> </body> </html> the above one will set $username value, if in your post request coming on this page there is some username value. but to make a proper login page, if you just want to set username value in case of submit fail, then you may try below kind of code <html> <body> <form role="form" action="registration.php" method="post" id="login-form" onsubmit="return validateForm()"> <div class="form-group"> <label for="username" class="sr-only">username</label> <input type="text" name="username" id="username" class="form-control" placeholder="Enter Desired Username" value="<?php echo isset($username)? $username : '' ?>" autocomplete="on"> <button type="submit">Login</button </div> </form> <script> function validateForm(){ var condition = false;// var username = document.getElementById("username").value; if(username.length < 3){ alert("User name must be more than 3 character"); return false; }else{ return true; } } </script> </body> </html> A: I just ran into this problem in Chrome. Turned out the autofill in my browser was filling it in the field for site 'localhost'. Confirmed after running the code in Firefox where I have no autofill setup. Deleted the entry from my Saved Passwords in Chrome and works fine now.
Why is My HTML code printing root in the username input field?
I am a newbie in programming world so if i am asking something silly, really for the same. The problem i am facing is that while using the below mentioned code it prints root automatically in the username input field. I have no clue why its doing so, can anyone please help. <form role="form" action="registration.php" method="post" id="login-form"> <div class="form-group"> <label for="username" class="sr-only">username</label> <input type="text" name="username" id="username" class="form-control" placeholder="Enter Desired Username" value="<?php echo isset($username)? $username : '' ?>" autocomplete="on"> <p><?php echo isset($error['username']) ? $error['username'] : '' ?></p> </div>
[ "I am trying to reply, I hope it will support you to do what you want or help you to think about how to do.\nOn Login page( the page you are showing us):\n\n\n<?php\r\nif(isset($_POST['username'])){\r\n $username = $_POST['username'];\r\n}else{\r\n $username = \"\";\r\n}\r\n\r\n?>\r\n\r\n<html>\r\n<body>\r\n<form role=\"form\" action=\"registration.php\" method=\"post\" id=\"login-form\">\r\n <div class=\"form-group\">\r\n <label for=\"username\" class=\"sr-only\">username</label>\r\n <input type=\"text\" name=\"username\" id=\"username\" class=\"form-control\" placeholder=\"Enter Desired Username\" \r\n value=\"<?php echo isset($username)? $username : '' ?>\"\r\n autocomplete=\"on\">\r\n <p><?php echo isset($error['username']) ? $error['username'] : '' ?></p>\r\n <button type=\"submit\">Login</button\r\n </div>\r\n</form>\r\n</body>\r\n\r\n</html>\n\n\n\nthe above one will set $username value, if in your post request coming on this page there is some username value.\nbut to make a proper login page, if you just want to set username value in case of submit fail, then you may try below kind of code\n\n\n<html>\r\n<body>\r\n<form role=\"form\" action=\"registration.php\" method=\"post\" id=\"login-form\" onsubmit=\"return validateForm()\">\r\n <div class=\"form-group\">\r\n <label for=\"username\" class=\"sr-only\">username</label>\r\n <input type=\"text\" name=\"username\" id=\"username\" class=\"form-control\" placeholder=\"Enter Desired Username\" \r\n value=\"<?php echo isset($username)? $username : '' ?>\"\r\n autocomplete=\"on\">\r\n <button type=\"submit\">Login</button\r\n </div>\r\n</form>\r\n\r\n<script>\r\n function validateForm(){\r\n \r\n var condition = false;//\r\n var username = document.getElementById(\"username\").value;\r\n \r\n if(username.length < 3){\r\n alert(\"User name must be more than 3 character\");\r\n return false;\r\n }else{\r\n return true;\r\n }\r\n \r\n }\r\n</script>\r\n</body>\r\n\r\n</html>\n\n\n\n", "I just ran into this problem in Chrome. Turned out the autofill in my browser was filling it in the field for site 'localhost'. Confirmed after running the code in Firefox where I have no autofill setup. Deleted the entry from my Saved Passwords in Chrome and works fine now.\n" ]
[ 0, 0 ]
[]
[]
[ "html", "php" ]
stackoverflow_0060913832_html_php.txt
Q: How can I fix dark textures? - Godot 3.5.1 Mono So, I'm making a game in Godot 3.5.1 Mono and I'm using a Texture in a 3D space (Spatial) while I'm using it as a Control Element and it is showing up as dark in the editor and in-game. Here is what it looks like in the Editor, 3D space (Spatial), and the GUI (Control) Here is the window of the scene and the import settings I want a normal texture like this - not dark A: Have two copies of the Texture. You probably can make it look correct in 2D by changing "HDR mode" to "Force RGBE" when the compress mode is "Video RAM". However fixing the 2D look might ruin the 3D look (this appears to be related to whether or not the png was saved with multiplied alpha - I don't know for sure, and I don't mean the import setting - so your mileage may vary). If you cannot find import settings that works for both 2D and 3D, I suggest to have two copies of the image file, one for 2D and one for 3D. So they can both have correct import settings for the context in which they are used. In fact, I would default to that in the future.
How can I fix dark textures? - Godot 3.5.1 Mono
So, I'm making a game in Godot 3.5.1 Mono and I'm using a Texture in a 3D space (Spatial) while I'm using it as a Control Element and it is showing up as dark in the editor and in-game. Here is what it looks like in the Editor, 3D space (Spatial), and the GUI (Control) Here is the window of the scene and the import settings I want a normal texture like this - not dark
[ "Have two copies of the Texture.\nYou probably can make it look correct in 2D by changing \"HDR mode\" to \"Force RGBE\" when the compress mode is \"Video RAM\". However fixing the 2D look might ruin the 3D look (this appears to be related to whether or not the png was saved with multiplied alpha - I don't know for sure, and I don't mean the import setting - so your mileage may vary).\nIf you cannot find import settings that works for both 2D and 3D, I suggest to have two copies of the image file, one for 2D and one for 3D. So they can both have correct import settings for the context in which they are used. In fact, I would default to that in the future.\n" ]
[ 1 ]
[]
[]
[ "godot", "textures" ]
stackoverflow_0074678891_godot_textures.txt
Q: float: right; messes up the vertical alignment of elements in HTML I was trying to align these two vector images (instagram and mail) to the right of the div using CSS. main.css: .vector{ height: 35px; width: 35px; } index.html: <head> <div class="container-fluid p-2 bg-primary text-white"> <a href="index.html"><img class="logo" src="../public/img/alazkanat2.png"></a> <a><img class="vector" src="../public/img/instagram.png"></a> <a><img class="vector" src="../public/img/mail.png"></a> </div> </head> I tried to align using (in main.css) by adding float: right;: .vector{ height: 35px; width: 35px; float: right; } Resulted with: I've tried couple of methods however some didn't even affect the images and some made it worse. I also tried Why does the vertical alignment stop working when 'float: right' is being used? which is a similar problem to mine but didn't do anything. (NOTE: Please comment if you need more details from the code) A: While not tagged, it seems that the posted code is using bootstrap. The below example will use bootstrap classes so that it might integrate better. Perhaps try use d-flex (display: flex) on the container with align-items-center (align-items: center). Give the first item a mr-auto (margin-right: auto) so it pushes the other icons to the right. Example: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <header> <div class="d-flex align-items-center container-fluid p-2 bg-primary text-white"> <a href="#" class="mr-auto"><img class="logo" src="https://picsum.photos/100"></a> <a><img class="vector" src="https://picsum.photos/50?random=1"></a> <a><img class="vector" src="https://picsum.photos/50?random=2"></a> </div> </header>
float: right; messes up the vertical alignment of elements in HTML
I was trying to align these two vector images (instagram and mail) to the right of the div using CSS. main.css: .vector{ height: 35px; width: 35px; } index.html: <head> <div class="container-fluid p-2 bg-primary text-white"> <a href="index.html"><img class="logo" src="../public/img/alazkanat2.png"></a> <a><img class="vector" src="../public/img/instagram.png"></a> <a><img class="vector" src="../public/img/mail.png"></a> </div> </head> I tried to align using (in main.css) by adding float: right;: .vector{ height: 35px; width: 35px; float: right; } Resulted with: I've tried couple of methods however some didn't even affect the images and some made it worse. I also tried Why does the vertical alignment stop working when 'float: right' is being used? which is a similar problem to mine but didn't do anything. (NOTE: Please comment if you need more details from the code)
[ "While not tagged, it seems that the posted code is using bootstrap. The below example will use bootstrap classes so that it might integrate better.\nPerhaps try use d-flex (display: flex) on the container with align-items-center (align-items: center).\nGive the first item a mr-auto (margin-right: auto) so it pushes the other icons to the right.\nExample:\n\n\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n\n<header>\n <div class=\"d-flex align-items-center container-fluid p-2 bg-primary text-white\">\n <a href=\"#\" class=\"mr-auto\"><img class=\"logo\" src=\"https://picsum.photos/100\"></a>\n <a><img class=\"vector\" src=\"https://picsum.photos/50?random=1\"></a>\n <a><img class=\"vector\" src=\"https://picsum.photos/50?random=2\"></a>\n </div>\n</header>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074679205_css_html.txt
Q: How to make my function take less time in python? I am trying to do this problem: https://www.chegg.com/homework-help/questions-and-answers/blocks-pyramid-def-pyramidblocks-n-m-h-pyramid-structure-although-ancient-mesoamerican-fam-q38542637 This is my code: def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) for i in range(h)) But the problem is that whenever I try to test it, it tells me that it is too slow, so is there a way to make it take less time? I also tried to do it with lists, but with that too it takes too much time. def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) for i in range(h)) def pyramid_blocks(n, m, h): r=[] t=[] mlp=[] for i in range(h): r.append(n+i) t.append(m+i) for i, j in zip(r,t): mlp.append(i*j) return sum(mlp) A: You should use math to understand the components that are part of the answer. you need to calculate sum of all numbers until h, denote s, and the sum of all squares 1^2+2^2+3+2+... denotes sum_power it comes down to: h*m*n + s*n + s*m + sum_power this is a working solution: import time def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) for i in range(h)) def efficient_pyramid_blocks(n, m, h): s = (h-1)*h/2 sum_power = (h-1)*h*(2*(h-1)+1)/6 return int(h*n*m + s*(n+m) + sum_power) if __name__ == '__main__': h = 100000 m = 32 n = 47 start = time.time() print(pyramid_blocks(n, m, h)) print(time.time()-start) start = time.time() print(efficient_pyramid_blocks(n, m, h)) print(time.time() - start) and the output is: 333723479800000 0.016993045806884766 333723479800000 1.2159347534179688e-05 A: A bit of math can help: here we use a symbolic calculator to get the equation for the blocks in the pyramid using a sigma sum of (n+count)*(m+count) from count = 0 to count = h-1 Then we just paste the equation into code (the double slash // is just to use integer division instead of float division): def count_blocks(n,m,h): return (2*(h**3)+3*(h**2)*m+3*(h**2)*n+6*h*m*n-3*(h**2)-3*h*m-3*h*n+h)//6 Edit: This also outputs the correct result of 10497605327499753 for n,m,h = (2123377, 2026271, 2437)
How to make my function take less time in python?
I am trying to do this problem: https://www.chegg.com/homework-help/questions-and-answers/blocks-pyramid-def-pyramidblocks-n-m-h-pyramid-structure-although-ancient-mesoamerican-fam-q38542637 This is my code: def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) for i in range(h)) But the problem is that whenever I try to test it, it tells me that it is too slow, so is there a way to make it take less time? I also tried to do it with lists, but with that too it takes too much time. def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) for i in range(h)) def pyramid_blocks(n, m, h): r=[] t=[] mlp=[] for i in range(h): r.append(n+i) t.append(m+i) for i, j in zip(r,t): mlp.append(i*j) return sum(mlp)
[ "You should use math to understand the components that are part of the answer. you need to calculate sum of all numbers until h, denote s, and the sum of all squares 1^2+2^2+3+2+... denotes sum_power\nit comes down to: h*m*n + s*n + s*m + sum_power\nthis is a working solution:\nimport time\n\ndef pyramid_blocks(n, m, h):\n return sum((n+i)*(m+i) for i in range(h))\n\n\ndef efficient_pyramid_blocks(n, m, h):\n s = (h-1)*h/2\n sum_power = (h-1)*h*(2*(h-1)+1)/6\n return int(h*n*m + s*(n+m) + sum_power)\n\n\nif __name__ == '__main__':\n h = 100000\n m = 32\n n = 47\n start = time.time()\n print(pyramid_blocks(n, m, h))\n print(time.time()-start)\n start = time.time()\n print(efficient_pyramid_blocks(n, m, h))\n print(time.time() - start)\n\nand the output is:\n333723479800000\n0.016993045806884766\n333723479800000\n1.2159347534179688e-05\n\n", "A bit of math can help:\nhere we use a symbolic calculator to get the equation for the blocks in the pyramid using a sigma sum of (n+count)*(m+count) from count = 0 to count = h-1\nThen we just paste the equation into code (the double slash // is just to use integer division instead of float division):\ndef count_blocks(n,m,h):\n return (2*(h**3)+3*(h**2)*m+3*(h**2)*n+6*h*m*n-3*(h**2)-3*h*m-3*h*n+h)//6\n\nEdit: This also outputs the correct result of 10497605327499753 for n,m,h = (2123377, 2026271, 2437)\n" ]
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074664728_list_python.txt
Q: Restructuring JSON in JOLT I want my ouput in such a way that integration Entity comes inside integrationEntities. Left side is the current output. Right side is the desired output. I also tried the below but it didn't worked. What changes do I need to make in my spec to get the desired output like the right side? Any idea? **My JSON input- ** { "PURCHASE_ORDER_DISPATCH": { "MsgData": { "Transaction": { "PO_POD_HDR_EVW1": { "WG_ADDR_SEQ_NUM": 1, "WG_PO_CNTCT_EMAIL": "PeggyMeincke@westfieldgrp.com", "WG_REQUESTOR_EMAIL": "ZacharyEngels@westfieldgrp.com", "WG_REQ_FIRST_NAME": "Zachary", "WG_REQ_LAST_NAME": "Engels", "WG_DELIVER_TO": "ZacharyEngels@westfieldgrp.com", "BUSINESS_UNIT": "OFIC", "PO_ID": 25052, "VENDOR_SETID": "WCOS", "VENDOR_ID": 35958, "VNDR_LOC": 1, "PO_POD_LN_EVW1": { "WG_REQ_ID": 25694, "WG_CATEGORY_CD": "FSSUP", "WG_ITEM_TYPE": 0, "WG_ACCOUNT": 641100, "WG_DEPT_ID": 30400, "WG_PRODUCT": "", "BUSINESS_UNIT": "OFIC", "PO_ID": 25052, "WG_ASSET_GROUP": "", "WG_CAPITALIZE": "NO", "WG_PROFILE_ID": "", "WG_SPLIT_TYPE": 1, "WG_ASSET_LOC": "HOME", "WG_PROJECT": "", "VENDOR_SETID": "WCOS", "VENDOR_ID": 35958, "VNDR_LOC": 1, "LINE_NBR": 1, "INV_ITEM_ID": "", "DESCR254_MIXED": "147-1518156-3620845,1GreenMountainCoffeeRoastersCaramelVanillaCreamKeurigSingle-ServeK-CupPods,LightRoastCoffee,32Count", "UNIT_OF_MEASURE": "EA", "ITM_ID_VNDR": "B0798CX2Q9", "INV_ITEM_WEIGHT": 0, "INV_ITEM_HEIGHT": 0, "INV_ITEM_VOLUME": 0, "INV_ITEM_LENGTH": 0, "INV_ITEM_WIDTH": 0, "VNDR_CATALOG_ID": "", "MFG_ID": "", "MFG_ITM_ID": 5000196305, "CNTRCT_ID": "", "VERSION_NBR": 0, "CNTRCT_LINE_NBR": 0, "CAT_LINE_NBR": 0, "RELEASE_NBR": 0, "CANCEL_STATUS": "A", "UPN_ID": "", "PO_POD_SHP_EVW1": { "WG_SHIP_ADDR_TYPE": 0, "WG_CUST_ADDR_CODE": "OFIC", "BUSINESS_UNIT": "OFIC", "PO_ID": 25052, "VENDOR_SETID": "WCOS", "VENDOR_ID": 35958, "VNDR_LOC": 1, "LINE_NBR": 1, "SCHED_NBR": 1, "DUE_DT": "2020-01-29", "SHIPTO_ID": "OFIC", "DESCR_SHIPTO": "OHIOFARMERSINSURANCECOMPANY", "ADDRESS1_SHIPTO": "OHIOFARMERSINSURANCECOMPANY", "ADDRESS2_SHIPTO": "1PARKCIRCLE", "ADDRESS3_SHIPTO": "POBOX5001", "ADDRESS4_SHIPTO": "", "CITY_SHIPTO": "WESTFIELDCENTER", "STATE_SHIPTO": "OH", "POSTAL_SHIPTO": "44251-5001", "COUNTRY_SHIPTO": "USA", "PRICE_PO": 14.99, "FREIGHT_TERMS": "FOBDEST", "QTY_PO": 1, "SHIP_TYPE_ID": "BEST_WAY", "CANCEL_STATUS": "A", "ATTN_TO": "", "STD_ID_NUM_SHIPTO": "" }, "PSCAMA": { "AUDIT_ACTN": "A" } }, "PSCAMA": { "AUDIT_ACTN": "A" } }, "PSCAMA": { "LANGUAGE_CD": "ENG", "AUDIT_ACTN": "A", "BASE_LANGUAGE_CD": "ENG", "MSG_SEQ_FLG": "", "PROCESS_INSTANCE": 1199010, "PUBLISH_RULE_ID": "WG_MAIN_RULE", "MSGNODENAME": "" } } } } } JOLT Spec [ { "operation": "modify-overwrite-beta", "spec": { "*": { "*": { "*": { "*": { "requestorDetails": "=concat(@(1,WG_REQ_FIRST_NAME),' ',@(1,WG_REQ_LAST_NAME))" } } } } } }, { "operation": "shift", "spec": { "#integrationTrackingNumber": "IntegrationEntities.integrationEntity.integrationEntityHeader.integrationTrackingNumber", "#referenceCodeForEntity": "IntegrationEntities.integrationEntity.integrationEntityHeader.referenceCodeForEntity", "#additionalInfo": "IntegrationEntities.integrationEntity.integrationEntityHeader.additionalInfo", "*": { "*": { "*": { "*": { "PO_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.externalId", "#APPROVED": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.status", "PO_AMT_TTL": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.grossTotalAmount", "#test.test\\@test.com": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.checkoutBuyer.userEmailId", "requestorDetails": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.requesterDetails", "FREIGHT_TERMS": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode", "WG_REQUESTOR_EMAIL": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userEmailId", "WG_DELIVER_TO": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTo.userEmailId", "#OFIC": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.company.companyCode", "BUSINESS_UNIT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.businessUnit.buCode", "PYMNT_TERMS_CD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.paymentTermId", "#1": [ "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.costingSplitLevel", "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.costingSplitType" ], "WG_ADDR_SEQ_NUM": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierAddress.addressERPID", "CURRENCY_CD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierCurrencyCode", "@WG_ADDR_SEQ_NUM": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierAddressERPID", "VENDOR_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierERPID", "WG_PO_CNTCT_EMAIL": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.suppPOContactEmail", "#2": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierPOContactType", "WG_REQ_FIRST_NAME": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userFirstName", "WG_REQ_LAST_NAME": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userLastName", "@CURRENCY_CD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.currency", "@WG_DELIVER_TO": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.deliverToUser.userEmailId", "*": { "WG_REQ_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poDescription", "#STANDARD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poType", "LINE_NBR": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.lineNumber", "WG_CATEGORY_CD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.categoryCode", "WG_ITEM_TYPE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.itemType", "MFG_ITM_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.manufacturerPartID", "ITM_ID_VNDR": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.supplierPartID", "WG_ACCOUNT": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[0].value", "#name4": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[0].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[0].type", "#GL_ACCOUNT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[0].name" }, "WG_DEPT_ID": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[1].value", "#name3": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[1].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[1].type", "#Westfield Department": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[1].name" }, "WG_PRODUCT": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[2].value", "#name6": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[2].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[2].type", "#Product/Parcel": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[2].name" }, "WG_PROJECT": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[3].value", "#name5": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[3].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[3].type", "#Project Code": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[3].name" }, "WG_ASSET_GROUP": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[4].value", "#name10": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[4].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[4].type", "#Asset Group": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[4].name" }, "WG_CAPITALIZE": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[5].value", "#name9": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[5].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[5].type", "#Capitalize": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[5].name" }, "WG_PROFILE_ID": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[6].value", "#name9": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[6].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[6].type", "#Profile Id": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[6].name" }, "WG_ASSET_LOC": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[7].value", "#name2": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[7].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[7].type", "#Business Unit": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[7].name" }, "BUSINESS_UNIT": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[8].value", "#name7": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[8].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[8].type", "#GL_ACCOUNT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[8].name" }, "*": { "@WG_SHIP_ADDR_TYPE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddressType", "WG_SHIP_ADDR_TYPE": { "2": { "@(2,DESCR_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressName", "@(2,ADDRESS1_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine1", "@(2,ADDRESS2_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine2", "@(2,ADDRESS3_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine3", "@(2,ADDRESS4_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine4", "@(2,CITY_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.city", "@(2,POSTAL_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.zip", "@(2,STATE_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.state", "@(2,COUNTRY_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.country" } }, "WG_CUST_ADDR_CODE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressCode", "FREIGHT_TERMS": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode", "SHIPTO_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.locationCode.location.locationCode", "DUE_DT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliverOn", "@DUE_DT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.deliveryOn", "PRICE_PO": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.marketPrice", "QTY_PO": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.itemQuantity", "@WG_CUST_ADDR_CODE": { "2": { "@(2,DESCR_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressName", "@(2,ADDRESS1_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressLine1", "@(2,ADDRESS2_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressLine2", "@(2,ADDRESS3_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressLine3", "@(2,ADDRESS4_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressLine4", "@(2,CITY_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.city", "@(2,POSTAL_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.zip", "@(2,STATE_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.state", "@(2,COUNTRY_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.country" } }, "#1": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.costingSplitType" } } } } } } } }, { "operation": "modify-overwrite-beta", "spec": { "*": { "*": { "*": { "*": { "*": { "*": { "product": "=divide(1,@(1,itemQuantity))", "itemTotalAmount": "=divide(@(1,marketPrice),@(1,product))", "distributedAmount": "=divide(@(1,marketPrice),@(1,product))" } } } } } } } }, { "operation": "shift", "spec": { "*": { "*": { "integrationEntityHeader": "&2.&1.&", "integrationEntityDetails": { "*": { "externalId": "&4.&3.&2.&1.&", "status": "&4.&3.&2.&1.&", "poHeader": { "poDescription": "&5.&4.&3.&2.&1.&", "poType": "&5.&4.&3.&2.&1.&", "grossTotalAmount": "&5.&4.&3.&2.&1.&", "checkoutBuyer": { "userEmailId": "&6.&5.&4.&3.&2.&1.&" }, "requesterDetails": "&5.&4.&3.&2.&1.&", "userEmailId": "&5.&4.&3.&2.&1.&", "deliveryTo": { "userEmailId": "&6.&5.&4.&3.&2.&1.&" }, "deliveryTermCode": "&5.&4.&3.&2.&1.&", "shipToAddressType": "&5.&4.&3.&2.&1.&", "shipToAddress": "&5.&4.&3.&2.&1.&", "company": "&5.&4.&3.&2.&1.&", "businessUnit": "&5.&4.&3.&2.&1.&", "locationCode": "&5.&4.&3.&2.&1.&", "deliverOn": "&5.&4.&3.&2.&1.&", "paymentTermId": "&5.&4.&3.&2.&1.&", "costingSplitLevel": "&5.&4.&3.&2.&1.&", "costingSplitType": "&5.&4.&3.&2.&1.&", "supplierAddress": "&5.&4.&3.&2.&1.&", "supplierAddressERPID": "&5.&4.&3.&2.&1.&", "supplierCurrencyCode": "&5.&4.&3.&2.&1.&", "supplierERPID": "&5.&4.&3.&2.&1.&", "suppPOContactEmail": "&5.&4.&3.&2.&1.&", "supplierPOContactType": "&5.&4.&3.&2.&1.&" }, "items": { "item": { "lineNumber": "&6.&5.&4.&3.&2.&1.&", "requesterDetails": "&6.&5.&4.&3.&2.&1.&", "categoryCode": "&6.&5.&4.&3.&2.&1.&", "currency": "&6.&5.&4.&3.&2.&1.&", "deliverToUser": { "userEmailId": "&7.&6.&5.&4.&3.&2.&1.&" }, "deliveryOn": "&6.&5.&4.&3.&2.&1.&", "itemTotalAmount": "&6.&5.&4.&3.&2.&1.&", "itemType": "&6.&5.&4.&3.&2.&1.&", "manufacturerPartID": "&6.&5.&4.&3.&2.&1.&", "marketPrice": "&6.&5.&4.&3.&2.&1.&", "itemQuantity": "&6.&5.&4.&3.&2.&1.&", "shipToAddressCode": "&6.&5.&4.&3.&2.&1.&", "shipToAddressType": "&6.&5.&4.&3.&2.&1.&", "costingSplitType": "&6.&5.&4.&3.&2.&1.&", "supplierPartID": "&6.&5.&4.&3.&2.&1.&", "validCombinations": { "itemDetails": { "@(2,distributedAmount)": "&8.&7.&6.&5.&4.&3.&2.&1.distributedAmount", "validRules": { "field": { "*": { "id": "&11.&10.&9.&8.&7.&6.&5.&4.&3.&2.[&1].&", "type": "&11.&10.&9.&8.&7.&6.&5.&4.&3.&2.[&1].&", "name": "&11.&10.&9.&8.&7.&6.&5.&4.&3.&2.[&1].&", "value": "&11.&10.&9.&8.&7.&6.&5.&4.&3.&2.[&1].&" } } } } } } } } } } } } }, { "operation": "cardinality", "spec": { "*": { "*": { "*": { "*": { "status": "ONE", "poHeader": { "*": "ONE", "checkoutBuyer": { "userEmailId": "ONE" }, "company": { "*": "ONE" } }, "items": { "item": { "costingSplitType": "ONE", "validCombinations": { "itemDetails": { "validRules": { "field": { "id": "ONE", "type": "ONE", "name": "ONE", "value": "ONE" } } } } } } } } } } } }, { "operation": "shift", "spec": { "*": { "*": "&1.&[]" } } } ] A: You can add an extra shift transformation to the end containing a # wildcard at the right-hand-side such as { "operation": "shift", "spec": { "*": { "*": { "*": "integrationDetails.&2.&1[#2].&" } } } }
Restructuring JSON in JOLT
I want my ouput in such a way that integration Entity comes inside integrationEntities. Left side is the current output. Right side is the desired output. I also tried the below but it didn't worked. What changes do I need to make in my spec to get the desired output like the right side? Any idea? **My JSON input- ** { "PURCHASE_ORDER_DISPATCH": { "MsgData": { "Transaction": { "PO_POD_HDR_EVW1": { "WG_ADDR_SEQ_NUM": 1, "WG_PO_CNTCT_EMAIL": "PeggyMeincke@westfieldgrp.com", "WG_REQUESTOR_EMAIL": "ZacharyEngels@westfieldgrp.com", "WG_REQ_FIRST_NAME": "Zachary", "WG_REQ_LAST_NAME": "Engels", "WG_DELIVER_TO": "ZacharyEngels@westfieldgrp.com", "BUSINESS_UNIT": "OFIC", "PO_ID": 25052, "VENDOR_SETID": "WCOS", "VENDOR_ID": 35958, "VNDR_LOC": 1, "PO_POD_LN_EVW1": { "WG_REQ_ID": 25694, "WG_CATEGORY_CD": "FSSUP", "WG_ITEM_TYPE": 0, "WG_ACCOUNT": 641100, "WG_DEPT_ID": 30400, "WG_PRODUCT": "", "BUSINESS_UNIT": "OFIC", "PO_ID": 25052, "WG_ASSET_GROUP": "", "WG_CAPITALIZE": "NO", "WG_PROFILE_ID": "", "WG_SPLIT_TYPE": 1, "WG_ASSET_LOC": "HOME", "WG_PROJECT": "", "VENDOR_SETID": "WCOS", "VENDOR_ID": 35958, "VNDR_LOC": 1, "LINE_NBR": 1, "INV_ITEM_ID": "", "DESCR254_MIXED": "147-1518156-3620845,1GreenMountainCoffeeRoastersCaramelVanillaCreamKeurigSingle-ServeK-CupPods,LightRoastCoffee,32Count", "UNIT_OF_MEASURE": "EA", "ITM_ID_VNDR": "B0798CX2Q9", "INV_ITEM_WEIGHT": 0, "INV_ITEM_HEIGHT": 0, "INV_ITEM_VOLUME": 0, "INV_ITEM_LENGTH": 0, "INV_ITEM_WIDTH": 0, "VNDR_CATALOG_ID": "", "MFG_ID": "", "MFG_ITM_ID": 5000196305, "CNTRCT_ID": "", "VERSION_NBR": 0, "CNTRCT_LINE_NBR": 0, "CAT_LINE_NBR": 0, "RELEASE_NBR": 0, "CANCEL_STATUS": "A", "UPN_ID": "", "PO_POD_SHP_EVW1": { "WG_SHIP_ADDR_TYPE": 0, "WG_CUST_ADDR_CODE": "OFIC", "BUSINESS_UNIT": "OFIC", "PO_ID": 25052, "VENDOR_SETID": "WCOS", "VENDOR_ID": 35958, "VNDR_LOC": 1, "LINE_NBR": 1, "SCHED_NBR": 1, "DUE_DT": "2020-01-29", "SHIPTO_ID": "OFIC", "DESCR_SHIPTO": "OHIOFARMERSINSURANCECOMPANY", "ADDRESS1_SHIPTO": "OHIOFARMERSINSURANCECOMPANY", "ADDRESS2_SHIPTO": "1PARKCIRCLE", "ADDRESS3_SHIPTO": "POBOX5001", "ADDRESS4_SHIPTO": "", "CITY_SHIPTO": "WESTFIELDCENTER", "STATE_SHIPTO": "OH", "POSTAL_SHIPTO": "44251-5001", "COUNTRY_SHIPTO": "USA", "PRICE_PO": 14.99, "FREIGHT_TERMS": "FOBDEST", "QTY_PO": 1, "SHIP_TYPE_ID": "BEST_WAY", "CANCEL_STATUS": "A", "ATTN_TO": "", "STD_ID_NUM_SHIPTO": "" }, "PSCAMA": { "AUDIT_ACTN": "A" } }, "PSCAMA": { "AUDIT_ACTN": "A" } }, "PSCAMA": { "LANGUAGE_CD": "ENG", "AUDIT_ACTN": "A", "BASE_LANGUAGE_CD": "ENG", "MSG_SEQ_FLG": "", "PROCESS_INSTANCE": 1199010, "PUBLISH_RULE_ID": "WG_MAIN_RULE", "MSGNODENAME": "" } } } } } JOLT Spec [ { "operation": "modify-overwrite-beta", "spec": { "*": { "*": { "*": { "*": { "requestorDetails": "=concat(@(1,WG_REQ_FIRST_NAME),' ',@(1,WG_REQ_LAST_NAME))" } } } } } }, { "operation": "shift", "spec": { "#integrationTrackingNumber": "IntegrationEntities.integrationEntity.integrationEntityHeader.integrationTrackingNumber", "#referenceCodeForEntity": "IntegrationEntities.integrationEntity.integrationEntityHeader.referenceCodeForEntity", "#additionalInfo": "IntegrationEntities.integrationEntity.integrationEntityHeader.additionalInfo", "*": { "*": { "*": { "*": { "PO_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.externalId", "#APPROVED": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.status", "PO_AMT_TTL": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.grossTotalAmount", "#test.test\\@test.com": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.checkoutBuyer.userEmailId", "requestorDetails": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.requesterDetails", "FREIGHT_TERMS": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode", "WG_REQUESTOR_EMAIL": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userEmailId", "WG_DELIVER_TO": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTo.userEmailId", "#OFIC": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.company.companyCode", "BUSINESS_UNIT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.businessUnit.buCode", "PYMNT_TERMS_CD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.paymentTermId", "#1": [ "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.costingSplitLevel", "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.costingSplitType" ], "WG_ADDR_SEQ_NUM": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierAddress.addressERPID", "CURRENCY_CD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierCurrencyCode", "@WG_ADDR_SEQ_NUM": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierAddressERPID", "VENDOR_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierERPID", "WG_PO_CNTCT_EMAIL": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.suppPOContactEmail", "#2": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.supplierPOContactType", "WG_REQ_FIRST_NAME": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userFirstName", "WG_REQ_LAST_NAME": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.requesterDetails.userLastName", "@CURRENCY_CD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.currency", "@WG_DELIVER_TO": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.deliverToUser.userEmailId", "*": { "WG_REQ_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poDescription", "#STANDARD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.poType", "LINE_NBR": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.lineNumber", "WG_CATEGORY_CD": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.categoryCode", "WG_ITEM_TYPE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.itemType", "MFG_ITM_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.manufacturerPartID", "ITM_ID_VNDR": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.supplierPartID", "WG_ACCOUNT": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[0].value", "#name4": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[0].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[0].type", "#GL_ACCOUNT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[0].name" }, "WG_DEPT_ID": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[1].value", "#name3": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[1].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[1].type", "#Westfield Department": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[1].name" }, "WG_PRODUCT": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[2].value", "#name6": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[2].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[2].type", "#Product/Parcel": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[2].name" }, "WG_PROJECT": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[3].value", "#name5": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[3].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[3].type", "#Project Code": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[3].name" }, "WG_ASSET_GROUP": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[4].value", "#name10": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[4].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[4].type", "#Asset Group": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[4].name" }, "WG_CAPITALIZE": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[5].value", "#name9": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[5].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[5].type", "#Capitalize": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[5].name" }, "WG_PROFILE_ID": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[6].value", "#name9": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[6].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[6].type", "#Profile Id": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[6].name" }, "WG_ASSET_LOC": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[7].value", "#name2": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[7].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[7].type", "#Business Unit": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[7].name" }, "BUSINESS_UNIT": { "@": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[8].value", "#name7": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[8].id", "#AUTO_COMPLETE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[8].type", "#GL_ACCOUNT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.validCombinations.itemDetails.validRules.field[8].name" }, "*": { "@WG_SHIP_ADDR_TYPE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddressType", "WG_SHIP_ADDR_TYPE": { "2": { "@(2,DESCR_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressName", "@(2,ADDRESS1_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine1", "@(2,ADDRESS2_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine2", "@(2,ADDRESS3_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine3", "@(2,ADDRESS4_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressLine4", "@(2,CITY_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.city", "@(2,POSTAL_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.zip", "@(2,STATE_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.state", "@(2,COUNTRY_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.country" } }, "WG_CUST_ADDR_CODE": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.shipToAddress.addressCode", "FREIGHT_TERMS": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliveryTermCode", "SHIPTO_ID": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.locationCode.location.locationCode", "DUE_DT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.poHeader.deliverOn", "@DUE_DT": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.deliveryOn", "PRICE_PO": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.marketPrice", "QTY_PO": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.itemQuantity", "@WG_CUST_ADDR_CODE": { "2": { "@(2,DESCR_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressName", "@(2,ADDRESS1_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressLine1", "@(2,ADDRESS2_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressLine2", "@(2,ADDRESS3_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressLine3", "@(2,ADDRESS4_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.addressLine4", "@(2,CITY_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.city", "@(2,POSTAL_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.zip", "@(2,STATE_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.state", "@(2,COUNTRY_SHIPTO)": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.shipToAddress.country" } }, "#1": "IntegrationEntities.integrationEntity.integrationEntityDetails.poDetails.items.item.costingSplitType" } } } } } } } }, { "operation": "modify-overwrite-beta", "spec": { "*": { "*": { "*": { "*": { "*": { "*": { "product": "=divide(1,@(1,itemQuantity))", "itemTotalAmount": "=divide(@(1,marketPrice),@(1,product))", "distributedAmount": "=divide(@(1,marketPrice),@(1,product))" } } } } } } } }, { "operation": "shift", "spec": { "*": { "*": { "integrationEntityHeader": "&2.&1.&", "integrationEntityDetails": { "*": { "externalId": "&4.&3.&2.&1.&", "status": "&4.&3.&2.&1.&", "poHeader": { "poDescription": "&5.&4.&3.&2.&1.&", "poType": "&5.&4.&3.&2.&1.&", "grossTotalAmount": "&5.&4.&3.&2.&1.&", "checkoutBuyer": { "userEmailId": "&6.&5.&4.&3.&2.&1.&" }, "requesterDetails": "&5.&4.&3.&2.&1.&", "userEmailId": "&5.&4.&3.&2.&1.&", "deliveryTo": { "userEmailId": "&6.&5.&4.&3.&2.&1.&" }, "deliveryTermCode": "&5.&4.&3.&2.&1.&", "shipToAddressType": "&5.&4.&3.&2.&1.&", "shipToAddress": "&5.&4.&3.&2.&1.&", "company": "&5.&4.&3.&2.&1.&", "businessUnit": "&5.&4.&3.&2.&1.&", "locationCode": "&5.&4.&3.&2.&1.&", "deliverOn": "&5.&4.&3.&2.&1.&", "paymentTermId": "&5.&4.&3.&2.&1.&", "costingSplitLevel": "&5.&4.&3.&2.&1.&", "costingSplitType": "&5.&4.&3.&2.&1.&", "supplierAddress": "&5.&4.&3.&2.&1.&", "supplierAddressERPID": "&5.&4.&3.&2.&1.&", "supplierCurrencyCode": "&5.&4.&3.&2.&1.&", "supplierERPID": "&5.&4.&3.&2.&1.&", "suppPOContactEmail": "&5.&4.&3.&2.&1.&", "supplierPOContactType": "&5.&4.&3.&2.&1.&" }, "items": { "item": { "lineNumber": "&6.&5.&4.&3.&2.&1.&", "requesterDetails": "&6.&5.&4.&3.&2.&1.&", "categoryCode": "&6.&5.&4.&3.&2.&1.&", "currency": "&6.&5.&4.&3.&2.&1.&", "deliverToUser": { "userEmailId": "&7.&6.&5.&4.&3.&2.&1.&" }, "deliveryOn": "&6.&5.&4.&3.&2.&1.&", "itemTotalAmount": "&6.&5.&4.&3.&2.&1.&", "itemType": "&6.&5.&4.&3.&2.&1.&", "manufacturerPartID": "&6.&5.&4.&3.&2.&1.&", "marketPrice": "&6.&5.&4.&3.&2.&1.&", "itemQuantity": "&6.&5.&4.&3.&2.&1.&", "shipToAddressCode": "&6.&5.&4.&3.&2.&1.&", "shipToAddressType": "&6.&5.&4.&3.&2.&1.&", "costingSplitType": "&6.&5.&4.&3.&2.&1.&", "supplierPartID": "&6.&5.&4.&3.&2.&1.&", "validCombinations": { "itemDetails": { "@(2,distributedAmount)": "&8.&7.&6.&5.&4.&3.&2.&1.distributedAmount", "validRules": { "field": { "*": { "id": "&11.&10.&9.&8.&7.&6.&5.&4.&3.&2.[&1].&", "type": "&11.&10.&9.&8.&7.&6.&5.&4.&3.&2.[&1].&", "name": "&11.&10.&9.&8.&7.&6.&5.&4.&3.&2.[&1].&", "value": "&11.&10.&9.&8.&7.&6.&5.&4.&3.&2.[&1].&" } } } } } } } } } } } } }, { "operation": "cardinality", "spec": { "*": { "*": { "*": { "*": { "status": "ONE", "poHeader": { "*": "ONE", "checkoutBuyer": { "userEmailId": "ONE" }, "company": { "*": "ONE" } }, "items": { "item": { "costingSplitType": "ONE", "validCombinations": { "itemDetails": { "validRules": { "field": { "id": "ONE", "type": "ONE", "name": "ONE", "value": "ONE" } } } } } } } } } } } }, { "operation": "shift", "spec": { "*": { "*": "&1.&[]" } } } ]
[ "You can add an extra shift transformation to the end containing a # wildcard at the right-hand-side such as\n{\n \"operation\": \"shift\",\n \"spec\": {\n \"*\": {\n \"*\": {\n \"*\": \"integrationDetails.&2.&1[#2].&\"\n }\n }\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "jolt", "json", "mapping", "transformation" ]
stackoverflow_0074679494_jolt_json_mapping_transformation.txt
Q: Moving CALayer's mask on scroll in a Scrollview I am experimenting with iOS SDK and I have the following UIView structure: UIView UIImageView - only a background image UIImageView (with a CALayer mask) UIScrollView Label Very simple structure, UIScrollView is transparent layer and second UIImageView has a mask on it. What I am trying to do is that CALayer mask would move its position according to position of the Content in the scroll view. If user scrolls, mask's position should be updated. I already solved this problem by using UIScrollView's delegate: - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGPoint contentOffset = scrollView.contentOffset; contentOffset.y = -contentOffset.y; self.overlayImageView.viewlayer.mask.position = contentOffset; } Mask is created in viewDidLoad and does not change during view controller's lifecycle. The problem is that the mask position updating is too slow. That way it looks the mask is following the scroll view's content, not scrolling with it. The scrollViewDidScroll delegate method is called correctly. For you to better understand the problem, I am attaching a video I made in iOS simulator. http://www.youtube.com/watch?v=w3xRl3LTngY So the question is: Is there a way to make mask updating faster or this is the limit of iOS? A: CALayer are implicit animated for some properties like position try to disable them: - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; CGPoint contentOffset = scrollView.contentOffset; contentOffset.y = -contentOffset.y; self.overlayImageView.viewlayer.mask.position = contentOffset; [CATransaction commit]; } A: For me solution was as following: func scrollViewDidScroll(_ scrollView: UIScrollView) { CATransaction.begin() CATransaction.setDisableActions(true) layerGradient?.frame = scrollView.safeAreaLayoutGuide.layoutFrame CATransaction.commit() }
Moving CALayer's mask on scroll in a Scrollview
I am experimenting with iOS SDK and I have the following UIView structure: UIView UIImageView - only a background image UIImageView (with a CALayer mask) UIScrollView Label Very simple structure, UIScrollView is transparent layer and second UIImageView has a mask on it. What I am trying to do is that CALayer mask would move its position according to position of the Content in the scroll view. If user scrolls, mask's position should be updated. I already solved this problem by using UIScrollView's delegate: - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGPoint contentOffset = scrollView.contentOffset; contentOffset.y = -contentOffset.y; self.overlayImageView.viewlayer.mask.position = contentOffset; } Mask is created in viewDidLoad and does not change during view controller's lifecycle. The problem is that the mask position updating is too slow. That way it looks the mask is following the scroll view's content, not scrolling with it. The scrollViewDidScroll delegate method is called correctly. For you to better understand the problem, I am attaching a video I made in iOS simulator. http://www.youtube.com/watch?v=w3xRl3LTngY So the question is: Is there a way to make mask updating faster or this is the limit of iOS?
[ "CALayer are implicit animated for some properties like position try to disable them:\n- (void)scrollViewDidScroll:(UIScrollView *)scrollView\n{\n\n[CATransaction begin];\n [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];\nCGPoint contentOffset = scrollView.contentOffset;\ncontentOffset.y = -contentOffset.y;\n\nself.overlayImageView.viewlayer.mask.position = contentOffset;\n[CATransaction commit];\n\n}\n\n", "For me solution was as following:\nfunc scrollViewDidScroll(_ scrollView: UIScrollView) {\n CATransaction.begin()\n CATransaction.setDisableActions(true)\n layerGradient?.frame = scrollView.safeAreaLayoutGuide.layoutFrame\n CATransaction.commit()\n}\n\n" ]
[ 17, 0 ]
[]
[]
[ "core_animation", "core_graphics", "ios", "uiimage", "uiview" ]
stackoverflow_0017592265_core_animation_core_graphics_ios_uiimage_uiview.txt
Q: Filtering on multiple fields in an Elasticsearch ObjectField() I am having trouble figuring out the filtering syntax for ObjectFields() in django-elasticsearch-dsl. In particular, when I try to filter on multiple subfields of the same ObjectField(), I'm getting incorrect results. For example, consider the following document class ItemDocument(Document): product = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), 'description': fields.TextField() }) details = fields.ObjectField(properties={ 'category_id': fields.IntegerField(), 'id': fields.IntegerField(), 'value': fields.FloatField() }) description = fields.TextField() I want to find an Item with a detail object that has both category_id == 3 and value < 1.5, so I created the following query x = ItemDocument.search().filter(Q("match",details__category_id=3) & Q("range",details__value={'lt':1.5})).execute() Unfortunately, this returns all items which have a detail object with category_id==3 and a separate detail object with value < 1.5 e.g. { "product": ... "details": [ { "category_id": 3, "id": 7, "value": 20.0 }, { "category_id": 4, "id": 7, "value": 1.0 }, ... ] } instead of my desired result of all items that have a detail object with both category_id==3 AND value < 1.5 e.g. { "product": ... "details": [ { "category_id": 3, "id": 7, "value": 1.0 }, ... ] } How do I properly format this query using django-elasticsearch-dsl? A: You can use the nested query in Elasticsearch to filter on multiple subfields of the same ObjectField. Here is an example of how you can do this in django-elasticsearch-dsl: x = ItemDocument.search().query( "nested", path="details", query=Q("match", details__category_id=3) & Q("range", details__value={'lt':1.5}) ).execute() The nested query allows you to filter on multiple subfields of the details object, and only return documents that have a detail object with both category_id==3 and value < 1.5. You can also use the inner_hits option with the nested query to get the details of the matching detail objects: x = ItemDocument.search().query( "nested", path="details", query=Q("match", details__category_id=3) & Q("range", details__value={'lt':1.5}), inner_hits={} ).execute() This will add a nested field to each search result, which contains the details of the matching detail objects. You can access this field in your code like this: results = x.to_dict() for result in results['hits']['hits']: nested_results = result['inner_hits']['details']['hits']['hits'] # do something with nested_results
Filtering on multiple fields in an Elasticsearch ObjectField()
I am having trouble figuring out the filtering syntax for ObjectFields() in django-elasticsearch-dsl. In particular, when I try to filter on multiple subfields of the same ObjectField(), I'm getting incorrect results. For example, consider the following document class ItemDocument(Document): product = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), 'description': fields.TextField() }) details = fields.ObjectField(properties={ 'category_id': fields.IntegerField(), 'id': fields.IntegerField(), 'value': fields.FloatField() }) description = fields.TextField() I want to find an Item with a detail object that has both category_id == 3 and value < 1.5, so I created the following query x = ItemDocument.search().filter(Q("match",details__category_id=3) & Q("range",details__value={'lt':1.5})).execute() Unfortunately, this returns all items which have a detail object with category_id==3 and a separate detail object with value < 1.5 e.g. { "product": ... "details": [ { "category_id": 3, "id": 7, "value": 20.0 }, { "category_id": 4, "id": 7, "value": 1.0 }, ... ] } instead of my desired result of all items that have a detail object with both category_id==3 AND value < 1.5 e.g. { "product": ... "details": [ { "category_id": 3, "id": 7, "value": 1.0 }, ... ] } How do I properly format this query using django-elasticsearch-dsl?
[ "You can use the nested query in Elasticsearch to filter on multiple subfields of the same ObjectField. Here is an example of how you can do this in django-elasticsearch-dsl:\nx = ItemDocument.search().query(\n \"nested\",\n path=\"details\",\n query=Q(\"match\", details__category_id=3) & Q(\"range\", details__value={'lt':1.5})\n).execute()\n\nThe nested query allows you to filter on multiple subfields of the details object, and only return documents that have a detail object with both category_id==3 and value < 1.5.\nYou can also use the inner_hits option with the nested query to get the details of the matching detail objects:\nx = ItemDocument.search().query(\n \"nested\",\n path=\"details\",\n query=Q(\"match\", details__category_id=3) & Q(\"range\", details__value={'lt':1.5}),\n inner_hits={}\n).execute()\n\nThis will add a nested field to each search result, which contains the details of the matching detail objects. You can access this field in your code like this:\nresults = x.to_dict()\nfor result in results['hits']['hits']:\n nested_results = result['inner_hits']['details']['hits']['hits']\n # do something with nested_results\n\n" ]
[ 1 ]
[]
[]
[ "django", "elasticsearch", "elasticsearch_dsl_py", "python" ]
stackoverflow_0074679018_django_elasticsearch_elasticsearch_dsl_py_python.txt
Q: does @Transactional annotation merge new transaction into exisiting transaction i am having a simple controller /hello which internally calls Repository layer for a transaction using the default propagation level i.e Propagation.REQUIRED. @Controller public void hello(data) -> doTransaction(data) @Repository @Transactional public void doTransaction(data){ jdbcTemplateInsertA(data); Thread.sleep(15*1000); jdbcTemplateUpdateB(data); } as per online docs REQUIRED is the default propagation. Spring checks if there is an active transaction, and if nothing exists, it creates a new one. Otherwise, the business logic appends to the currently active transaction: now let's say i hit the API 2 times, with data1 and then data2, before request 1 was finished API was hit 2nd time. would there be only a single transaction or two separate independent transactions? Also, i want to know is using @Transactional with jdbcTemplate valid? i am having doubt on how jdbcTemplate internally gets the same connection object that was used by @Transactional annotation considering pool size >=2. UPDATE: You will have a transaction per thread. -> any docs/resources where i can find this? For 2nd part, let me rephrase my question. Let's say using hikari pool with size as 5 as per my understanding @Transactional would pick some connection from pool, let's say it picked up connectionId1554 now, when i call jdbc.execute(), how spring ensure that it uses connectionId1554 and not any other available connection from the pool A: You will have a transaction per thread. If you have two requests, then you will have two threads (from your web container, like Tomcat), and therefore you'll have two separate transactions. Based on the code and (lack of) configuration it is hard to tell how you setup your JdbcTemplate. Most likely the connection used by the JdbcTemplate comes from a database connection pool. If you've configured two connections then you can only use two connections and the usage of those connections will block other requests to the database if they are in use. Now, that being said, database connection pools are generally programmed to be super smart and one database connection can be used between multiple database requests/transactions depending on configuration settings. A: let's say i hit the API 2 times, with data1 and then data2, before request 1 was finished API was hit 2nd time. would there be only a single transaction or two separate independent transactions? Each incoming request to your api will result in an independent transaction being started. If you think this through this makes sense: if you have 2 users each making a request at the same time, you would want each of their requests to be handled independently, it would be odd if both of their requests joined and were handled as a single transaction. i want to know is using @Transactional with jdbcTemplate valid? i am having doubt on how jdbcTemplate internally gets the same connection object that was used by @Transactional annotation This depends on how you have configured a Datasource and a connection pool. Are you running this on an appserver like Webpshere, Weblogic or WildFly? They provide Datasource connection pooling integrated with a TransactionManager too.
does @Transactional annotation merge new transaction into exisiting transaction
i am having a simple controller /hello which internally calls Repository layer for a transaction using the default propagation level i.e Propagation.REQUIRED. @Controller public void hello(data) -> doTransaction(data) @Repository @Transactional public void doTransaction(data){ jdbcTemplateInsertA(data); Thread.sleep(15*1000); jdbcTemplateUpdateB(data); } as per online docs REQUIRED is the default propagation. Spring checks if there is an active transaction, and if nothing exists, it creates a new one. Otherwise, the business logic appends to the currently active transaction: now let's say i hit the API 2 times, with data1 and then data2, before request 1 was finished API was hit 2nd time. would there be only a single transaction or two separate independent transactions? Also, i want to know is using @Transactional with jdbcTemplate valid? i am having doubt on how jdbcTemplate internally gets the same connection object that was used by @Transactional annotation considering pool size >=2. UPDATE: You will have a transaction per thread. -> any docs/resources where i can find this? For 2nd part, let me rephrase my question. Let's say using hikari pool with size as 5 as per my understanding @Transactional would pick some connection from pool, let's say it picked up connectionId1554 now, when i call jdbc.execute(), how spring ensure that it uses connectionId1554 and not any other available connection from the pool
[ "You will have a transaction per thread. If you have two requests, then you will have two threads (from your web container, like Tomcat), and therefore you'll have two separate transactions.\nBased on the code and (lack of) configuration it is hard to tell how you setup your JdbcTemplate. Most likely the connection used by the JdbcTemplate comes from a database connection pool. If you've configured two connections then you can only use two connections and the usage of those connections will block other requests to the database if they are in use. Now, that being said, database connection pools are generally programmed to be super smart and one database connection can be used between multiple database requests/transactions depending on configuration settings.\n", "\nlet's say i hit the API 2 times, with data1 and then data2, before request 1 was finished API was hit 2nd time.\nwould there be only a single transaction or two separate independent transactions?\n\nEach incoming request to your api will result in an independent transaction being started. If you think this through this makes sense: if you have 2 users each making a request at the same time, you would want each of their requests to be handled independently, it would be odd if both of their requests joined and were handled as a single transaction.\n\ni want to know is using @Transactional with jdbcTemplate valid? i am having doubt on how jdbcTemplate internally gets the same connection object that was used by @Transactional annotation\n\nThis depends on how you have configured a Datasource and a connection pool. Are you running this on an appserver like Webpshere, Weblogic or WildFly? They provide Datasource connection pooling integrated with a TransactionManager too.\n" ]
[ 1, 1 ]
[]
[]
[ "hibernate", "java", "jdbctemplate", "spring_boot", "spring_transactions" ]
stackoverflow_0074679220_hibernate_java_jdbctemplate_spring_boot_spring_transactions.txt
Q: Python web client to access API of an online supermarket Suppose you are writing a python web client to access an API of an online supermarket. Given below are the API details. Base URL= http://host1.open.uom.lk:8080 enter image description here``` Write a python program to retrieve all the products from the API Server and print the total number of products currently stored in the server. Hint: the json response will be of the following example format: { "message": "success", "data": [ { "id": 85, "productName": "Araliya Basmathi Rice", "description": "White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.", "category": "Rice", "brand": "CIC", "expiredDate": "2023.05.04", "manufacturedDate": "2022.02.20", "batchNumber": 324567, "unitPrice": 1020, "quantity": 200, "createdDate": "2022.02.24" }, { "id": 86, "productName": "Araliya Basmathi Rice", "description": "White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.", "category": "Rice", "brand": "CIC", "expiredDate": "2023.05.04", "manufacturedDate": "2022.02.20", "batchNumber": 324567, "unitPrice": 1020, "quantity": 200, "createdDate": "2022.02.24" }, ... ... } Please help me to answer for this question. I tried below code but it's showing an error for me: import requests BASE_URL = "http://host1.open.uom.lk:8080" response = requests.post(f"{BASE_URL}/api/products/", json=data) print(response.json()) parsed = json.load(response.text()) len(parsed[“data”]) A: Here is an example of how you could write a Python program to retrieve all the products from the API server and print the total number of products currently stored in the server: import requests # Define the base URL of the API BASE_URL = "http://host1.open.uom.lk:8080" # Use the requests library to make a GET request to the API's /api/products/ endpoint response = requests.get(f"{BASE_URL}/api/products/") # Check the status code of the response to make sure the request was successful if response.status_code == 200: # If the request was successful, parse the JSON response products = response.json() # Retrieve the list of products from the "data" key in the JSON response products_list = products["data"] # Print the total number of products stored in the server print(f"Total number of products in the server: {len(products_list)}") else: # If the request was not successful, print an error message print(f"An error occurred: {response.text}") This code should print the total number of products stored in the server.
Python web client to access API of an online supermarket
Suppose you are writing a python web client to access an API of an online supermarket. Given below are the API details. Base URL= http://host1.open.uom.lk:8080 enter image description here``` Write a python program to retrieve all the products from the API Server and print the total number of products currently stored in the server. Hint: the json response will be of the following example format: { "message": "success", "data": [ { "id": 85, "productName": "Araliya Basmathi Rice", "description": "White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.", "category": "Rice", "brand": "CIC", "expiredDate": "2023.05.04", "manufacturedDate": "2022.02.20", "batchNumber": 324567, "unitPrice": 1020, "quantity": 200, "createdDate": "2022.02.24" }, { "id": 86, "productName": "Araliya Basmathi Rice", "description": "White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.", "category": "Rice", "brand": "CIC", "expiredDate": "2023.05.04", "manufacturedDate": "2022.02.20", "batchNumber": 324567, "unitPrice": 1020, "quantity": 200, "createdDate": "2022.02.24" }, ... ... } Please help me to answer for this question. I tried below code but it's showing an error for me: import requests BASE_URL = "http://host1.open.uom.lk:8080" response = requests.post(f"{BASE_URL}/api/products/", json=data) print(response.json()) parsed = json.load(response.text()) len(parsed[“data”])
[ "Here is an example of how you could write a Python program to retrieve all the products from the API server and print the total number of products currently stored in the server:\nimport requests\n\n# Define the base URL of the API\nBASE_URL = \"http://host1.open.uom.lk:8080\"\n\n# Use the requests library to make a GET request to the API's /api/products/ endpoint\nresponse = requests.get(f\"{BASE_URL}/api/products/\")\n\n# Check the status code of the response to make sure the request was successful\nif response.status_code == 200:\n # If the request was successful, parse the JSON response\n products = response.json()\n \n # Retrieve the list of products from the \"data\" key in the JSON response\n products_list = products[\"data\"]\n \n # Print the total number of products stored in the server\n print(f\"Total number of products in the server: {len(products_list)}\")\nelse:\n # If the request was not successful, print an error message\n print(f\"An error occurred: {response.text}\")\n\nThis code should print the total number of products stored in the server.\n" ]
[ 0 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074679483_api_python.txt
Q: Rust split string by nothing In js I would do this "abc".split("") // ["a","b","c"] I want something simlimar in rust let splits = String::from("abc").split("") // does not work with empty string!!! let letters = ( splits.next().unwrap(), splits.next().unwrap(), splits.next().unwrap(), ) // ('a','b','c') I want something simlimar in rust but it does not work. no error no nothing A: You could use this: let s = String::from("abc"); let mut chars = s.chars(); let letters = ( chars.next().unwrap(), chars.next().unwrap(), chars.next().unwrap(), );
Rust split string by nothing
In js I would do this "abc".split("") // ["a","b","c"] I want something simlimar in rust let splits = String::from("abc").split("") // does not work with empty string!!! let letters = ( splits.next().unwrap(), splits.next().unwrap(), splits.next().unwrap(), ) // ('a','b','c') I want something simlimar in rust but it does not work. no error no nothing
[ "You could use this:\nlet s = String::from(\"abc\");\nlet mut chars = s.chars();\n\nlet letters = (\n chars.next().unwrap(),\n chars.next().unwrap(),\n chars.next().unwrap(),\n);\n\n" ]
[ 1 ]
[]
[]
[ "rust", "split" ]
stackoverflow_0074679544_rust_split.txt
Q: Use trained ML to classify new dataset I have save my ML model that have been train. ML that I chose is SVM and I'm using pickle to save it. How can I use this model to classify new dataset which in csv file that have no sentiment label in it? I'm using Jupyter Notebook to do this project A: It would be useful to know what library (sklearn, pytorch, tensorflow, etc.) you used to train the model, but for this example I'm going to assume you used the pickle library to pickle and the sklearn library to train the model. At some point you used something like pickle.dump(model, open(filename, 'wb')) to save your model. You can also use pickle to load the model through pickle.load(open(filename, 'rb')) and then call the model through model.predict(new_X) where new_X represents the dataframe you want to make the predictions on.
Use trained ML to classify new dataset
I have save my ML model that have been train. ML that I chose is SVM and I'm using pickle to save it. How can I use this model to classify new dataset which in csv file that have no sentiment label in it? I'm using Jupyter Notebook to do this project
[ "It would be useful to know what library (sklearn, pytorch, tensorflow, etc.) you used to train the model, but for this example I'm going to assume you used the pickle library to pickle and the sklearn library to train the model.\nAt some point you used something like pickle.dump(model, open(filename, 'wb')) to save your model.\nYou can also use pickle to load the model through pickle.load(open(filename, 'rb')) and then call the model through model.predict(new_X) where new_X represents the dataframe you want to make the predictions on.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "machine_learning", "python", "sentiment_analysis" ]
stackoverflow_0074679490_jupyter_notebook_machine_learning_python_sentiment_analysis.txt
Q: How can i call a different functions seperately using a single button I have to create a calculator but i have to use separate functions for add , subtract , division and multiply there should be an equal to (=) button which upon clicking should display the result operators should be selected using the dropdown box <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>calculator</title> </head> <body> <h1 align="center">calculator</h1> <script type="text/javascript"> function add() { var a=parseInt(document.getElementById("firstnumber").value); var b=parseInt(document.getElementById("secondnumber").value); var c=a+b document.getElementById("answer").innerHTML=c; } function sub() { var a=parseInt(document.getElementById("firstnumber").value); var b=parseInt(document.getElementById("secondnumber").value); var c=a-b; document.getElementById("answer").innerHTML=c; } function mul() { var a=parseInt(document.getElementById("firstnumber").value); var b=parseInt(document.getElementById("secondnumber").value); var c=a*b; document.getElementById("answer").innerHTML=c; } function div() { var a=parseInt(document.getElementById("firstnumber").value); var b=parseInt(document.getElementById("secondnumber").value); var c=a/b; document.getElementById("answer").innerHTML=c; } </script> <p>First Number: <input id="firstnumber"></p> <p>Second Number: <input id="secondnumber"></p> <select id="operators"> <option value="add" onclick="add()">+</option> <option value="sub" onclick="sub()">-</option> <option value="mul" onclick="mul()">*</option> <option value="div" onclick="div()">/</option> </select> <button onclick="add.call(this);sub.call(this);mul.call(this);div.call(this);">=</button> <p id="answer"></p> </body> </html> A: i think thats what you were looking for. make sure to read what i wrote under the code index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>calculator</title> </head> <body> <h1 align="center">calculator</h1> <p>First Number: <input id="firstnumber" /></p> <p>Second Number: <input id="secondnumber" /></p> <select id="operators"> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> <button id="calcBtn">=</button> <p id="answer"></p> <script src="script.js"></script> </body> </html> script.js: document.getElementById("calcBtn").addEventListener("click", () => { let operator = document.getElementById("operators").value; let a = parseInt(document.getElementById("firstnumber").value); let b = parseInt(document.getElementById("secondnumber").value); switch (operator) { case "add": add(); break; case "sub": sub(); break; case "mul": mul(); break; case "div": div(); break; default: break; } function add() { let c = a + b; document.getElementById("answer").innerHTML = c; } function sub() { let c = a - b; document.getElementById("answer").innerHTML = c; } function mul() { let c = a * b; document.getElementById("answer").innerHTML = c; } function div() { let c = a / b; document.getElementById("answer").innerHTML = c; } }); dont use onclick, give element an id and then add event listenner to it works the same but addeventlistenner is better you can replace .addEventListener("click", () => { with .addEventListener("click", function() { its up to you always place your script tag directly above the body tag use script src instead of script > code, it makes the html more clean use let instead of var switch case its like if, but in situations like that better, because its easier to write what to do depending on the value usage: switch(variable){ case "variable value": code break; } i think thats all A: To call multiple functions using a single button, you can use a JavaScript function that calls the other functions in the desired order. Here is an example of how you can do that: <!-- HTML code for the calculator --> <p>First Number: <input id="firstnumber"></p> <p>Second Number: <input id="secondnumber"></p> <select id="operators"> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> <button onclick="computeResult()">=</button> <p id="answer"></p> <!-- JavaScript code for the calculator --> <script> function computeResult() { // Get the selected operator var operator = document.getElementById("operators").value; // Call the appropriate function based on the selected operator if (operator === "add") { add(); } else if (operator === "sub") { sub(); } else if (operator === "mul") { mul(); } else if (operator === "div") { div(); } } function add() { var a = parseInt(document.getElementById("firstnumber").value); var b = parseInt(document.getElementById("secondnumber").value); var c = a + b; document.getElementById("answer").innerHTML = c; } function sub() { var a = parseInt(document.getElementById("firstnumber").value); var b = parseInt(document.getElementById("secondnumber").value); var c = a - b; document.getElementById("answer").innerHTML = c; } function mul() { var a = parseInt(document.getElementById("firstnumber").value); var b = parseInt(document.getElementById("secondnumber").value); var c = a * b; document.getElementById("answer").innerHTML = c; } function div() { var a = parseInt(document.getElementById("firstnumber").value); var b = parseInt(document.getElementById("secondnumber").value); var c = a / b; document.getElementById("answer").innerHTML = c; } </script> In this example, the computeResult() function is called when the = button is clicked. It gets the selected operator from the dropdown box, and then calls the appropriate function (add(), sub(), mul(), or div()) based on the selected operator.
How can i call a different functions seperately using a single button
I have to create a calculator but i have to use separate functions for add , subtract , division and multiply there should be an equal to (=) button which upon clicking should display the result operators should be selected using the dropdown box <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>calculator</title> </head> <body> <h1 align="center">calculator</h1> <script type="text/javascript"> function add() { var a=parseInt(document.getElementById("firstnumber").value); var b=parseInt(document.getElementById("secondnumber").value); var c=a+b document.getElementById("answer").innerHTML=c; } function sub() { var a=parseInt(document.getElementById("firstnumber").value); var b=parseInt(document.getElementById("secondnumber").value); var c=a-b; document.getElementById("answer").innerHTML=c; } function mul() { var a=parseInt(document.getElementById("firstnumber").value); var b=parseInt(document.getElementById("secondnumber").value); var c=a*b; document.getElementById("answer").innerHTML=c; } function div() { var a=parseInt(document.getElementById("firstnumber").value); var b=parseInt(document.getElementById("secondnumber").value); var c=a/b; document.getElementById("answer").innerHTML=c; } </script> <p>First Number: <input id="firstnumber"></p> <p>Second Number: <input id="secondnumber"></p> <select id="operators"> <option value="add" onclick="add()">+</option> <option value="sub" onclick="sub()">-</option> <option value="mul" onclick="mul()">*</option> <option value="div" onclick="div()">/</option> </select> <button onclick="add.call(this);sub.call(this);mul.call(this);div.call(this);">=</button> <p id="answer"></p> </body> </html>
[ "i think thats what you were looking for.\nmake sure to read what i wrote under the code\nindex.html:\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>calculator</title>\n </head>\n <body>\n <h1 align=\"center\">calculator</h1>\n <p>First Number: <input id=\"firstnumber\" /></p>\n <p>Second Number: <input id=\"secondnumber\" /></p>\n <select id=\"operators\">\n <option value=\"add\">+</option>\n <option value=\"sub\">-</option>\n <option value=\"mul\">*</option>\n <option value=\"div\">/</option>\n </select>\n\n <button id=\"calcBtn\">=</button>\n <p id=\"answer\"></p>\n <script src=\"script.js\"></script>\n </body>\n</html>\n\nscript.js:\ndocument.getElementById(\"calcBtn\").addEventListener(\"click\", () => {\n let operator = document.getElementById(\"operators\").value;\n let a = parseInt(document.getElementById(\"firstnumber\").value);\n let b = parseInt(document.getElementById(\"secondnumber\").value);\n switch (operator) {\n case \"add\":\n add();\n break;\n case \"sub\":\n sub();\n break;\n case \"mul\":\n mul();\n break;\n case \"div\":\n div();\n break;\n\n default:\n break;\n }\n function add() {\n let c = a + b;\n document.getElementById(\"answer\").innerHTML = c;\n }\n\n function sub() {\n let c = a - b;\n document.getElementById(\"answer\").innerHTML = c;\n }\n\n function mul() {\n let c = a * b;\n document.getElementById(\"answer\").innerHTML = c;\n }\n\n function div() {\n let c = a / b;\n document.getElementById(\"answer\").innerHTML = c;\n }\n});\n\n\ndont use onclick, give element an id and then add event listenner to it works the same but addeventlistenner is better you can replace .addEventListener(\"click\", () => { with .addEventListener(\"click\", function() {\nits up to you\nalways place your script tag directly above the body tag\nuse script src instead of script > code, it makes the html more clean\nuse let instead of var\nswitch case its like if, but in situations like that better, because its easier to write what to do depending on the value\nusage:\n\nswitch(variable){\n case \"variable value\":\n code\n break;\n}\n\ni think thats all\n", "To call multiple functions using a single button, you can use a JavaScript function that calls the other functions in the desired order.\nHere is an example of how you can do that:\n<!-- HTML code for the calculator -->\n<p>First Number: <input id=\"firstnumber\"></p>\n<p>Second Number: <input id=\"secondnumber\"></p>\n<select id=\"operators\">\n <option value=\"add\">+</option>\n <option value=\"sub\">-</option>\n <option value=\"mul\">*</option>\n <option value=\"div\">/</option>\n</select>\n\n<button onclick=\"computeResult()\">=</button>\n<p id=\"answer\"></p>\n\n<!-- JavaScript code for the calculator -->\n<script>\n function computeResult() {\n // Get the selected operator\n var operator = document.getElementById(\"operators\").value;\n\n // Call the appropriate function based on the selected operator\n if (operator === \"add\") {\n add();\n } else if (operator === \"sub\") {\n sub();\n } else if (operator === \"mul\") {\n mul();\n } else if (operator === \"div\") {\n div();\n }\n }\n\n function add() {\n var a = parseInt(document.getElementById(\"firstnumber\").value);\n var b = parseInt(document.getElementById(\"secondnumber\").value);\n var c = a + b;\n document.getElementById(\"answer\").innerHTML = c;\n }\n\n function sub() {\n var a = parseInt(document.getElementById(\"firstnumber\").value);\n var b = parseInt(document.getElementById(\"secondnumber\").value);\n var c = a - b;\n document.getElementById(\"answer\").innerHTML = c;\n }\n\n function mul() {\n var a = parseInt(document.getElementById(\"firstnumber\").value);\n var b = parseInt(document.getElementById(\"secondnumber\").value);\n var c = a * b;\n document.getElementById(\"answer\").innerHTML = c;\n }\n\n function div() {\n var a = parseInt(document.getElementById(\"firstnumber\").value);\n var b = parseInt(document.getElementById(\"secondnumber\").value);\n var c = a / b;\n document.getElementById(\"answer\").innerHTML = c;\n }\n</script>\n\nIn this example, the computeResult() function is called when the = button is clicked. It gets the selected operator from the dropdown box, and then calls the appropriate function (add(), sub(), mul(), or div()) based on the selected operator.\n" ]
[ 0, 0 ]
[]
[]
[ "html", "javascript" ]
stackoverflow_0074679398_html_javascript.txt
Q: Unity: Use Inherited properties component or Inspector Injected components I'm new to Unity but have development experience. I'd like to know whether I should be using the inherited properties in my MonoBehaviour scripts, or if I should be injecting everything from the inspector instead. I'm following a tutorial that has suggested writing some code like this: public class BirdScript : MonoBehaviour { public Rigidbody2D myRigidbody; So that the Inspector can inject the component's Rigidbody2D into it: When playing with the code, I noticed that MonoBehaviour extends Component and I can do this.rigidbody2D instead. I got told off by Intellisense for this, but it suggested instead using: GetComponent<Rigidbody2D>(). Using this, instead of my code reading: void Update() { myRigidbody.velocity = Vector2.up * 10; } I can write: void Update() { GetComponent<Rigidbody2D>().velocity = Vector2.up * 10; } But which is better? I'm thinking GetComponent<Rigidbody2D>() because it makes sure that I'm directly referencing the current rigid body that my script is attached to, instead of requiring me to apply things in the Inspector, but maybe this is too inflexible for Unity? In general, the style seems more lenient towards making things public instead of private for the sake of the Inspector. Any advice on some best practices I can use to make these kinds of decisions? A: Assigning a reference through the inspector or referencing an attached component using GetComponent<T> are both valid options. Although I would generally avoid calling GetComponent<Rigidbody2D>() in the Update() function since it's expensive, and instead cache the reference in Start(). The Start method is called after all initialization methods have been completed, so it is safe to use GetComponent in this method to access fully initialized components. private Rigidbody _rigidbody; private void Start() { _rigidbody = GetComponent<Rigidbody2D>(); } Referencing Components One potential downside of referencing components through drag-and-drop in the Unity Inspector is that managing your project's dependencies can be challenging. This is because drag-and-drop references can create implicit dependencies that are not immediately obvious from looking at the code. This can make it difficult to understand how different parts of your project are interconnected and can make it harder to refactor or modify your code in the future. As such, .GetComponent provides an alternative in-code solution. GameObject.GetComponent One potential downside of using GetComponent to create component references in Unity is that it can make your code more difficult to read and understand because GetComponent calls could be spread throughout your code. In contrast, drag-and-drop references in the Unity Inspector can be easily seen and understood by looking at the inspector window for a particular game object. Another potential downside of using GetComponent is that it can make your code more fragile. This is because GetComponent calls rely on the components attached to the game object at runtime and will throw an error if the required component is not present. However, this could be alleviated using the RequireComponent attribute, making said components dependent. In contrast, drag-and-drop references in the Unity Inspector are checked at edit time and will only allow you to reference components attached to the game object. This can help to prevent runtime errors in your code. Overall, whether to use GetComponent or drag-and-drop references in the Unity Inspector will depend on your personal preferences and the specific needs of your project. Both approaches have advantages and disadvantages, and the best approach for your project depends on the specific circumstances.
Unity: Use Inherited properties component or Inspector Injected components
I'm new to Unity but have development experience. I'd like to know whether I should be using the inherited properties in my MonoBehaviour scripts, or if I should be injecting everything from the inspector instead. I'm following a tutorial that has suggested writing some code like this: public class BirdScript : MonoBehaviour { public Rigidbody2D myRigidbody; So that the Inspector can inject the component's Rigidbody2D into it: When playing with the code, I noticed that MonoBehaviour extends Component and I can do this.rigidbody2D instead. I got told off by Intellisense for this, but it suggested instead using: GetComponent<Rigidbody2D>(). Using this, instead of my code reading: void Update() { myRigidbody.velocity = Vector2.up * 10; } I can write: void Update() { GetComponent<Rigidbody2D>().velocity = Vector2.up * 10; } But which is better? I'm thinking GetComponent<Rigidbody2D>() because it makes sure that I'm directly referencing the current rigid body that my script is attached to, instead of requiring me to apply things in the Inspector, but maybe this is too inflexible for Unity? In general, the style seems more lenient towards making things public instead of private for the sake of the Inspector. Any advice on some best practices I can use to make these kinds of decisions?
[ "Assigning a reference through the inspector or referencing an attached component using GetComponent<T> are both valid options. Although I would generally avoid calling GetComponent<Rigidbody2D>() in the Update() function since it's expensive, and instead cache the reference in Start().\nThe Start method is called after all initialization methods have been completed, so it is safe to use GetComponent in this method to access fully initialized components.\nprivate Rigidbody _rigidbody;\n\nprivate void Start() {\n _rigidbody = GetComponent<Rigidbody2D>();\n}\n\nReferencing Components\nOne potential downside of referencing components through drag-and-drop in the Unity Inspector is that managing your project's dependencies can be challenging. This is because drag-and-drop references can create implicit dependencies that are not immediately obvious from looking at the code. This can make it difficult to understand how different parts of your project are interconnected and can make it harder to refactor or modify your code in the future. As such, .GetComponent provides an alternative in-code solution.\nGameObject.GetComponent\nOne potential downside of using GetComponent to create component references in Unity is that it can make your code more difficult to read and understand because GetComponent calls could be spread throughout your code. In contrast, drag-and-drop references in the Unity Inspector can be easily seen and understood by looking at the inspector window for a particular game object.\nAnother potential downside of using GetComponent is that it can make your code more fragile. This is because GetComponent calls rely on the components attached to the game object at runtime and will throw an error if the required component is not present. However, this could be alleviated using the RequireComponent attribute, making said components dependent.\nIn contrast, drag-and-drop references in the Unity Inspector are checked at edit time and will only allow you to reference components attached to the game object. This can help to prevent runtime errors in your code.\nOverall, whether to use GetComponent or drag-and-drop references in the Unity Inspector will depend on your personal preferences and the specific needs of your project. Both approaches have advantages and disadvantages, and the best approach for your project depends on the specific circumstances.\n" ]
[ 0 ]
[]
[]
[ "c#", "unity3d" ]
stackoverflow_0074678902_c#_unity3d.txt
Q: how to get image in numpy format from openCV live camera? I'm using the UTKFace dataset for predicting the age and gender. I'm converting the images into gray before feeding into network then I'm using the my laptop's camera for real time detection using opencv. The issue is I can't figure out how to convert the detected image into numpy array format so that i can predict the age and gender.
how to get image in numpy format from openCV live camera?
I'm using the UTKFace dataset for predicting the age and gender. I'm converting the images into gray before feeding into network then I'm using the my laptop's camera for real time detection using opencv. The issue is I can't figure out how to convert the detected image into numpy array format so that i can predict the age and gender.
[]
[]
[ "You can use the OpenCV cv2.cvtColor function to convert the image captured from the camera to grayscale, and then use the numpy.asarray function to convert the OpenCV image to a NumPy array. Here is an example:\nimport cv2\nimport numpy as np\n\n# Capture image from camera\ncapture = cv2.VideoCapture(0)\nret, frame = capture.read()\n\n# Convert image to grayscale\ngray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n# Convert to NumPy array\ngray_np = np.asarray(gray)\n\n# Use NumPy array for further processing\n...\n\nAlternatively, you can use the cv2.imdecode function to directly decode the image data from the camera as a NumPy array, without the need to convert it to grayscale first:\nimport cv2\nimport numpy as np\n\n# Capture image from camera\ncapture = cv2.VideoCapture(0)\nret, frame = capture.read()\n\n# Decode image data as NumPy array\nframe_np = np.fromstring(frame.tostring(), dtype=np.uint8)\nframe_np = frame_np.reshape((frame.shape[0], frame.shape[1], frame.shape[2]))\n\n# Use NumPy array for further processing\n...\n\nNote that in both cases, the resulting NumPy array will be in grayscale format, with a single channel (i.e., a 2D array), so you will need to adjust your processing accordingly.\n" ]
[ -2 ]
[ "google_colaboratory", "machine_learning", "opencv", "python_3.x" ]
stackoverflow_0074679550_google_colaboratory_machine_learning_opencv_python_3.x.txt
Q: How can I show dynamically changing value on background service notification using Flutter? I am trying to show the value scanned from BLE on background service notification even when app is closed. So I used [flutter_background_service] 1 However, I don't know how to show dynamically changing value as it shows on widget. I am in trouble.. Can i ask for your help? Thank you. Timer.periodic(const Duration(seconds: 1), (timer) async { if (service is AndroidServiceInstance) { if (await service.isForegroundService()) { /// OPTIONAL for use custom notification /// the notification id must be equals with AndroidConfiguration when you call configure() method. flutterLocalNotificationsPlugin.show( 888, 'App Name', 'value: ${}, // <- I want to put value in here. const NotificationDetails( android: AndroidNotificationDetails( 'my_foreground', 'MY FOREGROUND SERVICE', icon: 'ic_bg_service_small', ongoing: true, ), ), ); } } 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.');}....
How can I show dynamically changing value on background service notification using Flutter?
I am trying to show the value scanned from BLE on background service notification even when app is closed. So I used [flutter_background_service] 1 However, I don't know how to show dynamically changing value as it shows on widget. I am in trouble.. Can i ask for your help? Thank you. Timer.periodic(const Duration(seconds: 1), (timer) async { if (service is AndroidServiceInstance) { if (await service.isForegroundService()) { /// OPTIONAL for use custom notification /// the notification id must be equals with AndroidConfiguration when you call configure() method. flutterLocalNotificationsPlugin.show( 888, 'App Name', 'value: ${}, // <- I want to put value in here. const NotificationDetails( android: AndroidNotificationDetails( 'my_foreground', 'MY FOREGROUND SERVICE', icon: 'ic_bg_service_small', ongoing: true, ), ), ); } }
[ "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 ]
[]
[]
[ "background", "flutter", "notifications" ]
stackoverflow_0074073032_background_flutter_notifications.txt
Q: I want to creat a matrix in a loop that adds the new data each time to the same matrix my code is this ` x0=input('Enter first guess (Must be grater than 0): '); e=input('Enter the desired telorance : '); n=input(['Enter the desired number of ' ... 'Iteration (Must be grater than 0): ']); for Q=[0.0001,0.0002,0.0005,0.001,0.002,0.005,0.01,0.02] for Re=[10000,20000,50000,100000,200000,500000,1000000] syms f t=(1:n); eq=(-0.869*log((Q./3.7) + (2.523./(Re*sqrt(f))))).^-2; g=@(f) (-0.869*log((Q./3.7) + (2.523./(Re*sqrt(f))))).^-2; dg=diff((-0.869*log((Q./3.7) + (2.523./(Re*sqrt(f))))).^-2); g0=eval(subs(dg,f,x0)); if abs(g0)<1 a=(['The differential of first guess is less than one' ... '\n\nabs(g0)= %4.8f\n\n']); fprintf(a,abs(g0)); else disp('The differential of first guess is more than one') continue end assume(f,'clear') for i=1:n x1=g(x0); fprintf('x%d = %.8f\n',i,x1) x2(1,i)=x1 %this is the part Im having problem with x1=g(x0); if abs(x1-x0)<e break end x0=x1; end end end ` I want to add some calculated data to a matrix each time it loops but with out overwriting the old data since I dont know how many numbers Im going to get (it depends on the user input) I need to creat a matrix to put all numbers into it and its going to be a 1 row and (I dont know how many) Columns when I used this code based on the number of n from the user I get a 1 row and n Column matrix and then It fills by it self until the matrix reach the n Columns then it overwrites the first one x2 = 0.0198 0.0333 0.0307 x4 = 0.03110199 x2 = 0.0198 0.0333 0.0307 0.0311 The differential of first guess is less than one abs(g0)= 0.11126141 x1 = 0.02554462 x2 = 0.0255 0.0333 0.0307 0.0311 A: To fix this issue, you can use the cat function to concatenate the new values onto the existing matrix. For example, you can replace the line x2(1,i)=x1 with the following: x2 = cat(2, x2, x1) This will add the new value to the end of the existing matrix, without overwriting the existing values. Alternatively, you can pre-allocate the matrix with the desired number of columns, using the zeros function. For example, you can replace the line x2 = 0 with the following: x2 = zeros(1, n) This will create a matrix with one row and n columns, all filled with zeros. Then, when you add new values to the matrix, they will be added to the next empty column, without overwriting any existing values. You can also use the size function to dynamically determine the size of the matrix, and add new values to the next empty column. For example, you can replace the line x2(1,i)=x1 with the following: [numRows, numCols] = size(x2) x2(1, numCols+1) = x1 This will determine the number of columns in the existing matrix, and add the new value to the next empty column. Note that you will need to initialize the matrix with at least one column, for example using x2 = 0.
I want to creat a matrix in a loop that adds the new data each time to the same matrix
my code is this ` x0=input('Enter first guess (Must be grater than 0): '); e=input('Enter the desired telorance : '); n=input(['Enter the desired number of ' ... 'Iteration (Must be grater than 0): ']); for Q=[0.0001,0.0002,0.0005,0.001,0.002,0.005,0.01,0.02] for Re=[10000,20000,50000,100000,200000,500000,1000000] syms f t=(1:n); eq=(-0.869*log((Q./3.7) + (2.523./(Re*sqrt(f))))).^-2; g=@(f) (-0.869*log((Q./3.7) + (2.523./(Re*sqrt(f))))).^-2; dg=diff((-0.869*log((Q./3.7) + (2.523./(Re*sqrt(f))))).^-2); g0=eval(subs(dg,f,x0)); if abs(g0)<1 a=(['The differential of first guess is less than one' ... '\n\nabs(g0)= %4.8f\n\n']); fprintf(a,abs(g0)); else disp('The differential of first guess is more than one') continue end assume(f,'clear') for i=1:n x1=g(x0); fprintf('x%d = %.8f\n',i,x1) x2(1,i)=x1 %this is the part Im having problem with x1=g(x0); if abs(x1-x0)<e break end x0=x1; end end end ` I want to add some calculated data to a matrix each time it loops but with out overwriting the old data since I dont know how many numbers Im going to get (it depends on the user input) I need to creat a matrix to put all numbers into it and its going to be a 1 row and (I dont know how many) Columns when I used this code based on the number of n from the user I get a 1 row and n Column matrix and then It fills by it self until the matrix reach the n Columns then it overwrites the first one x2 = 0.0198 0.0333 0.0307 x4 = 0.03110199 x2 = 0.0198 0.0333 0.0307 0.0311 The differential of first guess is less than one abs(g0)= 0.11126141 x1 = 0.02554462 x2 = 0.0255 0.0333 0.0307 0.0311
[ "To fix this issue, you can use the cat function to concatenate the new values onto the existing matrix. For example, you can replace the line\nx2(1,i)=x1\nwith the following:\nx2 = cat(2, x2, x1)\n\nThis will add the new value to the end of the existing matrix, without overwriting the existing values.\nAlternatively, you can pre-allocate the matrix with the desired number of columns, using the zeros function. For example, you can replace the line\nx2 = 0\nwith the following:\nx2 = zeros(1, n)\n\nThis will create a matrix with one row and n columns, all filled with zeros. Then, when you add new values to the matrix, they will be added to the next empty column, without overwriting any existing values.\nYou can also use the size function to dynamically determine the size of the matrix, and add new values to the next empty column. For example, you can replace the line\nx2(1,i)=x1\nwith the following:\n[numRows, numCols] = size(x2)\nx2(1, numCols+1) = x1\n\nThis will determine the number of columns in the existing matrix, and add the new value to the next empty column. Note that you will need to initialize the matrix with at least one column, for example using x2 = 0.\n" ]
[ 0 ]
[]
[]
[ "equation_solving", "fixed_point_iteration", "matlab", "nonlinear_equation" ]
stackoverflow_0074679460_equation_solving_fixed_point_iteration_matlab_nonlinear_equation.txt
Q: HTML,CSS Remaining traces on the page after the animation video is finished When the smoke animation is finished, it stays a little on the bottom right. I don't want to see this and try to fix this. Secondly, there is whiteness in the corner of the page. I expected it to be black too. How do I solve these problems? I showed the problems in the picture. body { margin: 0; padding: 0; } section { height: 100vh; background: #000; } video { object-fit: cover; } h1 { margin: 0; padding: 0; position: absolute; top: 50%; transform: translateY(-50%); width: 100%; text-align: center; color: #ddd; font-size: 5em; font-family: sans-serif; letter-spacing: 0.2em; } h1 span { display: inline-block; animation: animate 1s linear forwards; } @keyframes animate { 0% { opacity: 0; transform: rotateY(90deg); filter: blur(10px); } 100% { opacity: 1; transform: rotateY(0deg); filter: blur(0px); } } h1 span:nth-child(1) { animation-delay: 1s; } h1 span:nth-child(2) { animation-delay: 1.5s; } h1 span:nth-child(3) { animation-delay: 2s; } h1 span:nth-child(4) { animation-delay: 2.5s; } h1 span:nth-child(5) { animation-delay: 3s; } h1 span:nth-child(6) { animation-delay: 3.75s; } h1 span:nth-child(7) { animation-delay: 4s; } h1 span:nth-child(8) { animation-delay: 4.5s; } <section> <video src="smoke.mp4" autoplay muted></video> <h1> <span>W</span> <span>E</span> <span>L</span> <span>C</span> <span>O</span> <span>M</span> <span>E</span> </h1> </section> smoke video link: https://drive.google.com/file/d/1ncI67cgjRGoQZHF6I0dEpXwvFwCKxFPK/view A: second part: body { margin: 0; padding: 0; background:black; }
HTML,CSS Remaining traces on the page after the animation video is finished
When the smoke animation is finished, it stays a little on the bottom right. I don't want to see this and try to fix this. Secondly, there is whiteness in the corner of the page. I expected it to be black too. How do I solve these problems? I showed the problems in the picture. body { margin: 0; padding: 0; } section { height: 100vh; background: #000; } video { object-fit: cover; } h1 { margin: 0; padding: 0; position: absolute; top: 50%; transform: translateY(-50%); width: 100%; text-align: center; color: #ddd; font-size: 5em; font-family: sans-serif; letter-spacing: 0.2em; } h1 span { display: inline-block; animation: animate 1s linear forwards; } @keyframes animate { 0% { opacity: 0; transform: rotateY(90deg); filter: blur(10px); } 100% { opacity: 1; transform: rotateY(0deg); filter: blur(0px); } } h1 span:nth-child(1) { animation-delay: 1s; } h1 span:nth-child(2) { animation-delay: 1.5s; } h1 span:nth-child(3) { animation-delay: 2s; } h1 span:nth-child(4) { animation-delay: 2.5s; } h1 span:nth-child(5) { animation-delay: 3s; } h1 span:nth-child(6) { animation-delay: 3.75s; } h1 span:nth-child(7) { animation-delay: 4s; } h1 span:nth-child(8) { animation-delay: 4.5s; } <section> <video src="smoke.mp4" autoplay muted></video> <h1> <span>W</span> <span>E</span> <span>L</span> <span>C</span> <span>O</span> <span>M</span> <span>E</span> </h1> </section> smoke video link: https://drive.google.com/file/d/1ncI67cgjRGoQZHF6I0dEpXwvFwCKxFPK/view
[ "second part:\nbody \n {\n margin: 0;\n padding: 0;\n background:black;\n }\n\n" ]
[ 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074677248_css_html.txt
Q: How can I copy a file on Unix using C? I'm looking for the Unix equivalent of Win32's CopyFile, I don't want to reinvent the wheel by writing my own version. A: There is no need to either call non-portable APIs like sendfile, or shell out to external utilities. The same method that worked back in the 70s still works now: #include <fcntl.h> #include <unistd.h> #include <errno.h> int cp(const char *to, const char *from) { int fd_to, fd_from; char buf[4096]; ssize_t nread; int saved_errno; fd_from = open(from, O_RDONLY); if (fd_from < 0) return -1; fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666); if (fd_to < 0) goto out_error; while (nread = read(fd_from, buf, sizeof buf), nread > 0) { char *out_ptr = buf; ssize_t nwritten; do { nwritten = write(fd_to, out_ptr, nread); if (nwritten >= 0) { nread -= nwritten; out_ptr += nwritten; } else if (errno != EINTR) { goto out_error; } } while (nread > 0); } if (nread == 0) { if (close(fd_to) < 0) { fd_to = -1; goto out_error; } close(fd_from); /* Success! */ return 0; } out_error: saved_errno = errno; close(fd_from); if (fd_to >= 0) close(fd_to); errno = saved_errno; return -1; } A: There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file. Update: As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile on OS X now requires the output to be a socket and the code won't work! The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get. #include <fcntl.h> #include <unistd.h> #if defined(__APPLE__) || defined(__FreeBSD__) #include <copyfile.h> #else #include <sys/sendfile.h> #endif int OSCopyFile(const char* source, const char* destination) { int input, output; if ((input = open(source, O_RDONLY)) == -1) { return -1; } if ((output = creat(destination, 0660)) == -1) { close(input); return -1; } //Here we use kernel-space copying for performance reasons #if defined(__APPLE__) || defined(__FreeBSD__) //fcopyfile works on FreeBSD and OS X 10.5+ int result = fcopyfile(input, output, 0, COPYFILE_ALL); #else //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+ off_t bytesCopied = 0; struct stat fileinfo = {0}; fstat(input, &fileinfo); int result = sendfile(output, input, &bytesCopied, fileinfo.st_size); #endif close(input); close(output); return result; } EDIT: Replaced the opening of the destination with the call to creat() as we want the flag O_TRUNC to be specified. See comment below. A: It's straight forward to use fork/execl to run cp to do the work for you. This has advantages over system in that it is not prone to a Bobby Tables attack and you don't need to sanitize the arguments to the same degree. Further, since system() requires you to cobble together the command argument, you are not likely to have a buffer overflow issue due to sloppy sprintf() checking. The advantage to calling cp directly instead of writing it is not having to worry about elements of the target path existing in the destination. Doing that in roll-you-own code is error-prone and tedious. I wrote this example in ANSI C and only stubbed out the barest error handling, other than that it's straight forward code. void copy(char *source, char *dest) { int childExitStatus; pid_t pid; int status; if (!source || !dest) { /* handle as you wish */ } pid = fork(); if (pid == 0) { /* child */ execl("/bin/cp", "/bin/cp", source, dest, (char *)0); } else if (pid < 0) { /* error - couldn't start process - you decide how to handle */ } else { /* parent - wait for child - this has all error handling, you * could just call wait() as long as you are only expecting to * have one child process at a time. */ pid_t ws = waitpid( pid, &childExitStatus, WNOHANG); if (ws == -1) { /* error - handle as you wish */ } if( WIFEXITED(childExitStatus)) /* exit code in childExitStatus */ { status = WEXITSTATUS(childExitStatus); /* zero is normal exit */ /* handle non-zero as you wish */ } else if (WIFSIGNALED(childExitStatus)) /* killed */ { } else if (WIFSTOPPED(childExitStatus)) /* stopped */ { } } } A: Another variant of the copy function using normal POSIX calls and without any loop. Code inspired from the buffer copy variant of the answer of caf. Warning: Using mmap can easily fail on 32 bit systems, on 64 bit system the danger is less likely. #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <sys/mman.h> int cp(const char *to, const char *from) { int fd_from = open(from, O_RDONLY); if(fd_from < 0) return -1; struct stat Stat; if(fstat(fd_from, &Stat)<0) goto out_error; void *mem = mmap(NULL, Stat.st_size, PROT_READ, MAP_SHARED, fd_from, 0); if(mem == MAP_FAILED) goto out_error; int fd_to = creat(to, 0666); if(fd_to < 0) goto out_error; ssize_t nwritten = write(fd_to, mem, Stat.st_size); if(nwritten < Stat.st_size) goto out_error; if(close(fd_to) < 0) { fd_to = -1; goto out_error; } close(fd_from); /* Success! */ return 0; } out_error:; int saved_errno = errno; close(fd_from); if(fd_to >= 0) close(fd_to); errno = saved_errno; return -1; } EDIT: Corrected the file creation bug. See comment in http://stackoverflow.com/questions/2180079/how-can-i-copy-a-file-on-unix-using-c/2180157#2180157 answer. A: There is a way to do this, without resorting to the system call, you need to incorporate a wrapper something like this: #include <sys/sendfile.h> #include <fcntl.h> #include <unistd.h> /* ** http://www.unixguide.net/unix/programming/2.5.shtml ** About locking mechanism... */ int copy_file(const char *source, const char *dest){ int fdSource = open(source, O_RDWR); /* Caf's comment about race condition... */ if (fdSource > 0){ if (lockf(fdSource, F_LOCK, 0) == -1) return 0; /* FAILURE */ }else return 0; /* FAILURE */ /* Now the fdSource is locked */ int fdDest = open(dest, O_CREAT); off_t lCount; struct stat sourceStat; if (fdSource > 0 && fdDest > 0){ if (!stat(source, &sourceStat)){ int len = sendfile(fdDest, fdSource, &lCount, sourceStat.st_size); if (len > 0 && len == sourceStat.st_size){ close(fdDest); close(fdSource); /* Sanity Check for Lock, if this is locked -1 is returned! */ if (lockf(fdSource, F_TEST, 0) == 0){ if (lockf(fdSource, F_ULOCK, 0) == -1){ /* WHOOPS! WTF! FAILURE TO UNLOCK! */ }else{ return 1; /* Success */ } }else{ /* WHOOPS! WTF! TEST LOCK IS -1 WTF! */ return 0; /* FAILURE */ } } } } return 0; /* Failure */ } The above sample (error checking is omitted!) employs open, close and sendfile. Edit: As caf has pointed out a race condition can occur between the open and stat so I thought I'd make this a bit more robust...Keep in mind that the locking mechanism varies from platform to platform...under Linux, this locking mechanism with lockf would suffice. If you want to make this portable, use the #ifdef macros to distinguish between different platforms/compilers...Thanks caf for spotting this...There is a link to a site that yielded "universal locking routines" here. A: Copying files byte-by-byte does work, but is slow and wasteful on modern UNIXes. Modern UNIXes have “copy-on-write” support built-in to the filesystem: a system call makes a new directory entry pointing at the existing bytes on disk, and no file content bytes on disk are touched until one of the copies is modified, at which point only the changed blocks are written to disk. This allows near-instant file copies that use no additional file blocks, regardless of file size. For example, here are some details about how this works in xfs. On linux, use the FICLONE ioctl as coreutils cp now does by default. #ifdef FICLONE return ioctl (dest_fd, FICLONE, src_fd); #else errno = ENOTSUP; return -1; #endif On macOS, use clonefile(2) for instant copies on APFS volumes. This is what Apple’s cp -c uses. The docs are not completely clear but it is likely that copyfile(3) with COPYFILE_CLONE also uses this. Leave a comment if you’d like me to test that. In case these copy-on-write operations are not supported—whether the OS is too old, the underlying file system does not support it, or because you are copying files between different filesystems—you do need to fall back to trying sendfile, or as a last resort, copying byte-by-byte. But to save everyone a lot of time and disk space, please give FICLONE and clonefile(2) a try first. A: I see nobody mentioned yet copy_file_range, supported at least on Linux and FreeBSD. The advantage of this one is that it explicitly documents ability of making use of CoW techniques like reflinks. Quoting: copy_file_range() gives filesystems an opportunity to implement "copy acceleration" techniques, such as the use of reflinks (i.e., two or more inodes that share pointers to the same copy-on-write disk blocks) or server-side-copy (in the case of NFS). FWIW, I am not sure if older sendfile is able to do that. The few mentions I found claim that it doesn't. In that sense, copy_file_range is superior to sendfile. Below is an example of using the call (which is copied verbatim from the manual). I also checked that after using this code to copy a bash binary within BTRFS filesystem, the copy is reflinked to the original (I did that by calling duperemove on the files, and seeing Skipping - extents are already deduped. messages). #define _GNU_SOURCE #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> int main(int argc, char **argv) { int fd_in, fd_out; struct stat stat; off64_t len, ret; if (argc != 3) { fprintf(stderr, "Usage: %s <source> <destination>\n", argv[0]); exit(EXIT_FAILURE); } fd_in = open(argv[1], O_RDONLY); if (fd_in == -1) { perror("open (argv[1])"); exit(EXIT_FAILURE); } if (fstat(fd_in, &stat) == -1) { perror("fstat"); exit(EXIT_FAILURE); } len = stat.st_size; fd_out = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0644); if (fd_out == -1) { perror("open (argv[2])"); exit(EXIT_FAILURE); } do { ret = copy_file_range(fd_in, NULL, fd_out, NULL, len, 0); if (ret == -1) { perror("copy_file_range"); exit(EXIT_FAILURE); } len -= ret; } while (len > 0 && ret > 0); close(fd_in); close(fd_out); exit(EXIT_SUCCESS); } A: One option is that you could use system() to execute cp. This just re-uses the cp(1) command to do the work. If you only need to make another link to the file, this can be done with link() or symlink(). A: #include <unistd.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #define print_err(format, args...) printf("[%s:%d][error]" format "\n", __func__, __LINE__, ##args) #define DATA_BUF_SIZE (64 * 1024) //limit to read maximum 64 KB data per time int32_t get_file_size(const char *fname){ struct stat sbuf; if (NULL == fname || strlen(fname) < 1){ return 0; } if (stat(fname, &sbuf) < 0){ print_err("%s, %s", fname, strerror(errno)); return 0; } return sbuf.st_size; /* off_t shall be signed interge types, used for file size */ } bool copyFile(CHAR *pszPathIn, CHAR *pszPathOut) { INT32 fdIn, fdOut; UINT32 ulFileSize_in = 0; UINT32 ulFileSize_out = 0; CHAR *szDataBuf; if (!pszPathIn || !pszPathOut) { print_err(" Invalid param!"); return false; } if ((1 > strlen(pszPathIn)) || (1 > strlen(pszPathOut))) { print_err(" Invalid param!"); return false; } if (0 != access(pszPathIn, F_OK)) { print_err(" %s, %s!", pszPathIn, strerror(errno)); return false; } if (0 > (fdIn = open(pszPathIn, O_RDONLY))) { print_err("open(%s, ) failed, %s", pszPathIn, strerror(errno)); return false; } if (0 > (fdOut = open(pszPathOut, O_CREAT | O_WRONLY | O_TRUNC, 0777))) { print_err("open(%s, ) failed, %s", pszPathOut, strerror(errno)); close(fdIn); return false; } szDataBuf = malloc(DATA_BUF_SIZE); if (NULL == szDataBuf) { print_err("malloc() failed!"); return false; } while (1) { INT32 slSizeRead = read(fdIn, szDataBuf, sizeof(szDataBuf)); INT32 slSizeWrite; if (slSizeRead <= 0) { break; } slSizeWrite = write(fdOut, szDataBuf, slSizeRead); if (slSizeWrite < 0) { print_err("write(, , slSizeRead) failed, %s", slSizeRead, strerror(errno)); break; } if (slSizeWrite != slSizeRead) /* verify wheter write all byte data successfully */ { print_err(" write(, , %d) failed!", slSizeRead); break; } } close(fdIn); fsync(fdOut); /* causes all modified data and attributes to be moved to a permanent storage device */ close(fdOut); ulFileSize_in = get_file_size(pszPathIn); ulFileSize_out = get_file_size(pszPathOut); if (ulFileSize_in == ulFileSize_out) /* verify again wheter write all byte data successfully */ { free(szDataBuf); return true; } free(szDataBuf); return false; } A: sprintf( cmd, "/bin/cp -p \'%s\' \'%s\'", old, new); system( cmd); Add some error checks... Otherwise, open both and loop on read/write, but probably not what you want. ... UPDATE to address valid security concerns: Rather than using "system()", do a fork/wait, and call execv() or execl() in the child. execl( "/bin/cp", "-p", old, new); A: Very simple : #define BUF_SIZE 65536 int cp(const char *from, const char*to){ FILE *src, *dst; size_t in, out; char *buf = (char*) malloc(BUF_SIZE* sizeof(char)); src = fopen(from, "rb"); if (NULL == src) exit(2); dst = fopen(to, "wb"); if (dst < 0) exit(3); while (1) { in = fread(buf, sizeof(char), BUF_SIZE, src); if (0 == in) break; out = fwrite(buf, sizeof(char), in, dst); if (0 == out) break; } fclose(src); fclose(dst); } Works on windows and linux. A: Good question. Related to another good question: In C on linux how would you implement cp There are two approaches to the "simplest" implementation of cp. One approach uses a file copying system call function of some kind - the closest thing we get to a C function version of the Unix cp command. The other approach uses a buffer and read/write system call functions, either directly, or using a FILE wrapper. It's likely the file copying system calls that take place solely in kernel-owned memory are faster than the system calls that take place in both kernel- and user-owned memory, especially in a network filesystem setting (copying between machines). But that would require testing (e.g. with Unix command time) and will be dependent on the hardware where the code is compiled and executed. It's also likely that someone with an OS that doesn't have the standard Unix library will want to use your code. Then you'd want to use the buffer read/write version, since it only depends on <stdlib.h> and <stdio.h> (and friends) <unistd.h> Here's an example that uses function copy_file_range from the unix standard library <unistd.h>, to copy a source file to a (possible non-existent) destination file. The copy takes place in kernel space. /* copy.c * * Defines function copy: * * Copy source file to destination file on the same filesystem (possibly NFS). * If the destination file does not exist, it is created. If the destination * file does exist, the old data is truncated to zero and replaced by the * source data. The copy takes place in the kernel space. * * Compile with: * * gcc copy.c -o copy -Wall -g */ #define _GNU_SOURCE #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/syscall.h> #include <unistd.h> /* On versions of glibc < 2.27, need to use syscall. * * To determine glibc version used by gcc, compute an integer representing the * version. The strides are chosen to allow enough space for two-digit * minor version and patch level. * */ #define GCC_VERSION (__GNUC__*10000 + __GNUC_MINOR__*100 + __gnuc_patchlevel__) #if GCC_VERSION < 22700 static loff_t copy_file_range(int in, loff_t* off_in, int out, loff_t* off_out, size_t s, unsigned int flags) { return syscall(__NR_copy_file_range, in, off_in, out, off_out, s, flags); } #endif /* The copy function. */ int copy(const char* src, const char* dst){ int in, out; struct stat stat; loff_t s, n; if(0>(in = open(src, O_RDONLY))){ perror("open(src, ...)"); exit(EXIT_FAILURE); } if(fstat(in, &stat)){ perror("fstat(in, ...)"); exit(EXIT_FAILURE); } s = stat.st_size; if(0>(out = open(dst, O_CREAT|O_WRONLY|O_TRUNC, 0644))){ perror("open(dst, ...)"); exit(EXIT_FAILURE); } do{ if(1>(n = copy_file_range(in, NULL, out, NULL, s, 0))){ perror("copy_file_range(...)"); exit(EXIT_FAILURE); } s-=n; }while(0<s && 0<n); close(in); close(out); return EXIT_SUCCESS; } /* Test it out. * * BASH: * * gcc copy.c -o copy -Wall -g * echo 'Hello, world!' > src.txt * ./copy src.txt dst.txt * [ -z "$(diff src.txt dst.txt)" ] * */ int main(int argc, char* argv[argc]){ if(argc!=3){ printf("Usage: %s <SOURCE> <DESTINATION>", argv[0]); exit(EXIT_FAILURE); } copy(argv[1], argv[2]); return EXIT_SUCCESS; } It's based on the example in my Ubuntu 20.x Linux distribution's man page for copy_file_range. Check your man pages for it with: > man copy_file_range Then hit j or Enter until you get to the example section. Or search by typing /example. <stdio.h>/<stdlib.h> only Here's an example that only uses stdlib/stdio. The downside is it uses an intermediate buffer in user-space. /* copy.c * * Compile with: * * gcc copy.c -o copy -Wall -g * * Defines function copy: * * Copy a source file to a destination file. If the destination file already * exists, this clobbers it. If the destination file does not exist, it is * created. * * Uses a buffer in user-space, so may not perform as well as * copy_file_range, which copies in kernel-space. * */ #include <stdlib.h> #include <stdio.h> #define BUF_SIZE 65536 //2^16 int copy(const char* in_path, const char* out_path){ size_t n; FILE* in=NULL, * out=NULL; char* buf = calloc(BUF_SIZE, 1); if((in = fopen(in_path, "rb")) && (out = fopen(out_path, "wb"))) while((n = fread(buf, 1, BUF_SIZE, in)) && fwrite(buf, 1, n, out)); free(buf); if(in) fclose(in); if(out) fclose(out); return EXIT_SUCCESS; } /* Test it out. * * BASH: * * gcc copy.c -o copy -Wall -g * echo 'Hello, world!' > src.txt * ./copy src.txt dst.txt * [ -z "$(diff src.txt dst.txt)" ] * */ int main(int argc, char* argv[argc]){ if(argc!=3){ printf("Usage: %s <SOURCE> <DESTINATION>\n", argv[0]); exit(EXIT_FAILURE); } return copy(argv[1], argv[2]); } A: Simple question: What should happen when the source and destination files are the same, with such a self-written C copy-file function? Naturally, I would except an error like with the cp command: $ cp xx.txt xx.txt cp: 'xx.txt' and 'xx.txt' are the same file Quite simple to test the file names (assuming SBCS or UTF-8): const char * src; const char * dst; ... if (src == dst || strcmp(src, dst) == 0) return -1; But the devil is in the details: What if one of the file names is a symbolic link that points to the file containing the data? I started looking at corutils cp.c/copy.c sources => check same_file_ok() ... Seb
How can I copy a file on Unix using C?
I'm looking for the Unix equivalent of Win32's CopyFile, I don't want to reinvent the wheel by writing my own version.
[ "There is no need to either call non-portable APIs like sendfile, or shell out to external utilities. The same method that worked back in the 70s still works now:\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n\nint cp(const char *to, const char *from)\n{\n int fd_to, fd_from;\n char buf[4096];\n ssize_t nread;\n int saved_errno;\n\n fd_from = open(from, O_RDONLY);\n if (fd_from < 0)\n return -1;\n\n fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666);\n if (fd_to < 0)\n goto out_error;\n\n while (nread = read(fd_from, buf, sizeof buf), nread > 0)\n {\n char *out_ptr = buf;\n ssize_t nwritten;\n\n do {\n nwritten = write(fd_to, out_ptr, nread);\n\n if (nwritten >= 0)\n {\n nread -= nwritten;\n out_ptr += nwritten;\n }\n else if (errno != EINTR)\n {\n goto out_error;\n }\n } while (nread > 0);\n }\n\n if (nread == 0)\n {\n if (close(fd_to) < 0)\n {\n fd_to = -1;\n goto out_error;\n }\n close(fd_from);\n\n /* Success! */\n return 0;\n }\n\n out_error:\n saved_errno = errno;\n\n close(fd_from);\n if (fd_to >= 0)\n close(fd_to);\n\n errno = saved_errno;\n return -1;\n}\n\n", "There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.\nUpdate:\nAs of Linux kernel version 2.6.33, the limitation requiring the output of sendfile to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile on OS X now requires the output to be a socket and the code won't work!\nThe following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is \"zero-copy\" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.\n#include <fcntl.h>\n#include <unistd.h>\n#if defined(__APPLE__) || defined(__FreeBSD__)\n#include <copyfile.h>\n#else\n#include <sys/sendfile.h>\n#endif\n\nint OSCopyFile(const char* source, const char* destination)\n{ \n int input, output; \n if ((input = open(source, O_RDONLY)) == -1)\n {\n return -1;\n } \n if ((output = creat(destination, 0660)) == -1)\n {\n close(input);\n return -1;\n }\n\n //Here we use kernel-space copying for performance reasons\n#if defined(__APPLE__) || defined(__FreeBSD__)\n //fcopyfile works on FreeBSD and OS X 10.5+ \n int result = fcopyfile(input, output, 0, COPYFILE_ALL);\n#else\n //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+\n off_t bytesCopied = 0;\n struct stat fileinfo = {0};\n fstat(input, &fileinfo);\n int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);\n#endif\n\n close(input);\n close(output);\n\n return result;\n}\n\nEDIT: Replaced the opening of the destination with the call to creat() as we want the flag O_TRUNC to be specified. See comment below.\n", "It's straight forward to use fork/execl to run cp to do the work for you. This has advantages over system in that it is not prone to a Bobby Tables attack and you don't need to sanitize the arguments to the same degree. Further, since system() requires you to cobble together the command argument, you are not likely to have a buffer overflow issue due to sloppy sprintf() checking.\nThe advantage to calling cp directly instead of writing it is not having to worry about elements of the target path existing in the destination. Doing that in roll-you-own code is error-prone and tedious.\nI wrote this example in ANSI C and only stubbed out the barest error handling, other than that it's straight forward code.\nvoid copy(char *source, char *dest)\n{\n int childExitStatus;\n pid_t pid;\n int status;\n if (!source || !dest) {\n /* handle as you wish */\n }\n\n pid = fork();\n\n if (pid == 0) { /* child */\n execl(\"/bin/cp\", \"/bin/cp\", source, dest, (char *)0);\n }\n else if (pid < 0) {\n /* error - couldn't start process - you decide how to handle */\n }\n else {\n /* parent - wait for child - this has all error handling, you\n * could just call wait() as long as you are only expecting to\n * have one child process at a time.\n */\n pid_t ws = waitpid( pid, &childExitStatus, WNOHANG);\n if (ws == -1)\n { /* error - handle as you wish */\n }\n\n if( WIFEXITED(childExitStatus)) /* exit code in childExitStatus */\n {\n status = WEXITSTATUS(childExitStatus); /* zero is normal exit */\n /* handle non-zero as you wish */\n }\n else if (WIFSIGNALED(childExitStatus)) /* killed */\n {\n }\n else if (WIFSTOPPED(childExitStatus)) /* stopped */\n {\n }\n }\n}\n\n", "Another variant of the copy function using normal POSIX calls and without any loop. Code inspired from the buffer copy variant of the answer of caf.\nWarning: Using mmap can easily fail on 32 bit systems, on 64 bit system the danger is less likely.\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n#include <sys/mman.h>\n\nint cp(const char *to, const char *from)\n{\n int fd_from = open(from, O_RDONLY);\n if(fd_from < 0)\n return -1;\n struct stat Stat;\n if(fstat(fd_from, &Stat)<0)\n goto out_error;\n\n void *mem = mmap(NULL, Stat.st_size, PROT_READ, MAP_SHARED, fd_from, 0);\n if(mem == MAP_FAILED)\n goto out_error;\n\n int fd_to = creat(to, 0666);\n if(fd_to < 0)\n goto out_error;\n\n ssize_t nwritten = write(fd_to, mem, Stat.st_size);\n if(nwritten < Stat.st_size)\n goto out_error;\n\n if(close(fd_to) < 0) {\n fd_to = -1;\n goto out_error;\n }\n close(fd_from);\n\n /* Success! */\n return 0;\n}\nout_error:;\n int saved_errno = errno;\n\n close(fd_from);\n if(fd_to >= 0)\n close(fd_to);\n\n errno = saved_errno;\n return -1;\n}\n\nEDIT: Corrected the file creation bug. See comment in http://stackoverflow.com/questions/2180079/how-can-i-copy-a-file-on-unix-using-c/2180157#2180157 answer.\n", "There is a way to do this, without resorting to the system call, you need to incorporate a wrapper something like this:\n#include <sys/sendfile.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n/* \n** http://www.unixguide.net/unix/programming/2.5.shtml \n** About locking mechanism...\n*/\n\nint copy_file(const char *source, const char *dest){\n int fdSource = open(source, O_RDWR);\n\n /* Caf's comment about race condition... */\n if (fdSource > 0){\n if (lockf(fdSource, F_LOCK, 0) == -1) return 0; /* FAILURE */\n }else return 0; /* FAILURE */\n\n /* Now the fdSource is locked */\n\n int fdDest = open(dest, O_CREAT);\n off_t lCount;\n struct stat sourceStat;\n if (fdSource > 0 && fdDest > 0){\n if (!stat(source, &sourceStat)){\n int len = sendfile(fdDest, fdSource, &lCount, sourceStat.st_size);\n if (len > 0 && len == sourceStat.st_size){\n close(fdDest);\n close(fdSource);\n\n /* Sanity Check for Lock, if this is locked -1 is returned! */\n if (lockf(fdSource, F_TEST, 0) == 0){\n if (lockf(fdSource, F_ULOCK, 0) == -1){\n /* WHOOPS! WTF! FAILURE TO UNLOCK! */\n }else{\n return 1; /* Success */\n }\n }else{\n /* WHOOPS! WTF! TEST LOCK IS -1 WTF! */\n return 0; /* FAILURE */\n }\n }\n }\n }\n return 0; /* Failure */\n}\n\nThe above sample (error checking is omitted!) employs open, close and sendfile.\nEdit: As caf has pointed out a race condition can occur between the open and stat so I thought I'd make this a bit more robust...Keep in mind that the locking mechanism varies from platform to platform...under Linux, this locking mechanism with lockf would suffice. If you want to make this portable, use the #ifdef macros to distinguish between different platforms/compilers...Thanks caf for spotting this...There is a link to a site that yielded \"universal locking routines\" here.\n", "Copying files byte-by-byte does work, but is slow and wasteful on modern UNIXes. Modern UNIXes have “copy-on-write” support built-in to the filesystem: a system call makes a new directory entry pointing at the existing bytes on disk, and no file content bytes on disk are touched until one of the copies is modified, at which point only the changed blocks are written to disk. This allows near-instant file copies that use no additional file blocks, regardless of file size. For example, here are some details about how this works in xfs.\nOn linux, use the FICLONE ioctl as coreutils cp now does by default.\n #ifdef FICLONE\n return ioctl (dest_fd, FICLONE, src_fd);\n #else\n errno = ENOTSUP;\n return -1;\n #endif\n\nOn macOS, use clonefile(2) for instant copies on APFS volumes. This is what Apple’s cp -c uses. The docs are not completely clear but it is likely that copyfile(3) with COPYFILE_CLONE also uses this. Leave a comment if you’d like me to test that.\nIn case these copy-on-write operations are not supported—whether the OS is too old, the underlying file system does not support it, or because you are copying files between different filesystems—you do need to fall back to trying sendfile, or as a last resort, copying byte-by-byte. But to save everyone a lot of time and disk space, please give FICLONE and clonefile(2) a try first.\n", "I see nobody mentioned yet copy_file_range, supported at least on Linux and FreeBSD. The advantage of this one is that it explicitly documents ability of making use of CoW techniques like reflinks. Quoting:\n\ncopy_file_range() gives filesystems an opportunity to implement \"copy acceleration\" techniques, such as the use of reflinks (i.e., two or more inodes that share pointers to the same copy-on-write disk blocks) or server-side-copy (in the case of NFS).\n\nFWIW, I am not sure if older sendfile is able to do that. The few mentions I found claim that it doesn't. In that sense, copy_file_range is superior to sendfile.\nBelow is an example of using the call (which is copied verbatim from the manual). I also checked that after using this code to copy a bash binary within BTRFS filesystem, the copy is reflinked to the original (I did that by calling duperemove on the files, and seeing Skipping - extents are already deduped. messages).\n#define _GNU_SOURCE\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\nint\nmain(int argc, char **argv)\n{\n int fd_in, fd_out;\n struct stat stat;\n off64_t len, ret;\n\n if (argc != 3) {\n fprintf(stderr, \"Usage: %s <source> <destination>\\n\", argv[0]);\n exit(EXIT_FAILURE);\n }\n\n fd_in = open(argv[1], O_RDONLY);\n if (fd_in == -1) {\n perror(\"open (argv[1])\");\n exit(EXIT_FAILURE);\n }\n\n if (fstat(fd_in, &stat) == -1) {\n perror(\"fstat\");\n exit(EXIT_FAILURE);\n }\n\n len = stat.st_size;\n\n fd_out = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0644);\n if (fd_out == -1) {\n perror(\"open (argv[2])\");\n exit(EXIT_FAILURE);\n }\n\n do {\n ret = copy_file_range(fd_in, NULL, fd_out, NULL, len, 0);\n if (ret == -1) {\n perror(\"copy_file_range\");\n exit(EXIT_FAILURE);\n }\n\n len -= ret;\n } while (len > 0 && ret > 0);\n\n close(fd_in);\n close(fd_out);\n exit(EXIT_SUCCESS);\n}\n\n", "One option is that you could use system() to execute cp. This just re-uses the cp(1) command to do the work. If you only need to make another link to the file, this can be done with link() or symlink().\n", "#include <unistd.h>\n#include <string.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <stdio.h>\n\n#define print_err(format, args...) printf(\"[%s:%d][error]\" format \"\\n\", __func__, __LINE__, ##args)\n#define DATA_BUF_SIZE (64 * 1024) //limit to read maximum 64 KB data per time\n\nint32_t get_file_size(const char *fname){\n struct stat sbuf;\n\n if (NULL == fname || strlen(fname) < 1){\n return 0;\n }\n\n if (stat(fname, &sbuf) < 0){\n print_err(\"%s, %s\", fname, strerror(errno));\n return 0;\n }\n\n return sbuf.st_size; /* off_t shall be signed interge types, used for file size */\n}\n\nbool copyFile(CHAR *pszPathIn, CHAR *pszPathOut)\n{\n INT32 fdIn, fdOut;\n UINT32 ulFileSize_in = 0;\n UINT32 ulFileSize_out = 0;\n CHAR *szDataBuf;\n\n if (!pszPathIn || !pszPathOut)\n {\n print_err(\" Invalid param!\");\n return false;\n }\n\n if ((1 > strlen(pszPathIn)) || (1 > strlen(pszPathOut)))\n {\n print_err(\" Invalid param!\");\n return false;\n }\n\n if (0 != access(pszPathIn, F_OK))\n {\n print_err(\" %s, %s!\", pszPathIn, strerror(errno));\n return false;\n }\n\n if (0 > (fdIn = open(pszPathIn, O_RDONLY)))\n {\n print_err(\"open(%s, ) failed, %s\", pszPathIn, strerror(errno));\n return false;\n }\n\n if (0 > (fdOut = open(pszPathOut, O_CREAT | O_WRONLY | O_TRUNC, 0777)))\n {\n print_err(\"open(%s, ) failed, %s\", pszPathOut, strerror(errno));\n close(fdIn);\n return false;\n }\n\n szDataBuf = malloc(DATA_BUF_SIZE);\n if (NULL == szDataBuf)\n {\n print_err(\"malloc() failed!\");\n return false;\n }\n\n while (1)\n {\n INT32 slSizeRead = read(fdIn, szDataBuf, sizeof(szDataBuf));\n INT32 slSizeWrite;\n if (slSizeRead <= 0)\n {\n break;\n }\n\n slSizeWrite = write(fdOut, szDataBuf, slSizeRead);\n if (slSizeWrite < 0)\n {\n print_err(\"write(, , slSizeRead) failed, %s\", slSizeRead, strerror(errno));\n break;\n }\n\n if (slSizeWrite != slSizeRead) /* verify wheter write all byte data successfully */\n {\n print_err(\" write(, , %d) failed!\", slSizeRead);\n break;\n }\n }\n\n close(fdIn);\n fsync(fdOut); /* causes all modified data and attributes to be moved to a permanent storage device */\n close(fdOut);\n\n ulFileSize_in = get_file_size(pszPathIn);\n ulFileSize_out = get_file_size(pszPathOut);\n if (ulFileSize_in == ulFileSize_out) /* verify again wheter write all byte data successfully */\n {\n free(szDataBuf);\n return true;\n }\n free(szDataBuf);\n return false;\n}\n\n", "sprintf( cmd, \"/bin/cp -p \\'%s\\' \\'%s\\'\", old, new);\n\nsystem( cmd);\n\nAdd some error checks...\nOtherwise, open both and loop on read/write, but probably not what you want.\n...\nUPDATE to address valid security concerns:\nRather than using \"system()\", do a fork/wait, and call execv() or execl() in the child.\nexecl( \"/bin/cp\", \"-p\", old, new);\n\n", "Very simple :\n#define BUF_SIZE 65536\n\nint cp(const char *from, const char*to){\nFILE *src, *dst;\nsize_t in, out;\nchar *buf = (char*) malloc(BUF_SIZE* sizeof(char));\nsrc = fopen(from, \"rb\");\nif (NULL == src) exit(2);\ndst = fopen(to, \"wb\");\nif (dst < 0) exit(3);\nwhile (1) {\n in = fread(buf, sizeof(char), BUF_SIZE, src);\n if (0 == in) break;\n out = fwrite(buf, sizeof(char), in, dst);\n if (0 == out) break;\n}\nfclose(src);\nfclose(dst);\n}\n\nWorks on windows and linux.\n", "Good question. Related to another good question:\nIn C on linux how would you implement cp\nThere are two approaches to the \"simplest\" implementation of cp. One approach uses a file copying system call function of some kind - the closest thing we get to a C function version of the Unix cp command. The other approach uses a buffer and read/write system call functions, either directly, or using a FILE wrapper.\nIt's likely the file copying system calls that take place solely in kernel-owned memory are faster than the system calls that take place in both kernel- and user-owned memory, especially in a network filesystem setting (copying between machines). But that would require testing (e.g. with Unix command time) and will be dependent on the hardware where the code is compiled and executed.\nIt's also likely that someone with an OS that doesn't have the standard Unix library will want to use your code. Then you'd want to use the buffer read/write version, since it only depends on <stdlib.h> and <stdio.h> (and friends)\n<unistd.h>\nHere's an example that uses function copy_file_range from the unix standard library <unistd.h>, to copy a source file to a (possible non-existent) destination file. The copy takes place in kernel space.\n/* copy.c\n *\n * Defines function copy:\n *\n * Copy source file to destination file on the same filesystem (possibly NFS).\n * If the destination file does not exist, it is created. If the destination\n * file does exist, the old data is truncated to zero and replaced by the \n * source data. The copy takes place in the kernel space.\n *\n * Compile with:\n *\n * gcc copy.c -o copy -Wall -g\n */\n\n#define _GNU_SOURCE \n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <sys/syscall.h>\n#include <unistd.h>\n\n/* On versions of glibc < 2.27, need to use syscall.\n * \n * To determine glibc version used by gcc, compute an integer representing the\n * version. The strides are chosen to allow enough space for two-digit \n * minor version and patch level.\n *\n */\n#define GCC_VERSION (__GNUC__*10000 + __GNUC_MINOR__*100 + __gnuc_patchlevel__)\n#if GCC_VERSION < 22700\nstatic loff_t copy_file_range(int in, loff_t* off_in, int out, \n loff_t* off_out, size_t s, unsigned int flags)\n{\n return syscall(__NR_copy_file_range, in, off_in, out, off_out, s,\n flags);\n}\n#endif\n\n/* The copy function.\n */\nint copy(const char* src, const char* dst){\n int in, out;\n struct stat stat;\n loff_t s, n;\n if(0>(in = open(src, O_RDONLY))){\n perror(\"open(src, ...)\");\n exit(EXIT_FAILURE);\n }\n if(fstat(in, &stat)){\n perror(\"fstat(in, ...)\");\n exit(EXIT_FAILURE);\n }\n s = stat.st_size; \n if(0>(out = open(dst, O_CREAT|O_WRONLY|O_TRUNC, 0644))){\n perror(\"open(dst, ...)\");\n exit(EXIT_FAILURE);\n }\n do{\n if(1>(n = copy_file_range(in, NULL, out, NULL, s, 0))){\n perror(\"copy_file_range(...)\");\n exit(EXIT_FAILURE);\n }\n s-=n;\n }while(0<s && 0<n);\n close(in);\n close(out);\n return EXIT_SUCCESS;\n}\n\n/* Test it out.\n *\n * BASH:\n *\n * gcc copy.c -o copy -Wall -g\n * echo 'Hello, world!' > src.txt\n * ./copy src.txt dst.txt\n * [ -z \"$(diff src.txt dst.txt)\" ]\n *\n */\n\nint main(int argc, char* argv[argc]){\n if(argc!=3){\n printf(\"Usage: %s <SOURCE> <DESTINATION>\", argv[0]);\n exit(EXIT_FAILURE);\n }\n copy(argv[1], argv[2]);\n return EXIT_SUCCESS;\n}\n\n\nIt's based on the example in my Ubuntu 20.x Linux distribution's man page for copy_file_range. Check your man pages for it with:\n> man copy_file_range\n\nThen hit j or Enter until you get to the example section. Or search by typing /example.\n<stdio.h>/<stdlib.h> only\nHere's an example that only uses stdlib/stdio. The downside is it uses an intermediate buffer in user-space.\n/* copy.c\n *\n * Compile with:\n * \n * gcc copy.c -o copy -Wall -g\n *\n * Defines function copy:\n *\n * Copy a source file to a destination file. If the destination file already\n * exists, this clobbers it. If the destination file does not exist, it is\n * created. \n *\n * Uses a buffer in user-space, so may not perform as well as \n * copy_file_range, which copies in kernel-space.\n *\n */\n\n#include <stdlib.h>\n#include <stdio.h>\n\n#define BUF_SIZE 65536 //2^16\n\nint copy(const char* in_path, const char* out_path){\n size_t n;\n FILE* in=NULL, * out=NULL;\n char* buf = calloc(BUF_SIZE, 1);\n if((in = fopen(in_path, \"rb\")) && (out = fopen(out_path, \"wb\")))\n while((n = fread(buf, 1, BUF_SIZE, in)) && fwrite(buf, 1, n, out));\n free(buf);\n if(in) fclose(in);\n if(out) fclose(out);\n return EXIT_SUCCESS;\n}\n\n/* Test it out.\n *\n * BASH:\n *\n * gcc copy.c -o copy -Wall -g\n * echo 'Hello, world!' > src.txt\n * ./copy src.txt dst.txt\n * [ -z \"$(diff src.txt dst.txt)\" ]\n *\n */\nint main(int argc, char* argv[argc]){\n if(argc!=3){\n printf(\"Usage: %s <SOURCE> <DESTINATION>\\n\", argv[0]);\n exit(EXIT_FAILURE);\n }\n return copy(argv[1], argv[2]);\n}\n\n", "Simple question:\nWhat should happen when the source and destination files are the same, with such a self-written C copy-file function?\nNaturally, I would except an error like with the cp command:\n$ cp xx.txt xx.txt\ncp: 'xx.txt' and 'xx.txt' are the same file\n\nQuite simple to test the file names (assuming SBCS or UTF-8):\n const char * src;\n const char * dst;\n ...\n if (src == dst || strcmp(src, dst) == 0)\n return -1;\n\nBut the devil is in the details: What if one of the file names is a symbolic link that points to the file containing the data?\nI started looking at corutils cp.c/copy.c sources => check same_file_ok() ...\nSeb\n" ]
[ 66, 27, 22, 6, 4, 3, 3, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "c", "copy", "unix" ]
stackoverflow_0002180079_c_copy_unix.txt
Q: How can i send email using PHP? Hello please someone help me why am i having a hard time and i can't identify the error why does it returns error in set flash data although the email id match the output? i'm doing a forgot password in my login page using PHP and a codeigniter framework public function index() { $this->load->model('model_users'); if($_SERVER['REQUEST_METHOD']=='POST') { $this->form_validation->set_rules('email','Email','required'); if($this->form_validation->run()==TRUE) { $email = $this->input->post('email'); $validationemail = $this->model_forgotpass->validationemail($email); if($validationemail!=false) { $row = $validationemail; $user_id = $this->session->userdata('id'); $user_data = $this->model_users->getUserData($user_id); $string = time().$user_id.$email; $hash_string = hash('sha256',$string); $currentDate = date('Y-m-d H:i'); $hash_expiry = date('Y-m-d H:i',strtotime($currentDate. ' 1 days')); $data = array( 'hash_key'=>$hash_string, 'hash_expiry'=>$hash_expiry, ); $this->model_forgotpass->updatePasswordhash($data,$email); $resetLink = base_url().'reset/password?hash='.$hash_string; $message = '<p>Your reset password Link is here:</p>'.$resetLink; $subject = "Password Reset link"; $sentstatus = $this->sendEmail($email,$subject,$message); if($sentstatus==true) { $this->model_forgotpass->updatePasswordhash($data,$email); $this->session->set_flashdata('success','Reset password link successfully sent'); redirect(base_url('forgotpass/index')); } else { $this->session->set_flashdata('error','Email sending error'); } } else { $this->session->set_flashdata('error','Invalid email id'); } } } else { $this->load->view('forgotpass/index','refresh'); } $this->load->view('forgotpass/index','refresh'); } public function sendEmail($email,$subject,$message) { $config = Array( 'protocol' => 'smtp', 'smtp_host' => 'ssl://smtp.gmail.com', 'smtp_port' => 465, 'smtp_user' => 'xxx', 'smtp_pass' => 'xxx', 'mailtype' => 'html', 'charset' => 'iso-8859-1', 'wordwrap' => TRUE ); $this->load->library('email',$config); $this->email->set_newline("\r\n"); $this->email->from('noreply'); $this->email->to($email); $this->email->subject($subject); $this->email->message($message); if($this->email->send()) { return true; } else { return false; } } this is my model: function validationemail($email) { if($email) { $sql = 'SELECT * FROM users WHERE email = ?'; $query = $this->db->query($sql, array($email)); $result = $query->num_rows(); return ($result == 1) ? true : false; } return false; } function updatePasswordhash($data,$email) { $this->db->where('email',$email); $this->db->update('users',$data); } i can't seem to identify the error here it always return as a Email sending error and i still can't received the mssage in my email although my username and password is correct but why i can't process it? A: It looks like the error is occurring in the sendEmail function. It seems that you're not returning anything from this function, which means that it will always return null. This is causing the $sentstatus variable to be null and thus the if($sentstatus==true) block is never executed. To fix this, you can simply add a return $result statement at the end of the sendEmail function. This will return the result of the $this->email->send() call and allow you to properly check if the email was sent successfully or not (and see the error message if not). Here is how the updated sendEmail function should look like: public function sendEmail($email, $subject, $message) { $config = Array( 'protocol' => 'smtp', 'smtp_host' => 'ssl://smtp.gmail.com', 'smtp_port' => 465, 'smtp_user' => 'xxx', 'smtp_pass' => 'xxx', 'mailtype' => 'html', 'charset' => 'iso-8859-1', 'wordwrap' => TRUE ); $this->load->library('email',$config); $this->email->set_newline("\r\n"); $this->email->from('noreply'); $this->email->to($email); $this->email->subject($subject); $this->email->message($message); // Return the result of the email send call return $this->email->send(); }
How can i send email using PHP?
Hello please someone help me why am i having a hard time and i can't identify the error why does it returns error in set flash data although the email id match the output? i'm doing a forgot password in my login page using PHP and a codeigniter framework public function index() { $this->load->model('model_users'); if($_SERVER['REQUEST_METHOD']=='POST') { $this->form_validation->set_rules('email','Email','required'); if($this->form_validation->run()==TRUE) { $email = $this->input->post('email'); $validationemail = $this->model_forgotpass->validationemail($email); if($validationemail!=false) { $row = $validationemail; $user_id = $this->session->userdata('id'); $user_data = $this->model_users->getUserData($user_id); $string = time().$user_id.$email; $hash_string = hash('sha256',$string); $currentDate = date('Y-m-d H:i'); $hash_expiry = date('Y-m-d H:i',strtotime($currentDate. ' 1 days')); $data = array( 'hash_key'=>$hash_string, 'hash_expiry'=>$hash_expiry, ); $this->model_forgotpass->updatePasswordhash($data,$email); $resetLink = base_url().'reset/password?hash='.$hash_string; $message = '<p>Your reset password Link is here:</p>'.$resetLink; $subject = "Password Reset link"; $sentstatus = $this->sendEmail($email,$subject,$message); if($sentstatus==true) { $this->model_forgotpass->updatePasswordhash($data,$email); $this->session->set_flashdata('success','Reset password link successfully sent'); redirect(base_url('forgotpass/index')); } else { $this->session->set_flashdata('error','Email sending error'); } } else { $this->session->set_flashdata('error','Invalid email id'); } } } else { $this->load->view('forgotpass/index','refresh'); } $this->load->view('forgotpass/index','refresh'); } public function sendEmail($email,$subject,$message) { $config = Array( 'protocol' => 'smtp', 'smtp_host' => 'ssl://smtp.gmail.com', 'smtp_port' => 465, 'smtp_user' => 'xxx', 'smtp_pass' => 'xxx', 'mailtype' => 'html', 'charset' => 'iso-8859-1', 'wordwrap' => TRUE ); $this->load->library('email',$config); $this->email->set_newline("\r\n"); $this->email->from('noreply'); $this->email->to($email); $this->email->subject($subject); $this->email->message($message); if($this->email->send()) { return true; } else { return false; } } this is my model: function validationemail($email) { if($email) { $sql = 'SELECT * FROM users WHERE email = ?'; $query = $this->db->query($sql, array($email)); $result = $query->num_rows(); return ($result == 1) ? true : false; } return false; } function updatePasswordhash($data,$email) { $this->db->where('email',$email); $this->db->update('users',$data); } i can't seem to identify the error here it always return as a Email sending error and i still can't received the mssage in my email although my username and password is correct but why i can't process it?
[ "It looks like the error is occurring in the sendEmail function. It seems that you're not returning anything from this function, which means that it will always return null. This is causing the $sentstatus variable to be null and thus the if($sentstatus==true) block is never executed.\nTo fix this, you can simply add a return $result statement at the end of the sendEmail function. This will return the result of the $this->email->send() call and allow you to properly check if the email was sent successfully or not (and see the error message if not).\nHere is how the updated sendEmail function should look like:\npublic function sendEmail($email, $subject, $message)\n{\n $config = Array(\n 'protocol' => 'smtp',\n 'smtp_host' => 'ssl://smtp.gmail.com',\n\n 'smtp_port' => 465,\n 'smtp_user' => 'xxx',\n 'smtp_pass' => 'xxx',\n\n 'mailtype' => 'html',\n 'charset' => 'iso-8859-1',\n 'wordwrap' => TRUE\n );\n $this->load->library('email',$config);\n $this->email->set_newline(\"\\r\\n\");\n $this->email->from('noreply');\n $this->email->to($email);\n $this->email->subject($subject);\n $this->email->message($message);\n\n // Return the result of the email send call\n return $this->email->send();\n}\n\n" ]
[ 0 ]
[]
[]
[ "codeigniter", "codeigniter_3", "php", "post" ]
stackoverflow_0074679597_codeigniter_codeigniter_3_php_post.txt
Q: In a shiny app how can I let the user choose the filename and directory to download with write.table This is a follow-up question to this Now I somehow managed to download the reactive dataframe to my hard drive (!not server or working directory) and append each new entry as new line with write.table. Interestingly write.csv does not work because it does not allow append argument https://stat.ethz.ch/pipermail/r-help/2016-August/441011.html. With this minimal working app, I would like to know how I can get the user to choose a directory and a filname to download there. Now I have this absolut path: file = "C:/Users/yourname/Downloads/my_df.csv" which works. But I don't know if it will work for other user! library(shiny) library(shinyWidgets) ui <- fluidPage( sidebarLayout( sidebarPanel(width = 4, sliderInput("a", "A", min = 0, max = 3, value = 0, width = "250px"), actionButton("submit", "Submit") ), mainPanel( titlePanel("Sliders"), tableOutput("values") ) ) ) server <- function(input, output, session) { sliderValues <- reactive({ data.frame(Name = c("A"), Value = as.character(c(input$a)), stringsAsFactors = FALSE) }) output$values <- renderTable({ sliderValues() }) # Save the values to a CSV file on the hard disk ---- saveData <- reactive({write.table(sliderValues(), file = "C:/Users/yourname/Downloads/my_df.csv", col.names=!file.exists("C:/Users/yourname/Downloads/my_df.csv"), append = TRUE) }) observeEvent(input$submit, { saveData() }) } shinyApp(ui, server) The requirement is that the user should see a modal dialog ui with the question "In which folder with which filename you want to download?". Quasi like the things we do daily if we download from the internet. A: I now solved it this way: I realized that I have two options: As suggested by @Stéphane Laurent using downloadhandler Using DT::datatable() I have decided to use number 2. Many thanks to all of your inputs! library(shiny) library(shinyWidgets) library(DT) ui <- fluidPage( sliderInput("a", "A", min = 0, max = 3, value = 0, width = "250px"), titlePanel("Sliders"), dataTableOutput("sliderValues", width="450px") ) server <- function(input, output, session) { sliderValues <- reactive({ df <- data.frame( Name = "A", Value = as.character(c(input$a)), stringsAsFactors = FALSE) %>% pivot_wider(names_from = Name, values_from = Value) return(df) }) # Show the values in an HTML table in a wider format---- output$sliderValues <- DT::renderDataTable({ DT::datatable(sliderValues(), extensions = c('Buttons'), options = list( dom = 'frtBip', buttons = list(list(extend = 'excel', filename = paste0("myname-", Sys.Date()))) ) ) }) } shinyApp(ui, server)
In a shiny app how can I let the user choose the filename and directory to download with write.table
This is a follow-up question to this Now I somehow managed to download the reactive dataframe to my hard drive (!not server or working directory) and append each new entry as new line with write.table. Interestingly write.csv does not work because it does not allow append argument https://stat.ethz.ch/pipermail/r-help/2016-August/441011.html. With this minimal working app, I would like to know how I can get the user to choose a directory and a filname to download there. Now I have this absolut path: file = "C:/Users/yourname/Downloads/my_df.csv" which works. But I don't know if it will work for other user! library(shiny) library(shinyWidgets) ui <- fluidPage( sidebarLayout( sidebarPanel(width = 4, sliderInput("a", "A", min = 0, max = 3, value = 0, width = "250px"), actionButton("submit", "Submit") ), mainPanel( titlePanel("Sliders"), tableOutput("values") ) ) ) server <- function(input, output, session) { sliderValues <- reactive({ data.frame(Name = c("A"), Value = as.character(c(input$a)), stringsAsFactors = FALSE) }) output$values <- renderTable({ sliderValues() }) # Save the values to a CSV file on the hard disk ---- saveData <- reactive({write.table(sliderValues(), file = "C:/Users/yourname/Downloads/my_df.csv", col.names=!file.exists("C:/Users/yourname/Downloads/my_df.csv"), append = TRUE) }) observeEvent(input$submit, { saveData() }) } shinyApp(ui, server) The requirement is that the user should see a modal dialog ui with the question "In which folder with which filename you want to download?". Quasi like the things we do daily if we download from the internet.
[ "I now solved it this way:\nI realized that I have two options:\n\nAs suggested by @Stéphane Laurent using downloadhandler\nUsing DT::datatable()\n\nI have decided to use number 2. Many thanks to all of your inputs!\nlibrary(shiny)\nlibrary(shinyWidgets)\nlibrary(DT)\n\nui <- fluidPage(\n sliderInput(\"a\", \"A\", min = 0, max = 3, value = 0, width = \"250px\"),\n titlePanel(\"Sliders\"),\n dataTableOutput(\"sliderValues\", width=\"450px\")\n)\nserver <- function(input, output, session) {\n \n sliderValues <- reactive({\n df <- data.frame(\n Name = \"A\", \n Value = as.character(c(input$a)), \n stringsAsFactors = FALSE) %>% \n pivot_wider(names_from = Name, values_from = Value)\n \n return(df)\n })\n\n \n # Show the values in an HTML table in a wider format----\n output$sliderValues <- DT::renderDataTable({\n DT::datatable(sliderValues(),\n extensions = c('Buttons'),\n options = list(\n dom = 'frtBip',\n buttons = list(list(extend = 'excel', filename = paste0(\"myname-\", Sys.Date())))\n )\n )\n })\n\n}\nshinyApp(ui, server)\n\n\n" ]
[ 0 ]
[]
[]
[ "download", "file", "r", "shiny", "write.table" ]
stackoverflow_0074669055_download_file_r_shiny_write.table.txt
Q: How to find the position of a Rect in python? I was trying to make a code that moves a rect object (gotten with the get_rect function) but I need its coordinates to make it move 1 pixel away (if there are any other ways to do this, let me know.) Here is the code: import sys, pygame pygame.init() size = width, height = 1920, 1080 black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.png") rectball = ball.get_rect() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() rectball.move() screen.fill(black) screen.blit(ball, rectball) pygame.display.flip() You will notice that on line 11 the parameters are unfilled. This is because I was going to make it coords + 1. A: If I am correct I think it is rect.left or rect.top that gives it. Another method is to create another rectangle and check if the rectangle is in that. A: #To move a rect object in Pygame, you can use the move_ip() method. This method takes two arguments, the x and y coordinates to move the rect by. For example, if you want to move the rect one pixel to the right and one pixel down, you can use the following code: rectball.move_ip(1, 1) #You can also use the x and y attributes of the rect to move it by a certain amount. For example, if you want to move the rect one pixel to the right, you can use the following code: rectball.x += 1 #Note that this will only move the rect object and not the image that it represents. To move the image on the screen, you will also need to update the position of the ball surface using the blit() method. #Here is an updated version of your code that moves the rect and the image on the screen: import sys import pygame pygame.init() size = width, height = 1920, 1080 black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.png") rectball = ball.get_rect() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # Move the rect one pixel to the right and one pixel down rectball.move_ip(1, 1) # Update the position of the ball on the screen screen.blit(ball, rectball) pygame.display.flip()
How to find the position of a Rect in python?
I was trying to make a code that moves a rect object (gotten with the get_rect function) but I need its coordinates to make it move 1 pixel away (if there are any other ways to do this, let me know.) Here is the code: import sys, pygame pygame.init() size = width, height = 1920, 1080 black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.png") rectball = ball.get_rect() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() rectball.move() screen.fill(black) screen.blit(ball, rectball) pygame.display.flip() You will notice that on line 11 the parameters are unfilled. This is because I was going to make it coords + 1.
[ "If I am correct I think it is rect.left or rect.top that gives it. Another method is to create another rectangle and check if the rectangle is in that.\n", "#To move a rect object in Pygame, you can use the move_ip() method. This method takes two arguments, the x and y coordinates to move the rect by. For example, if you want to move the rect one pixel to the right and one pixel down, you can use the following code:\n\nrectball.move_ip(1, 1)\n\n#You can also use the x and y attributes of the rect to move it by a certain amount. For example, if you want to move the rect one pixel to the right, you can use the following code:\n\nrectball.x += 1\n\n#Note that this will only move the rect object and not the image that it represents. To move the image on the screen, you will also need to update the position of the ball surface using the blit() method.\n\n#Here is an updated version of your code that moves the rect and the image on the screen:\n\nimport sys\nimport pygame\n\npygame.init()\n\nsize = width, height = 1920, 1080\nblack = 0, 0, 0\n\nscreen = pygame.display.set_mode(size)\n\nball = pygame.image.load(\"ball.png\")\nrectball = ball.get_rect()\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n # Move the rect one pixel to the right and one pixel down\n rectball.move_ip(1, 1)\n\n # Update the position of the ball on the screen\n screen.blit(ball, rectball)\n\n pygame.display.flip()\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074679565_python.txt
Q: Selecting specific User I am trying to make an app that shows a users past expenses with C# querying a SQL Database. I have a program that shows the user their current expenses. They have to login using a unique username and password. When logged in, they should see only their expenses from the expenses table. I am currently using: Select * from ExpensesTbl Which shows everything, including other users information. I believe I need to use a WHERE clause, but I am unsure what it would look like as Im not sure what user is logged in. In example, table Expenses currently has two users (A and B). Can someone point me to how I can get just the information that pertains to only the logged user, instead of the information of all users? A: The solution for this is using IDs on each user, on ExpensesTbl create a Foreign Key that binds the ID with the information of this user on ExpensesTbl, then just do a SELECT * FROM WHERE ExpensesTbl.user_id = LoggedUser.id Please, take a read at those documents: https://www.w3schools.com/sql/sql_foreignkey.asp https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
Selecting specific User
I am trying to make an app that shows a users past expenses with C# querying a SQL Database. I have a program that shows the user their current expenses. They have to login using a unique username and password. When logged in, they should see only their expenses from the expenses table. I am currently using: Select * from ExpensesTbl Which shows everything, including other users information. I believe I need to use a WHERE clause, but I am unsure what it would look like as Im not sure what user is logged in. In example, table Expenses currently has two users (A and B). Can someone point me to how I can get just the information that pertains to only the logged user, instead of the information of all users?
[ "The solution for this is using IDs on each user, on ExpensesTbl create a Foreign Key that binds the ID with the information of this user on ExpensesTbl, then just do a\nSELECT * FROM WHERE ExpensesTbl.user_id = LoggedUser.id\n\nPlease, take a read at those documents:\nhttps://www.w3schools.com/sql/sql_foreignkey.asp\nhttps://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html\n" ]
[ 0 ]
[]
[]
[ "c#", "mysql", "sql" ]
stackoverflow_0074679554_c#_mysql_sql.txt
Q: Javascript onclick confirm form submit and flask app I want to add a confirmation to a form action: <form action="/delete" method="post"> <button id="deleteForm" class="btn btn-danger" onclick="deleteConfirm(this.form)">Delete</button> </form> And in my script.js I wrote the function: function deleteConfirm() { let text = "Are you sure?\nOk=Delete all data."; if (confirm(text) == true) { document.getElementById("deleteForm").submit(); } else { alert("Cancelled."); } } But with these codes when I click either ok or cancell, the form will submit. when I click cancel the alert show up but then the action /delete will execute. Is this an attribute of flask? Are there another ways to do this? A: prevent the form from being submitted when the user clicks "Cancel", you can add a return false; statement at the end of the deleteConfirm() function let text = "Are you sure?\nOk=Delete all data."; if (confirm(text) == true) { document.getElementById("deleteForm").submit(); } else { alert("Cancelled."); return false; } prevent the form from being submitted when the user clicks "Cancel", but it will still be submitted when they click "OK". EDIT : Wrap inside this one if still not working : function deleteConfirm() { let text = "Are you sure?\nOk=Delete all data."; if (confirm(text) == true) { return true; } else { alert("Cancelled."); return false; } } A: You need to add attribute type="button" to your button, and id "deleteForm" add to form <form id="deleteForm" action="/delete" method="post"> <button type="button" class="btn btn-danger" onclick="deleteConfirm(this.form)">Delete</button> </form> A: No need to use the onclick event of the button. Instead, attach type="submit" with your buttion. And add the onsubmit attribute with your form. This is the standard way of doing what you mentioned. function deleteConfirm(myForm) { let text = "Are you sure?\nOk=Delete all data."; if (confirm(text) == true) { return true; } else { alert("Cancelled."); return false; } } <form action="/delete" method="post" onsubmit="return deleteConfirm(this);"> <button id="deleteForm" type="submit" class="btn btn-danger">Delete</button> </form> A: There are like many ways to approach this question, but what i would do is that instead of having an entire javascript function just to display a on click alert i would just wrap it around a input. <input type="submit" value="Delete" onclick="return confirm('Are you sure you want to delete this data?')"> I have used this for like flask data delete and when the user clicks cancel it does not submit the form. Here is an example of what i just used: https://jsfiddle.net/12f6bvkq/
Javascript onclick confirm form submit and flask app
I want to add a confirmation to a form action: <form action="/delete" method="post"> <button id="deleteForm" class="btn btn-danger" onclick="deleteConfirm(this.form)">Delete</button> </form> And in my script.js I wrote the function: function deleteConfirm() { let text = "Are you sure?\nOk=Delete all data."; if (confirm(text) == true) { document.getElementById("deleteForm").submit(); } else { alert("Cancelled."); } } But with these codes when I click either ok or cancell, the form will submit. when I click cancel the alert show up but then the action /delete will execute. Is this an attribute of flask? Are there another ways to do this?
[ "prevent the form from being submitted when the user clicks \"Cancel\", you can add a return false; statement at the end of the deleteConfirm() function\nlet text = \"Are you sure?\\nOk=Delete all data.\";\nif (confirm(text) == true) {\n document.getElementById(\"deleteForm\").submit();\n} else {\n alert(\"Cancelled.\");\n return false;\n}\n\nprevent the form from being submitted when the user clicks \"Cancel\", but it will still be submitted when they click \"OK\".\nEDIT :\nWrap inside this one if still not working :\nfunction deleteConfirm() {\n\nlet text = \"Are you sure?\\nOk=Delete all data.\";\nif (confirm(text) == true) {\n return true;\n} else {\n alert(\"Cancelled.\");\n return false;\n}\n}\n\n", "You need to add attribute type=\"button\" to your button, and id \"deleteForm\" add to form\n\n\n<form id=\"deleteForm\" action=\"/delete\" method=\"post\">\n <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteConfirm(this.form)\">Delete</button>\n</form>\n\n\n\n", "No need to use the onclick event of the button. Instead, attach type=\"submit\" with your buttion. And add the onsubmit attribute with your form. This is the standard way of doing what you mentioned.\n\n\nfunction deleteConfirm(myForm) {\n let text = \"Are you sure?\\nOk=Delete all data.\";\n if (confirm(text) == true) {\n return true;\n } else {\n alert(\"Cancelled.\");\n return false;\n }\n}\n<form action=\"/delete\" method=\"post\" onsubmit=\"return deleteConfirm(this);\">\n <button id=\"deleteForm\" type=\"submit\" class=\"btn btn-danger\">Delete</button>\n</form>\n\n\n\n", "There are like many ways to approach this question, but what i would do is that instead of having an entire javascript function just to display a on click alert i would just wrap it around a input.\n<input type=\"submit\" value=\"Delete\"\n onclick=\"return confirm('Are you sure you want to delete this data?')\">\n\nI have used this for like flask data delete and when the user clicks cancel it does not submit the form.\nHere is an example of what i just used:\nhttps://jsfiddle.net/12f6bvkq/\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074678636_javascript.txt
Q: How to use symlinks in React Native projet? The symlink support is still not officially available in react-native https://github.com/facebook/metro/issues/1. It's actually possible to use symlinks in the package.json with npm (not yarn) { "name": "PROJECT", "version": "0.1.0", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "jest" }, "dependencies": { "my_module1": "file:../shared/my_module1/", "my_module2": "file:../shared/my_module2/", "react": "16.8.3", "react-native": "0.59.5", }, "devDependencies": { "babel-jest": "24.7.1", "jest": "24.7.1", "metro-react-native-babel-preset": "0.53.1", "react-test-renderer": "16.8.3" }, "jest": { "preset": "react-native" } } Although we will get my_module1 does not exist in the Haste module map To fix this we could do before a metro.config.js (formerly rn-cli.config.js) const path = require("path") const extraNodeModules = { /* to give access to react-native-firebase for a shared module for example */ "react-native-firebase": path.resolve(__dirname, "node_modules/react-native-firebase"), } const watchFolders = [ path.resolve(__dirname, "node_modules/my_module1"), path.resolve(__dirname, "node_modules/my_module2"), ] module.exports = { resolver: { extraNodeModules }, watchFolders, transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: false } }) } } Unfortunately it doesn't work anymore on react-native 0.59 The app is reloading, but changes in the source code are not reflected in the app. Anyone has a clue to achieve this? A: I had a similar issue and found haul. Follow haul getting started instructions. Add your local dependencies with file:../ e.g: // package.json "dependencies": { "name-of-your-local-dependency": "file:../" } reinstall node_modules with yarn --force Start the development server by yarn start (haul will replace your start script) Run react-native run-android or/and react-native run-ios A: None of the answers I found worked for me and it seems symlinks are not going to be supported anytime soon (see: https://github.com/facebook/metro/issues/1), so I had to do it manually. I am using onchange npm package and running that in my local package: onchange 'dist/**/*.js' -- cp -R ./dist ../../app/node_modules/@author/packagename That worked for me to achieve development and testing, while not breaking anything for production releases. I hope this can save my peers a few headaches. A: You can use yalc. Yalc will simulate a package publish without actually publishing it. Install it globally: npm i -g yalc In your local package: yalc publish In the application: yalc add package-name && yarn After you made some changes to the package, you can just run yalc push and it will automatically update every app that uses your local package A: After a few years working on this, we found a reliable way using yarn. Add your local dependencies with are inside a folder file:../CompanyPackages/package e.g: // package.json "dependencies": { "local-package": "file:../CompanyPackages/local-package" } Use a custom metro.config.js const path = require("path") const { mapValues } = require("lodash") // Add there all the Company packages useful to this app const CompanyPackagesRelative = { "CompanyPackages": "../CompanyPackages", } const CompanyPackages = mapValues(CompanyPackagesRelative, (relativePath) => path.resolve(relativePath) ) function createMetroConfiguration(projectPath) { projectPath = path.resolve(projectPath) const watchFolders = [...Object.values(CompanyPackages)] const extraNodeModules = { ...CompanyPackages, } // Should fix error "Unable to resolve module @babel/runtime/helpers/interopRequireDefault" // See https://github.com/facebook/metro/issues/7#issuecomment-508129053 // See https://dushyant37.medium.com/how-to-import-files-from-outside-of-root-directory-with-react-native-metro-bundler-18207a348427 const extraNodeModulesProxy = new Proxy(extraNodeModules, { get: (target, name) => { if (target[name]) { return target[name] } else { return path.join(projectPath, `node_modules/${name}`) } }, }) return { projectRoot: projectPath, watchFolders, resolver: { transform: { experimentalImportSupport: false, inlineRequires: true, }, extraNodeModules: extraNodeModulesProxy, }, } } module.exports = createMetroConfiguration(__dirname) A: Could never get my own environment working using any other suggestions, but found a hack that works well (though not ideal) that can be easily set up in just a few lines of code and without changing your RN project configuration. Use fs.watch for changes recursively in the directory where you're working on your library, and copy the updates over whenever there's been a change: import fs from 'fs' const srcDir = `./your-library-directory` const destDir = `../your-destination-directory` fs.watch("./src/", {recursive: true}, () => { console.log('copying...') fs.cp(srcDir, destDir, { overwrite: true, recursive: true }, function() { console.log('copied') }) })
How to use symlinks in React Native projet?
The symlink support is still not officially available in react-native https://github.com/facebook/metro/issues/1. It's actually possible to use symlinks in the package.json with npm (not yarn) { "name": "PROJECT", "version": "0.1.0", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "jest" }, "dependencies": { "my_module1": "file:../shared/my_module1/", "my_module2": "file:../shared/my_module2/", "react": "16.8.3", "react-native": "0.59.5", }, "devDependencies": { "babel-jest": "24.7.1", "jest": "24.7.1", "metro-react-native-babel-preset": "0.53.1", "react-test-renderer": "16.8.3" }, "jest": { "preset": "react-native" } } Although we will get my_module1 does not exist in the Haste module map To fix this we could do before a metro.config.js (formerly rn-cli.config.js) const path = require("path") const extraNodeModules = { /* to give access to react-native-firebase for a shared module for example */ "react-native-firebase": path.resolve(__dirname, "node_modules/react-native-firebase"), } const watchFolders = [ path.resolve(__dirname, "node_modules/my_module1"), path.resolve(__dirname, "node_modules/my_module2"), ] module.exports = { resolver: { extraNodeModules }, watchFolders, transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: false } }) } } Unfortunately it doesn't work anymore on react-native 0.59 The app is reloading, but changes in the source code are not reflected in the app. Anyone has a clue to achieve this?
[ "I had a similar issue and found haul. \n\nFollow haul getting started instructions. \nAdd your local dependencies with file:../ e.g:\n\n// package.json\n\"dependencies\": {\n \"name-of-your-local-dependency\": \"file:../\"\n}\n\n\nreinstall node_modules with yarn --force\nStart the development server by yarn start (haul will replace your start script)\nRun react-native run-android or/and react-native run-ios\n\n", "None of the answers I found worked for me and it seems symlinks are not going to be supported anytime soon (see: https://github.com/facebook/metro/issues/1), so I had to do it manually.\nI am using onchange npm package and running that in my local package: onchange 'dist/**/*.js' -- cp -R ./dist ../../app/node_modules/@author/packagename\nThat worked for me to achieve development and testing, while not breaking anything for production releases. I hope this can save my peers a few headaches.\n", "You can use yalc. Yalc will simulate a package publish without actually publishing it.\nInstall it globally:\nnpm i -g yalc\nIn your local package:\nyalc publish\nIn the application:\nyalc add package-name && yarn\nAfter you made some changes to the package, you can just run\nyalc push\nand it will automatically update every app that uses your local package\n", "After a few years working on this, we found a reliable way using yarn.\nAdd your local dependencies with are inside a folder file:../CompanyPackages/package e.g:\n// package.json\n\"dependencies\": {\n \"local-package\": \"file:../CompanyPackages/local-package\"\n}\n\nUse a custom metro.config.js\nconst path = require(\"path\")\nconst { mapValues } = require(\"lodash\")\n\n// Add there all the Company packages useful to this app\nconst CompanyPackagesRelative = {\n \"CompanyPackages\": \"../CompanyPackages\",\n}\n\nconst CompanyPackages = mapValues(CompanyPackagesRelative, (relativePath) =>\n path.resolve(relativePath)\n)\n\nfunction createMetroConfiguration(projectPath) {\n projectPath = path.resolve(projectPath)\n\n const watchFolders = [...Object.values(CompanyPackages)]\n const extraNodeModules = {\n ...CompanyPackages,\n }\n\n // Should fix error \"Unable to resolve module @babel/runtime/helpers/interopRequireDefault\"\n // See https://github.com/facebook/metro/issues/7#issuecomment-508129053\n // See https://dushyant37.medium.com/how-to-import-files-from-outside-of-root-directory-with-react-native-metro-bundler-18207a348427\n const extraNodeModulesProxy = new Proxy(extraNodeModules, {\n get: (target, name) => {\n if (target[name]) {\n return target[name]\n } else {\n return path.join(projectPath, `node_modules/${name}`)\n }\n },\n })\n\n return {\n projectRoot: projectPath,\n watchFolders,\n resolver: {\n transform: {\n experimentalImportSupport: false,\n inlineRequires: true,\n },\n extraNodeModules: extraNodeModulesProxy,\n },\n }\n}\n\nmodule.exports = createMetroConfiguration(__dirname)\n\n", "Could never get my own environment working using any other suggestions, but found a hack that works well (though not ideal) that can be easily set up in just a few lines of code and without changing your RN project configuration.\nUse fs.watch for changes recursively in the directory where you're working on your library, and copy the updates over whenever there's been a change:\nimport fs from 'fs'\n\nconst srcDir = `./your-library-directory`\nconst destDir = `../your-destination-directory`\n\nfs.watch(\"./src/\", {recursive: true}, () => {\n console.log('copying...')\n fs.cp(srcDir, destDir, { overwrite: true, recursive: true }, function() {\n console.log('copied')\n })\n})\n\n" ]
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "npm", "react_native", "symlink" ]
stackoverflow_0055953564_npm_react_native_symlink.txt
Q: Insert the generated sequence into the Redshift table I ran into a problem with Redshift. I'm generating a sequence of dates and want to embed it in a table to work with the range. But Redshift only supports generation on the leader node. It is not possible to insert the data on the nodes. Nowhere in the documentation have I found information on how to insert the generated sequences into tables. Maybe someone has encountered such a problem and can share their experience in solving it? My sequence: SELECT date '2019-12-31' + INTERVAL AS date_range FROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL; My query: CREATE TABLE public.date_sequence AS ( SELECT date '2019-12-31' + INTERVAL AS date_range FROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL ); I also tried inserting data from cte. Insert data into a temporary table. The result is the same: ERROR: Specified types or functions (one per INFO message) not supported on Redshift tables. A: In amazon redshift you cant populate a table with data with create table you have to use a insert as far as I know, my suggestion would be something like this INSERT INTO public.date_sequence SELECT date '2019-12-31' + INTERVAL AS date_range FROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL; A: Generate_series() is an unsupported function on Redshift. While it will still work on the leader node it is not a good idea to base your solutions on such functions. The better and supported approach is to use a recursive CTE - see https://docs.aws.amazon.com/redshift/latest/dg/r_WITH_clause.html I wrote up an example for making a series of dates in this answer - trying to create a date table in Redshift
Insert the generated sequence into the Redshift table
I ran into a problem with Redshift. I'm generating a sequence of dates and want to embed it in a table to work with the range. But Redshift only supports generation on the leader node. It is not possible to insert the data on the nodes. Nowhere in the documentation have I found information on how to insert the generated sequences into tables. Maybe someone has encountered such a problem and can share their experience in solving it? My sequence: SELECT date '2019-12-31' + INTERVAL AS date_range FROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL; My query: CREATE TABLE public.date_sequence AS ( SELECT date '2019-12-31' + INTERVAL AS date_range FROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL ); I also tried inserting data from cte. Insert data into a temporary table. The result is the same: ERROR: Specified types or functions (one per INFO message) not supported on Redshift tables.
[ "In amazon redshift you cant populate a table with data with create table you have to use a insert as far as I know, my suggestion would be something like this\nINSERT INTO public.date_sequence\nSELECT date '2019-12-31' + INTERVAL AS date_range\nFROM generate_series(1, (date '2041-01-01' - date '2020-01-01')) INTERVAL;\n\n", "Generate_series() is an unsupported function on Redshift. While it will still work on the leader node it is not a good idea to base your solutions on such functions.\nThe better and supported approach is to use a recursive CTE - see https://docs.aws.amazon.com/redshift/latest/dg/r_WITH_clause.html\nI wrote up an example for making a series of dates in this answer - trying to create a date table in Redshift\n" ]
[ 1, 0 ]
[]
[]
[ "amazon_redshift", "sql" ]
stackoverflow_0074674898_amazon_redshift_sql.txt
Q: Is there a method to retrieve first empty row in a Google spreadsheet with API? I'm trying to retrieve the first empty row in a Google spreadsheet. I'm aware of the SpreadsheetApp class, however I'm using Google sheet's API (Rust). Is it possible to use something similar to getLastRow() with Spreadsheet API? A: Yes, you can use the Spreadsheet API to retrieve the first empty row in a Google Sheets spreadsheet. The API provides a getLastRow() method that returns the index of the last row that has content. You can then use this value to find the first empty row by incrementing the last row index by one. Here is an example of how to do this using the Rust library for the Google Sheets API: use google_sheets4::{spreadsheets::{GetSpreadsheetByDataFilterRequest, Sheets}, Range}; // Authenticate with the Google Sheets API and get a client instance let client = Sheets::new(...); // Set the ID of the spreadsheet to retrieve let spreadsheet_id = "spreadsheet_id"; // Set the range of the data to retrieve let range = Range { sheet_id: 0, start_row_index: 0, end_row_index: 0, start_column_index: 0, end_column_index: 0, }; // Create a request to retrieve the data from the specified range let req = GetSpreadsheetByDataFilterRequest { spreadsheet_id: spreadsheet_id.to_string(), ranges: vec![range], ..Default::default() }; // Send the request and retrieve the response let res = client.spreadsheets().get_by_data_filter(req).doit().
Is there a method to retrieve first empty row in a Google spreadsheet with API?
I'm trying to retrieve the first empty row in a Google spreadsheet. I'm aware of the SpreadsheetApp class, however I'm using Google sheet's API (Rust). Is it possible to use something similar to getLastRow() with Spreadsheet API?
[ "Yes, you can use the Spreadsheet API to retrieve the first empty row in a Google Sheets spreadsheet. The API provides a getLastRow() method that returns the index of the last row that has content. You can then use this value to find the first empty row by incrementing the last row index by one. Here is an example of how to do this using the Rust library for the Google Sheets API:\nuse google_sheets4::{spreadsheets::{GetSpreadsheetByDataFilterRequest, Sheets},\n Range};\n\n// Authenticate with the Google Sheets API and get a client instance\nlet client = Sheets::new(...);\n\n// Set the ID of the spreadsheet to retrieve\nlet spreadsheet_id = \"spreadsheet_id\";\n\n// Set the range of the data to retrieve\nlet range = Range {\n sheet_id: 0,\n start_row_index: 0,\n end_row_index: 0,\n start_column_index: 0,\n end_column_index: 0,\n};\n\n// Create a request to retrieve the data from the specified range\nlet req = GetSpreadsheetByDataFilterRequest {\n spreadsheet_id: spreadsheet_id.to_string(),\n ranges: vec![range],\n ..Default::default()\n};\n\n// Send the request and retrieve the response\nlet res = client.spreadsheets().get_by_data_filter(req).doit().\n\n" ]
[ 0 ]
[]
[]
[ "google_sheets_api" ]
stackoverflow_0074679614_google_sheets_api.txt
Q: How to embed RRULE JS Library in VMWare VRO task I'm trying to create a custom action in VMWare VRO which uses JS for its scripting logic. I'm trying to embed two libraries into a single code block so I can use them. Unfortunately, VRO doesn't use includes or the concept of libraries per se so it all has to be in the same giant script block. I'd like to use this RRULE JS library: https://github.com/conrad-vanl/rrule Which I can embed in one code block no problem. But it's dependent on the underscore library. https://github.com/jashkenas/underscore Which I can't seem to get to embed without throwing the following error: TypeError: Cannot read property "n" from undefined (unnamed script#2293) Which I'm guessing has something to do with the way the underscore library is formatted. Here is a gist with my current attempt at embedding both. https://gist.github.com/rsaturns/aceceabb87fc28879ffdb214425a2a15 If I can get both the RRULE and Underscore libraries to be embedded in the same file I think I will be able to get this working. A: VRO doesn't use a regular JavaScript engine such as the ones that run in the browser or server side Node.js . It uses the Rhino engine, which is based on Java, and as such it has a lot of quirky differences with regular JavaScript. There are quite a few differences in syntax and behavior compared to regular JS, so it can be expected that a lot of things that you think should work, will not work inside VRO. Some of the limitations that VRO js has: JS feature basically stop at ES5, but some features of ES5 aren't even implemented. Not all of the API is available inside VRO, and some objects, methods or functions have been replaced with an equivalent (Console.log is equivalent to System.log in VRO) You can't normally use external JS libraries such as axios, jQuery, lodash, etc... (you can try to get around this limitation a number of ways, which I'll explain) If you want to use an external library inside VRO, there are a few things to consider, but these are the most important: The JS version that the library is/depends on. The APIs and JS features that the library depends on. If your library is based on pre-ES5 JavaScript and does not use any special, browser-specific or node.js specific APIs, it should work out of the box inside VRO. If not, then you can try a few things to try to get it to work inside VRO: Use a transpiler (and bundler if you need) (such as Babel+Webpack, SWC, Esbuild, to name just a few) to downgrade the source code of the library you want to use into an older version of JS into a single JS file. You might need to use polyfills if you use some browser or Node.js APIs because they will not work inside VRO even when transpiled and downgraded. Put the resulting JS code into the same VRO workflow/action that you want to use it in and use it directly (I don't recommend this, as it can become a mess quite fast and is unreadable) Put the resulting JS code into a VRO resource element, then inside your VRO workflow/action , get the content of this resource element (it will be a string at this point) and use the eval() or the Function constructor to parse and evaluate the library code. It will then be available to use inside the rest of the workflow/action. (I recommend this method, since it is the least error prone, takes 1-3 lines of code only and is more readable) You could do the same thing, but additionnaly split the library code into as many smaller working modules/objects/functions as you want to have better performance and potentially work around VRO's limitations when working with huge files. This is what worked for me in general, but I can't guarantee that it will work in all cases. Because of the bizarre nature of the Rhino engine and limitations of VRO, you could run into other problems or limitations and won't be able to use the JS library that you want to use. For example, if your library code is too big, VRO will not be able to use it as it will run out of memory, or the workflow/action will crash, or it will just stop evaluating the library code midway and be useless. There are 2 other ways to use external libraries inside VRO workflows/actions, but they don't use the normal VRO engine. Just keep in mind that using this way, you cannot directly access all of the VRO APIs such as resource elements, plugins ,etc. So it has some limitations : Use the Node.js runtime of VRO instead of the default one (Rhino) to code your workflow/actions. You can use external and regular Node.js libraries such as lodash this way, without needing to transpile or bundle or downgrade it. (This is the best way to use external libraries, as they should work as you would expect normally in JS). There are 2 ways to do this and the documentation is quite useful in explaining in more details : https://docs.vmware.com/en/vRealize-Orchestrator/8.10/com.vmware.vrealize.orchestrator-using-client-guide.doc/GUID-13E3704E-A325-4CB1-AF57-45FEBDBBD159.html You can code a microservice or something that uses all the JS libraries you would need and expose them as a REST api in some server hosted somewhere, then call these endpoints from your VRO workflow/action.(This requires the most effort and is not really recommended for simple scripting) I hope this will help people that need to do something like this in the future, as it took me quite a while of trial and error to get to this point.
How to embed RRULE JS Library in VMWare VRO task
I'm trying to create a custom action in VMWare VRO which uses JS for its scripting logic. I'm trying to embed two libraries into a single code block so I can use them. Unfortunately, VRO doesn't use includes or the concept of libraries per se so it all has to be in the same giant script block. I'd like to use this RRULE JS library: https://github.com/conrad-vanl/rrule Which I can embed in one code block no problem. But it's dependent on the underscore library. https://github.com/jashkenas/underscore Which I can't seem to get to embed without throwing the following error: TypeError: Cannot read property "n" from undefined (unnamed script#2293) Which I'm guessing has something to do with the way the underscore library is formatted. Here is a gist with my current attempt at embedding both. https://gist.github.com/rsaturns/aceceabb87fc28879ffdb214425a2a15 If I can get both the RRULE and Underscore libraries to be embedded in the same file I think I will be able to get this working.
[ "VRO doesn't use a regular JavaScript engine such as the ones that run in the browser or server side Node.js . It uses the Rhino engine, which is based on Java, and as such it has a lot of quirky differences with regular JavaScript.\nThere are quite a few differences in syntax and behavior compared to regular JS, so it can be expected that a lot of things that you think should work, will not work inside VRO.\nSome of the limitations that VRO js has:\n\nJS feature basically stop at ES5, but some features of ES5 aren't even implemented.\nNot all of the API is available inside VRO, and some objects, methods or functions have been replaced with an equivalent (Console.log is equivalent to System.log in VRO)\nYou can't normally use external JS libraries such as axios, jQuery, lodash, etc... (you can try to get around this limitation a number of ways, which I'll explain)\n\nIf you want to use an external library inside VRO, there are a few things to consider, but these are the most important:\n\nThe JS version that the library is/depends on.\nThe APIs and JS features that the library depends on.\n\nIf your library is based on pre-ES5 JavaScript and does not use any special, browser-specific or node.js specific APIs, it should work out of the box inside VRO.\nIf not, then you can try a few things to try to get it to work inside VRO:\n\nUse a transpiler (and bundler if you need) (such as Babel+Webpack, SWC, Esbuild, to name just a few) to downgrade the source code of the library you want to use into an older version of JS into a single JS file.\nYou might need to use polyfills if you use some browser or Node.js APIs because they will not work inside VRO even when transpiled and downgraded.\nPut the resulting JS code into the same VRO workflow/action that you want to use it in and use it directly (I don't recommend this, as it can become a mess quite fast and is unreadable)\nPut the resulting JS code into a VRO resource element, then inside your VRO workflow/action , get the content of this resource element (it will be a string at this point) and use the eval() or the Function constructor to parse and evaluate the library code. It will then be available to use inside the rest of the workflow/action. (I recommend this method, since it is the least error prone, takes 1-3 lines of code only and is more readable)\nYou could do the same thing, but additionnaly split the library code into as many smaller working modules/objects/functions as you want to have better performance and potentially work around VRO's limitations when working with huge files.\n\nThis is what worked for me in general, but I can't guarantee that it will work in all cases. Because of the bizarre nature of the Rhino engine and limitations of VRO, you could run into other problems or limitations and won't be able to use the JS library that you want to use. For example, if your library code is too big, VRO will not be able to use it as it will run out of memory, or the workflow/action will crash, or it will just stop evaluating the library code midway and be useless.\nThere are 2 other ways to use external libraries inside VRO workflows/actions, but they don't use the normal VRO engine.\nJust keep in mind that using this way, you cannot directly access all of the VRO APIs such as resource elements, plugins ,etc. So it has some limitations :\n\nUse the Node.js runtime of VRO instead of the default one (Rhino) to code your workflow/actions. You can use external and regular Node.js libraries such as lodash this way, without needing to transpile or bundle or downgrade it. (This is the best way to use external libraries, as they should work as you would expect normally in JS). There are 2 ways to do this and the documentation is quite useful in explaining in more details : https://docs.vmware.com/en/vRealize-Orchestrator/8.10/com.vmware.vrealize.orchestrator-using-client-guide.doc/GUID-13E3704E-A325-4CB1-AF57-45FEBDBBD159.html\nYou can code a microservice or something that uses all the JS libraries you would need and expose them as a REST api in some server hosted somewhere, then call these endpoints from your VRO workflow/action.(This requires the most effort and is not really recommended for simple scripting)\n\nI hope this will help people that need to do something like this in the future, as it took me quite a while of trial and error to get to this point.\n" ]
[ 0 ]
[]
[]
[ "javascript", "rrule", "underscore.js" ]
stackoverflow_0056008225_javascript_rrule_underscore.js.txt
Q: How to catch keydown event inside child component There is a component that catches keyDown event. It has a counter which is incremented by Arrow Right and decremented by Arrow Left. export default function App() { const [position, setPosition] = React.useState(0); // eslint-disable-next-line consistent-return React.useEffect(() => { const keyboardHandler = (event) => { const key = parseInt(event.keyCode || event.which || 0, 10); switch (key) { case LEFT_ARROW: setPosition((p) => p - 1); break; case RIGHT_ARROW: setPosition((p) => p + 1); break; default: break; } }; window.document.addEventListener("keydown", keyboardHandler); return () => { window.document.removeEventListener("keydown", keyboardHandler); }; }, []); return ( <div className="App"> {position} <br /> <Inner /> </div> ); } It works fine. Now, there is a child component that has an input field. I would like it to catch arrow left and arrow right so it IS NOT propagated to the main component. My guess was: export default function Inner() { React.useEffect(() => { const keyboardHandler = (event) => { const key = parseInt(event.keyCode || event.which || 0, 10); switch (key) { case LEFT_ARROW: event.stopPropagation(); break; case RIGHT_ARROW: event.stopPropagation(); break; default: break; } }; window.document.addEventListener("keydown", keyboardHandler); return () => { window.document.removeEventListener("keydown", keyboardHandler); }; }, []); return <input name="test" />; } But it does not seem to work. The child receives the event AND the parent receives the event as well. I guess the problem is that the event handler is linked to the window.document, but how do I change it? Here is the codesandbox example: https://codesandbox.io/s/bold-pare-fvd305 Thank you in advance! A: You can ignore the keyDown if it was made inside the input field. You just need to check event.target: import "./styles.css"; import React from "react"; const LEFT_ARROW = 37; const RIGHT_ARROW = 39; export default function App() { const [position, setPosition] = React.useState(0); // eslint-disable-next-line consistent-return React.useEffect(() => { const keyboardHandler = (event) => { const key = parseInt(event.keyCode || event.which || 0, 10); if (event.target.name !== "test"){ switch (key) { case LEFT_ARROW: setPosition((p) => p - 1); break; case RIGHT_ARROW: setPosition((p) => p + 1); break; default: break; } }; } window.document.addEventListener("keydown", keyboardHandler); return () => { window.document.removeEventListener("keydown", keyboardHandler); }; }, []); return ( <div className="App"> {position} <br /> <input name="test" /> </div> ); }
How to catch keydown event inside child component
There is a component that catches keyDown event. It has a counter which is incremented by Arrow Right and decremented by Arrow Left. export default function App() { const [position, setPosition] = React.useState(0); // eslint-disable-next-line consistent-return React.useEffect(() => { const keyboardHandler = (event) => { const key = parseInt(event.keyCode || event.which || 0, 10); switch (key) { case LEFT_ARROW: setPosition((p) => p - 1); break; case RIGHT_ARROW: setPosition((p) => p + 1); break; default: break; } }; window.document.addEventListener("keydown", keyboardHandler); return () => { window.document.removeEventListener("keydown", keyboardHandler); }; }, []); return ( <div className="App"> {position} <br /> <Inner /> </div> ); } It works fine. Now, there is a child component that has an input field. I would like it to catch arrow left and arrow right so it IS NOT propagated to the main component. My guess was: export default function Inner() { React.useEffect(() => { const keyboardHandler = (event) => { const key = parseInt(event.keyCode || event.which || 0, 10); switch (key) { case LEFT_ARROW: event.stopPropagation(); break; case RIGHT_ARROW: event.stopPropagation(); break; default: break; } }; window.document.addEventListener("keydown", keyboardHandler); return () => { window.document.removeEventListener("keydown", keyboardHandler); }; }, []); return <input name="test" />; } But it does not seem to work. The child receives the event AND the parent receives the event as well. I guess the problem is that the event handler is linked to the window.document, but how do I change it? Here is the codesandbox example: https://codesandbox.io/s/bold-pare-fvd305 Thank you in advance!
[ "You can ignore the keyDown if it was made inside the input field. You just need to check event.target:\nimport \"./styles.css\";\nimport React from \"react\";\n\n\nconst LEFT_ARROW = 37;\nconst RIGHT_ARROW = 39;\n\nexport default function App() {\n const [position, setPosition] = React.useState(0);\n\n // eslint-disable-next-line consistent-return\n React.useEffect(() => {\n const keyboardHandler = (event) => {\n const key = parseInt(event.keyCode || event.which || 0, 10);\n if (event.target.name !== \"test\"){\n switch (key) {\n case LEFT_ARROW:\n setPosition((p) => p - 1);\n break;\n case RIGHT_ARROW:\n setPosition((p) => p + 1);\n break;\n default:\n break;\n }\n };\n }\n window.document.addEventListener(\"keydown\", keyboardHandler);\n return () => {\n window.document.removeEventListener(\"keydown\", keyboardHandler);\n };\n }, []);\n\n return (\n <div className=\"App\">\n {position}\n <br />\n <input name=\"test\" />\n </div>\n );\n}\n\n" ]
[ 0 ]
[]
[]
[ "event_handling", "events", "javascript", "keydown", "reactjs" ]
stackoverflow_0074678321_event_handling_events_javascript_keydown_reactjs.txt
Q: How to Disable and Enable WordPress Scrolling Using JS by Timer I have a question regarding Javascript Scrolling. How do I disable scrolling after visitors enter our website, then scrolling is active again 5-10 seconds later like the berakal.com site? I have got the JS on the website, but it is encrypted which is very difficult for me to decode. A: To disable scrolling on a website, you can use the overflow: hidden CSS property on the <body> element of the page. This will prevent the user from scrolling the page using their mouse or trackpad. To enable scrolling again after a certain amount of time, you can use a JavaScript timer to set a delay before removing the overflow: hidden property from the <body> element. Here is an example of how you might implement this: // Set the overflow property on the body element to prevent scrolling document.body.style.overflow = "hidden"; // Use a timer to enable scrolling after 5 seconds setTimeout(function() { document.body.style.overflow = "auto"; }, 5000); // 5000 milliseconds = 5 seconds This will disable scrolling on the page when the user first enters the website, then re-enable scrolling after 5 seconds. You can adjust the time delay to suit your needs.
How to Disable and Enable WordPress Scrolling Using JS by Timer
I have a question regarding Javascript Scrolling. How do I disable scrolling after visitors enter our website, then scrolling is active again 5-10 seconds later like the berakal.com site? I have got the JS on the website, but it is encrypted which is very difficult for me to decode.
[ "To disable scrolling on a website, you can use the overflow: hidden CSS property on the <body> element of the page. This will prevent the user from scrolling the page using their mouse or trackpad.\nTo enable scrolling again after a certain amount of time, you can use a JavaScript timer to set a delay before removing the overflow: hidden property from the <body> element.\nHere is an example of how you might implement this:\n// Set the overflow property on the body element to prevent scrolling\ndocument.body.style.overflow = \"hidden\";\n\n// Use a timer to enable scrolling after 5 seconds\nsetTimeout(function() {\n document.body.style.overflow = \"auto\";\n}, 5000); // 5000 milliseconds = 5 seconds\n\nThis will disable scrolling on the page when the user first enters the website, then re-enable scrolling after 5 seconds. You can adjust the time delay to suit your needs.\n" ]
[ 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074679200_javascript.txt
Q: React Native: npm link local dependency, unable to resolve module I am developing a button ui package for react native. I try to build an example project to test this button. The directory structure is as follows: my-button/ package.json index.js example/ package.json index.js I try to use npm link: cd my-button npm link cd example npm link my-button In example/node_modules/ I can see my-button symlink, VSCode also can auto complete function in my-button package. But execute example app will show error: Unable to resolve module my-button ... Module does not exist in the module map or in these directories: ... But the path in the error message is correct. Don't know where I was wrong, or in React-Native have any special way to deal with link local dependency? I also tried npm install file:../.. It works fine in this way, but not easy to update dependency in example/ after I edited my-button. A: The npm link command doesn't work because React Native packager doesn't support symlinks. After a little research, I discovered that there are two ways to go about it. Use haul packager in the example app. Haul supports symlinks, so you can use npm link as usual. Use local dependency via file:../ and then edit files in node_modules folder or reinstall every time you make changes. I found Haul to work great for this use-case and even set-up a little starter project that also includes storybook, which is really helpful if you have many components to switch between. A: Try wml (https://github.com/wix/wml) It's an alternative to npm link that actually copies changed files from source to destination folders # add the link to wml using `wml add <src> <dest>` wml add ~/my-package ~/main-project/node_modules/my-package # start watching all links added wml start A: I couldn't always make it work with yarn link. What i found extra useful is yalc: First install it globally once forever: npm install -g yalc In the local library/package (i'll call it my-local-package), and run: yalc publish Then in your project which uses my-local-package as a dependency, run: (if you already have added it with any other way, first uninstall it (npm uninstall -S my-lockal-package) yalc add my-local-package npm install If my-local-package is a native module, then run react-native run-android to link the dependency. (or run-ios) If you make any change in the my-lockal-package, then: cd path/of/my-local-package yalc push //updates the local package cd path/to/my-project npm install react-native run-android (or run-ios) In case the update hasn't been applied, try to cd android && ./gradlew clean && cd .. and then rerun: react-native run-android. A: I'm having the same issue while developing a native module wrapper around an existing native SDK. At first I followed @aayush-shrestha's suggestion to install the package locally. Like this: npm install ../<package-folder> --save This works as long as I reference the module via NativeModules. Import it: import { NativeModules } from 'react-native'; And then access a module called ActualModuleName like this: NativeModules.ActualModuleName But it fails when I attempt to import the module by name: import { ActualModuleName } from 'react-native-actualmodulename' To make that work I had to first pack the package. Run this in the package's root directory: npm pack This generates a gzipped tarball: react-native-actualmodulename-1.0.0.tgz Now install that in your app: npm install <path/to>/react-native-actualmodulename-1.0.0.tgz An enormous downside to this is that you have to re-pack the package every time you make a change to the module. The only workaround I know of is to modify the package's files in node_modules directly and then copy those changes back to your repo when you're done. But the upside is that your app's source can import ActualModuleName the same way you'll import it once it's released via npm; no environment-specific code necessary. A: Ran into the same problem. While I could not make npm link work as it should, I worked around it by installing the local package in the project folder npm install ../<package-folder> --save This will install the package like a regular package but from the local folder. The downside is that the changes you make on the package will not be reflected. You will have to npm install after every change. A: You can use npm link using Metro. Just add the source folder of the linked package to watchFolders in your metro.config.js. A: Change your package.json //... "dependencies": { //... "my-button" : "file:../" }, //... A: I also came across this problem. After visiting the below link, I came to know that react- native does not support symlinks.[Click here][1] However, I have solved this by adding these lines in the metro.config.js file. Please replace your_module_name with your module name. const path = require('path'); const thirdPartyPath = path.resolve(__dirname + '/../your_module_name/'); // Path of your local module const thirdParty= { 'your_module_name': thirdPartyPath, }; const watchFolders = [ thirdPartyPath]; module.exports = { // existing dependencies resolver: { thirdParty, }, watchFolders }; A: I ran into the same problem. I tried to install a local module using npm, and kept running into the issue of not being able to resolve the module, even though I could see the folder in node_modules and autocomplete of class and method names worked. I was able to bypass it by installing the local library using yarn instead of npm after seeing this open issue on github. Issue was opened September 2020 and no comment from Facebook as of yet. A: This work for me: step 1 go to package: npm link packageNameHere This will link this package to global node_module step 2 go to directory which you want to use this package and run these npm link pathToPackageDirectory npm install pathToPackageDirectory ex: npm link ~/myDemoPackage This will link global node_moudle to this project If you want to import package to file, USE FILE PATH INSTEAD OF PACKAGE NAME ! ex: my package name is stripe-api-helper. my code are in src/index.ts then I need to resolve like this: import { postStripe, Item } from '@aliciaForDemo/stripe-api-helper/src' if u use '@aliciaForDemo/stripe-api-helper' it will fail. A: Could never get my own environment working using any other suggestions, but found a hack that works well (though not ideal) that can be easily set up in just a few lines of code and without changing your RN project configuration. Use fs.watch for changes recursively in the directory where you're working on your library, and copy the updates over whenever there's been a change: import fs from 'fs' const srcDir = `./your-library-directory` const destDir = `../your-destination-directory` fs.watch("./src/", {recursive: true}, () => { console.log('copying...') fs.cp(srcDir, destDir, { overwrite: true, recursive: true }, function() { console.log('copied') }) })
React Native: npm link local dependency, unable to resolve module
I am developing a button ui package for react native. I try to build an example project to test this button. The directory structure is as follows: my-button/ package.json index.js example/ package.json index.js I try to use npm link: cd my-button npm link cd example npm link my-button In example/node_modules/ I can see my-button symlink, VSCode also can auto complete function in my-button package. But execute example app will show error: Unable to resolve module my-button ... Module does not exist in the module map or in these directories: ... But the path in the error message is correct. Don't know where I was wrong, or in React-Native have any special way to deal with link local dependency? I also tried npm install file:../.. It works fine in this way, but not easy to update dependency in example/ after I edited my-button.
[ "The npm link command doesn't work because React Native packager doesn't support symlinks.\nAfter a little research, I discovered that there are two ways to go about it.\n\nUse haul packager in the example app. Haul supports symlinks, so you can use npm link as usual.\nUse local dependency via file:../ and then edit files in node_modules folder or reinstall every time you make changes.\n\nI found Haul to work great for this use-case and even set-up a little starter project that also includes storybook, which is really helpful if you have many components to switch between.\n", "Try wml (https://github.com/wix/wml)\nIt's an alternative to npm link that actually copies changed files from source to destination folders\n# add the link to wml using `wml add <src> <dest>`\nwml add ~/my-package ~/main-project/node_modules/my-package\n\n# start watching all links added\nwml start\n\n", "I couldn't always make it work with yarn link. What i found extra useful is yalc:\nFirst install it globally once forever:\nnpm install -g yalc\n\nIn the local library/package (i'll call it my-local-package), and run:\nyalc publish\n\nThen in your project which uses my-local-package as a dependency, run:\n(if you already have added it with any other way, first uninstall it (npm uninstall -S my-lockal-package)\nyalc add my-local-package\nnpm install\n\nIf my-local-package is a native module, then run react-native run-android to link the dependency. (or run-ios)\nIf you make any change in the my-lockal-package, then:\ncd path/of/my-local-package\nyalc push //updates the local package\ncd path/to/my-project\nnpm install\nreact-native run-android (or run-ios)\n\nIn case the update hasn't been applied, try to cd android && ./gradlew clean && cd .. and then rerun: react-native run-android. \n", "I'm having the same issue while developing a native module wrapper around an existing native SDK. At first I followed @aayush-shrestha's suggestion to install the package locally. Like this:\nnpm install ../<package-folder> --save\n\nThis works as long as I reference the module via NativeModules. Import it:\nimport { NativeModules } from 'react-native';\n\nAnd then access a module called ActualModuleName like this:\nNativeModules.ActualModuleName\n\nBut it fails when I attempt to import the module by name:\nimport { ActualModuleName } from 'react-native-actualmodulename'\n\nTo make that work I had to first pack the package. Run this in the package's root directory:\nnpm pack\n\nThis generates a gzipped tarball:\nreact-native-actualmodulename-1.0.0.tgz\n\nNow install that in your app:\nnpm install <path/to>/react-native-actualmodulename-1.0.0.tgz\n\nAn enormous downside to this is that you have to re-pack the package every time you make a change to the module. The only workaround I know of is to modify the package's files in node_modules directly and then copy those changes back to your repo when you're done.\nBut the upside is that your app's source can import ActualModuleName the same way you'll import it once it's released via npm; no environment-specific code necessary.\n", "Ran into the same problem. While I could not make npm link work as it should, I worked around it by installing the local package in the project folder\nnpm install ../<package-folder> --save\n\nThis will install the package like a regular package but from the local folder. \nThe downside is that the changes you make on the package will not be reflected. You will have to npm install after every change.\n", "You can use npm link using Metro. Just add the source folder of the linked package to watchFolders in your metro.config.js.\n", "Change your package.json\n//...\n\"dependencies\": {\n //...\n \"my-button\" : \"file:../\"\n },\n//...\n\n", "I also came across this problem. After visiting the below link, I came to know that react- native does not support symlinks.[Click here][1]\nHowever, I have solved this by adding these lines in the metro.config.js file. Please replace your_module_name with your module name.\nconst path = require('path');\n\nconst thirdPartyPath = path.resolve(__dirname + '/../your_module_name/'); // Path of your local module\n\nconst thirdParty= {\n 'your_module_name': thirdPartyPath,\n };\n\nconst watchFolders = [ thirdPartyPath];\n\nmodule.exports = {\n// existing dependencies\nresolver: {\n thirdParty,\n },\n watchFolders\n};\n\n", "I ran into the same problem.\nI tried to install a local module using npm, and kept running into the issue of not being able to resolve the module, even though I could see the folder in node_modules and autocomplete of class and method names worked.\nI was able to bypass it by installing the local library using yarn instead of npm after seeing this open issue on github. Issue was opened September 2020 and no comment from Facebook as of yet.\n", "This work for me:\nstep 1 go to package:\nnpm link packageNameHere\n\nThis will link this package to global node_module\nstep 2 go to directory which you want to use this package and run these\nnpm link pathToPackageDirectory\nnpm install pathToPackageDirectory\n\nex: npm link ~/myDemoPackage\nThis will link global node_moudle to this project\nIf you want to import package to file, USE FILE PATH INSTEAD OF PACKAGE NAME !\nex:\nmy package name is stripe-api-helper. my code are in src/index.ts\nthen I need to resolve like this:\nimport { postStripe, Item } from '@aliciaForDemo/stripe-api-helper/src'\n\nif u use '@aliciaForDemo/stripe-api-helper' it will fail.\n", "Could never get my own environment working using any other suggestions, but found a hack that works well (though not ideal) that can be easily set up in just a few lines of code and without changing your RN project configuration.\nUse fs.watch for changes recursively in the directory where you're working on your library, and copy the updates over whenever there's been a change:\nimport fs from 'fs'\n\nconst srcDir = `./your-library-directory`\nconst destDir = `../your-destination-directory`\n\nfs.watch(\"./src/\", {recursive: true}, () => {\n console.log('copying...')\n fs.cp(srcDir, destDir, { overwrite: true, recursive: true }, function() {\n console.log('copied')\n })\n})\n\n" ]
[ 72, 52, 17, 9, 4, 4, 2, 1, 0, 0, 0 ]
[ "For those still looking for a simple solution without other dependency, try this:\nyarn --version\n1.21.1\n\nnpm --version\n6.13.4\n\n\nInstall in project root\n\ncd my-button\nyarn install or npm install\n\n\nregister linking in my-button\n\nyarn link or npm link\n\n\nInstall example project\n\ncd example\nyarn add ../ or npm add ../\n\n\nlink to my-button\n\nyarn link my-button or npm link my-button\n\n\ncomplete pod installation (if necessary)\n\ncd ios\npod install\n\n", "Try to run \nnpm run watch\n\ninside the button package. Currently, I'm using this to apply changes from the library to my main project. Please let me know if it works!\n" ]
[ -3, -6 ]
[ "npm", "npm_link", "react_native" ]
stackoverflow_0044061155_npm_npm_link_react_native.txt
Q: Finding the minimum difference between elements in an array that are at least N indices apart I have an integer array with some finite number of values. My job is to find the minimum difference between any two elements in the array with indices that are separated by at least N spaces. Consider that the array contains: 4, 10, 11, 9, 17 and the constraint is a separation of 3 indices. The minimum difference would then be 5, coming from 9-4 What is an algorithm to solve this problem. I was thinking it was something similar to the closest pair algorithm, but not sure. Could that be applied here? A: Yes, you could use a variant of the closest pair algorithm to solve this problem. The key difference is that instead of looking for the minimum difference between any two elements in the array, you would only consider pairs of elements that are separated by at least N indices. Here's one way you could solve the problem: Sort the array in ascending order. Initialize a variable min_diff to the maximum possible value. Iterate over the elements in the array with an outer loop variable i. Within the outer loop, iterate over the elements in the array with an inner loop variable j. If the difference between i and j is less than N, skip this iteration of the inner loop. Otherwise, calculate the difference between the two elements and update min_diff if necessary. This algorithm has a time complexity of O(n^2), so it may not be suitable for large arrays. However, it is simple to implement and should work for small arrays. Another possible solution is to use a divide and conquer approach, similar to the one used in the closest pair algorithm. In this case, you would divide the array into two halves, find the minimum difference in each half, and then find the minimum difference between the two halves. This would have a time complexity of O(n log n), which is more efficient than the previous approach. You could also try using a sliding window approach, where you keep a window of size N and move it along the array, updating the minimum difference as you go. This would have a time complexity of O(n), which is the most efficient of the three approaches. However, it may be more difficult to implement.
Finding the minimum difference between elements in an array that are at least N indices apart
I have an integer array with some finite number of values. My job is to find the minimum difference between any two elements in the array with indices that are separated by at least N spaces. Consider that the array contains: 4, 10, 11, 9, 17 and the constraint is a separation of 3 indices. The minimum difference would then be 5, coming from 9-4 What is an algorithm to solve this problem. I was thinking it was something similar to the closest pair algorithm, but not sure. Could that be applied here?
[ "Yes, you could use a variant of the closest pair algorithm to solve this problem. The key difference is that instead of looking for the minimum difference between any two elements in the array, you would only consider pairs of elements that are separated by at least N indices.\nHere's one way you could solve the problem:\nSort the array in ascending order.\nInitialize a variable min_diff to the maximum possible value.\nIterate over the elements in the array with an outer loop variable i.\nWithin the outer loop, iterate over the elements in the array with an inner loop variable j.\nIf the difference between i and j is less than N, skip this iteration of the inner loop.\nOtherwise, calculate the difference between the two elements and update min_diff if necessary.\nThis algorithm has a time complexity of O(n^2), so it may not be suitable for large arrays. However, it is simple to implement and should work for small arrays.\nAnother possible solution is to use a divide and conquer approach, similar to the one used in the closest pair algorithm. In this case, you would divide the array into two halves, find the minimum difference in each half, and then find the minimum difference between the two halves. This would have a time complexity of O(n log n), which is more efficient than the previous approach.\nYou could also try using a sliding window approach, where you keep a window of size N and move it along the array, updating the minimum difference as you go. This would have a time complexity of O(n), which is the most efficient of the three approaches. However, it may be more difficult to implement.\n" ]
[ 0 ]
[]
[]
[ "algorithm" ]
stackoverflow_0074679569_algorithm.txt
Q: how can i change this column using R? This is my data frame. borrow date borrow time 2020-01-01 0 2020-01-01 0 2020-01-01 1 2020-01-01 1 2020-01-01 1 2020-01-01 2 2020-01-01 2 2020-01-01 2 2020-01-01 2 2020-01-01 2 2020-01-02 0 2020-01-02 1 2020-01-02 2 2020-01-02 2 2020-01-03 0 2020-01-03 0 2020-01-03 1 2020-01-03 1 2020-01-03 2 I want to change 'borrow date' column using 'borrow date' and 'borrow time'. This is what I want. borrow date 2020-01-01 0:00 2020-01-01 0:00 2020-01-01 1:00 2020-01-01 1:00 2020-01-01 1:00 2020-01-01 2:00 2020-01-01 2:00 2020-01-01 2:00 2020-01-01 2:00 2020-01-01 2:00 2020-01-02 0:00 2020-01-02 1:00 2020-01-02 2:00 2020-01-02 2:00 2020-01-03 0:00 2020-01-03 0:00 2020-01-03 1:00 2020-01-03 1:00 2020-01-03 2:00 If I can, I want to make this code using 'for'and 'if'. A: We can use df1$`borrow date` <- with(df1, as.POSIXct(paste(`borrow date`, `borrow time`), format = "%Y-%d-%d %H")) A: Here is an alternative: Note the column will stay as character class: library(dplyr) df %>% mutate(borrowtime = paste(borrowtime, "00", sep = ":")) borrowdate borrowtime 1 2020-01-01 0:00 2 2020-01-01 0:00 3 2020-01-01 1:00 4 2020-01-01 1:00 5 2020-01-01 1:00 6 2020-01-01 2:00 7 2020-01-01 2:00 8 2020-01-01 2:00 9 2020-01-01 2:00 10 2020-01-01 2:00 11 2020-01-02 0:00 12 2020-01-02 1:00 13 2020-01-02 2:00 14 2020-01-02 2:00 15 2020-01-03 0:00 16 2020-01-03 0:00 17 2020-01-03 1:00 18 2020-01-03 1:00 19 2020-01-03 2:00
how can i change this column using R?
This is my data frame. borrow date borrow time 2020-01-01 0 2020-01-01 0 2020-01-01 1 2020-01-01 1 2020-01-01 1 2020-01-01 2 2020-01-01 2 2020-01-01 2 2020-01-01 2 2020-01-01 2 2020-01-02 0 2020-01-02 1 2020-01-02 2 2020-01-02 2 2020-01-03 0 2020-01-03 0 2020-01-03 1 2020-01-03 1 2020-01-03 2 I want to change 'borrow date' column using 'borrow date' and 'borrow time'. This is what I want. borrow date 2020-01-01 0:00 2020-01-01 0:00 2020-01-01 1:00 2020-01-01 1:00 2020-01-01 1:00 2020-01-01 2:00 2020-01-01 2:00 2020-01-01 2:00 2020-01-01 2:00 2020-01-01 2:00 2020-01-02 0:00 2020-01-02 1:00 2020-01-02 2:00 2020-01-02 2:00 2020-01-03 0:00 2020-01-03 0:00 2020-01-03 1:00 2020-01-03 1:00 2020-01-03 2:00 If I can, I want to make this code using 'for'and 'if'.
[ "We can use\ndf1$`borrow date` <- with(df1, as.POSIXct(paste(`borrow date`,\n `borrow time`), format = \"%Y-%d-%d %H\"))\n\n", "Here is an alternative: Note the column will stay as character class:\nlibrary(dplyr)\n\ndf %>% \n mutate(borrowtime = paste(borrowtime, \"00\", sep = \":\"))\n\n borrowdate borrowtime\n1 2020-01-01 0:00\n2 2020-01-01 0:00\n3 2020-01-01 1:00\n4 2020-01-01 1:00\n5 2020-01-01 1:00\n6 2020-01-01 2:00\n7 2020-01-01 2:00\n8 2020-01-01 2:00\n9 2020-01-01 2:00\n10 2020-01-01 2:00\n11 2020-01-02 0:00\n12 2020-01-02 1:00\n13 2020-01-02 2:00\n14 2020-01-02 2:00\n15 2020-01-03 0:00\n16 2020-01-03 0:00\n17 2020-01-03 1:00\n18 2020-01-03 1:00\n19 2020-01-03 2:00\n\n" ]
[ 3, 1 ]
[]
[]
[ "dataframe", "for_loop", "if_statement", "r" ]
stackoverflow_0074679403_dataframe_for_loop_if_statement_r.txt