id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
09c608f6e8904e1b2efbdebc67dc5b850516d1ff
Stackoverflow Stackexchange Q: How can I get the devices battery level in javascript I am doing a network call every 15 seconds in my app, and if the users device battery percent is lower than 20%, than I would like to do the call every 30 seconds instead. How do I get the user's devices current battery level? Is it possible? Any help would be appreciated. A: Take a look at the Battery Status API. It doesn't work in all browsers, but it's a start. For browsers that support it, something like this should work: navigator.getBattery().then(function(battery) { battery.addEventListener('levelchange', function() { // Do stuff when the level changes, you can get it // from battery.level document.write((battery.level*100)+"%"); }) document.write((battery.level*100)+"%"); });
Q: How can I get the devices battery level in javascript I am doing a network call every 15 seconds in my app, and if the users device battery percent is lower than 20%, than I would like to do the call every 30 seconds instead. How do I get the user's devices current battery level? Is it possible? Any help would be appreciated. A: Take a look at the Battery Status API. It doesn't work in all browsers, but it's a start. For browsers that support it, something like this should work: navigator.getBattery().then(function(battery) { battery.addEventListener('levelchange', function() { // Do stuff when the level changes, you can get it // from battery.level document.write((battery.level*100)+"%"); }) document.write((battery.level*100)+"%"); });
stackoverflow
{ "language": "en", "length": 116, "provenance": "stackexchange_0000F.jsonl.gz:842255", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44471747" }
9edc10144e5c7c41e9d7e5a62529caedcdf127eb
Stackoverflow Stackexchange Q: How to create a test account for Facebook account kit? We are developing an iOS App that uses Facebook account kit for login through sms. We uploaded our app on iTunes connect for app review and they are asking for testing credentials for testing the app. But Facebook doesn't provide any test user credentials. Now we want to know how apple can test the app for review. If there is any method to create a test user for Facebook account kit, let me know as soon as possible. Thanks, A: if you want to create an account facebook just go here To create a Facebook account: 1.Go to www.facebook.com/r.php. 2.Enter your name, email or mobile phone number, password, date of birth and gender. Click Sign Up. 3.To finish creating your account, you need to confirm your email or mobile phone number. for more http://toptrendinngtoday.com/index.php/2019/09/20/step-by-step-to-make-facebook-and-instagram-account/
Q: How to create a test account for Facebook account kit? We are developing an iOS App that uses Facebook account kit for login through sms. We uploaded our app on iTunes connect for app review and they are asking for testing credentials for testing the app. But Facebook doesn't provide any test user credentials. Now we want to know how apple can test the app for review. If there is any method to create a test user for Facebook account kit, let me know as soon as possible. Thanks, A: if you want to create an account facebook just go here To create a Facebook account: 1.Go to www.facebook.com/r.php. 2.Enter your name, email or mobile phone number, password, date of birth and gender. Click Sign Up. 3.To finish creating your account, you need to confirm your email or mobile phone number. for more http://toptrendinngtoday.com/index.php/2019/09/20/step-by-step-to-make-facebook-and-instagram-account/
stackoverflow
{ "language": "en", "length": 145, "provenance": "stackexchange_0000F.jsonl.gz:842292", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44471849" }
8083d773782e19ce023f5dd11145e9585fd49833
Stackoverflow Stackexchange Q: Xcode 9 Bug: Cannot find cdtool After installing Xcode 9 beta, Xcode 8 gives me an error when compiling a project: Cannot find cdtool at '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Agents/cdtool': Cannot find a simulator runtime for platform <DVTPlatform:0x7fd67af0a930:'com.apple.platform.iphonesimulator':<DVTFilePath:0x7fd67af0a7c0:'/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform'>>. I suspect Xcode 9 modified some shared state with Xcode 8 (set a path, overwrote a file, etc.). But I've tried deleting and both Xcodes to no avail. The project uses Core Data and it's clearly failing when trying to compile the xcdatamodel. I can still compile and run under Xcode 9. A: Didn't work for me because I also have a Watch app and got the error on the Watch SDK. I ended up deleting both Xcode 8 and 9 Beta, deleting /Library/Developer and ~/Library/Developer. Then reinstalled Xcode 8 and it worked.
Q: Xcode 9 Bug: Cannot find cdtool After installing Xcode 9 beta, Xcode 8 gives me an error when compiling a project: Cannot find cdtool at '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Agents/cdtool': Cannot find a simulator runtime for platform <DVTPlatform:0x7fd67af0a930:'com.apple.platform.iphonesimulator':<DVTFilePath:0x7fd67af0a7c0:'/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform'>>. I suspect Xcode 9 modified some shared state with Xcode 8 (set a path, overwrote a file, etc.). But I've tried deleting and both Xcodes to no avail. The project uses Core Data and it's clearly failing when trying to compile the xcdatamodel. I can still compile and run under Xcode 9. A: Didn't work for me because I also have a Watch app and got the error on the Watch SDK. I ended up deleting both Xcode 8 and 9 Beta, deleting /Library/Developer and ~/Library/Developer. Then reinstalled Xcode 8 and it worked. A: An Apple engineer reached out about this... Those of you with cdtool errors in Xcode 8, I suspect you installed the iOS 10.3 Simulator runtime from Xcode 9. It was discovered this week that this causes a problem with cdtool in Xcode 8.3. You can work around that by moving iOS 10.3.simruntime aside and restarting CoreSimulatorService (source): sudo mkdir /Library/Developer/CoreSimulator/Profiles/Runtimes/Backup sudo mv /Library/Developer/CoreSimulator/Profiles/Runtimes/{,Backup/}iOS\ 10.3.simruntime sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService Then restart Xcode, Simulator, etc. Those of you that deleted CoreSimulator.framework and thus cannot run Xcode.app any more can reinstall CoreSimulator.framework with: installer -pkg /Applications/Xcode-beta.app/Contents/Resources/Packages/XcodeSystemResources.pkg -target / A: You can also remove the 10.3 folder from /Library/Developer/CoreSimulator/Profiles/Runtimes Restart Xcode in order to take effect (may not be needed). A: I agree with this answer. In addition I first removed all existing(took backup) Xcode version from machine.Then kept xcode 8.3.3 in Application folder. Made the project to open with default Xcode 8.3.2. Problem got resolved. The problem came when I updated Xcode 9 beta to 9.2.
stackoverflow
{ "language": "en", "length": 292, "provenance": "stackexchange_0000F.jsonl.gz:842327", "question_score": "61", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44471971" }
48ec200568e52d6f71567c1f01fa3e392ffa1f00
Stackoverflow Stackexchange Q: How do I resolve "Failed to create process" in Anaconda? I downloaded Anaconda 3.6, but when I tried "conda update conda" or tried opening jupyter notebook, it shows Failed to create process. Please help! A: I have uninstalled 64-bit software, removed shortcuts, installed 32-bit software and ran below command at the Anaconda prompt. (base) PS C:\anaconda3\Scripts> conda install -c anaconda anaconda-navigator Once updates done, navigator client opened with no issues.
Q: How do I resolve "Failed to create process" in Anaconda? I downloaded Anaconda 3.6, but when I tried "conda update conda" or tried opening jupyter notebook, it shows Failed to create process. Please help! A: I have uninstalled 64-bit software, removed shortcuts, installed 32-bit software and ran below command at the Anaconda prompt. (base) PS C:\anaconda3\Scripts> conda install -c anaconda anaconda-navigator Once updates done, navigator client opened with no issues.
stackoverflow
{ "language": "en", "length": 71, "provenance": "stackexchange_0000F.jsonl.gz:842337", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44471991" }
85c02daec453779fdfe0ef63d173d6a70967e382
Stackoverflow Stackexchange Q: How can I play audio (playsound) in the background of a Python script? I am just writing a small Python game for fun and I have a function that does the beginning narrative. I am trying to get the audio to play in the background, but unfortunately the MP3 file plays first before the function continues. How do I get it to run in the background? import playsound def displayIntro(): playsound.playsound('storm.mp3',True) print('') print('') print_slow('The year is 1845, you have just arrived home...') Also, is there a way of controlling the volume of the playsound module? I am using a Mac, and I am not wedded to using playsound. It just seems to be the only module that I can get working. A: There is a library in Pygame called mixer and you can add an MP3 file to the folder with the Python script inside and put code like this inside: from pygame import mixer mixer.init() mixer.music.load("mysong.mp3") mixer.music.play()
Q: How can I play audio (playsound) in the background of a Python script? I am just writing a small Python game for fun and I have a function that does the beginning narrative. I am trying to get the audio to play in the background, but unfortunately the MP3 file plays first before the function continues. How do I get it to run in the background? import playsound def displayIntro(): playsound.playsound('storm.mp3',True) print('') print('') print_slow('The year is 1845, you have just arrived home...') Also, is there a way of controlling the volume of the playsound module? I am using a Mac, and I am not wedded to using playsound. It just seems to be the only module that I can get working. A: There is a library in Pygame called mixer and you can add an MP3 file to the folder with the Python script inside and put code like this inside: from pygame import mixer mixer.init() mixer.music.load("mysong.mp3") mixer.music.play() A: Well, you could just use pygame.mixer.music.play(x): #!/usr/bin/env python3 # Any problems contact me on Instagram, @vulnerabilties import pygame pygame.mixer.init() pygame.mixer.music.load('filename.extention') pygame.mixer.music.play(999) # Your code here A: Just change True to False (I use Python 3.7.1) import playsound playsound.playsound('storm.mp3', False) print ('...') A: You could try just_playback. It's a wrapper I wrote around miniaudio that plays audio in the background while providing playback control functionality like pausing, resuming, seeking and setting the playback volume. A: A nice way to do it is to use vlc. Very common and supported library. pip install python-vlc Then writing your code import vlc #Then instantiate a MediaPlayer object player = vlc.MediaPlayer("/path/to/song.mp3") #And then use the play method player.play() #You can also use the methods pause() and stop if you need. player.pause() player.stop #And for the super fancy thing you can even use a playlist :) playlist = ['/path/to/song1.mp3', '/path/to/song2.mp3', '/path/to/song3.mp3'] for song in playlist: player = vlc.MediaPlayer(song) player.play() A: In Windows: Use winsound.SND_ASYNC to play them asynchronously: import winsound winsound.PlaySound("filename", winsound.SND_ASYNC | winsound.SND_ALIAS ) To stop playing winsound.PlaySound(None, winsound.SND_ASYNC) On Mac or other platforms: You can try this Pygame/SDL pygame.mixer.init() pygame.mixer.music.load("file.mp3") pygame.mixer.music.play() A: from pygame import mixer mixer.music.init() mixer.music.load("audio.mp3") # Paste The audio file location mixer.play() A: Use vlc import vlc player = None def play(sound_file): global player if player is not None: player.stop() player = vlc.MediaPlayer("file://" + sound_file) player.play() A: I used a separate thread to play the sound without blocking the main thread. It works on Ubuntu as well. from threading import Thread from playsound import playsound def play(path): """ Play sound file in a separate thread (don't block current thread) """ def play_thread_function: playsound(path) play_thread = Thread(target=play_thread_function) play_thread.start() A: This is a solution to reproduce similar length sounds. This solution worked to me to solve the error: The specified device is not open or recognized by MCI. Here follow the syntax as a class method, but you can change it to work even without a class. Import these packages: import multiprocessing import threading import time Define this function: def _reproduce_sound_nb(self, str_, time_s): def reproduce_and_kill(str_, time_sec=time_s): p = multiprocessing.Process(target=playsound, args=(str_,)) p.start() time.sleep(time_sec) p.terminate() threading.Thread(target=reproduce_and_kill, args=(str_, time_s), daemon=True).start() In the main program/method: self._reproduce_sound_nb(sound_path, 3) # path to the sound, seconds after sound stop -> to manage the process end
stackoverflow
{ "language": "en", "length": 535, "provenance": "stackexchange_0000F.jsonl.gz:842385", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472162" }
acbcc21450ba88f3d68a00f404a1e2d1473eb1d0
Stackoverflow Stackexchange Q: react-native SectionList scrollTo I'm new to react-native and tried using SectionList. Everything's working fine, so far. However, I can't seem to use the scrollToLocation function as defined in facebook's documentation. Anyone tried using it or anything similar? Basically, I want to scroll to a specific, section and item. return Promise.all([ props.orderActions.set(orders, true), props.orderActions.set(orders, false), ]).then(() => { return this._ordersList.scrollToLocation({ animated: false, sectionIndex: 0, itemIndex: historyItems.length - 1 }) }) _ordersList is a reference to the SectionList component. Thanks! A: Upgrading to 0.45 did it. Had performance issues but managed to fix it by using PureComponent
Q: react-native SectionList scrollTo I'm new to react-native and tried using SectionList. Everything's working fine, so far. However, I can't seem to use the scrollToLocation function as defined in facebook's documentation. Anyone tried using it or anything similar? Basically, I want to scroll to a specific, section and item. return Promise.all([ props.orderActions.set(orders, true), props.orderActions.set(orders, false), ]).then(() => { return this._ordersList.scrollToLocation({ animated: false, sectionIndex: 0, itemIndex: historyItems.length - 1 }) }) _ordersList is a reference to the SectionList component. Thanks! A: Upgrading to 0.45 did it. Had performance issues but managed to fix it by using PureComponent
stackoverflow
{ "language": "en", "length": 96, "provenance": "stackexchange_0000F.jsonl.gz:842398", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472196" }
d0ec7ff9019bbccd61b8d97df13d817d9e26e916
Stackoverflow Stackexchange Q: Can I use third party java libraries(.jar) for Android development with Kotlin? I haven't moved to Kotlin for Android development yet, just wondering if Kotlin supports the available third party libraries for Android as is or they need to be updated in order to work with Kotlin? A: Yes, as Kotlin is 100% interoperable with Java, and both works on JVM. so one can easily use Java libraries with Kotlin. Please refer this.
Q: Can I use third party java libraries(.jar) for Android development with Kotlin? I haven't moved to Kotlin for Android development yet, just wondering if Kotlin supports the available third party libraries for Android as is or they need to be updated in order to work with Kotlin? A: Yes, as Kotlin is 100% interoperable with Java, and both works on JVM. so one can easily use Java libraries with Kotlin. Please refer this. A: yes, Kotlin is fully interoperable with Java A: Of course you can do that, see the examples : https://kotlinlang.org/docs/reference/java-interop.html https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html
stackoverflow
{ "language": "en", "length": 95, "provenance": "stackexchange_0000F.jsonl.gz:842406", "question_score": "27", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472214" }
a01196b6aa9de1ee648dd49607a4210f4b3e410f
Stackoverflow Stackexchange Q: ios 10 youtube iframe not playing I'm using the following iframe in my HTML code: <iframe src="<iframeurl>">?autoplay=1" frameborder="0" allowfullscreen></iframe> On iPhone with iOS10 this doesn't autoplay. I'm getting the red play button and stuff. On windows chrome and others all works fine autoplay starts correctly. But not with the iphone. Is there anything I could do in javascript or by manipulating the URL to make this autoplay? I'm aware that Apple used to disallow autoplay before iOS10 so maybe I'm doing something wrong here.. A: You're experiencing this because Apple doesn't allow embedded media to play automatically — the user always initiates playback. This is mentioned in YouTube's IFrame Player API documentation as well. And no, I don't think you can and should override this since that is a bad practice.
Q: ios 10 youtube iframe not playing I'm using the following iframe in my HTML code: <iframe src="<iframeurl>">?autoplay=1" frameborder="0" allowfullscreen></iframe> On iPhone with iOS10 this doesn't autoplay. I'm getting the red play button and stuff. On windows chrome and others all works fine autoplay starts correctly. But not with the iphone. Is there anything I could do in javascript or by manipulating the URL to make this autoplay? I'm aware that Apple used to disallow autoplay before iOS10 so maybe I'm doing something wrong here.. A: You're experiencing this because Apple doesn't allow embedded media to play automatically — the user always initiates playback. This is mentioned in YouTube's IFrame Player API documentation as well. And no, I don't think you can and should override this since that is a bad practice. A: Just add the play trigger to onClick and then execute call the click event from an AJAX response. Should do the trick ;) A: It is not that iOS prevents any video from autoplaying (at least not so since iOS 10), but it is unmuted videos that are prevented from playing without user interaction. So if you embed a YouTube video with muted=1 appended to the URL, autoplay works again. P.S. the muted parameter is not documented for the YouTube embedded players. It is nowhere to be found in the official doc: https://developers.google.com/youtube/player_parameters. Yet it has been working for quite a while. If you worry it may not work someday, you can take the programmatic approach via the iframe API: first mute the video and then play it when the ready event is emitted. A: putting this in config.xml worked for me: <allow-navigation href="*://*youtube.com" />
stackoverflow
{ "language": "en", "length": 278, "provenance": "stackexchange_0000F.jsonl.gz:842420", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472256" }
5f1570a6337b4a0776db9866db5567486fd1cad7
Stackoverflow Stackexchange Q: Imagecreatefromwebp(): WebP decode: fail to decode input data I am trying to convert a webp file to JPEG using imagecreatefromwebp() but unfortunately, it throws me a warning: Warning: imagecreatefromwebp(): WebP decode: fail to decode input data. Here's my code $filename = dirname(__FILE__)."\\".$keyword."1.webp"; // $keyword = 'xyz'; $im = imagecreatefromwebp($filename); // Convert it to a jpeg file with 100% quality imagejpeg($im, './example.jpeg', 100); imagedestroy($im); Please help. A: i am using this code, it works fine for me. Here $data contains the base64encoded data $im = imagecreatefromwebp($data); $imageResult = imagejpeg($im, $destinationPath . $fileName, 100); imagedestroy($im); The imagecreatefromwebp() function accepts either a valid file or URL. You can also pass the your binary data in that function. You can check the function definition and example here http://php.net/manual/en/function.imagecreatefromwebp.php
Q: Imagecreatefromwebp(): WebP decode: fail to decode input data I am trying to convert a webp file to JPEG using imagecreatefromwebp() but unfortunately, it throws me a warning: Warning: imagecreatefromwebp(): WebP decode: fail to decode input data. Here's my code $filename = dirname(__FILE__)."\\".$keyword."1.webp"; // $keyword = 'xyz'; $im = imagecreatefromwebp($filename); // Convert it to a jpeg file with 100% quality imagejpeg($im, './example.jpeg', 100); imagedestroy($im); Please help. A: i am using this code, it works fine for me. Here $data contains the base64encoded data $im = imagecreatefromwebp($data); $imageResult = imagejpeg($im, $destinationPath . $fileName, 100); imagedestroy($im); The imagecreatefromwebp() function accepts either a valid file or URL. You can also pass the your binary data in that function. You can check the function definition and example here http://php.net/manual/en/function.imagecreatefromwebp.php
stackoverflow
{ "language": "en", "length": 125, "provenance": "stackexchange_0000F.jsonl.gz:842435", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472308" }
35377c8149157359e66087c3af8043b1e790bc61
Stackoverflow Stackexchange Q: Where to store JSON file inside Laravel folder structure I want to store some data in a JSON file. The data will be decoded using json_decode function and passed to view. File example: { "rooms": [ { "name": "Aula Magna 1", "camera_url": "camera url", "audio_card": "audio card" }, { "name": "Aula Magna 2", "camera_url": "camera url", "audio_card": "audio card" }, { "name": "Aula Minor", "camera_url": "camera url", "audio_card": "audio card" }] } I want to convert this file into an array so I can access it inside a view like so @foreach( $rooms as $room) .... @endforeach Where inside Laravel folder structutre should be data file like this stored? A: You should put your files inside storage folder as it is non-public directory you can also place in resources folder but it is not the best place, as this folder is used for source files and is usually stored in source code repository (e.g. git).
Q: Where to store JSON file inside Laravel folder structure I want to store some data in a JSON file. The data will be decoded using json_decode function and passed to view. File example: { "rooms": [ { "name": "Aula Magna 1", "camera_url": "camera url", "audio_card": "audio card" }, { "name": "Aula Magna 2", "camera_url": "camera url", "audio_card": "audio card" }, { "name": "Aula Minor", "camera_url": "camera url", "audio_card": "audio card" }] } I want to convert this file into an array so I can access it inside a view like so @foreach( $rooms as $room) .... @endforeach Where inside Laravel folder structutre should be data file like this stored? A: You should put your files inside storage folder as it is non-public directory you can also place in resources folder but it is not the best place, as this folder is used for source files and is usually stored in source code repository (e.g. git).
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:842447", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472345" }
2c76c5277cd9b43ec691be9b264fed150bb087bc
Stackoverflow Stackexchange Q: Sending statistics to Google Analytics from java desktop application I have a JavaFX desktop application which allows users to login, load and save data on remote host using HttpRequest GET and POST methods (for instance, by pressing buttons Login, Load, Save). I'd like to monitor user's interaction with that application using Google Analytics. Are there any usage examples of how this can be done? I guess, I need to add listeners to those buttons and call GA API? Maybe some examples of how to connect to google and what parameters need to be passed there? Thanks in advance! A: I found the solution using the following library It has a GA tracker constuctor where you can put your application name and tracking code: private static final JGoogleAnalyticsTracker MONITOR = new JGoogleAnalyticsTracker("My app", "UA-10086test-1"); And then use it's method "trackAsynchronously()" whenever you want with required description: Main.getMonitor().trackAsynchronously(new FocusPoint("Submit login")); Compiled it locally and added to my pom: <dependency> <groupId>jgoogleanalytics</groupId> <artifactId>jgoogleanalytics</artifactId> <version>0.5</version> </dependency>
Q: Sending statistics to Google Analytics from java desktop application I have a JavaFX desktop application which allows users to login, load and save data on remote host using HttpRequest GET and POST methods (for instance, by pressing buttons Login, Load, Save). I'd like to monitor user's interaction with that application using Google Analytics. Are there any usage examples of how this can be done? I guess, I need to add listeners to those buttons and call GA API? Maybe some examples of how to connect to google and what parameters need to be passed there? Thanks in advance! A: I found the solution using the following library It has a GA tracker constuctor where you can put your application name and tracking code: private static final JGoogleAnalyticsTracker MONITOR = new JGoogleAnalyticsTracker("My app", "UA-10086test-1"); And then use it's method "trackAsynchronously()" whenever you want with required description: Main.getMonitor().trackAsynchronously(new FocusPoint("Submit login")); Compiled it locally and added to my pom: <dependency> <groupId>jgoogleanalytics</groupId> <artifactId>jgoogleanalytics</artifactId> <version>0.5</version> </dependency>
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:842498", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472530" }
e04555d4bc981d50bb615941e77cb6e7a9cc452d
Stackoverflow Stackexchange Q: how to use bootstrap with Laravel 5.2 I need use bootstrap 3 with My Laravel app. I have download bootstarp and paste it Laravel public-css folder. now I need integrate its with My Laravel app. how can I do this? I do not use bootstrap theme. only css and js files. I need exit cdn. A: Laravel 5.2 comes with bootstrap sass in place. You can find it under the resources directory: https://github.com/laravel/laravel/blob/5.2/resources/assets/sass/app.scss Just uncomment the @import line and build the public resources with gulp or something. To include the javascript just include it in your document head like you would any other resource. <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=" crossorigin="anonymous"></script>
Q: how to use bootstrap with Laravel 5.2 I need use bootstrap 3 with My Laravel app. I have download bootstarp and paste it Laravel public-css folder. now I need integrate its with My Laravel app. how can I do this? I do not use bootstrap theme. only css and js files. I need exit cdn. A: Laravel 5.2 comes with bootstrap sass in place. You can find it under the resources directory: https://github.com/laravel/laravel/blob/5.2/resources/assets/sass/app.scss Just uncomment the @import line and build the public resources with gulp or something. To include the javascript just include it in your document head like you would any other resource. <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=" crossorigin="anonymous"></script> A: I found an solution try this one download the bootstrap package and copy bootstrap.min.css into your public/css folder copy bootstrap.min.js into your public/js folder Add the following to the head area of app.blade.php <link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet"> Before the closing in app.blade.php add <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="{{ asset('js/bootstrap.min.js') }}"></script> A: after past myapp/public/css/bootstrap.min.css file you have to import css boostrap sourse, <link rel="stylesheet" href="<?php echo asset ('css/bootstrap.min.css')?>" type="text/css"> A: Bootstrap is already included with Laravel. On Laravel 5.8 it is under public/css/app.css location you just need to add the file to the blade template to use bootstrap like this **<link href="{{ asset('css/app.css') }}" rel="stylesheet">**
stackoverflow
{ "language": "en", "length": 215, "provenance": "stackexchange_0000F.jsonl.gz:842519", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472597" }
7d6fc75a7082bd402f3b80445ea09cb7dd27e104
Stackoverflow Stackexchange Q: How to Convert java to kotlin in handler how to Convert java to kotlin in handler new Handler().postDelayed(new Runnable(){ @Override public void run() { /* Create an Intent that will start the Menu-Activity. */ Intent mainIntent = new Intent(Splash.this,Menu.class); Splash.this.startActivity(mainIntent); Splash.this.finish(); } }, 3000); A: Java converted to Kotlin: Handler(Looper.getMainLooper()).postDelayed({ val mainIntent = Intent(this, Menu::class.java) startActivity(mainIntent) finish() }, 3000) If you are using the androidx-core-ktx package, there is an extension function which reorders the arguments to be more suitable for Kotlin: Handler(Looper.getMainLooper()).postDelayed(1000) { // Do something }
Q: How to Convert java to kotlin in handler how to Convert java to kotlin in handler new Handler().postDelayed(new Runnable(){ @Override public void run() { /* Create an Intent that will start the Menu-Activity. */ Intent mainIntent = new Intent(Splash.this,Menu.class); Splash.this.startActivity(mainIntent); Splash.this.finish(); } }, 3000); A: Java converted to Kotlin: Handler(Looper.getMainLooper()).postDelayed({ val mainIntent = Intent(this, Menu::class.java) startActivity(mainIntent) finish() }, 3000) If you are using the androidx-core-ktx package, there is an extension function which reorders the arguments to be more suitable for Kotlin: Handler(Looper.getMainLooper()).postDelayed(1000) { // Do something }
stackoverflow
{ "language": "en", "length": 88, "provenance": "stackexchange_0000F.jsonl.gz:842567", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472765" }
a17469d7fc68b767a3f072a602b522c04e2f74ce
Stackoverflow Stackexchange Q: Event to fire when an angular *ngIf statement evaluates in template If I have the following: <div *ngIf="user$ | async as user" class="container"> <p>{{user.name}}</p> </div> Is there a way I can execute code when the div above finally appears on screen? A: The *ngIf will remove that DOM element and all attached components/directives. So you can just write a simple directive that executes an event when it's first created. When the *ngIf transitions from false to true the directive will be created (again, and again, etc...) @Directive({selector: '[after-if]'}) export class AfterIfDirective implements AfterContentInit { @Output('after-if') public after: EventEmitter<void> = new EventEmitter<void>(); public ngAfterContentInit(): void { // timeout helps prevent unexpected change errors setTimeout(()=> this.after.next()); } } Sample HTML: <div *ngIf="user$ | async as user" (after-if)="your expression"> <p>{{user.name}}</p> </div>
Q: Event to fire when an angular *ngIf statement evaluates in template If I have the following: <div *ngIf="user$ | async as user" class="container"> <p>{{user.name}}</p> </div> Is there a way I can execute code when the div above finally appears on screen? A: The *ngIf will remove that DOM element and all attached components/directives. So you can just write a simple directive that executes an event when it's first created. When the *ngIf transitions from false to true the directive will be created (again, and again, etc...) @Directive({selector: '[after-if]'}) export class AfterIfDirective implements AfterContentInit { @Output('after-if') public after: EventEmitter<void> = new EventEmitter<void>(); public ngAfterContentInit(): void { // timeout helps prevent unexpected change errors setTimeout(()=> this.after.next()); } } Sample HTML: <div *ngIf="user$ | async as user" (after-if)="your expression"> <p>{{user.name}}</p> </div> A: A solution without the creation of a new directive is to take advange of @ViewChild and @ViewChildren behaviour: Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated. 1. ViewChild The important part is If the view DOM changes wich means that in this case this'll only be triggered when the element is created or destroyed. First declare a variable name for the element, for the sample i used #userContent <div #userContent *ngIf="user$ | async as user" class="container"> <p>user.name</p> </div> Then add a @ViewChild reference inside your component: @ViewChild('userContent') set userContent(element) { if (element) { // here you get access only when element is rendered (or destroyed) } } This solution was provided inside another question, also @ViewChild behaviour detail is available here. 2. ViewChildren Another solution without using a new directive is to subscribe to @ViewChildren change observable, instead of using @ViewChild put it like this: @ViewChildren('userContent') private userContent: QueryList<any>; And then subscribe to it change observable: userContent.changes.pipe(takeUntil(this.$d)).subscribe((d: QueryList<any>) => { if (d.length) { // here you get access only when element is rendered } }); I've preferred the last way because to me it was easier to handle observables than validations inside setter's, also this approach is closer to the "Event" concept. Note about Observables: All observables need to be unsubscribed, otherwise you'll provoke memory leaks; there's a lot of ways to prevent that, as a recommendation, my favorite way is the RxJs function takeUntil, this part: pipe(takeUntil(this.$d)) and the following at your ngOnDestroy method: private $d = new Subject(); ngOnDestroy() { this.$d.next(); this.$d.complete(); } The reason I recommend this way is because the amount of extra code to implement it is very low, also; you can use the same variable for all of your subscriptions in the component (this.$d). For more details/options about unsubscription approaches see this other related question/answer.
stackoverflow
{ "language": "en", "length": 464, "provenance": "stackexchange_0000F.jsonl.gz:842569", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472771" }
7a5215534c7a500fa021cac7b9b995917ab8a242
Stackoverflow Stackexchange Q: How to let developers with non-Admin access edit Azure Functions I have setup an Azure function as an Admin and now I want to let my developers edit and test it, without sharing Admin access with them. How do I add them to our profile and permission them with non-admin access? A: You can use Role-Based Access Control (RBAC) to grant your developers access to the resource group that contains your Azure Function. Simply add them to the Contributor role for that resource group.
Q: How to let developers with non-Admin access edit Azure Functions I have setup an Azure function as an Admin and now I want to let my developers edit and test it, without sharing Admin access with them. How do I add them to our profile and permission them with non-admin access? A: You can use Role-Based Access Control (RBAC) to grant your developers access to the resource group that contains your Azure Function. Simply add them to the Contributor role for that resource group.
stackoverflow
{ "language": "en", "length": 85, "provenance": "stackexchange_0000F.jsonl.gz:842573", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472780" }
8ba5ddbc6411ba2b27cfeeeefd5f2738abd9a8d1
Stackoverflow Stackexchange Q: Changing the text and background color with Apple's PDFKit framework I'd like to change the text and background color of a displayed PDF document using Apple's PDFKit Framework to show the documents in "Night Mode" (dark background, light foreground, just like in Adobe Reader). I know the PDFPage class has a drawWithBox:toContext: method, which can be overwritten in a subclass to add effects (like watermark, as shown in this WWDC 2017 session), but I don't know how to set the color properties. Is there a way to do this with the PDFKit library or any other low-level API (Quartz) from Apple? A: For giving text color in pdf you can use, -(CGRect)addText:(NSString*)text withFrame:(CGRect)frame font:(NSString*)fontName fontSize:(float)fontSize andColor:(UIColor*)color{ const CGFloat *val = CGColorGetComponents(color.CGColor); CGContextRef currentContext = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(currentContext, val[0], val[1], val[2], val[3]); UIFont *font = [UIFont fontWithName:fontName size:fontSize]; CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*20-2*20, pageSize.height - 2*20 - 2*20) lineBreakMode:NSLineBreakByWordWrapping]; CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height); [text drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft]; frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height); return frame; } And for background color, use the following CGContextRef currentContext = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(currentContext, [UIColor blueColor].CGColor ); CGContextFillRect(currentContext, CGRectMake(0, 110.5, pageSize.width, pageSize.height));
Q: Changing the text and background color with Apple's PDFKit framework I'd like to change the text and background color of a displayed PDF document using Apple's PDFKit Framework to show the documents in "Night Mode" (dark background, light foreground, just like in Adobe Reader). I know the PDFPage class has a drawWithBox:toContext: method, which can be overwritten in a subclass to add effects (like watermark, as shown in this WWDC 2017 session), but I don't know how to set the color properties. Is there a way to do this with the PDFKit library or any other low-level API (Quartz) from Apple? A: For giving text color in pdf you can use, -(CGRect)addText:(NSString*)text withFrame:(CGRect)frame font:(NSString*)fontName fontSize:(float)fontSize andColor:(UIColor*)color{ const CGFloat *val = CGColorGetComponents(color.CGColor); CGContextRef currentContext = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(currentContext, val[0], val[1], val[2], val[3]); UIFont *font = [UIFont fontWithName:fontName size:fontSize]; CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*20-2*20, pageSize.height - 2*20 - 2*20) lineBreakMode:NSLineBreakByWordWrapping]; CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height); [text drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft]; frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height); return frame; } And for background color, use the following CGContextRef currentContext = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(currentContext, [UIColor blueColor].CGColor ); CGContextFillRect(currentContext, CGRectMake(0, 110.5, pageSize.width, pageSize.height));
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:842585", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472810" }
11e2ab6e525d6b06f2a94e00d5409fa5ec3ad638
Stackoverflow Stackexchange Q: Can not build ffmpeg with gpu acceleration on macOS I'm trying to use my GPU for video encoding/decoding operations on macOS. * *OS: MacOS 10.12.5 (Sierra) //hackintosh if it matters *CUDA Toolkit 8.0 installed *NVidia GTX 1080 with latest web driver Followed this guides: * *https://trac.ffmpeg.org/wiki/CompilationGuide/MacOSX *https://developer.nvidia.com/ffmpeg Config: ./configure --enable-cuda --enable-cuvid --enable-nvenc \ --enable-nonfree --enable-libnpp \ --extra-cflags=-I/Developer/NVIDIA/CUDA-8.0/include \ --extra-ldflags=-L/Developer/NVIDIA/CUDA-8.0/lib Got this error: ERROR: cuvid requested, but not all dependencies are satisfied: cuda config.log - full configure log I did not install Video Codec SDK (not sure how to make it on macOS, just thought that it may come with cuda toolkit) and according to this page I have a lot of limitations on OSX. Is it possible on macOS? Or this will work only for linux/windows?
Q: Can not build ffmpeg with gpu acceleration on macOS I'm trying to use my GPU for video encoding/decoding operations on macOS. * *OS: MacOS 10.12.5 (Sierra) //hackintosh if it matters *CUDA Toolkit 8.0 installed *NVidia GTX 1080 with latest web driver Followed this guides: * *https://trac.ffmpeg.org/wiki/CompilationGuide/MacOSX *https://developer.nvidia.com/ffmpeg Config: ./configure --enable-cuda --enable-cuvid --enable-nvenc \ --enable-nonfree --enable-libnpp \ --extra-cflags=-I/Developer/NVIDIA/CUDA-8.0/include \ --extra-ldflags=-L/Developer/NVIDIA/CUDA-8.0/lib Got this error: ERROR: cuvid requested, but not all dependencies are satisfied: cuda config.log - full configure log I did not install Video Codec SDK (not sure how to make it on macOS, just thought that it may come with cuda toolkit) and according to this page I have a lot of limitations on OSX. Is it possible on macOS? Or this will work only for linux/windows?
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:842598", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472853" }
a451dcc5873fdfd32d1b89b6f565e1bb35c107fb
Stackoverflow Stackexchange Q: How do I add Typescript definitions for Leaflet plugins I would like to use easy-buttons plugin with Typescript https://github.com/CliffCloud/Leaflet.EasyButton/blob/master/src/easy-button.js and but it doesn't come with Typescript annotations. A: It actually does now. You should just import * as L from 'leaflet'; import 'leaflet-easybutton/src/easy-button';
Q: How do I add Typescript definitions for Leaflet plugins I would like to use easy-buttons plugin with Typescript https://github.com/CliffCloud/Leaflet.EasyButton/blob/master/src/easy-button.js and but it doesn't come with Typescript annotations. A: It actually does now. You should just import * as L from 'leaflet'; import 'leaflet-easybutton/src/easy-button'; A: Step 1 - light up the errors The first step is to use the sample code as-is without Typescript annotations, and the errors will start lighting up in VS Code. // sample.ts L.easyBar([ L.easyButton('fa-file', function(btn, map){ }), L.easyButton('fa-save', function(btn, map){ }), L.easyButton('fa-edit', function(btn, map){ }), L.easyButton('fa-dot-circle-o', function(btn, map){ }) ]).addTo(map); To which we create a file called 'easy-button.d.ts' and refer to it in our Typescript file. // sample.ts import "./easy-button" L.easyBar([ L.easyButton('fa-file', function(btn, map){ }), L.easyButton('fa-save', function(btn, map){ }), L.easyButton('fa-edit', function(btn, map){ }), L.easyButton('fa-dot-circle-o', function(btn, map){ }) ]).addTo(map); And there's nothing in easy-button.d.ts // easy-button.d.ts // empty for now The error says error TS2339: Property 'easyBar' does not exist on type 'typeof L'. error TS2339: Property 'easyButton' does not exist on type 'typeof L'. Which is fair enough because we haven't defined these yet. If you refer to definition of easyBar and easyButton here and here, you will find there's a bit of magic occuring in the original Javascript declarations. It appears that these two functions don't take any arguments, but in reality they do. L.easyButton = function(/* args will pass automatically */){ var args = Array.prototype.concat.apply([L.Control.EasyButton],arguments); return new (Function.prototype.bind.apply(L.Control.EasyButton, args)); }; This function is going to call new on the L.Control.EasyButton class. The parameters are somewhat cryptic but you can infer them from this line that gives: initialize: function(icon, onClick, title, id) Step 2 - add the typings // easy-button.d.ts declare namespace L { function easyBar(); function easyButton(); } and now we are a bit closer: error TS2346: Supplied parameters do not match any signature of call target and that's quite obvious because we supplied 2 parameters 'fa-edit' and a callback to easyButton but we didn't declare any in our arguments. Our second attempt now looks like this: // easy-button.d.ts declare namespace L { function easyBar(buttons: any[]); function easyButton(icon: string, onClick: (btn: any, map: any)=>void); } and now all the Typescript warnings have gone away. But there's more that can be done. For one, easyButton actually takes 4 arguments. That's easy to fix - observe how optional arguments have a ? suffix: // easy-button.d.ts declare namespace L { function easyBar(buttons: any[]); function easyButton(icon: string, onClick: (btn: any, map: any)=>void, title?: string, id?: string); } Step 3 - provide return values The easyButton method actually returns an L.Control.EasyButton instance. Currently, the Typescript definition implies the easyButton returns type any. We don't want that! Typescript is helpful only when we provide typings. declare namespace L { function easyBar(buttons: Control.EasyButton[]): Control.EasyBar; function easyButton(icon: string, onClick: (btn: any, map: any)=>void, title?: string, id?: string) : Control.EasyButton; namespace Control { class EasyButton { }; class EasyBar { }; } } Typescript starts providing useful warnings again: error TS2339: Property 'addTo' does not exist on type 'EasyBar'. This is because EasyBar subclasses L.Control we need to bring that definition into our definition file. declare namespace L { function easyBar(buttons: Control.EasyButton[]): Control.EasyBar; function easyButton(icon: string, onClick: (btn: any, map: any)=>void, title?: string, id?: string) : Control.EasyButton; namespace Control { class EasyButton extends L.Control { } class EasyBar extends L.Control { } } } Step 4 - provide constructor arguments to EasyButton and EasyBar If you try to instantiate a new EasyButton, code completion suggests that you should pass in a L.ControlOptions object to configure this. Actually we need to define our own options. declare namespace L { function easyBar(buttons: Control.EasyButton[], options?: EasyBarOptions): Control.EasyBar; function easyButton(icon: string, onClick: (btn: any, map: any)=>void, title?: string, id?: string) : Control.EasyButton; interface EasyBarOptions { position?: ControlPosition id?: string leafletClasses?: boolean } interface EasyButtonOptions { position?: ControlPosition id?: string type?: 'replace'|'animate' states?: any leafletClasses?: boolean tagName?: string } namespace Control { class EasyButton extends L.Control { constructor(options?: EasyButtonOptions) } class EasyBar extends L.Control { constructor(options?: EasyBarOptions) } } } Things look better now on code completion: However, I cheated on the states option. I declared that as any. In actuality it ought to be interface EasyButtonOptions { position?: ControlPosition id?: string type?: 'replace'|'animate' states?: EasyButtonState[] leafletClasses?: boolean tagName?: string } interface EasyButtonState { stateName: string onClick: () => void title: string icon: string } Step 5 - add jsdoc hints Typescript will provide helpful comments to users of this plugin. Here's an example of how we might provide documentation for easyButton /** * Creates a easyButton * @param icon e.g. fa-globe * @param onClick the button click handler * @param label on the button * @param an id to tag the button with * @example * var helloPopup = L.popup().setContent('Hello World!'); * * L.easyButton('fa-globe', function(btn, map){ * helloPopup.setLatLng(map.getCenter()).openOn(map); * }).addTo( YOUR_LEAFLET_MAP ); */ function easyButton( icon: string, onClick: (btn: Control.EasyButton, map: L.Map) => void, title?: string, id?: string): Control.EasyButton; Step 6 Make modifications to augment leaflet types definitions (Starting with Leaflet 1.2.0) Remove the namespace declaration: declare namespace L { and replace it with module augmentation: import * as L from 'leaflet' declare module 'leaflet' { your test code should now read like this: import * as L from 'leaflet' import 'easy-button' Step 7 integrate into the original project sources Open up node_modules\leaflet-easybutton\package.json and add the following line below the style entry: "main": "src/easy-button.js", "style": "src/easy-button.css", "typings": "src/easy-button.d.ts", Move our easy-button.d.ts into node_modules/leaflet-easybutton/src, and test that everything still works. Then submit a pull request so that every one can benefit from the work! A: class EasyButton extends L.Control { constructor(options?: EasyButtonOptions) } Your new L.EasyButton takes a 'EasyButtonOptions' object for the constructor. This does not match the 'L.easyButton' examples A L.easyButton has the following options: function easyButton(icon: string, onClick: (btn: any, map: any)=>void, title?: string, id?: string) : Control.EasyButton; An EasyButtonOptions doesn't have a 'icon', 'onClick', 'title' or 'id' instead it takes: interface EasyButtonOptions { position?: ControlPosition id?: string type?: 'replace'|'animate' states?: EasyButtonState[] leafletClasses?: boolean tagName?: string } So therefore, what is the equivalent of new L.EasyButton() that matches L.easyButton('fa fa-icon', () => '..', 'title) ?
stackoverflow
{ "language": "en", "length": 1010, "provenance": "stackexchange_0000F.jsonl.gz:842600", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472856" }
541ca73fa20818a5e2160d644aa0a2214e19de6a
Stackoverflow Stackexchange Q: CSS half arch around full circle I am trying to create a half arch around a full circle like below. How would I create this in css? So far I have only created the circle but no idea how to do the arch. .circle { width: 45px; height: 45px; border-radius: 50%; font-size: 20px; color: #fff; line-height: 45px; text-align: center; position: relative; background: #BDBDBD; } <div class="circle">1</div> A: You can use :after pseudo-element to create half circle. You also need to use bottom-right and top-right border-radius. .circle { width: 100px; height: 100px; margin: 50px; position: relative; line-height: 100px; text-align: center; border-radius: 50%; background: #BDBDBD; color: white; } .circle:after { content: ''; position: absolute; top: 0; right: 0; border: 10px solid gray; border-left: 0; border-bottom-right-radius: 100px; border-top-right-radius: 100px; width: 55px; height: calc(100% + 10px); transform: translate(15px, -15px); } <div class="circle">1</div>
Q: CSS half arch around full circle I am trying to create a half arch around a full circle like below. How would I create this in css? So far I have only created the circle but no idea how to do the arch. .circle { width: 45px; height: 45px; border-radius: 50%; font-size: 20px; color: #fff; line-height: 45px; text-align: center; position: relative; background: #BDBDBD; } <div class="circle">1</div> A: You can use :after pseudo-element to create half circle. You also need to use bottom-right and top-right border-radius. .circle { width: 100px; height: 100px; margin: 50px; position: relative; line-height: 100px; text-align: center; border-radius: 50%; background: #BDBDBD; color: white; } .circle:after { content: ''; position: absolute; top: 0; right: 0; border: 10px solid gray; border-left: 0; border-bottom-right-radius: 100px; border-top-right-radius: 100px; width: 55px; height: calc(100% + 10px); transform: translate(15px, -15px); } <div class="circle">1</div> A: This is based on jcaron's comment on the question. I wrapped the circle with an outer-circle div to create the "white space between greys" area. Nenad Vracar's answer however seems to be much cleaner. .outer-circle { width: 45px; height: 45px; border-style: solid; border-width: 1x 1px 0 0; border-color: #BDBDBD #BDBDBD transparent transparent; border-radius: 50%; font-size: 20px; color: #fff; line-height: 45px; text-align: center; position: relative; background: #fff; padding: 3px; transform: rotate(45deg); } .circle { background: #BDBDBD; border-radius: 50%; transform: rotate(-45deg); } <div class="outer-circle"> <div class="circle"> 1 </div> </div> A: Yes use pseudo selector, but your parent background needs to be white or any other color that merge with pseudo selector i.e. the center part between circle and half arch or do that using canvas. body { background: #fff; } div { width: 100px; height: 100px; background: #ccc; border-radius: 50%; text-align: center; position: relative; margin-top: 30px; color: #fff; padding-top: 40px; box-sizing: border-box; } div:after { content: ""; position: absolute; border-top: 70px solid transparent; border-left: 70px solid transparent; border-right: 70px solid #ccc; border-bottom: 70px solid #ccc; border-radius: 50%; z-index: -2; transform: rotate(-45deg); left: -15px; top: -20px; } div:before { content: ""; position: absolute; border-top: 60px solid transparent; border-left: 60px solid transparent; border-right: 60px solid #fff; border-bottom: 60px solid #fff; border-radius: 50%; z-index: -1; transform: rotate(-45deg); top: -10px; left: -7px; } <div>1</div>
stackoverflow
{ "language": "en", "length": 358, "provenance": "stackexchange_0000F.jsonl.gz:842620", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472926" }
e2d6c4d432c782ded0a1e16490ab3807ee99b0a2
Stackoverflow Stackexchange Q: Swift - Get Image creationDate and Location A function in my app returns an image and I'm now trying to get the images creationDate and location. How is this possible with/without using PHAsset? A: According to Apple's documentation, you should be able to do that using: let location = asset.location let creationDate = asset.creationDate They are properties of PHAsset class. Take a look at: location and creationDate.
Q: Swift - Get Image creationDate and Location A function in my app returns an image and I'm now trying to get the images creationDate and location. How is this possible with/without using PHAsset? A: According to Apple's documentation, you should be able to do that using: let location = asset.location let creationDate = asset.creationDate They are properties of PHAsset class. Take a look at: location and creationDate. A: If you are using UIImagePickerControllerDelegate and it will return the phAsset in the info dictionary. Once you get the dictionary all the properties of phAsset will be available. class ViewController: UIViewController, UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let asset = info[.phAsset] as? PHAsset print(asset?.creationDate ?? "None") print(asset?.location ?? "None") dismiss(animated: true, completion:nil) }
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:842624", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472940" }
e32daf17ab31f8010e601ba8a047c7931de7be7f
Stackoverflow Stackexchange Q: How to configure static Private Address in AWS I have a requirement where I want to manage 3 instances in a VPC holding my applications having different functionality which are not public facing instances. At some point in time for managing the unnecessary instances usage, I would like to stop 2 of my instances and restart those instances when required. * *When I restart my instance I am getting a new private address which is causing my application to fail without running. *I can't assign Elastic IP as it is not a public facing instance *I don't want to reconfigure it every time I stop and start the instance. Any help is apprecated. A: You can assign multiple private IP-addresses within your EC2 instance. The first IP is always auto-assigned by AWS. The second IP, on the other hand, can be static and defined by your environment. For a more complete explanation on how to enable such a setup, I recommend the AWS documentation in multiple IP addresses. Multiple IP Addresses
Q: How to configure static Private Address in AWS I have a requirement where I want to manage 3 instances in a VPC holding my applications having different functionality which are not public facing instances. At some point in time for managing the unnecessary instances usage, I would like to stop 2 of my instances and restart those instances when required. * *When I restart my instance I am getting a new private address which is causing my application to fail without running. *I can't assign Elastic IP as it is not a public facing instance *I don't want to reconfigure it every time I stop and start the instance. Any help is apprecated. A: You can assign multiple private IP-addresses within your EC2 instance. The first IP is always auto-assigned by AWS. The second IP, on the other hand, can be static and defined by your environment. For a more complete explanation on how to enable such a setup, I recommend the AWS documentation in multiple IP addresses. Multiple IP Addresses A: When launching a new instance you can manually define the private IP address you'd like to use. To do this, on the 'Configure Instance Details' screen of the wizard, manually select a subnet to launch in, and then in the 'Network Interfaces' section that appears enter the private IP address you wish to use. Reference link
stackoverflow
{ "language": "en", "length": 229, "provenance": "stackexchange_0000F.jsonl.gz:842626", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44472944" }
88610c17b33cc8b177ad0ac3a07fb6b390f4fa0a
Stackoverflow Stackexchange Q: How do I specify a boxed field can be nullable in my Realm migration code? I'm using Kotlin and I want to add a new field to a RealmObject and that field can be nullable. Here's what I have in my migration: val schema = realm.schema.get(ZOLA_NOTIFICATION) if (!(schema?.hasField("agentId") ?: false)) { schema.addField("agentId", Long::class.java) } However, I receive an error message when this migration is run: Non-fatal Exception: io.realm.exceptions.RealmMigrationNeededException Field 'agentId' does not support null values in the existing Realm file. Either set @Required, use the primitive type for field 'agentId' or migrate using RealmObjectSchema.setNullable(). How do I specify that the Long::class.java should be the nullable type in the migration code? A: Unfortunately, Long::class.java // kotlin is equivalent to long.class // java Long::class.javaPrimitiveType // kotlin But what you need to add for nullable Long in Realm is Long.class // java So you need to use Long::class.javaObjectType // Long.class In migration, you can turn a required field to nullable field using RealmObjectSchema.setNullable(String field, boolean nullable) method.
Q: How do I specify a boxed field can be nullable in my Realm migration code? I'm using Kotlin and I want to add a new field to a RealmObject and that field can be nullable. Here's what I have in my migration: val schema = realm.schema.get(ZOLA_NOTIFICATION) if (!(schema?.hasField("agentId") ?: false)) { schema.addField("agentId", Long::class.java) } However, I receive an error message when this migration is run: Non-fatal Exception: io.realm.exceptions.RealmMigrationNeededException Field 'agentId' does not support null values in the existing Realm file. Either set @Required, use the primitive type for field 'agentId' or migrate using RealmObjectSchema.setNullable(). How do I specify that the Long::class.java should be the nullable type in the migration code? A: Unfortunately, Long::class.java // kotlin is equivalent to long.class // java Long::class.javaPrimitiveType // kotlin But what you need to add for nullable Long in Realm is Long.class // java So you need to use Long::class.javaObjectType // Long.class In migration, you can turn a required field to nullable field using RealmObjectSchema.setNullable(String field, boolean nullable) method.
stackoverflow
{ "language": "en", "length": 165, "provenance": "stackexchange_0000F.jsonl.gz:842726", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473284" }
19dbb3b1010751a26636b242985fc30c6c97ac05
Stackoverflow Stackexchange Q: How to Store Array Data Using Ionic Native Storage? I'm planning to use ionic native storage to store some translation history, whenever there's a word being translated. The translation action (date, translate word) will be store in the ionic native storage, and when I open history page, a list of translation history will be shown. Here's the most basic code I got from the ionic official website: export class HomePage { DataArray: Array<string> = []; constructor(public navCtrl: NavController, private storage: Storage) { } // set a key/value setData(){ this.storage.set('age', 'Max'); } // Or to get a key/value pair getData(){ this.storage.get('age').then((val) => { console.log('Your age is', val); }); } } A: use getItem and SetItem export class HomePage { DataArray: Array<string> = []; constructor(public navCtrl: NavController, private storage: NativeStorage) { } // set a key/value setData(){ this.storage.setItem('keyOfData', JSON.stringify(DataArray)); } // Or to get a key/value pair getData(){ this.storage.getItem('keyOfData').then((val) => { console.log('Your age is', JSON.parse(val)); }); } } the refrence Ionic native storage
Q: How to Store Array Data Using Ionic Native Storage? I'm planning to use ionic native storage to store some translation history, whenever there's a word being translated. The translation action (date, translate word) will be store in the ionic native storage, and when I open history page, a list of translation history will be shown. Here's the most basic code I got from the ionic official website: export class HomePage { DataArray: Array<string> = []; constructor(public navCtrl: NavController, private storage: Storage) { } // set a key/value setData(){ this.storage.set('age', 'Max'); } // Or to get a key/value pair getData(){ this.storage.get('age').then((val) => { console.log('Your age is', val); }); } } A: use getItem and SetItem export class HomePage { DataArray: Array<string> = []; constructor(public navCtrl: NavController, private storage: NativeStorage) { } // set a key/value setData(){ this.storage.setItem('keyOfData', JSON.stringify(DataArray)); } // Or to get a key/value pair getData(){ this.storage.getItem('keyOfData').then((val) => { console.log('Your age is', JSON.parse(val)); }); } } the refrence Ionic native storage
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:842742", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473329" }
bb0d92ea9d8bbe50589fc3da9ff6b2c8497f8284
Stackoverflow Stackexchange Q: How to show significance stars in R Markdown (rmarkdown) html output notes? I want to show regression outputs in HTML documents using R Markdown. I tried the texreg and stargazerpackages. My problem is now, that in the notes I can't bring the significance stars to life. Due to automatic generation it seems I can't escape them. I've been puzzling around with this and this but with no success. What am I missing? Thanks a lot!! Here's some code: ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r data} library(car) lm1 <- lm(prestige ~ income + education, data=Duncan) ``` ## with STARGAZER ```{r table1, results = "asis", message=FALSE} library(stargazer) stargazer(lm1, type="html", notes="stargazer html 1") # nothing stargazer(lm1, type="html", notes="stargazer html 2", star.char = "\\*") # nothing, even gone in table ``` ## with TEXREG ```{r table2, results = "asis", message=FALSE} library(texreg) htmlreg(lm1, custom.note="%stars. htmlreg") # nothing htmlreg(lm1, custom.note="%stars. htmlreg", star.symbol = "\\*") # still nothing! ``` Note: Question was a former sub-question I have now splitted. A: Use the HTML entity for the asterisk: star.symbol='&#42;' See http://www.ascii.cl/htmlcodes.htm. You could also add the "legend" manually: stargazer(lm1, type="html", notes = "<em>&#42;p&lt;0.1;&#42;&#42;p&lt;0.05;&#42;&#42;&#42;p&lt;0.01</em>", notes.append = F)
Q: How to show significance stars in R Markdown (rmarkdown) html output notes? I want to show regression outputs in HTML documents using R Markdown. I tried the texreg and stargazerpackages. My problem is now, that in the notes I can't bring the significance stars to life. Due to automatic generation it seems I can't escape them. I've been puzzling around with this and this but with no success. What am I missing? Thanks a lot!! Here's some code: ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r data} library(car) lm1 <- lm(prestige ~ income + education, data=Duncan) ``` ## with STARGAZER ```{r table1, results = "asis", message=FALSE} library(stargazer) stargazer(lm1, type="html", notes="stargazer html 1") # nothing stargazer(lm1, type="html", notes="stargazer html 2", star.char = "\\*") # nothing, even gone in table ``` ## with TEXREG ```{r table2, results = "asis", message=FALSE} library(texreg) htmlreg(lm1, custom.note="%stars. htmlreg") # nothing htmlreg(lm1, custom.note="%stars. htmlreg", star.symbol = "\\*") # still nothing! ``` Note: Question was a former sub-question I have now splitted. A: Use the HTML entity for the asterisk: star.symbol='&#42;' See http://www.ascii.cl/htmlcodes.htm. You could also add the "legend" manually: stargazer(lm1, type="html", notes = "<em>&#42;p&lt;0.1;&#42;&#42;p&lt;0.05;&#42;&#42;&#42;p&lt;0.01</em>", notes.append = F)
stackoverflow
{ "language": "en", "length": 191, "provenance": "stackexchange_0000F.jsonl.gz:842753", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473379" }
e58c9f1a5385da5d176189d540a4c4b2b77dcc97
Stackoverflow Stackexchange Q: How to Change Selected Radio Button Symbol ("X") in Completed Docusign document After completed signing the document.Selected radio buttons and checkboxes are shown as "X" in the completed document.Can we change this "X" symbol to tick mark or something else.Kindly find the Image attached. A: There is no option in DoucSign to customize how the checked radio buttons appears. Also note that, once a document has been signed no changes can be made to it.
Q: How to Change Selected Radio Button Symbol ("X") in Completed Docusign document After completed signing the document.Selected radio buttons and checkboxes are shown as "X" in the completed document.Can we change this "X" symbol to tick mark or something else.Kindly find the Image attached. A: There is no option in DoucSign to customize how the checked radio buttons appears. Also note that, once a document has been signed no changes can be made to it.
stackoverflow
{ "language": "en", "length": 76, "provenance": "stackexchange_0000F.jsonl.gz:842786", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473480" }
43097e9af398f856c218e93a525fb7e6176c7756
Stackoverflow Stackexchange Q: Firebase No properties to serialize found with object in release mode I've written a method for pushing real-time location data to Firebase: private void writeNewMarker(int sessionType, String myUuid, String datetime, Location location) { locationToDB = new LocationFromAndroid(); JSONObject jsonObjectCoords = new Coords(location.getLatitude() + "", location.getLongitude() + "", location.getAltitude() + ""); locationToDB.setFinish("false"); locationToDB.setLost("false"); locationToDB.setCoords(jsonObjectCoords); locationToDB.setDistanceToGo("0"); locationToDB.setHeading(location.getBearing() + ""); locationToDB.setNauwkeurigheid(location.getAccuracy() + ""); locationToDB.setSpeed(location.getSpeed() * 3.6 + ""); locationToDB.setSpeed2(location.getSpeed() + ""); locationToDB.setTimestamp(location.getTime() + ""); locationToDB.setWp_user(myUuid); locationToDB.setSessionType(sessionType); locationToDB.setTitle(title); if(myUuid != null && datetime != null && locationToDB.getTitle() != null && !myUuid.isEmpty() && !datetime.isEmpty()) { databaseRef.child(myUuid + "-Android" + sessionType + datetime).setValue(locationToDB); When I'm building the app in debug mode, it works perfectly fine. But when I'm building it in Release mode for Google Play, it stops working at this line: databaseRef.child(myUuid + "-Android" + sessionType + datetime).setValue(locationToDB); To be more specific: When I'm doing this, everything is OK: databaseRef.child(myUuid + "-Android" + sessionType + datetime).setValue("Test"); It does look like passing an object as value isn't possible within a signed APK? Error: Exception com.google.firebase.database.DatabaseException: No properties to serialize found on class A: Adding -keepclassmembers class com.yourcompany.models.** { *; } in proguard-rules.pro did the trick. Proguard Rules Documentation
Q: Firebase No properties to serialize found with object in release mode I've written a method for pushing real-time location data to Firebase: private void writeNewMarker(int sessionType, String myUuid, String datetime, Location location) { locationToDB = new LocationFromAndroid(); JSONObject jsonObjectCoords = new Coords(location.getLatitude() + "", location.getLongitude() + "", location.getAltitude() + ""); locationToDB.setFinish("false"); locationToDB.setLost("false"); locationToDB.setCoords(jsonObjectCoords); locationToDB.setDistanceToGo("0"); locationToDB.setHeading(location.getBearing() + ""); locationToDB.setNauwkeurigheid(location.getAccuracy() + ""); locationToDB.setSpeed(location.getSpeed() * 3.6 + ""); locationToDB.setSpeed2(location.getSpeed() + ""); locationToDB.setTimestamp(location.getTime() + ""); locationToDB.setWp_user(myUuid); locationToDB.setSessionType(sessionType); locationToDB.setTitle(title); if(myUuid != null && datetime != null && locationToDB.getTitle() != null && !myUuid.isEmpty() && !datetime.isEmpty()) { databaseRef.child(myUuid + "-Android" + sessionType + datetime).setValue(locationToDB); When I'm building the app in debug mode, it works perfectly fine. But when I'm building it in Release mode for Google Play, it stops working at this line: databaseRef.child(myUuid + "-Android" + sessionType + datetime).setValue(locationToDB); To be more specific: When I'm doing this, everything is OK: databaseRef.child(myUuid + "-Android" + sessionType + datetime).setValue("Test"); It does look like passing an object as value isn't possible within a signed APK? Error: Exception com.google.firebase.database.DatabaseException: No properties to serialize found on class A: Adding -keepclassmembers class com.yourcompany.models.** { *; } in proguard-rules.pro did the trick. Proguard Rules Documentation
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:842790", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473498" }
880f2081b3f8ce4ac9200f7816bc53fe7f26f6bf
Stackoverflow Stackexchange Q: asp.net core Cannot resolve TagHelper containing assembly I created TagHelper namespace is SomeName.Framework.TagHelpers class name ValidationTagHelper I'm registered my TagHelper in _ViewImports in project SomeName.Web @using SomeName.Framework.TagHelpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, SomeName.Framework.TagHelpers But still get error Cannot resolve TagHelper containing assembly 'SomeName.Framework.TagHelpers'. Error: Could not load file or assembly 'SomeName.Framework.TagHelpers, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified. Also I try @addTagHelper "*, SomeName.Framework.TagHelpers" A: In such cases, you need to specify folder, not assembly. For example, if project is in "proj-name/src/proj-name.csproj", then correct directive is @addTagHelper "*, proj-name" regardless of your namespace.
Q: asp.net core Cannot resolve TagHelper containing assembly I created TagHelper namespace is SomeName.Framework.TagHelpers class name ValidationTagHelper I'm registered my TagHelper in _ViewImports in project SomeName.Web @using SomeName.Framework.TagHelpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, SomeName.Framework.TagHelpers But still get error Cannot resolve TagHelper containing assembly 'SomeName.Framework.TagHelpers'. Error: Could not load file or assembly 'SomeName.Framework.TagHelpers, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified. Also I try @addTagHelper "*, SomeName.Framework.TagHelpers" A: In such cases, you need to specify folder, not assembly. For example, if project is in "proj-name/src/proj-name.csproj", then correct directive is @addTagHelper "*, proj-name" regardless of your namespace.
stackoverflow
{ "language": "en", "length": 96, "provenance": "stackexchange_0000F.jsonl.gz:842795", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473515" }
4fd7f8789d6f4dfd3fb0ecca52f2045d27868bbb
Stackoverflow Stackexchange Q: Java access static nested class How can i create a instance of the following Class and access its methods. Example: public class A { public static class B { public static class C { public static class D { public static class E { public void methodA() {} public void methodB(){} } } } } } A: You can use : A.B.C.D.E e = new A.B.C.D.E();//create an instance of class E e.methodA();//call methodA e.methodB();//call methodB Or like @Andreas mention in comment you can use import A.B.C.D.E;, so if your class is in another packager then you can call your class using name_of_package.A.B.C.D.E like this: import com.test.A.B.C.D.E; // ^^^^^^^^------------------------name of package public class Test { public static void main(String[] args) { E e = new E(); e.methodA(); e.methodB(); } }
Q: Java access static nested class How can i create a instance of the following Class and access its methods. Example: public class A { public static class B { public static class C { public static class D { public static class E { public void methodA() {} public void methodB(){} } } } } } A: You can use : A.B.C.D.E e = new A.B.C.D.E();//create an instance of class E e.methodA();//call methodA e.methodB();//call methodB Or like @Andreas mention in comment you can use import A.B.C.D.E;, so if your class is in another packager then you can call your class using name_of_package.A.B.C.D.E like this: import com.test.A.B.C.D.E; // ^^^^^^^^------------------------name of package public class Test { public static void main(String[] args) { E e = new E(); e.methodA(); e.methodB(); } }
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:842805", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473529" }
6ee4199890253808d468051a451e85a043773f78
Stackoverflow Stackexchange Q: Merging host and container volume contents in docker I have a project with a docker image whose volume contains contents on start up. Are there any methods to MERGE the contents of both host and container on the volume yet keep the host contents persistent over in the container? this is my compose.yml services: db: image: mysql environment: MYSQL_DATABASE: ninja MYSQL_ROOT_PASSWORD: pwd app: image: invoiceninja/invoiceninja volumes: - ./install-wipay.sh:/install-wipay.sh - ./composer.json:/var/www/app/composer.json # would like to merge and persist this volume - ~/Documents/Git/heroku/invoiceninja/app/:/var/www/app - ~/Documents/Git/omnipay-wipay/:/var/repo/omnipay-wipay/:ro - ./.env:/var/www/app/.env:ro - ./storage:/var/www/app/docker-backup-storage:rw - ./logo:/var/www/app/docker-backup-public/logo/ links: - db:mysql env_file: .env web: image: nginx volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro
Q: Merging host and container volume contents in docker I have a project with a docker image whose volume contains contents on start up. Are there any methods to MERGE the contents of both host and container on the volume yet keep the host contents persistent over in the container? this is my compose.yml services: db: image: mysql environment: MYSQL_DATABASE: ninja MYSQL_ROOT_PASSWORD: pwd app: image: invoiceninja/invoiceninja volumes: - ./install-wipay.sh:/install-wipay.sh - ./composer.json:/var/www/app/composer.json # would like to merge and persist this volume - ~/Documents/Git/heroku/invoiceninja/app/:/var/www/app - ~/Documents/Git/omnipay-wipay/:/var/repo/omnipay-wipay/:ro - ./.env:/var/www/app/.env:ro - ./storage:/var/www/app/docker-backup-storage:rw - ./logo:/var/www/app/docker-backup-public/logo/ links: - db:mysql env_file: .env web: image: nginx volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro
stackoverflow
{ "language": "en", "length": 101, "provenance": "stackexchange_0000F.jsonl.gz:842807", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473532" }
e03ab63d3692a26ea66ff633ad3de7a4c5ecc42f
Stackoverflow Stackexchange Q: rest api to trigger a concourse pipeline/job I am able to use the below code to do a get request on the concourse api to fetch the pipeline build details. However post request to trigger the pipeline build does not work and no error is reported . Here is the code url = "http://192.168.100.4:8080/api/v1/teams/main/" r = requests.get(url + 'auth/token') json_data = json.loads(r.text) cookie = {'ATC-Authorization': 'Bearer '+ json_data["value"]} r = requests.post(url + 'pipelines/pipe-name/jobs/job-name/builds' , cookies=cookie) print r.text print r.content r = requests.get(url + 'pipelines/pipe-name/jobs/job-name/builds/17', cookies=cookie) print r.text A: You may use Session : [...] The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance [...] url = "http://192.168.100.4:8080/api/v1/teams/main/" req_sessions = requests.Session() #load session instance r = req_sessions.get(url + 'auth/token') json_data = json.loads(r.text) cookie = {'ATC-Authorization': 'Bearer '+ json_data["value"]} r = req_sessions.post(url + 'pipelines/pipe-name/jobs/job-name/builds', cookies=cookie) print r.text print r.content r = req_sessions.get(url + 'pipelines/pipe-name/jobs/job-name/builds/17') print r.text
Q: rest api to trigger a concourse pipeline/job I am able to use the below code to do a get request on the concourse api to fetch the pipeline build details. However post request to trigger the pipeline build does not work and no error is reported . Here is the code url = "http://192.168.100.4:8080/api/v1/teams/main/" r = requests.get(url + 'auth/token') json_data = json.loads(r.text) cookie = {'ATC-Authorization': 'Bearer '+ json_data["value"]} r = requests.post(url + 'pipelines/pipe-name/jobs/job-name/builds' , cookies=cookie) print r.text print r.content r = requests.get(url + 'pipelines/pipe-name/jobs/job-name/builds/17', cookies=cookie) print r.text A: You may use Session : [...] The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance [...] url = "http://192.168.100.4:8080/api/v1/teams/main/" req_sessions = requests.Session() #load session instance r = req_sessions.get(url + 'auth/token') json_data = json.loads(r.text) cookie = {'ATC-Authorization': 'Bearer '+ json_data["value"]} r = req_sessions.post(url + 'pipelines/pipe-name/jobs/job-name/builds', cookies=cookie) print r.text print r.content r = req_sessions.get(url + 'pipelines/pipe-name/jobs/job-name/builds/17') print r.text
stackoverflow
{ "language": "en", "length": 159, "provenance": "stackexchange_0000F.jsonl.gz:842810", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473538" }
5c38bb6fffeb823de57d69cad3ddcb011f9eb672
Stackoverflow Stackexchange Q: How to create a diagonal background effect, using CSS Is it possible to create the effect shown in the following image, using CSS? Basically I want to create <div>s that have a background split diagonally with a block color on side and white on the other? A: You can use linear-gradient on background. See the following example: body { height:100vh; width:100vw; background:linear-gradient(160deg, red, red 60%, white 60%, white); }
Q: How to create a diagonal background effect, using CSS Is it possible to create the effect shown in the following image, using CSS? Basically I want to create <div>s that have a background split diagonally with a block color on side and white on the other? A: You can use linear-gradient on background. See the following example: body { height:100vh; width:100vw; background:linear-gradient(160deg, red, red 60%, white 60%, white); }
stackoverflow
{ "language": "en", "length": 70, "provenance": "stackexchange_0000F.jsonl.gz:842838", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473615" }
6802985086f559f1d9ecf3ebbd6c8be861c64e4a
Stackoverflow Stackexchange Q: Laravel 5.4: How do I get records from just this week? To get all records of the current day, I did $dt = Carbon::now(); $dataToday = Data::whereDay('created_at', $dt->day)->get(); To get records from this week, I tried the following but without success. $dataThisWeek = Data::where('created_at', $dt->weekOfYear); $dataThisWeek = Data::where('created_at', $dt->weekOfMonth); $dataThisWeek = Data::whereWeek('created_at', $dt->week); How do we approach this with Eloquent and Carbon (preferably) or a native MYSQL function? A: You can also try $dataThisWeek = Data::where(\DB::raw("WEEKOFYEAR(created_at)"), $dt->weekOfYear)->get();
Q: Laravel 5.4: How do I get records from just this week? To get all records of the current day, I did $dt = Carbon::now(); $dataToday = Data::whereDay('created_at', $dt->day)->get(); To get records from this week, I tried the following but without success. $dataThisWeek = Data::where('created_at', $dt->weekOfYear); $dataThisWeek = Data::where('created_at', $dt->weekOfMonth); $dataThisWeek = Data::whereWeek('created_at', $dt->week); How do we approach this with Eloquent and Carbon (preferably) or a native MYSQL function? A: You can also try $dataThisWeek = Data::where(\DB::raw("WEEKOFYEAR(created_at)"), $dt->weekOfYear)->get(); A: Try this: Data::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get(); To set the week start/end: Carbon::setWeekStartsAt(Carbon::SUNDAY); Carbon::setWeekEndsAt(Carbon::SATURDAY); A: For some reason using Laravel 7.4^ the accepted solution above is not working on my end. No data is shown, to fix it I added a format like this: $now = Carbon::now(); Data::whereBetween("created_at", [ $now->startOfWeek()->format('Y-m-d'), //This will return date in format like this: 2022-01-10 $now->endOfWeek()->format('Y-m-d') ])->get(); A: To complete @user320487 answer: To avoid conflict between different third-party libraries, static setters should not be used. Use $weekEndsAt optional parameter instead when using endOfWeek method. Data::whereBetween('created_at', [Carbon::now()->startOfWeek(Carbon::SUNDAY), Carbon::now()->endOfWeek(Carbon::SATURDAY)])->get(); You can also use the 'first_day_of_week' locale setting to change the start of week according to current locale selected and implicitly the end of week.
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:842861", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473685" }
2a4f7e31b149a2d865fd67f18672e24a00bf0751
Stackoverflow Stackexchange Q: BATCH | echo multiple variables to file Directory contains 2 (or more) video files with any random names. video1.mkv video2.mkv Need to find out duration of every video. To do that we use MediaInfo. setlocal EnableDelayedExpansion for %%a in (*.mkv) do ( for /f "usebackq" %%a in (`"mediainfo --Inform=Video;%%Duration%% %%a"`) do set duration=%%a echo "!duration!" > "data.txt" ) Problem is, it prints only 1 value/duration (I think for last file). It works, buy only for one file. How do I make it work with all files present in directory? A: just use >> instead of >, which appends instead of overriding setlocal EnableDelayedExpansion for %%a in (*.mkv) do ( for /f "usebackq" %%a in (`"mediainfo --Inform=Video;%%Duration%% %%a"`) do set duration=%%a echo "!duration!" >> "data.txt" )
Q: BATCH | echo multiple variables to file Directory contains 2 (or more) video files with any random names. video1.mkv video2.mkv Need to find out duration of every video. To do that we use MediaInfo. setlocal EnableDelayedExpansion for %%a in (*.mkv) do ( for /f "usebackq" %%a in (`"mediainfo --Inform=Video;%%Duration%% %%a"`) do set duration=%%a echo "!duration!" > "data.txt" ) Problem is, it prints only 1 value/duration (I think for last file). It works, buy only for one file. How do I make it work with all files present in directory? A: just use >> instead of >, which appends instead of overriding setlocal EnableDelayedExpansion for %%a in (*.mkv) do ( for /f "usebackq" %%a in (`"mediainfo --Inform=Video;%%Duration%% %%a"`) do set duration=%%a echo "!duration!" >> "data.txt" ) A: If mediainfo.exe is somewhere in the path this name doesn't need to be quoted, but as the .mkv file names most likely do contain spaces change the quoting like this: @Echo off&SetLocal EnableExtensions EnableDelayedExpansion ( For %%a in (*.mkv) do ( Set "Duration=" For /f "delims=" %%b in ( 'mediainfo --Inform^=Video^;%%Duration%% "%%a"' ) do set "Duration=%%b" echo !Duration!,"%%a" ) ) > "data.txt" It isn't of much use to have the duration without knowing which file it belongs to, so this sample run with *.mpg files has the file name appended. 2595000,"R:\video\Der Traum ihres Lebens - Das Erste 2010-07-09 20-15-00.mpg" 5333160,"R:\video\Dirty Harry 3 - Der Unerbittliche - RTL2 2010-05-29 00-10-00.mpg" 5651960,"R:\video\Die Spur des Falken - Das Erste 2010-05-28 00-40-00.mpg" A: as long as MediaInfo is in %Path% the way I have been doing this is by the use of a temp text file. for %%a in (*.mkv) do set mkv=%%a&& call :one goto eof :one mediainfo "--Inform=General;%%Duration%%" "%mkv%" >> filetemp.txt set /p dur= < filetemp.txt echo %dur% pause del filetemp.txt :eof I use a variation of this to encode my TV shows with ffmpeg, using MediaInfo to get the duration, framerate, and frame height, from 1-15 shows I have recorded over the week.
stackoverflow
{ "language": "en", "length": 329, "provenance": "stackexchange_0000F.jsonl.gz:842890", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473793" }
45aac3861c5198996050c3279d24c27e14893cf4
Stackoverflow Stackexchange Q: Laravel collection where clause Is possible in Laravel apply where condition to a collection and the result of that put in another collection without change the first one? Ex: $documenti = DB::table("RVW_DocumentiDettaglio") ->select("*") ->where("IDAzienda", "=", $request->session()->get("operatore.IDAzienda")) ->whereIn("CodiceStato", [Documento::E_DOC, Documento::W_DOC, Documento::OK_DOC]) ->orderBy("IDDocumentoTestata", "asc"); // Ciclo le voci spesa foreach ($voci_spesa as $voce_spesa) { Log_Controller::debug("Documenti:" . $documenti->get()); if ($voce_spesa["Manuale"]) { $dettaglio = $documenti->where("Descrizione", "like", "%" . $voce_spesa["Descrizione"] . "%"); } else { $dettaglio = $documenti->where("Descrizione", "=", $voce_spesa["Descrizione"]); } Log_Controller::debug("Dettaglio:" . $dettaglio->get()); } die; With $documenti I get the first collection, in the foreach I apply the where condition and put the result to $dettaglio collection, but the first one ($documenti) was also changed. Why? It's like shared object A: You can certainly apply where clauses to Collections along with a good number of other methods including filtering and mapping. See the documentation here: Collections where clauses $collection = Item::all(); $filtered = $collection->where('price', 100); $filtered->all();
Q: Laravel collection where clause Is possible in Laravel apply where condition to a collection and the result of that put in another collection without change the first one? Ex: $documenti = DB::table("RVW_DocumentiDettaglio") ->select("*") ->where("IDAzienda", "=", $request->session()->get("operatore.IDAzienda")) ->whereIn("CodiceStato", [Documento::E_DOC, Documento::W_DOC, Documento::OK_DOC]) ->orderBy("IDDocumentoTestata", "asc"); // Ciclo le voci spesa foreach ($voci_spesa as $voce_spesa) { Log_Controller::debug("Documenti:" . $documenti->get()); if ($voce_spesa["Manuale"]) { $dettaglio = $documenti->where("Descrizione", "like", "%" . $voce_spesa["Descrizione"] . "%"); } else { $dettaglio = $documenti->where("Descrizione", "=", $voce_spesa["Descrizione"]); } Log_Controller::debug("Dettaglio:" . $dettaglio->get()); } die; With $documenti I get the first collection, in the foreach I apply the where condition and put the result to $dettaglio collection, but the first one ($documenti) was also changed. Why? It's like shared object A: You can certainly apply where clauses to Collections along with a good number of other methods including filtering and mapping. See the documentation here: Collections where clauses $collection = Item::all(); $filtered = $collection->where('price', 100); $filtered->all();
stackoverflow
{ "language": "en", "length": 153, "provenance": "stackexchange_0000F.jsonl.gz:842927", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473906" }
9363ae0e7f76d2ce4bcdebe0b0a153751fb2bbd0
Stackoverflow Stackexchange Q: Xcode 9 doesn't have any simulator device I just downloaded xcode 9 beta, but there is no simulator within it. Try to add new simulator but the create button doesn't work. Please help By "no simulator within it" I mean there is option to build with simulator. See . Also, the create button doesn't work A: It is a simulator but you need to close Xcode 8 if you have it open and restart Xcode 9 beta.
Q: Xcode 9 doesn't have any simulator device I just downloaded xcode 9 beta, but there is no simulator within it. Try to add new simulator but the create button doesn't work. Please help By "no simulator within it" I mean there is option to build with simulator. See . Also, the create button doesn't work A: It is a simulator but you need to close Xcode 8 if you have it open and restart Xcode 9 beta. A: This may happen due to multiple Xcode installed on machine or might be the deployment target is higher than the simulator OS version. In order to resolve this navigate to following location : Xcode > Preference > location > comindline Tool > change the xcode version and decrease the deployment target. A: You may have removed iOS Simulators when you cleaned up disk space. I think I may have used DaisyDisk to remove files when I ran out of space. You can re-add simulators using the Devices & Simulators window. (Shift + Command + 2) A: Go to Xcode Preferences -> Locations and go to the Derived Data location in Finder: Just remove all contents from it, then right click on Xcode icon and quit it, and reopen it: A: Delete the derived data, close all your running Xcodes and restart your computer. It just helped me. A: Apart from the simulators not showing, my project's storyboard was messed up also after upgrading to XCode 9. I simply restarted XCode and voila! Did not have to delete derived files - though it would probably not hurt. A: You can do the same that @badhan-ganesh suggests (cleaning derived data) using the Xcode keyboard shortcut to clean derived data: shift+alt+cmd+k If needed, you can clean the project using Xcode keyboard shortcut: shift+cmd+k After that, restart Xcode and simulators should be available again. A: Having a higher deployment target than what is installed on your simualtors also causes this. A: Ensure your Deployment Target version in Build Settings is also set to the desired version (and that you have that version of the respective simulator installed). Suppose, if that were set to 10.3 and I didn’t have an iOS 10.3 simulator installed, I wouldn’t be able to see any simulators. But because it’s set to 10.1, and I have 10.1 simulators installed, I can see them. A: When my xcode updated to 9.4 I face the same problem at first time. After force quit and start again solve the problem for me. A: If you upgraded Xcode then follow the steps * *Delete derived data, Xcode-> Preferences -> Locations and select arrow symbol just before Advance button -> select all files and delete. *Quit Xcode *Quit Xcode from Dock *Open Xcode again. :-) Hope this will help you. A: I have Xcode 8.3 and Xcode 9.1, I came to this post to find a solution to missing simulators after forced upgrade to 9.1... I was about to do the suggestion to remove the entire DerivedData directory, lucky closing Xcode 9.1 and restarting it worked. Moreover, I had to close all simulator(s). I had to rebuild app apps on simulator again.
stackoverflow
{ "language": "en", "length": 526, "provenance": "stackexchange_0000F.jsonl.gz:842931", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44473923" }
84d11181acb0b80dfd806d1be3c3a2fa755cd097
Stackoverflow Stackexchange Q: mapStateToProps not getting called at all I am trying to create a container which is subscribed to the store using mapStateToProps. I am able to change the state using reducers in this fashion export default function firstReducer(state={}, action) { switch(action.type){ case 'ADD_USERNAME': return Object.assign({}, state, { username: action.payload }); default: return state; } } However, mapStateToProps is not getting called even once. Where am I going wrong export default class myComponent extends React.Component{ render(){ return( <h1>this.props.userName</h1> ) } } function mapStateToProps(state){ console.log("Hey"); return{ userName: state.username }; } export const myContainer = connect(mapStateToProps, null)(myComponent); A: Two things that you need to take care of First have you component name not being with Uppercase letter and second remove the export default from the component, otherwise when you will be importing it as default you wouldn't be using the component that you have connected the store with class MyComponent extends React.Component{ render(){ return( <h1>this.props.userName</h1> ) } } function mapStateToProps(state){ console.log("Hey"); return{ userName: state.username }; } export default connect(mapStateToProps, null)(MyComponent);
Q: mapStateToProps not getting called at all I am trying to create a container which is subscribed to the store using mapStateToProps. I am able to change the state using reducers in this fashion export default function firstReducer(state={}, action) { switch(action.type){ case 'ADD_USERNAME': return Object.assign({}, state, { username: action.payload }); default: return state; } } However, mapStateToProps is not getting called even once. Where am I going wrong export default class myComponent extends React.Component{ render(){ return( <h1>this.props.userName</h1> ) } } function mapStateToProps(state){ console.log("Hey"); return{ userName: state.username }; } export const myContainer = connect(mapStateToProps, null)(myComponent); A: Two things that you need to take care of First have you component name not being with Uppercase letter and second remove the export default from the component, otherwise when you will be importing it as default you wouldn't be using the component that you have connected the store with class MyComponent extends React.Component{ render(){ return( <h1>this.props.userName</h1> ) } } function mapStateToProps(state){ console.log("Hey"); return{ userName: state.username }; } export default connect(mapStateToProps, null)(MyComponent);
stackoverflow
{ "language": "en", "length": 167, "provenance": "stackexchange_0000F.jsonl.gz:842956", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474031" }
637021009342058f3aab45b5f8b37d8197193f7b
Stackoverflow Stackexchange Q: PowerShell PSScriptRoot is null When I run $PSScriptRoot it returns null. I am using PS version 4. $val = Join-Path -Path $PSScriptRoot WebPlatformInstaller_amd64_en-US.msi Error Join-Path : Cannot bind argument to parameter 'Path' because it is an empty string. A: If using ISE use: $psISE.CurrentFile.FullPath When ISE is launched, $psISE is created and can be used to determine the current path of the ISE instance. This was introduced in version 3.0. See ISE Object Model Hierarchy If you wanted to get the path in either shell or ISE you could use something like this: if ($psISE) { Split-Path -Path $psISE.CurrentFile.FullPath } else { $global:PSScriptRoot }
Q: PowerShell PSScriptRoot is null When I run $PSScriptRoot it returns null. I am using PS version 4. $val = Join-Path -Path $PSScriptRoot WebPlatformInstaller_amd64_en-US.msi Error Join-Path : Cannot bind argument to parameter 'Path' because it is an empty string. A: If using ISE use: $psISE.CurrentFile.FullPath When ISE is launched, $psISE is created and can be used to determine the current path of the ISE instance. This was introduced in version 3.0. See ISE Object Model Hierarchy If you wanted to get the path in either shell or ISE you could use something like this: if ($psISE) { Split-Path -Path $psISE.CurrentFile.FullPath } else { $global:PSScriptRoot } A: You can use $PWD.Path It works in PowerShell ISE and Powershell Console. It returns the Present Working Directory. $PSScriptRoot is the Root Path of where the current script is saved. When used in a command it will return blank as there is no script who's current path you are looking for. A: You have to make sure that this expression is in a saved .ps1 script. This can happened in following cases: * *You use this statement in PowerShell ISE console *You use this statement in PowerShell console without a script file *You marked only this expression for execution in PowerShell ISE
stackoverflow
{ "language": "en", "length": 208, "provenance": "stackexchange_0000F.jsonl.gz:842969", "question_score": "24", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474074" }
fbccb04445ae271976c3ec23f3f32a319adf379f
Stackoverflow Stackexchange Q: How to Retrieve the Definitions of a Word from WordNet I was trying to find a way to get just the definition(s) of a given word from WordNet from NLTK. I tried the following code, but I got an error saying 'WordNetCorpusReader' object has no attribute 'definition': from nltk.corpus import wordnet definition = wordnet.definition('game') print(definition) I tried to look in many books but found no relevant information. A: Looking at https://pythonprogramming.net/wordnet-nltk-tutorial/, I think the answer would be: from nltk.corpus import wordnet syns = wordnet.synsets("game") print(syns[0].definition())
Q: How to Retrieve the Definitions of a Word from WordNet I was trying to find a way to get just the definition(s) of a given word from WordNet from NLTK. I tried the following code, but I got an error saying 'WordNetCorpusReader' object has no attribute 'definition': from nltk.corpus import wordnet definition = wordnet.definition('game') print(definition) I tried to look in many books but found no relevant information. A: Looking at https://pythonprogramming.net/wordnet-nltk-tutorial/, I think the answer would be: from nltk.corpus import wordnet syns = wordnet.synsets("game") print(syns[0].definition())
stackoverflow
{ "language": "en", "length": 86, "provenance": "stackexchange_0000F.jsonl.gz:842972", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474077" }
e77d87d0861cc8d1229842bb045d78d8d16cdb7d
Stackoverflow Stackexchange Q: Extract only text in Hindi from a file containing both Hindi and English I have a file containing lines like ted 1-1 1.0 politicians do not have permission to do what needs to be done. राजनीतिज्ञों के पास जो कार्य करना चाहिए, वह करने कि अनुमति नहीं है. I have to write a program which reads the file line by line and gives the output in a file containing only the Hindi part. Here the first word indicates the source of the last two segments. Also, the last two sentences are translations of each other. Basically, I am trying to create a parallel corpus out of this file. A: you can do this by checking Unicode character. import codecs,string def detect_language(character): maxchar = max(character) if u'\u0900' <= maxchar <= u'\u097f': return 'hindi' with codecs.open('letter.txt', encoding='utf-8') as f: input = f.read() for i in input: isEng = detect_language(i) if isEng == "hindi": #Hindi Character #add this to another file print(i,end="\t") print(isEng) Hope this helps
Q: Extract only text in Hindi from a file containing both Hindi and English I have a file containing lines like ted 1-1 1.0 politicians do not have permission to do what needs to be done. राजनीतिज्ञों के पास जो कार्य करना चाहिए, वह करने कि अनुमति नहीं है. I have to write a program which reads the file line by line and gives the output in a file containing only the Hindi part. Here the first word indicates the source of the last two segments. Also, the last two sentences are translations of each other. Basically, I am trying to create a parallel corpus out of this file. A: you can do this by checking Unicode character. import codecs,string def detect_language(character): maxchar = max(character) if u'\u0900' <= maxchar <= u'\u097f': return 'hindi' with codecs.open('letter.txt', encoding='utf-8') as f: input = f.read() for i in input: isEng = detect_language(i) if isEng == "hindi": #Hindi Character #add this to another file print(i,end="\t") print(isEng) Hope this helps A: Open two files—one for reading and the other for writing. Iterate over lines in your input file, using an if condition with a regex check to filter non-hindi lines, and write to the output file. import re hindi_lines = [] with open('in.txt', 'r') as f, open('out.txt', 'w') as f2: for line in f: if not (re.search(r'[a-zA-Z0-9]', line) or line.strip()): f2.write(line)
stackoverflow
{ "language": "en", "length": 225, "provenance": "stackexchange_0000F.jsonl.gz:842975", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474085" }
5a844d544cd7c495e6918cfb43323c0cc7b361d8
Stackoverflow Stackexchange Q: curl not downloading file inside container while building Below is my Dockerfile, no matter what option I attempted , react-dom.js file is not getting inside of the container at /app/js/ location. FROM resin/rpi-raspbian:wheezy ENV PYTHON_VERSION 2.7.13 # Install dependencies RUN apt-get update && \ apt-get -y install curl && \ apt-get -y install vim && \ apt-get -y install python2.7-minimal && \ apt-get -y install python-pip && \ apt-get -y install python-dev && \ apt-get -y install gcc && \ rm -rf /var/lib/apt/lists/* # RUN apt-get -y install vim RUN mkdir -p /app/js/ VOLUME ["/app/"] # Define working directory WORKDIR /app/ RUN curl -sf -o /app/js/react-dom.js -L https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js A: I have run your dockerfile, and it just works. I guess the image you used doesn't had quite recent ssl certificates bundle. The image you are using (resin/rpi-raspbian:wheezy) had plenty of release since you used it last time ! Just pull the new image and rebuild your container and you should be good !
Q: curl not downloading file inside container while building Below is my Dockerfile, no matter what option I attempted , react-dom.js file is not getting inside of the container at /app/js/ location. FROM resin/rpi-raspbian:wheezy ENV PYTHON_VERSION 2.7.13 # Install dependencies RUN apt-get update && \ apt-get -y install curl && \ apt-get -y install vim && \ apt-get -y install python2.7-minimal && \ apt-get -y install python-pip && \ apt-get -y install python-dev && \ apt-get -y install gcc && \ rm -rf /var/lib/apt/lists/* # RUN apt-get -y install vim RUN mkdir -p /app/js/ VOLUME ["/app/"] # Define working directory WORKDIR /app/ RUN curl -sf -o /app/js/react-dom.js -L https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js A: I have run your dockerfile, and it just works. I guess the image you used doesn't had quite recent ssl certificates bundle. The image you are using (resin/rpi-raspbian:wheezy) had plenty of release since you used it last time ! Just pull the new image and rebuild your container and you should be good ! A: I tried it out and It worked for me as well. If you are using docker-compose up and have a volume set to your local in the docker-compose.yml, then if you ssh into that container to list the directory, you will be staring at your local machine's directory. Your file would still be in the image though.
stackoverflow
{ "language": "en", "length": 222, "provenance": "stackexchange_0000F.jsonl.gz:843029", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474220" }
410daa49022666edfc014015683619b1cc1292be
Stackoverflow Stackexchange Q: osx mariaDB how to set max_allowed_packet I am trying to set 'max_allowed_packet' in 'my.cnf' which on my iMac is located in: /usr/local/etc/ I've tried: SET GLOBAL max_allowed_packet=1073741824; I've also tried adding a section: [mysqld] SET GLOBAL max_allowed_packet=1073741824; But neither have worked such that the setting is carried forward for reboots. If I open a terminal and enter: SET GLOBAL max_allowed_packet=1073741824; Directly into the terminal it works find, but isn't kept on reboot, how do I resolve this? A: The solution works when editing my.cnf, No need for SET GLOBAL prefix: [mysqld] max_allowed_packet=500M
Q: osx mariaDB how to set max_allowed_packet I am trying to set 'max_allowed_packet' in 'my.cnf' which on my iMac is located in: /usr/local/etc/ I've tried: SET GLOBAL max_allowed_packet=1073741824; I've also tried adding a section: [mysqld] SET GLOBAL max_allowed_packet=1073741824; But neither have worked such that the setting is carried forward for reboots. If I open a terminal and enter: SET GLOBAL max_allowed_packet=1073741824; Directly into the terminal it works find, but isn't kept on reboot, how do I resolve this? A: The solution works when editing my.cnf, No need for SET GLOBAL prefix: [mysqld] max_allowed_packet=500M
stackoverflow
{ "language": "en", "length": 93, "provenance": "stackexchange_0000F.jsonl.gz:843091", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474426" }
09eebda5091bf076cc038667f3a891a64269d196
Stackoverflow Stackexchange Q: Doctrine 2 - How to use the Time column type I am having a problem with Time column type : i have this part of my entity "Match" : /** * @ORM\Column(type="date") */ private $creationDate; /** * @ORM\Column(type="time",nullable=true) */ private $creationTime; And every time i try to persist the entity i get the error : Error: Call to a member function format() on string in TimeType.php This is the part where i fill the CreationTime : $time = date("H:i:s",strtotime(date("Y-m-d H:i:s"))); $Match->setCreationTime($time); I tried to check the TimeType.php file and i found out that this function is the source of the problem : public function convertToDatabaseValue($value, AbstractPlatform $platform) { return ($value !== null) ? $value->format($platform->getTimeFormatString()) : null; } to be more sure i checked the AbstractPlatform class and found out that the member method getTimeFormatString always returns this string : 'H:i:s'. So any body can help ? A: try to use this: $Match->setCreationTime(new \Datetime());
Q: Doctrine 2 - How to use the Time column type I am having a problem with Time column type : i have this part of my entity "Match" : /** * @ORM\Column(type="date") */ private $creationDate; /** * @ORM\Column(type="time",nullable=true) */ private $creationTime; And every time i try to persist the entity i get the error : Error: Call to a member function format() on string in TimeType.php This is the part where i fill the CreationTime : $time = date("H:i:s",strtotime(date("Y-m-d H:i:s"))); $Match->setCreationTime($time); I tried to check the TimeType.php file and i found out that this function is the source of the problem : public function convertToDatabaseValue($value, AbstractPlatform $platform) { return ($value !== null) ? $value->format($platform->getTimeFormatString()) : null; } to be more sure i checked the AbstractPlatform class and found out that the member method getTimeFormatString always returns this string : 'H:i:s'. So any body can help ? A: try to use this: $Match->setCreationTime(new \Datetime());
stackoverflow
{ "language": "en", "length": 154, "provenance": "stackexchange_0000F.jsonl.gz:843106", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474462" }
ce1be5e5b7dee4adce7caecd55e2bc9477e2ba60
Stackoverflow Stackexchange Q: How to create public and private key with openssl? My questions are * *How to create * *a public key *and private key with OpenSSL in windows? *How to put the created public key * *in .crt file and *the private one in .pcks8 file I want to use these two keys to sign a SAML assertion in Java. Thanks in advance. A: You can generate a public-private keypair with the genrsa context (the last number is the keylength in bits): openssl genrsa -out keypair.pem 2048 To extract the public part, use the rsa context: openssl rsa -in keypair.pem -pubout -out publickey.crt Finally, convert the original keypair to PKCS#8 format with the pkcs8 context: openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in keypair.pem -out pkcs8.key
Q: How to create public and private key with openssl? My questions are * *How to create * *a public key *and private key with OpenSSL in windows? *How to put the created public key * *in .crt file and *the private one in .pcks8 file I want to use these two keys to sign a SAML assertion in Java. Thanks in advance. A: You can generate a public-private keypair with the genrsa context (the last number is the keylength in bits): openssl genrsa -out keypair.pem 2048 To extract the public part, use the rsa context: openssl rsa -in keypair.pem -pubout -out publickey.crt Finally, convert the original keypair to PKCS#8 format with the pkcs8 context: openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in keypair.pem -out pkcs8.key
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:843120", "question_score": "53", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474516" }
17526baf453c8f2777ba601fefdd67c79f837d00
Stackoverflow Stackexchange Q: How to filter by item contained in a list in realm react native? I'm doing the following query: realm.objects('Maker').filtered("categories CONTAINS $0", categoryObject) But I'm getting this error: Only 'equal' and 'not equal' operators are supported for object comparison And here's my schema: { name: 'MakerOption', primaryKey: 'serverId', properties: { serverId: 'int', name: 'string', categories: {type: 'list', objectType: 'Category'}, } { name: 'Category', primaryKey: 'serverId', properties: { serverId: 'int', name: 'string' } The documentation is quite sparse on this subject. Is there an alternative method for doing this? A: Filtering by properties on linked or child objects can be done by specifying a keypath in the query e.g. car.color == 'blue' So you are looking for the following query: realm.objects('Maker').filtered("categories.serverId == $0", categoryObject.serverId)
Q: How to filter by item contained in a list in realm react native? I'm doing the following query: realm.objects('Maker').filtered("categories CONTAINS $0", categoryObject) But I'm getting this error: Only 'equal' and 'not equal' operators are supported for object comparison And here's my schema: { name: 'MakerOption', primaryKey: 'serverId', properties: { serverId: 'int', name: 'string', categories: {type: 'list', objectType: 'Category'}, } { name: 'Category', primaryKey: 'serverId', properties: { serverId: 'int', name: 'string' } The documentation is quite sparse on this subject. Is there an alternative method for doing this? A: Filtering by properties on linked or child objects can be done by specifying a keypath in the query e.g. car.color == 'blue' So you are looking for the following query: realm.objects('Maker').filtered("categories.serverId == $0", categoryObject.serverId)
stackoverflow
{ "language": "en", "length": 123, "provenance": "stackexchange_0000F.jsonl.gz:843152", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474621" }
939f9172c6090652064cfe4c4ef55a281b7f56c2
Stackoverflow Stackexchange Q: Pyopencl Enqueue Copy is too slow for large buffers Let us assume that I am executing this simple kernel: __kernel void sine(__global float *res){ int i = get_global_id(0); res[i] = sin((float)i); } So I am basically computing sine of n number of samples. I have a numpy empty array of float32 with shape n and a WRITE_ONLY buffer of the same size as the numpy array. Calling that kernel with n global size with the input buffer takes about 0.2ms for n=10000000, now, using Equeue Copy to copy the data from the buffer to the empty array takes about 100ms. My question is, is it normal to have this time? Is there is anyway to improve it?
Q: Pyopencl Enqueue Copy is too slow for large buffers Let us assume that I am executing this simple kernel: __kernel void sine(__global float *res){ int i = get_global_id(0); res[i] = sin((float)i); } So I am basically computing sine of n number of samples. I have a numpy empty array of float32 with shape n and a WRITE_ONLY buffer of the same size as the numpy array. Calling that kernel with n global size with the input buffer takes about 0.2ms for n=10000000, now, using Equeue Copy to copy the data from the buffer to the empty array takes about 100ms. My question is, is it normal to have this time? Is there is anyway to improve it?
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:843156", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474639" }
fbe911aa0dae8b192eb5971fc3ce189f442fbe85
Stackoverflow Stackexchange Q: Force show "Select deployment target" dialog Is there a way to force the "Select deployment target" dialog to show in Android Studio? Currently the only method I know is to hit stop to get the dialog again. But this produces weird workflows with a lot of overhead when developing an app that runs on >=2 devices and you need to jump between targets and do not want the other app to stop. Currently I am hitting stop and then open the app from the launcher and not android studio. But I find myself often reproducing a state which I already had before. I really hope there is a magic key-stroke I did not yet find to force show this dialog ..-) A: Ctrl + shift + f10 did the trick for me. Alternatively you can right-click on your main activity on the project pane on the left and select run MyActivity Or you can simply select more than one device in "Select deployment target" dialog using shift+click.
Q: Force show "Select deployment target" dialog Is there a way to force the "Select deployment target" dialog to show in Android Studio? Currently the only method I know is to hit stop to get the dialog again. But this produces weird workflows with a lot of overhead when developing an app that runs on >=2 devices and you need to jump between targets and do not want the other app to stop. Currently I am hitting stop and then open the app from the launcher and not android studio. But I find myself often reproducing a state which I already had before. I really hope there is a magic key-stroke I did not yet find to force show this dialog ..-) A: Ctrl + shift + f10 did the trick for me. Alternatively you can right-click on your main activity on the project pane on the left and select run MyActivity Or you can simply select more than one device in "Select deployment target" dialog using shift+click.
stackoverflow
{ "language": "en", "length": 168, "provenance": "stackexchange_0000F.jsonl.gz:843192", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474751" }
4be618c92abc9c4360b55b2bcc8d01f282d175b2
Stackoverflow Stackexchange Q: Is MySQL now() interval in milliseconds possible? I'm trying to only select the rows within 500 MS but I'm not sure if this is even possible with just MySQL? My current code is: $stmt = $mysqli->prepare('SELECT chat_user, chat_msg FROM chat_msg WHERE chat_id = ? AND chat_time > (NOW() - INTERVAL 1 SECOND) AND chat_user != ?'); I was unable to insert that in a code block. A: MySQL's DATE_SUB function (documentation here) accepts MICROSECOND as one of the interval type, so you can subtract 500 * 1000 microseconds and convert it into Timestamp, e.g.: $stmt = $mysqli->prepare('SELECT chat_user, chat_msg FROM chat_msg WHERE chat_id = ? AND chat_time > (NOW() - INTERVAL 500000 MICROSECOND) AND chat_user != ?'); If chat_time is of Timestamp type, you can use TIMESTAMP(NOW() - INTERVAL 500000 MICROSECOND); or UNIX_TIMESTAMP(NOW() - INTERVAL 500000 MICROSECOND); in the WHERE condition.
Q: Is MySQL now() interval in milliseconds possible? I'm trying to only select the rows within 500 MS but I'm not sure if this is even possible with just MySQL? My current code is: $stmt = $mysqli->prepare('SELECT chat_user, chat_msg FROM chat_msg WHERE chat_id = ? AND chat_time > (NOW() - INTERVAL 1 SECOND) AND chat_user != ?'); I was unable to insert that in a code block. A: MySQL's DATE_SUB function (documentation here) accepts MICROSECOND as one of the interval type, so you can subtract 500 * 1000 microseconds and convert it into Timestamp, e.g.: $stmt = $mysqli->prepare('SELECT chat_user, chat_msg FROM chat_msg WHERE chat_id = ? AND chat_time > (NOW() - INTERVAL 500000 MICROSECOND) AND chat_user != ?'); If chat_time is of Timestamp type, you can use TIMESTAMP(NOW() - INTERVAL 500000 MICROSECOND); or UNIX_TIMESTAMP(NOW() - INTERVAL 500000 MICROSECOND); in the WHERE condition. A: To convert and select time into milliseconds Use the UNIX_TIMESTAMP function. SELECT chat_user, chat_msg, (UNIX_TIMESTAMP(chat_time)*1000) As chattime FROM chat_msg UNIX_TIMESTAMP will get you seconds and you need to multiply by 1000 to get milliseconds.
stackoverflow
{ "language": "en", "length": 177, "provenance": "stackexchange_0000F.jsonl.gz:843195", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474758" }
77e1ab481a2c36fe57ff56bcc44d1fd906c32804
Stackoverflow Stackexchange Q: Capture variable from for-loop for using later in QPushButton Disclaimer: I've read other questions like this already (eg. this one) but didn't find a working solution for me yet (or I just don't understand them :)) When I create a lambda inside a for loop accessing data from the scope of the block I get a pylint warning (cell-var-from-loop) because of the way Python captures work. E.g: for key, value in data.items(): button = QtGui.QPushButton('show data') button.clicked.connect(lambda: show_data(value)) table_widget.setCellWidget(1, 1, button) There are more questions like this but I still don't now how I systematically solve this issue. I tried to provide default values to the lambda like suggested here: for key, value in data.items(): button = QtGui.QPushButton('show data') button.clicked.connect(lambda v=value: show_data(v)) table_widget.setCellWidget(1, 1, button) But when I do it like this weird things happen - while value ought to be a string in my example show_data is being called with a bool. Am I doing something totally wrong? Should this approach work? A: The clicked signal sends a checked parameter. So try: button.clicked.connect(lambda checked, v=value: show_data(v))
Q: Capture variable from for-loop for using later in QPushButton Disclaimer: I've read other questions like this already (eg. this one) but didn't find a working solution for me yet (or I just don't understand them :)) When I create a lambda inside a for loop accessing data from the scope of the block I get a pylint warning (cell-var-from-loop) because of the way Python captures work. E.g: for key, value in data.items(): button = QtGui.QPushButton('show data') button.clicked.connect(lambda: show_data(value)) table_widget.setCellWidget(1, 1, button) There are more questions like this but I still don't now how I systematically solve this issue. I tried to provide default values to the lambda like suggested here: for key, value in data.items(): button = QtGui.QPushButton('show data') button.clicked.connect(lambda v=value: show_data(v)) table_widget.setCellWidget(1, 1, button) But when I do it like this weird things happen - while value ought to be a string in my example show_data is being called with a bool. Am I doing something totally wrong? Should this approach work? A: The clicked signal sends a checked parameter. So try: button.clicked.connect(lambda checked, v=value: show_data(v))
stackoverflow
{ "language": "en", "length": 178, "provenance": "stackexchange_0000F.jsonl.gz:843212", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474805" }
d3d806792a580f98ec267dbc1b52363e34d2ae43
Stackoverflow Stackexchange Q: Get a Enum with a string in Swift I want to get the value from an enum after the user selected 'action' in a picker view. So I have as string: selectedGenre = "action". How can I get "28" from the case? public enum MovieGenres: String { case action = "28" case adventure = "12" case animation = "16" ... } I need to have something like this: MoveGenres.("selectedgenre").rawValue A: You can use the rawValue to get the Strings: MovieGenres.Action.rawValue // 28 And to get it from a String: let twentyEight = MovieGenres(rawValue: "28") Another tip, it´s Swift convention to name your cases with lowercases, like this: MovieGenres.action.rawValue // 28 Update: enum MovieGenre: String { case action case adventure case animation var value: Int { switch self { case .action: return 28 case .adventure: return 12 case .animation: return 16 } } } let action = MovieGenre(rawValue: "action")?.value // 28 let adventure = MovieGenre(rawValue: "adventure")?.value // 12 let animation = MovieGenre(rawValue: "animation")?.value // 16 let none = MovieGenre(rawValue: "none")?.value // nil if let value = MovieGenre(rawValue: pickerValue)?.value { print(value) }
Q: Get a Enum with a string in Swift I want to get the value from an enum after the user selected 'action' in a picker view. So I have as string: selectedGenre = "action". How can I get "28" from the case? public enum MovieGenres: String { case action = "28" case adventure = "12" case animation = "16" ... } I need to have something like this: MoveGenres.("selectedgenre").rawValue A: You can use the rawValue to get the Strings: MovieGenres.Action.rawValue // 28 And to get it from a String: let twentyEight = MovieGenres(rawValue: "28") Another tip, it´s Swift convention to name your cases with lowercases, like this: MovieGenres.action.rawValue // 28 Update: enum MovieGenre: String { case action case adventure case animation var value: Int { switch self { case .action: return 28 case .adventure: return 12 case .animation: return 16 } } } let action = MovieGenre(rawValue: "action")?.value // 28 let adventure = MovieGenre(rawValue: "adventure")?.value // 12 let animation = MovieGenre(rawValue: "animation")?.value // 16 let none = MovieGenre(rawValue: "none")?.value // nil if let value = MovieGenre(rawValue: pickerValue)?.value { print(value) } A: Probably you wanna do something like this instead... There is a difference between rawValue and value of the case you wanna get... so at first you wanna get the case: //Get the value from picker let selectedValueString = MovieGenres(rawValue: picker.value).myDesiredValue Now to the enum: //The raw Values are the same if you choose String type public enum MovieGenres: String { case action case adventure case animation var myDesiredValue: String{ switch self{ case action: return "28" case adventure: return "12" case animation: return "16" } } } A: First of all this is how you define your enum enum MovieGenre: String { case action case adventure case animation var code: Int { switch self { case .action: return 28 case .adventure: return 12 case .animation: return 16 } } } Now given a string let stringFromPicker = "action" You can try to build your enum value if let movieGenre = MovieGenre(rawValue: stringFromPicker) { print(movieGenre.code) // 28 } As you can see I renamed MovieGenres as MovieGenre, infact an enum name should be singular.
stackoverflow
{ "language": "en", "length": 354, "provenance": "stackexchange_0000F.jsonl.gz:843230", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474857" }
53c67daa23c4f59be2cf4b24140a9bd15548bf41
Stackoverflow Stackexchange Q: How to print to stderr in fish shell? In a fish-shell script, how do you print an error message to stderr? For example, this message should go to the stderr stream rather than the default stdout stream. echo "Error: $argv[1] is not a valid option" A: You can redirect the output to stderr, for example: echo "Error: $argv[1] is not a valid option" 1>&2 As a reference, here are some common IO-redirections that work in fish*. foo 1>&2 # Redirects stdout to stderr, same as bash bar 2>&1 # Redirects stderr to stdout, same as bash bar ^&1 # Redirects stderr to stdout, the fish way using a caret ^ * The file descriptors for stdin, stdout, and stderr are 0, 1, and 2. * The & implies you want to redirect to a file stream instead of a file. * Comparison of redirection in various shells (bash, fish, ksh, tcsh, zsh)
Q: How to print to stderr in fish shell? In a fish-shell script, how do you print an error message to stderr? For example, this message should go to the stderr stream rather than the default stdout stream. echo "Error: $argv[1] is not a valid option" A: You can redirect the output to stderr, for example: echo "Error: $argv[1] is not a valid option" 1>&2 As a reference, here are some common IO-redirections that work in fish*. foo 1>&2 # Redirects stdout to stderr, same as bash bar 2>&1 # Redirects stderr to stdout, same as bash bar ^&1 # Redirects stderr to stdout, the fish way using a caret ^ * The file descriptors for stdin, stdout, and stderr are 0, 1, and 2. * The & implies you want to redirect to a file stream instead of a file. * Comparison of redirection in various shells (bash, fish, ksh, tcsh, zsh)
stackoverflow
{ "language": "en", "length": 153, "provenance": "stackexchange_0000F.jsonl.gz:843232", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474860" }
be7a5ee2eeeab39dc1f8b1e247f6837e8978b800
Stackoverflow Stackexchange Q: How to create Mqtt Android Client with SSH Tunneling? I want to connect with my MQTT broker and get some data from Android App. The Mqtt server has implemented with SSH layer for security reasons. I want connect Mqtt broker over SSH tunnel. How to achieve this? IS there any opensource library? Note : I am able to connect by putty.exe -ssh -L 1883:ipaddress:22 username@ipaddress and username and password. A: If you are limited to SSH you might be able to use the one of the libraries mentioned in this answer: https://stackoverflow.com/a/1367997/6581384 Otherwise, If your requirements are flexible, it would be easier to reconfigure the MQTT broker and client to use SSL/TLS instead.
Q: How to create Mqtt Android Client with SSH Tunneling? I want to connect with my MQTT broker and get some data from Android App. The Mqtt server has implemented with SSH layer for security reasons. I want connect Mqtt broker over SSH tunnel. How to achieve this? IS there any opensource library? Note : I am able to connect by putty.exe -ssh -L 1883:ipaddress:22 username@ipaddress and username and password. A: If you are limited to SSH you might be able to use the one of the libraries mentioned in this answer: https://stackoverflow.com/a/1367997/6581384 Otherwise, If your requirements are flexible, it would be easier to reconfigure the MQTT broker and client to use SSL/TLS instead.
stackoverflow
{ "language": "en", "length": 114, "provenance": "stackexchange_0000F.jsonl.gz:843249", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44474924" }
33d7dd6a6679f22ee58c6ff3890502f2ae9452a0
Stackoverflow Stackexchange Q: Distinguishing Tuple1 in quasiquote matching Suppose I want a macro that takes an expression and returns the arity if it's a tuple literal. Something like this works for tuples but returns Some(1) instead of None for everything else: import scala.reflect.macros.blackbox.Context class ArityMacros(val c: Context) { import c.universe._ def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match { case q"(..$xs)" => q"_root_.scala.Some(${ xs.size })" case _ => q"_root_.scala.None" } } import scala.language.experimental.macros def arity[A](a: A): Option[Int] = macro ArityMacros.arity[A] I know I can do something like this: class ArityMacros(val c: Context) { import c.universe._ def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match { case q"scala.Tuple1.apply[$_]($_)" => q"_root_.scala.Some(1)" case q"(..$xs)" if xs.size > 1 => q"_root_.scala.Some(${ xs.size })" case other => q"_root_.scala.None" } } But feel like there should be a nicer way to distinguish the Tuple1 and non-tuple cases (and maybe that I've used it in the past?).
Q: Distinguishing Tuple1 in quasiquote matching Suppose I want a macro that takes an expression and returns the arity if it's a tuple literal. Something like this works for tuples but returns Some(1) instead of None for everything else: import scala.reflect.macros.blackbox.Context class ArityMacros(val c: Context) { import c.universe._ def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match { case q"(..$xs)" => q"_root_.scala.Some(${ xs.size })" case _ => q"_root_.scala.None" } } import scala.language.experimental.macros def arity[A](a: A): Option[Int] = macro ArityMacros.arity[A] I know I can do something like this: class ArityMacros(val c: Context) { import c.universe._ def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match { case q"scala.Tuple1.apply[$_]($_)" => q"_root_.scala.Some(1)" case q"(..$xs)" if xs.size > 1 => q"_root_.scala.Some(${ xs.size })" case other => q"_root_.scala.None" } } But feel like there should be a nicer way to distinguish the Tuple1 and non-tuple cases (and maybe that I've used it in the past?).
stackoverflow
{ "language": "en", "length": 147, "provenance": "stackexchange_0000F.jsonl.gz:843302", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475069" }
9f322610d81d81ff7566cd29f5009f5e7cb01c96
Stackoverflow Stackexchange Q: How to enable scrolling with a touchpad (IntelliJ)? I just downloaded the latest release of IntelliJ and recognized that I can't scroll in the code while using the touchpad of my notebook. I tried to add a mouse binding to the scroll actions but it doesn't work. My touchpad works fine with all other programms btw.
Q: How to enable scrolling with a touchpad (IntelliJ)? I just downloaded the latest release of IntelliJ and recognized that I can't scroll in the code while using the touchpad of my notebook. I tried to add a mouse binding to the scroll actions but it doesn't work. My touchpad works fine with all other programms btw.
stackoverflow
{ "language": "en", "length": 57, "provenance": "stackexchange_0000F.jsonl.gz:843323", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475134" }
19c10f5a90c5580827cfc44312b208bb9611e862
Stackoverflow Stackexchange Q: Does module.exports in node js create a shallow copy or deep copy of the exported objects or functions? For example, If I have 2 modules try1.js and try2.js try1.js module.exports.msg = "hello world"; try2.js try1 = require('./try1'); try1.msg = "changed message"; Does the change in the contents of msg made in try2.js affect try value of msg in try1.js? A: There is no copy at all made. module.exports is an object and that object is shared directly. If you modify properties on that object, then all who have loaded that module will see those changes. Does the change in the contents of msg made in try2.js affect try value of msg in try1.js? Yes, it does. There are no copies. The exports object is shared directly. Any changes you make to that exported object will be seen by all who are using that module. FYI, a module could use Object.freeze(module.exports) to prevent changes to that object after the desired properties are added.
Q: Does module.exports in node js create a shallow copy or deep copy of the exported objects or functions? For example, If I have 2 modules try1.js and try2.js try1.js module.exports.msg = "hello world"; try2.js try1 = require('./try1'); try1.msg = "changed message"; Does the change in the contents of msg made in try2.js affect try value of msg in try1.js? A: There is no copy at all made. module.exports is an object and that object is shared directly. If you modify properties on that object, then all who have loaded that module will see those changes. Does the change in the contents of msg made in try2.js affect try value of msg in try1.js? Yes, it does. There are no copies. The exports object is shared directly. Any changes you make to that exported object will be seen by all who are using that module. FYI, a module could use Object.freeze(module.exports) to prevent changes to that object after the desired properties are added. A: Yes, it affects it. Try doing the following. Save this code to a file m1.js: module.exports.msg = 'hello world'; module.exports.prn = function() { console.log( module.exports.msg ); } Then run the node console and try the following: > const m1 = require('./m1') undefined > m1.prn() xxx > m1.msg = 'changed' 'changed' > m1.prn() changed
stackoverflow
{ "language": "en", "length": 217, "provenance": "stackexchange_0000F.jsonl.gz:843335", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475168" }
c6781374ceaef863942860d449629bf782b92345
Stackoverflow Stackexchange Q: How to get enclosed class? I know Class.getDeclaredClasses() can obtains all the classes that it has declared but doesn't including anonymous classes. I'd like to know is there a way to get all the enclosed classes via the enclosing class ? for example, I want to get the all enclosed classes defined in Root for test purpose. class Root{ void run(){ Runnable task = new Runnable(){ public void run(){} }; task.getClass().getEnclosingClass();// return Root.class // but I want to get all enclosed class via Root.class, for example: // Root.class... == task.getClass() } } the expected result is : [class of task]. A: If you know the naming scheme of your anonymous classes, you can try to load it with Root's ClassLoader: Naming scheme for javac is <enclosing_class_name>$<anonymous_class_number>: Class<?> enclosing = Root.class; try{ Class<?> anon1 = enclosing.getClassLoader().loadClass(enclosing.getName() + "$1"); System.out.println(anon1); // prints: class Root$1 } catch (ClassNotFoundException e) { System.out.println("no anonymous classes"); }
Q: How to get enclosed class? I know Class.getDeclaredClasses() can obtains all the classes that it has declared but doesn't including anonymous classes. I'd like to know is there a way to get all the enclosed classes via the enclosing class ? for example, I want to get the all enclosed classes defined in Root for test purpose. class Root{ void run(){ Runnable task = new Runnable(){ public void run(){} }; task.getClass().getEnclosingClass();// return Root.class // but I want to get all enclosed class via Root.class, for example: // Root.class... == task.getClass() } } the expected result is : [class of task]. A: If you know the naming scheme of your anonymous classes, you can try to load it with Root's ClassLoader: Naming scheme for javac is <enclosing_class_name>$<anonymous_class_number>: Class<?> enclosing = Root.class; try{ Class<?> anon1 = enclosing.getClassLoader().loadClass(enclosing.getName() + "$1"); System.out.println(anon1); // prints: class Root$1 } catch (ClassNotFoundException e) { System.out.println("no anonymous classes"); }
stackoverflow
{ "language": "en", "length": 152, "provenance": "stackexchange_0000F.jsonl.gz:843346", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475201" }
55d6f156d3191fd447bd0f26d8f2f5d5a924e00a
Stackoverflow Stackexchange Q: Module compiled with swift 4.0 cannot be imported in swift 3.1 Apparently I have managed to build my project in Xcode 9 beta and now I only get the error Module compiled with swift 4.0 cannot be imported in swift 3.1 When I run the project in Xcode 8. The module in my case are Alamofire. I have tried to restart Xcode but nothing happens any ideas how to solve this issue? A: I had the same problem and cleaning the build folder helped: Command+Option+Shift+K or Product -> Option+Clean
Q: Module compiled with swift 4.0 cannot be imported in swift 3.1 Apparently I have managed to build my project in Xcode 9 beta and now I only get the error Module compiled with swift 4.0 cannot be imported in swift 3.1 When I run the project in Xcode 8. The module in my case are Alamofire. I have tried to restart Xcode but nothing happens any ideas how to solve this issue? A: I had the same problem and cleaning the build folder helped: Command+Option+Shift+K or Product -> Option+Clean A: You have two options that you can do: Clean the project and then try to re-build your solution and see if it works. If it don´t work and you still get the same error message then do the following steps and it should work for you: * *Open your podfile and remove Alamofire *Run pod update *Re-add Alamofire to your podfile *Run pod update *When this is done, clean your project and run it A: Just deleting Derived data worked for me, no need to do Pod install again A: Same problem here but using Carthage. And here is the answer: * *rm -rf ~/Library/Caches/org.carthage.CarthageKit/DerivedData *delete the Carthage folder for the project *Update Carthage: carthage update --platform iOS And voilà! A: I met this problem in a project where dependency is managed by Carthage. In my case, I didn't set command line tool in xcode (Type in xcodebuild -version, you will know whether you set it up or not), so first step is to go to XCode --> Preference --> Locations then select the xcode you want to serve as command line tool. Then you can follow the steps that @Domsware mentioned above to rebuild all frameworks you are gonna use. =============================================== Same problem here but using Carthage. And here is the answer: rm -rf ~/Library/Caches/org.carthage.CarthageKit/DerivedData delete the Carthage folder for the project Update Carthage: carthage update --platform iOS =============================================== Then don't forget to delete old links under 'Linked frameworks and libraries' and drag all frameworks from /Carthage folder under you project to 'Linked frameworks and libraries'. Then voilà! For those who are using CocoaPods, I suspect (Disclaimer: I didn't encounter this problem in project where CocoaPods is the dependency manager) the solution would be run the following command in terminal: $ pod deintegrate $ pod clean $ pod install where you might need to install 'deintegrate' and 'clean' tool for CocoaPod $ sudo gem install cocoapods-deintegrate cocoapods-clean more details see post How to remove CocoaPods from a project? A: Add following lines at the end of your pod file: post_install do |installer| print "Setting the default SWIFT_VERSION to 4.0\n" installer.pods_project.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '4.0' end installer.pods_project.targets.each do |target| if ['SomeTarget-iOS', 'SomeTarget-watchOS'].include? "#{target}" print "Setting #{target}'s SWIFT_VERSION to 3.0\n" target.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '3.0' end else print "Setting #{target}'s SWIFT_VERSION to Undefined (Xcode will automatically resolve)\n" target.build_configurations.each do |config| config.build_settings.delete('SWIFT_VERSION') end end end end
stackoverflow
{ "language": "en", "length": 487, "provenance": "stackexchange_0000F.jsonl.gz:843368", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475274" }
0fd54c90f3e38a199cdf3ad41df8084cf8d31a71
Stackoverflow Stackexchange Q: Avoid a second of blank page using Pre-Bootstrap Loading Screen For Angular2 I'm animating pre-bootstrap loading in Angular 2 like this: <app-root> <div class="background"> <div class="wrapper"> <div class="loading-ball"> </div> </div> </div> </app-root> but when I added a lazy loading module functionality I started seeing a 1 second blank page between the animation and the final page Probably that was cause because I finish loading the app-root component before load the final module. What is the way to avoid this? A: This is happen because the your app-component load the lazy component from the server so it takes some time in this it shows the blank screen. You can avoid this by importing the code in the app-component.html. <div class="background" *ngIf="loading"> <div class="wrapper"> <div class="loading-ball"> </div> </div> </div> This should be overlay all the screen and in app.component.ts constructor( private _router: Router ) { } loading = false; ngOnInit() { this._router.events.subscribe(v => this.navigationInterceptor(v)); } navigationInterceptor(event: RouterEvent): void { if (event instanceof NavigationStart) { this.loading = true; } if (event instanceof NavigationEnd) { this.loading = false; } if (event instanceof NavigationCancel) { this.loading = false; } if (event instanceof NavigationError) { this.loading = false; } }
Q: Avoid a second of blank page using Pre-Bootstrap Loading Screen For Angular2 I'm animating pre-bootstrap loading in Angular 2 like this: <app-root> <div class="background"> <div class="wrapper"> <div class="loading-ball"> </div> </div> </div> </app-root> but when I added a lazy loading module functionality I started seeing a 1 second blank page between the animation and the final page Probably that was cause because I finish loading the app-root component before load the final module. What is the way to avoid this? A: This is happen because the your app-component load the lazy component from the server so it takes some time in this it shows the blank screen. You can avoid this by importing the code in the app-component.html. <div class="background" *ngIf="loading"> <div class="wrapper"> <div class="loading-ball"> </div> </div> </div> This should be overlay all the screen and in app.component.ts constructor( private _router: Router ) { } loading = false; ngOnInit() { this._router.events.subscribe(v => this.navigationInterceptor(v)); } navigationInterceptor(event: RouterEvent): void { if (event instanceof NavigationStart) { this.loading = true; } if (event instanceof NavigationEnd) { this.loading = false; } if (event instanceof NavigationCancel) { this.loading = false; } if (event instanceof NavigationError) { this.loading = false; } }
stackoverflow
{ "language": "en", "length": 195, "provenance": "stackexchange_0000F.jsonl.gz:843424", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475447" }
2e9e8a7d0b4cb028f9d824844da1f92c5dee9564
Stackoverflow Stackexchange Q: Slicing a Dask Dataframe I have the following code where I like to do a train/test split on a Dask dataframe df = dd.read_csv(csv_filename, sep=',', encoding="latin-1", names=cols, header=0, dtype='str') But when I try to do slices like for train, test in cv.split(X, y): df.fit(X[train], y[train]) it fails with the error KeyError: '[11639 11641 11642 ..., 34997 34998 34999] not in index' Any ideas? A: Dask.dataframe doesn't support row-wise slicing. It does support the loc operation if you have a sensible index. However in your case of train/test splitting you will probably be better served by the random_split method. train, test = df.random_split([0.80, 0.20]) You could also make many splits and concat in different ways splits = df.random_split([0.20, 0.20, 0.20, 0.20, 0.20]) for i in range(5): trains = [splits[j] for j in range(5) if j != i] train = dd.concat(trains, axis=0) test = splits[i]
Q: Slicing a Dask Dataframe I have the following code where I like to do a train/test split on a Dask dataframe df = dd.read_csv(csv_filename, sep=',', encoding="latin-1", names=cols, header=0, dtype='str') But when I try to do slices like for train, test in cv.split(X, y): df.fit(X[train], y[train]) it fails with the error KeyError: '[11639 11641 11642 ..., 34997 34998 34999] not in index' Any ideas? A: Dask.dataframe doesn't support row-wise slicing. It does support the loc operation if you have a sensible index. However in your case of train/test splitting you will probably be better served by the random_split method. train, test = df.random_split([0.80, 0.20]) You could also make many splits and concat in different ways splits = df.random_split([0.20, 0.20, 0.20, 0.20, 0.20]) for i in range(5): trains = [splits[j] for j in range(5) if j != i] train = dd.concat(trains, axis=0) test = splits[i]
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:843441", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475492" }
5bf38e3440560db681bbdc3854f64a8681d7eec7
Stackoverflow Stackexchange Q: How to prevent my program from running in a non-administrator account that has UAC turned off? I'm using this line in the app.manifest in order to raise an UAC prompt that demands administrative privileges in order for my program to run: <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> It works. However, I found out that if the program is executed in a standard user account and UAC is turned-off, the program still runs - without administrative privileges -. What I want, is to prevent it from running in this scenario. Instead, it should give a message like: "Sorry, this program requires administrative privileges to run". And then it should close itself. Most questions I found here in SO, are about how to elevate an application when UAC is turned off. That's not what I'm searching. Thanks in advance for your help! A: You have to check if your user is administrator with this: if (!WindowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { // show messagebox "Sorry, this program requires administrative privileges to run" Application.Exit(); }
Q: How to prevent my program from running in a non-administrator account that has UAC turned off? I'm using this line in the app.manifest in order to raise an UAC prompt that demands administrative privileges in order for my program to run: <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> It works. However, I found out that if the program is executed in a standard user account and UAC is turned-off, the program still runs - without administrative privileges -. What I want, is to prevent it from running in this scenario. Instead, it should give a message like: "Sorry, this program requires administrative privileges to run". And then it should close itself. Most questions I found here in SO, are about how to elevate an application when UAC is turned off. That's not what I'm searching. Thanks in advance for your help! A: You have to check if your user is administrator with this: if (!WindowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { // show messagebox "Sorry, this program requires administrative privileges to run" Application.Exit(); }
stackoverflow
{ "language": "en", "length": 167, "provenance": "stackexchange_0000F.jsonl.gz:843443", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475499" }
6b92c81e0c967c4d9f1a226006265c3184f8a44a
Stackoverflow Stackexchange Q: Cross validation in deep neural networks How do you perform cross-validation in a deep neural network? I know that to perform cross validation to will train it on all folds except one and test it on the excluded fold. Then do this for k fold times and average the accuries for each fold. How do you do this for each iteration. Do you update the parameters at each fold? Or you perform k-fold cross validation for each iteration? Or is each training on all folds but one fold considered as one iteration? A: Stratified cross validation There are a couple of solution available to run deep neural network in fold-cross validation. def create_baseline(): # create model model = Sequential() model.add(Dense(60, input_dim=11, kernel_initializer='normal', activation='relu')) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model # evaluate model with standardized dataset estimator = KerasClassifier(build_fn=create_baseline, epochs=100, batch_size=5, verbose=0) kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed) results = cross_val_score(estimator, X, encoded_Y, cv=kfold) print("Baseline: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
Q: Cross validation in deep neural networks How do you perform cross-validation in a deep neural network? I know that to perform cross validation to will train it on all folds except one and test it on the excluded fold. Then do this for k fold times and average the accuries for each fold. How do you do this for each iteration. Do you update the parameters at each fold? Or you perform k-fold cross validation for each iteration? Or is each training on all folds but one fold considered as one iteration? A: Stratified cross validation There are a couple of solution available to run deep neural network in fold-cross validation. def create_baseline(): # create model model = Sequential() model.add(Dense(60, input_dim=11, kernel_initializer='normal', activation='relu')) model.add(Dense(1, kernel_initializer='normal', activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model # evaluate model with standardized dataset estimator = KerasClassifier(build_fn=create_baseline, epochs=100, batch_size=5, verbose=0) kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed) results = cross_val_score(estimator, X, encoded_Y, cv=kfold) print("Baseline: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100)) A: Cross-validation is a general technique in ML to prevent overfitting. There is no difference between doing it on a deep-learning model and doing it on a linear regression. The idea is the same for all ML models. The basic idea behind CV, you described in your question is correct. But the question how do you do this for each iteration does not make sense. There is nothing in CV algorithm that relates to iterations while training. You trained your model and only then you evaluate it. Do you update the parameters at each fold?. You train the same model k-times and most probably each time you will have different parameters. The answer that CV is not needed in DL is wrong. The basic idea of CV is to have a better estimate of how your model is performing on a limited dataset. So if your dataset is small the ability to train k models will give you a better estimate (the downsize is that you spend ~k times more time). If you have 100mln examples, most probably having 5% testing/validation set will already give you a good estimate.
stackoverflow
{ "language": "en", "length": 353, "provenance": "stackexchange_0000F.jsonl.gz:843501", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475682" }
db71b50c7f7614a42fa7dea695dae2b9e4f3fcf2
Stackoverflow Stackexchange Q: Add Operation with numbers I wrote this code as part of a calculator, for practice. It mostly works as intended. However, the add operation concatenates the two numbers instead of adding them. Why? function calcApp (aNumber, bNumber) { var a = prompt("Enter A number :"); var b = prompt("Enter B number :"); var mathSign = prompt("Enter Math Sign :"); aNumber = a; bNumber = b; if (mathSign == "+") { alert(a + b); } else if (mathSign == "-") { alert(a - b); } else if (mathSign == "*") { alert(a * b); } else if (mathSign == "/") { alert(a / b); } else { prompt("Enter a valid Math sign!!") } } calcApp(); A: prompt returns a string. When you use the + operator on strings, they are concatenated. You have to get the number value of the user's input. You can do that in a variety of different ways: var str = '5.4'; console.log(parseInt(str, 10)); // parse integer from decimal numeric string console.log(parseFloat(str)); console.log(+str); console.log(Number(str));
Q: Add Operation with numbers I wrote this code as part of a calculator, for practice. It mostly works as intended. However, the add operation concatenates the two numbers instead of adding them. Why? function calcApp (aNumber, bNumber) { var a = prompt("Enter A number :"); var b = prompt("Enter B number :"); var mathSign = prompt("Enter Math Sign :"); aNumber = a; bNumber = b; if (mathSign == "+") { alert(a + b); } else if (mathSign == "-") { alert(a - b); } else if (mathSign == "*") { alert(a * b); } else if (mathSign == "/") { alert(a / b); } else { prompt("Enter a valid Math sign!!") } } calcApp(); A: prompt returns a string. When you use the + operator on strings, they are concatenated. You have to get the number value of the user's input. You can do that in a variety of different ways: var str = '5.4'; console.log(parseInt(str, 10)); // parse integer from decimal numeric string console.log(parseFloat(str)); console.log(+str); console.log(Number(str)); A: prompt will returns a string. You need to convert it to number. You can use Number object to convert string to number. If you are using Number object then check for NaN (Not-A-Number). For Example, Number('55 abc') returns NaN Careful when use parseInt which will strip decimal numbers. For Example, parseInt('12.99') returns 12. Here's your code updated with Number object, function calcApp (aNumber, bNumber) { var a = prompt("Enter A number :"); var b = prompt("Enter B number :"); var mathSign = prompt("Enter Math Sign :"); aNumber = a; bNumber = b; //Convert to number a = Number(a); <---------- b = Number(b); <---------- if (mathSign == "+") { alert(a + b); } else if (mathSign == "-") { alert(a - b); } else if (mathSign == "*") { alert(a * b); } else if (mathSign == "/") { alert(a / b); } else { prompt("Enter a valid Math sign!!") } } calcApp();
stackoverflow
{ "language": "en", "length": 321, "provenance": "stackexchange_0000F.jsonl.gz:843522", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475750" }
2b41454a6f8bb95eb76bcb7df599b286eb0b132d
Stackoverflow Stackexchange Q: How to enable flash in Selenium python firefox When I open firefox it has Flash installed in it but when I open it through selenium That version of firefox has not Flash in it. How to enable flash in selenium . This is the test code I am working with : firefoxProfile = FirefoxProfile() firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so','true') b = webdriver.Firefox(firefoxProfile, executable_path=r"C:\\Program Files\geckodriver-v0.16.1-win64\geckodriver.exe") b.get("http://www.python.org") A: Try adding the following to your current code: firefoxProfile.set_preference("plugin.state.flash", 2)
Q: How to enable flash in Selenium python firefox When I open firefox it has Flash installed in it but when I open it through selenium That version of firefox has not Flash in it. How to enable flash in selenium . This is the test code I am working with : firefoxProfile = FirefoxProfile() firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so','true') b = webdriver.Firefox(firefoxProfile, executable_path=r"C:\\Program Files\geckodriver-v0.16.1-win64\geckodriver.exe") b.get("http://www.python.org") A: Try adding the following to your current code: firefoxProfile.set_preference("plugin.state.flash", 2)
stackoverflow
{ "language": "en", "length": 73, "provenance": "stackexchange_0000F.jsonl.gz:843534", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475782" }
995b7df441022bf5a0c3c6bb4d04f93bfeb9d498
Stackoverflow Stackexchange Q: Swift how to declare realm results? How to declare Results generic I want to declare it like global variable in UITableViewController and fill within viewDidLoad func Here's my code class ContactsController: UITableViewController { var contacts = Results<Contact>() override func viewDidLoad() { super.viewDidLoad() contacts = Domain.FetchContacts() } } But I get error Cannot invoke initializer for type 'Results' with no arguments How can I declare it? A: I declared results generic like this var contacts: Results<Contact>? = nil
Q: Swift how to declare realm results? How to declare Results generic I want to declare it like global variable in UITableViewController and fill within viewDidLoad func Here's my code class ContactsController: UITableViewController { var contacts = Results<Contact>() override func viewDidLoad() { super.viewDidLoad() contacts = Domain.FetchContacts() } } But I get error Cannot invoke initializer for type 'Results' with no arguments How can I declare it? A: I declared results generic like this var contacts: Results<Contact>? = nil A: You can declare the contacts like this: var contacts: Results<Contact>! or var contacts: Results<Contact>? A: var contacts: Results<Contact> = realm.objects(Contact.self).filter("FALSEPREDICATE") A: You need to make your declaration as a optional type. Remove () and put ? after variable declaration like var contacts = Results?
stackoverflow
{ "language": "en", "length": 123, "provenance": "stackexchange_0000F.jsonl.gz:843558", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475843" }
b61f49d970284f2fd1ec8ef1172418902cd5c7db
Stackoverflow Stackexchange Q: cannot run container after commit changes Just basic and simple steps illustrating what I have tried: * *docker pull mysql/mysql-server *sudo docker run -i -t mysql/mysql-server:latest /bin/bash *yum install vi *vi /etc/my.cnf -> bind-address=0.0.0.0 *exit *docker ps *docker commit new_image_name *docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret -d new_image_name docker ps -a STATUS - Exited (1) Please let me know what I did wrong. A: Instead of trying to modify an existing image, try and use (for testing) MYSQL_ROOT_HOST=%. That would allow root login from any IP. (As seen in docker-library/mysql issue 241) sudo docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_ROOT_HOST=% -d mysql/mysql-server:latest The README mentions: By default, MySQL creates the 'root'@'localhost' account. This account can only be connected to from inside the container, requiring the use of the docker exec command as noted under Connect to MySQL from the MySQL Command Line Client. To allow connections from other hosts, set this environment variable. As an example, the value "172.17.0.1", which is the default Docker gateway IP, will allow connections from the Docker host machine.
Q: cannot run container after commit changes Just basic and simple steps illustrating what I have tried: * *docker pull mysql/mysql-server *sudo docker run -i -t mysql/mysql-server:latest /bin/bash *yum install vi *vi /etc/my.cnf -> bind-address=0.0.0.0 *exit *docker ps *docker commit new_image_name *docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret -d new_image_name docker ps -a STATUS - Exited (1) Please let me know what I did wrong. A: Instead of trying to modify an existing image, try and use (for testing) MYSQL_ROOT_HOST=%. That would allow root login from any IP. (As seen in docker-library/mysql issue 241) sudo docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_ROOT_HOST=% -d mysql/mysql-server:latest The README mentions: By default, MySQL creates the 'root'@'localhost' account. This account can only be connected to from inside the container, requiring the use of the docker exec command as noted under Connect to MySQL from the MySQL Command Line Client. To allow connections from other hosts, set this environment variable. As an example, the value "172.17.0.1", which is the default Docker gateway IP, will allow connections from the Docker host machine.
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:843608", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44475975" }
f4291386d9f0da064526895530e9740d81ea770a
Stackoverflow Stackexchange Q: Unable to understand a pointer statement I am doing a ctf problem and there is a line i can't understand. int (*fp)(char *)=(int(*)(char *))&puts, i; Can anyone explain me what does this mean? A: fp is a pointer (*fp) to a function (*fp)( that accepts 1 argument of type char (*fp)(char) and returns a value of type int int (*fp)(char) The pointer is initialized with the address of puts after a mostly redundant conversion. int (*fp)(char *)=(int(*)(char *))&puts int (*fp)(char *)=(int(*)(char *))puts // & redundant int (*fp)(const char *)=puts The object i is not initialized. It has type int int (*fp)(char *)=(int(*)(char *))&puts, i;
Q: Unable to understand a pointer statement I am doing a ctf problem and there is a line i can't understand. int (*fp)(char *)=(int(*)(char *))&puts, i; Can anyone explain me what does this mean? A: fp is a pointer (*fp) to a function (*fp)( that accepts 1 argument of type char (*fp)(char) and returns a value of type int int (*fp)(char) The pointer is initialized with the address of puts after a mostly redundant conversion. int (*fp)(char *)=(int(*)(char *))&puts int (*fp)(char *)=(int(*)(char *))puts // & redundant int (*fp)(const char *)=puts The object i is not initialized. It has type int int (*fp)(char *)=(int(*)(char *))&puts, i; A: First there is a variable declaration: int (*fp)(char *) fp is a pointer to function, which is taking a char * parameter and returning int. Then fp is initialized to a value: (int(*)(char *))&puts The value is the address of the puts function, cast to the same type as fp. And finally, there is another variable declaration: int /* ... */, i; A: There are two parts to this declaration: int (*fp)(char *)=(int(*)(char *))&puts, i; first is: int (*fp)(char *)=(int(*)(char *))&puts; explanation: This is function pointer declaration and initialisation in single statement. Where fp is the pointer to the function puts. If you print value of fp and puts they will have same value, that is address of puts. #include<stdio.h> int main() { int (*fp)(char *)=(int(*)(char *))&puts, i; printf("puts %p\n",puts); printf("fp %p\n",fp); } and second is: int i;
stackoverflow
{ "language": "en", "length": 244, "provenance": "stackexchange_0000F.jsonl.gz:843630", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476055" }
14d353798c69c062c4ef1e5c5db56a349205cd12
Stackoverflow Stackexchange Q: Calculation accurate time difference with built-in modules start = time.clock() print("test ") time.sleep(1) print(time.clock()-start) The final line prints the result normally but sometimes it gives a result less than 1 (0.9962501944182808 or 0.9886929485969909 etc.) If I have made the code sleep for 1 second with time.sleep(1) I would have thought that the result would always greater than 1. It is not precise so how can I calculate time consumed by my code with built-in modules? A: From the documentation The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. Also, you can read this answer about the sleep function's accuracy.
Q: Calculation accurate time difference with built-in modules start = time.clock() print("test ") time.sleep(1) print(time.clock()-start) The final line prints the result normally but sometimes it gives a result less than 1 (0.9962501944182808 or 0.9886929485969909 etc.) If I have made the code sleep for 1 second with time.sleep(1) I would have thought that the result would always greater than 1. It is not precise so how can I calculate time consumed by my code with built-in modules? A: From the documentation The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. Also, you can read this answer about the sleep function's accuracy.
stackoverflow
{ "language": "en", "length": 139, "provenance": "stackexchange_0000F.jsonl.gz:843680", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476182" }
381bcd7c3246e47c543feccf56fbaa27d398e781
Stackoverflow Stackexchange Q: Is it possible to format dateComponent to display as hh:mm:ss? I'm trying to display a countdown in a hh:mm:ss format but since I'm not outputting the Date but the dateComponents, I can't use formatter.dateFormat. Is there a possibility to format the dateComponents? Currently I get an output that looks like this: Hour: 5, Minute: 12, Second: 45 func nextEventCalculator() -> DateComponents { let now = Date() let calendar = Calendar.current let components = DateComponents(calendar: calendar, hour: 12, minute: 15) // <- 12:15 pm let nextEvent = calendar.nextDate(after: now, matching: components, matchingPolicy: .nextTime)! let diff = calendar.dateComponents([.hour, .minute, .second], from: now, to: nextEvent) dateCountdownLabel.text = "\(diff)" return diff } A: Use DateComponentsFormatter with a unitsStyle of .positional: let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional dateCountdownLabel.text = formatter.string(from: diff)
Q: Is it possible to format dateComponent to display as hh:mm:ss? I'm trying to display a countdown in a hh:mm:ss format but since I'm not outputting the Date but the dateComponents, I can't use formatter.dateFormat. Is there a possibility to format the dateComponents? Currently I get an output that looks like this: Hour: 5, Minute: 12, Second: 45 func nextEventCalculator() -> DateComponents { let now = Date() let calendar = Calendar.current let components = DateComponents(calendar: calendar, hour: 12, minute: 15) // <- 12:15 pm let nextEvent = calendar.nextDate(after: now, matching: components, matchingPolicy: .nextTime)! let diff = calendar.dateComponents([.hour, .minute, .second], from: now, to: nextEvent) dateCountdownLabel.text = "\(diff)" return diff } A: Use DateComponentsFormatter with a unitsStyle of .positional: let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional dateCountdownLabel.text = formatter.string(from: diff)
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:843696", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476224" }
f2effec661e80afb8842fc1796bd229447dab0ff
Stackoverflow Stackexchange Q: XGBoost monotonic constraints don't work XGBoost (0.6a2) ignores monotone_constraints. I use it in line with tutorial, but params_constrained['monotone_constraints'] = "(1,-1)" causes the same results as unconstrained models. Are monotonic constraints in production now? Does anyone have a successful experience?
Q: XGBoost monotonic constraints don't work XGBoost (0.6a2) ignores monotone_constraints. I use it in line with tutorial, but params_constrained['monotone_constraints'] = "(1,-1)" causes the same results as unconstrained models. Are monotonic constraints in production now? Does anyone have a successful experience?
stackoverflow
{ "language": "en", "length": 40, "provenance": "stackexchange_0000F.jsonl.gz:843752", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476422" }
238662b333845cb1d01ee0e3c2b88183a83bf57f
Stackoverflow Stackexchange Q: do generic type param shadow reference types? (java) Let's say we have the following scenario: public class SomeClass { } And now we have a generic class with type parameter SomeClass instead of T. public class GenericClass <SomeClass> { List<SomeClass> list; public GenericClass() { list = new ArrayList<>(); } public void add(SomeClass obj) { list.add(obj); } } Will the type parameter SomeClass shadow the reference datatype SomeClass in the whole GenericClass? A: Yes. That's a name shadow in this context. You can still disambiguate with the fully qualified class name (as long you as you use a package, as you should). Also, this is a good argument for using conventional short type names for your generic types.
Q: do generic type param shadow reference types? (java) Let's say we have the following scenario: public class SomeClass { } And now we have a generic class with type parameter SomeClass instead of T. public class GenericClass <SomeClass> { List<SomeClass> list; public GenericClass() { list = new ArrayList<>(); } public void add(SomeClass obj) { list.add(obj); } } Will the type parameter SomeClass shadow the reference datatype SomeClass in the whole GenericClass? A: Yes. That's a name shadow in this context. You can still disambiguate with the fully qualified class name (as long you as you use a package, as you should). Also, this is a good argument for using conventional short type names for your generic types. A: In a word - yes, it will shadow SomeClass. You could still use the fully qualified class name (e.g., com.exmaple.SomeClass) to reference it, though.
stackoverflow
{ "language": "en", "length": 143, "provenance": "stackexchange_0000F.jsonl.gz:843754", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476432" }
57de3ddc66b398e3d355867f33333182d354766e
Stackoverflow Stackexchange Q: Titanium app won't build in Android after upgrading SDK, resource entry accept is already defined After upgrading to Titanium SDK 6.1.0.GA, my app no longer builds. It gives the error: [ERROR] Failed to package application: [ERROR] [ERROR] /Users/justintoth/Documents/housters-mobile/build/android/res/values/strings.xml:51: error: Resource entry accept is already defined. [ERROR] /Users/justintoth/Documents/housters-mobile/build/android/res/values/admob_strings.xml:5: Originally defined here. Neither strings.xml or admob_strings.xml are files that I myself created or have edited, they are auto-generated. Also, I don't even use admob in my app, Titanium seems to be including it no matter what, which is very wasteful in my opinion. Here is the full build log: https://gist.github.com/justintoth/c33f2eb540d6891db99d557bc3f10be7 It works fine on iOS, the issue is only on Android. Any ideas?
Q: Titanium app won't build in Android after upgrading SDK, resource entry accept is already defined After upgrading to Titanium SDK 6.1.0.GA, my app no longer builds. It gives the error: [ERROR] Failed to package application: [ERROR] [ERROR] /Users/justintoth/Documents/housters-mobile/build/android/res/values/strings.xml:51: error: Resource entry accept is already defined. [ERROR] /Users/justintoth/Documents/housters-mobile/build/android/res/values/admob_strings.xml:5: Originally defined here. Neither strings.xml or admob_strings.xml are files that I myself created or have edited, they are auto-generated. Also, I don't even use admob in my app, Titanium seems to be including it no matter what, which is very wasteful in my opinion. Here is the full build log: https://gist.github.com/justintoth/c33f2eb540d6891db99d557bc3f10be7 It works fine on iOS, the issue is only on Android. Any ideas?
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:843769", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476471" }
030c2ea99879de914dd4ef0581f23848a01ec928
Stackoverflow Stackexchange Q: SWI-Prolog read http header I don't fully understand how SWI Prolog handles http. I have the following code which mostly works apart from the get_header/1. I need to be able to reader the header file of the http request to get a value. How do I do that? Do I use http_read_header/2 ? If so how? :- http_handler(root(handle), myhandle,[]). myhandle(Request):- get_header(H), http_read_json_dict(Request,DictIn), handle_dict(DictIn,DictOut), reply_json(DictOut). get_header(H):- http_read_header(current_input, H), something(H). A: First, when posting a question about the HTTP libraries, please include the full code. This means the server and client that you use to post the request. From just your question, nobody has any idea what you are doing. This is typical for questions about HTTP libraries, and I hope becomes less common in the future. Second, the Request is already a list of Name(Value) elements. Any header field that was sent by the client is included in this list. It is simply a matter of looking up the value in this list, using typical predicates that reason over lists, such as member/2 and option/3. For example, if the client has submitted the header The-Field: x, then member(the_field(Value), Request), ... will yield Value = x.
Q: SWI-Prolog read http header I don't fully understand how SWI Prolog handles http. I have the following code which mostly works apart from the get_header/1. I need to be able to reader the header file of the http request to get a value. How do I do that? Do I use http_read_header/2 ? If so how? :- http_handler(root(handle), myhandle,[]). myhandle(Request):- get_header(H), http_read_json_dict(Request,DictIn), handle_dict(DictIn,DictOut), reply_json(DictOut). get_header(H):- http_read_header(current_input, H), something(H). A: First, when posting a question about the HTTP libraries, please include the full code. This means the server and client that you use to post the request. From just your question, nobody has any idea what you are doing. This is typical for questions about HTTP libraries, and I hope becomes less common in the future. Second, the Request is already a list of Name(Value) elements. Any header field that was sent by the client is included in this list. It is simply a matter of looking up the value in this list, using typical predicates that reason over lists, such as member/2 and option/3. For example, if the client has submitted the header The-Field: x, then member(the_field(Value), Request), ... will yield Value = x.
stackoverflow
{ "language": "en", "length": 195, "provenance": "stackexchange_0000F.jsonl.gz:843787", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476529" }
991009a7a08cd4e7ffed5b00488f6e14c62ab63b
Stackoverflow Stackexchange Q: How can I have an SVG polyline points in percentages? I want to be able to create the SVG path where 0,0 would be top left of the screen and 100,100 would be bottom right. This is what I have so far, it just creates the graph in the centre, not what I had in mind. * { margin: 0; padding: 0; } html, body, svg { overflow-x: hidden; overflow-y: hidden; width: 100%; height: 100%; } polyline { fill: none; stroke: gray; stroke-width: 5; } <svg viewbox="0 0 100 100"> <polyline points="0,0 5,10 20,20 30,5 50, 20, 100,100"> </svg> Could anybody help with this? Is it even possible? A: Presumably you just want to stop preserving the aspect ratio of the viewBox like so... * { margin: 0; padding: 0; } html, body, svg { overflow-x: hidden; overflow-y: hidden; width: 100%; height: 100%; } polyline { fill: none; stroke: gray; stroke-width: 5; } <svg viewBox="0 0 100 100" preserveAspectRatio="none"> <polyline points="0,0 5,10 20,20 30,5 50, 20, 100,100"> </svg>
Q: How can I have an SVG polyline points in percentages? I want to be able to create the SVG path where 0,0 would be top left of the screen and 100,100 would be bottom right. This is what I have so far, it just creates the graph in the centre, not what I had in mind. * { margin: 0; padding: 0; } html, body, svg { overflow-x: hidden; overflow-y: hidden; width: 100%; height: 100%; } polyline { fill: none; stroke: gray; stroke-width: 5; } <svg viewbox="0 0 100 100"> <polyline points="0,0 5,10 20,20 30,5 50, 20, 100,100"> </svg> Could anybody help with this? Is it even possible? A: Presumably you just want to stop preserving the aspect ratio of the viewBox like so... * { margin: 0; padding: 0; } html, body, svg { overflow-x: hidden; overflow-y: hidden; width: 100%; height: 100%; } polyline { fill: none; stroke: gray; stroke-width: 5; } <svg viewBox="0 0 100 100" preserveAspectRatio="none"> <polyline points="0,0 5,10 20,20 30,5 50, 20, 100,100"> </svg>
stackoverflow
{ "language": "en", "length": 169, "provenance": "stackexchange_0000F.jsonl.gz:843799", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476602" }
3e3121b55b52739ecbd62664eaade22aed63eb90
Stackoverflow Stackexchange Q: What is the difference between Keras model.evaluate() and model.predict()? I used Keras biomedical image segmentation to segment brain neurons. I used model.evaluate() it gave me Dice coefficient: 0.916. However, when I used model.predict(), then loop through the predicted images by calculating the Dice coefficient, the Dice coefficient is 0.82. Why are these two values different? A: The model.evaluate function predicts the output for the given input and then computes the metrics function specified in the model.compile and based on y_true and y_pred and returns the computed metric value as the output. The model.predict just returns back the y_pred So if you use model.predict and then compute the metrics yourself, the computed metric value should turn out to be the same as model.evaluate For example, one would use model.predict instead of model.evaluate in evaluating an RNN/ LSTM based models where the output needs to be fed as input in next time step
Q: What is the difference between Keras model.evaluate() and model.predict()? I used Keras biomedical image segmentation to segment brain neurons. I used model.evaluate() it gave me Dice coefficient: 0.916. However, when I used model.predict(), then loop through the predicted images by calculating the Dice coefficient, the Dice coefficient is 0.82. Why are these two values different? A: The model.evaluate function predicts the output for the given input and then computes the metrics function specified in the model.compile and based on y_true and y_pred and returns the computed metric value as the output. The model.predict just returns back the y_pred So if you use model.predict and then compute the metrics yourself, the computed metric value should turn out to be the same as model.evaluate For example, one would use model.predict instead of model.evaluate in evaluating an RNN/ LSTM based models where the output needs to be fed as input in next time step A: The problem lies in the fact that every metric in Keras is evaluated in a following manner: * *For each batch a metric value is evaluated. *A current value of loss (after k batches is equal to a mean value of your metric across computed k batches). *The final result is obtained as a mean of all losses computed for all batches. Most of the most popular metrics (like mse, categorical_crossentropy, mae) etc. - as a mean of loss value of each example - have a property that such evaluation ends up with a proper result. But in case of Dice Coefficient - a mean of its value across all of the batches is not equal to actual value computed on a whole dataset and as model.evaluate() uses such way of computations - this is the direct cause of your problem. A: The keras.evaluate() function will give you the loss value for every batch. The keras.predict() function will give you the actual predictions for all samples in a batch, for all batches. So even if you use the same data, the differences will be there because the value of a loss function will be almost always different than the predicted values. These are two different things. A: It is about regularization. model.predict() returns the final output of the model, i.e. answer. While model.evaluate() returns the loss. The loss is used to train the model (via backpropagation) and it is not the answer. This video of ML Tokyo should help to understand the difference between model.evaluate() and model.predict().
stackoverflow
{ "language": "en", "length": 410, "provenance": "stackexchange_0000F.jsonl.gz:843833", "question_score": "58", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476706" }
a84f53479c04d4f7ec0edd715e1131f050913308
Stackoverflow Stackexchange Q: Accessing private members when implementing in a .cpp file I'm trying to implement code for a .h file in a .cpp file. This is the header file: class ProcessOrders { public: double process_shipment(int q, double c); double process_order(int q); private: std::stack<Inventory> Inventory_on_hand; // keep track of inventory on hand std::stack<Order> orders_to_be_filled; // keep track of orders }; The problem is that the functions process_shipment and process_order require the ability to push things onto the private stacks, but I get an "unable to resolve identifier" error if I try to refer to them in the .cpp file. This is probably really obvious, but how do I get access to the private members while implementing the public ones in the .cpp file? I can't modify the header file. A: When you implement member functions outside of their class you need to prefix all member functions' names with ClassName::. Doing that enables you to just access every private variable with their respective name. Also do not forget to #include your header file of your class at the top of your .cpp file. double ProcessOrders::process_shipment(int q, double c) { /*...*/ Inventory_on_hand. //... } double ProcessOrders::process_order(int q) { /*...*/ }
Q: Accessing private members when implementing in a .cpp file I'm trying to implement code for a .h file in a .cpp file. This is the header file: class ProcessOrders { public: double process_shipment(int q, double c); double process_order(int q); private: std::stack<Inventory> Inventory_on_hand; // keep track of inventory on hand std::stack<Order> orders_to_be_filled; // keep track of orders }; The problem is that the functions process_shipment and process_order require the ability to push things onto the private stacks, but I get an "unable to resolve identifier" error if I try to refer to them in the .cpp file. This is probably really obvious, but how do I get access to the private members while implementing the public ones in the .cpp file? I can't modify the header file. A: When you implement member functions outside of their class you need to prefix all member functions' names with ClassName::. Doing that enables you to just access every private variable with their respective name. Also do not forget to #include your header file of your class at the top of your .cpp file. double ProcessOrders::process_shipment(int q, double c) { /*...*/ Inventory_on_hand. //... } double ProcessOrders::process_order(int q) { /*...*/ } A: You can access them in the .cpp for the class. Header files contain declaration while .cpp files have definition. In the above code, both stacks are private which means they can be only accessed within the functions of the same class. So when you will define process_shipment in your .cpp file, you can push anything in the stack. You can access orders_to_be_filled stack within the double ProcessOrders::process_shipment(int q, double c) using the code this.orders_to_be_filled;
stackoverflow
{ "language": "en", "length": 271, "provenance": "stackexchange_0000F.jsonl.gz:843837", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476720" }
21b3730f6a2616cf69f3d9e71f4366ddbab9e5ce
Stackoverflow Stackexchange Q: Build project with "experimental/filesystem" using cmake I need to add a "experimental/filesystem" header to my project #include <experimental/filesystem> int main() { auto path = std::experimental::filesystem::current_path(); return 0; } So I used -lstdc++fs flag and linked with libstdc++fs.a cmake_minimum_required(VERSION 3.7) project(testcpp) set(CMAKE_CXX_FLAGS "-std=c++14 -lstdc++fs" ) set(SOURCE_FILES main.cpp) target_link_libraries(${PROJECT_NAME} /usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a) add_executable(testcpp ${SOURCE_FILES}) However, I have next error: CMake Error at CMakeLists.txt:9 (target_link_libraries): Cannot specify link libraries for target "testcpp" which is not built by this project. But if I compile directly, it`s OK: g++-7 -std=c++14 -lstdc++fs -c main.cpp -o main.o g++-7 -o main main.o /usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a Where is my mistake? A: It's just that the target_link_libraries() call has to come after the add_executable() call. Otherwise the testcpp target is not known yet. CMake parses everything sequential. So just for completeness, here is a working version of your example I've tested: cmake_minimum_required(VERSION 3.7) project(testcpp) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) # NOTE: The following would add library with absolute path # Which is bad for your projects cross-platform capabilities # Just let the linker search for it #add_library(stdc++fs UNKNOWN IMPORTED) #set_property(TARGET stdc++fs PROPERTY IMPORTED_LOCATION "/usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a") set(SOURCE_FILES main.cpp) add_executable(testcpp ${SOURCE_FILES}) target_link_libraries(${PROJECT_NAME} stdc++fs)
Q: Build project with "experimental/filesystem" using cmake I need to add a "experimental/filesystem" header to my project #include <experimental/filesystem> int main() { auto path = std::experimental::filesystem::current_path(); return 0; } So I used -lstdc++fs flag and linked with libstdc++fs.a cmake_minimum_required(VERSION 3.7) project(testcpp) set(CMAKE_CXX_FLAGS "-std=c++14 -lstdc++fs" ) set(SOURCE_FILES main.cpp) target_link_libraries(${PROJECT_NAME} /usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a) add_executable(testcpp ${SOURCE_FILES}) However, I have next error: CMake Error at CMakeLists.txt:9 (target_link_libraries): Cannot specify link libraries for target "testcpp" which is not built by this project. But if I compile directly, it`s OK: g++-7 -std=c++14 -lstdc++fs -c main.cpp -o main.o g++-7 -o main main.o /usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a Where is my mistake? A: It's just that the target_link_libraries() call has to come after the add_executable() call. Otherwise the testcpp target is not known yet. CMake parses everything sequential. So just for completeness, here is a working version of your example I've tested: cmake_minimum_required(VERSION 3.7) project(testcpp) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) # NOTE: The following would add library with absolute path # Which is bad for your projects cross-platform capabilities # Just let the linker search for it #add_library(stdc++fs UNKNOWN IMPORTED) #set_property(TARGET stdc++fs PROPERTY IMPORTED_LOCATION "/usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a") set(SOURCE_FILES main.cpp) add_executable(testcpp ${SOURCE_FILES}) target_link_libraries(${PROJECT_NAME} stdc++fs)
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:843863", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476810" }
af9b30290ef0afa8356c10f701356087e4069a1d
Stackoverflow Stackexchange Q: Access scope data after Firebase authentication I authorized the calendar api in my google sign in auth, using the following code (Angularfire2): let auth = new firebase.auth.GoogleAuthProvider(); auth.addScope('https://www.googleapis.com/auth/calendar'); this.afAuth.auth .signInWithPopup(auth).then((data) => { console.log(data); // nothing about calendar here }); Is there any way to access authorized scopes using FirebaseAuth? For example, access the calendar data after the user signs and authorizes the calendar auth. A: If you check out the reference docs, you'll see that there are examples for each provider, which demonstrate how to obtain the third-party OAuth token: // Using a redirect. firebase.auth().getRedirectResult().then(function(result) { if (result.credential) { // This gives you a Google Access Token. var token = result.credential.accessToken; } var user = result.user; }); Once you have the third-party token, you can use that directly against their APIs.
Q: Access scope data after Firebase authentication I authorized the calendar api in my google sign in auth, using the following code (Angularfire2): let auth = new firebase.auth.GoogleAuthProvider(); auth.addScope('https://www.googleapis.com/auth/calendar'); this.afAuth.auth .signInWithPopup(auth).then((data) => { console.log(data); // nothing about calendar here }); Is there any way to access authorized scopes using FirebaseAuth? For example, access the calendar data after the user signs and authorizes the calendar auth. A: If you check out the reference docs, you'll see that there are examples for each provider, which demonstrate how to obtain the third-party OAuth token: // Using a redirect. firebase.auth().getRedirectResult().then(function(result) { if (result.credential) { // This gives you a Google Access Token. var token = result.credential.accessToken; } var user = result.user; }); Once you have the third-party token, you can use that directly against their APIs.
stackoverflow
{ "language": "en", "length": 132, "provenance": "stackexchange_0000F.jsonl.gz:843865", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476822" }
9bc142f57008861e7d7d1f1ae229259b24cf5251
Stackoverflow Stackexchange Q: withTrashed on hasManyThrough relation How can withTrashed be applied on a hasManyThrough relation ? $this->hasManyThrough('App\Message', 'App\Deal')->withTrashed(); returns Call to undefined method Illuminate\Database\Query\Builder::withTrashed() when i'm doing: $messages = Auth::user()->messages()->with('deal')->orderBy('created_at', 'DESC')->get();` Here is my Deal model: <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Deal extends Model { use SoftDeletes; /* ... */ protected $dates = ['deleted_at']; public function user() { return $this->belongsTo('App\User'); } public function messages() { return $this->hasMany('App\Message'); // I've tried to put withTrashed() here, there is no error but it doesn't include soft deleting items. } } A: To all those coming to this late, there is now a native way of doing this with Laravel. $this->hasManyThrough('App\Message', 'App\Deal')->withTrashedParents(); This is not well documented but can be found in Illuminate\Database\Eloquent\Relations\HasManyThrough
Q: withTrashed on hasManyThrough relation How can withTrashed be applied on a hasManyThrough relation ? $this->hasManyThrough('App\Message', 'App\Deal')->withTrashed(); returns Call to undefined method Illuminate\Database\Query\Builder::withTrashed() when i'm doing: $messages = Auth::user()->messages()->with('deal')->orderBy('created_at', 'DESC')->get();` Here is my Deal model: <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Deal extends Model { use SoftDeletes; /* ... */ protected $dates = ['deleted_at']; public function user() { return $this->belongsTo('App\User'); } public function messages() { return $this->hasMany('App\Message'); // I've tried to put withTrashed() here, there is no error but it doesn't include soft deleting items. } } A: To all those coming to this late, there is now a native way of doing this with Laravel. $this->hasManyThrough('App\Message', 'App\Deal')->withTrashedParents(); This is not well documented but can be found in Illuminate\Database\Eloquent\Relations\HasManyThrough A: The error is thrown because you are requesting a messages with deleted ones without using SoftDelete trait in Message model. After I check the hasManyThrough relation code I found that there is no way to do it in this way, you should play around. Ex: get the deals of user with messages instead $deals = Auth::user()->deals()->withTrashed()->with('messages')->get(); foreach($deals as $deal) { //Do your logic here and you can access messages of deal with $deal->messages }
stackoverflow
{ "language": "en", "length": 196, "provenance": "stackexchange_0000F.jsonl.gz:843876", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476852" }
b0417d1cea5d23111700a10bf3eae4a1f991c0db
Stackoverflow Stackexchange Q: How to draw a rounded rectangle in Xamarin.iOS? I would like to draw a rectangle with rounded corners, but I'm pretty new to the platform and it's really different from, for example, WPF or UWP. I've seen examples in Objective-C, but I don't know how to translate to Xamarin.iOS. A: A rounded filled rectangle path: var rectanglePath = UIBezierPath.FromRoundedRect(new CGRect(0.0f, 0.0f, 200.0f, 100.0f), 50.0f); UIColor.Red.SetFill(); rectanglePath.Fill(); Using an ImageContext to create a UIImage: UIGraphics.BeginImageContext(new CGSize(200.0f, 100.0f)); var rectanglePath = UIBezierPath.FromRoundedRect(new CGRect(0.0f, 0.0f, 200.0f, 100.0f), 50.0f); UIColor.Red.SetFill(); rectanglePath.Fill(); var image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); Via UIView subclass: public class RoundedBox : UIView { public RoundedBox() { } public RoundedBox(Foundation.NSCoder coder) : base(coder) { } public RoundedBox(Foundation.NSObjectFlag t) : base(t) { } public RoundedBox(IntPtr handle) : base(handle) { } public RoundedBox(CoreGraphics.CGRect frame) : base(frame) { } public override void Draw(CGRect rect) { var rectanglePath = UIBezierPath.FromRoundedRect(rect, 50.0f); UIColor.Red.SetFill(); rectanglePath.Fill(); } }
Q: How to draw a rounded rectangle in Xamarin.iOS? I would like to draw a rectangle with rounded corners, but I'm pretty new to the platform and it's really different from, for example, WPF or UWP. I've seen examples in Objective-C, but I don't know how to translate to Xamarin.iOS. A: A rounded filled rectangle path: var rectanglePath = UIBezierPath.FromRoundedRect(new CGRect(0.0f, 0.0f, 200.0f, 100.0f), 50.0f); UIColor.Red.SetFill(); rectanglePath.Fill(); Using an ImageContext to create a UIImage: UIGraphics.BeginImageContext(new CGSize(200.0f, 100.0f)); var rectanglePath = UIBezierPath.FromRoundedRect(new CGRect(0.0f, 0.0f, 200.0f, 100.0f), 50.0f); UIColor.Red.SetFill(); rectanglePath.Fill(); var image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); Via UIView subclass: public class RoundedBox : UIView { public RoundedBox() { } public RoundedBox(Foundation.NSCoder coder) : base(coder) { } public RoundedBox(Foundation.NSObjectFlag t) : base(t) { } public RoundedBox(IntPtr handle) : base(handle) { } public RoundedBox(CoreGraphics.CGRect frame) : base(frame) { } public override void Draw(CGRect rect) { var rectanglePath = UIBezierPath.FromRoundedRect(rect, 50.0f); UIColor.Red.SetFill(); rectanglePath.Fill(); } }
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:843877", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476857" }
a763949094153fbb8296d09e741b9f94fda05158
Stackoverflow Stackexchange Q: How to lower CPU usage extracting camera frames using AVFoundation on iOS? I'm working on a machine learning project that needs to access camera frames at 60fps. Good picture quality is not a requirement, but processing time is. On my trial to achieve light processor usage for frame extraction I'm changing captureSession.sessionPreset from AVCaptureSessionPresetLow to AVCaptureSessionPresetHigh but the CPU usage keeps the same on an iPhone 6:  Note: On both scenarios I'm forcing 60 fps: captureDevice.activeVideoMaxFrameDuration = CMTimeMake(1, 60) captureDevice.activeVideoMinFrameDuration = CMTimeMake(1, 60) I'm fine with the 192x144 resolution for the low preset but any clue on how to achieve better results regarding processor usage (5-10%)?
Q: How to lower CPU usage extracting camera frames using AVFoundation on iOS? I'm working on a machine learning project that needs to access camera frames at 60fps. Good picture quality is not a requirement, but processing time is. On my trial to achieve light processor usage for frame extraction I'm changing captureSession.sessionPreset from AVCaptureSessionPresetLow to AVCaptureSessionPresetHigh but the CPU usage keeps the same on an iPhone 6:  Note: On both scenarios I'm forcing 60 fps: captureDevice.activeVideoMaxFrameDuration = CMTimeMake(1, 60) captureDevice.activeVideoMinFrameDuration = CMTimeMake(1, 60) I'm fine with the 192x144 resolution for the low preset but any clue on how to achieve better results regarding processor usage (5-10%)?
stackoverflow
{ "language": "en", "length": 108, "provenance": "stackexchange_0000F.jsonl.gz:843879", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476860" }
163091759223adee25684daad3016662dcb65fd8
Stackoverflow Stackexchange Q: android.support.customtabs.extra.KEEP_ALIVE What is the public API to pass on service name for custom tabs? Sample app uses the following and works as expected but i don't see it in official documentation. (https://developer.android.com/reference/android/support/customtabs/CustomTabsIntent.html) private static final String EXTRA_CUSTOM_TABS_KEEP_ALIVE = "android.support.customtabs.extra.KEEP_ALIVE"; Intent keepAliveIntent = new Intent().setClassName( context.getPackageName(), KeepAliveService.class.getCanonicalName()); intent.putExtra(EXTRA_CUSTOM_TABS_KEEP_ALIVE, keepAliveIntent); A: There is no public api for setting keep alive as for now. You can check it by yourself from the source code of CustomTabsIntent.Builder.
Q: android.support.customtabs.extra.KEEP_ALIVE What is the public API to pass on service name for custom tabs? Sample app uses the following and works as expected but i don't see it in official documentation. (https://developer.android.com/reference/android/support/customtabs/CustomTabsIntent.html) private static final String EXTRA_CUSTOM_TABS_KEEP_ALIVE = "android.support.customtabs.extra.KEEP_ALIVE"; Intent keepAliveIntent = new Intent().setClassName( context.getPackageName(), KeepAliveService.class.getCanonicalName()); intent.putExtra(EXTRA_CUSTOM_TABS_KEEP_ALIVE, keepAliveIntent); A: There is no public api for setting keep alive as for now. You can check it by yourself from the source code of CustomTabsIntent.Builder.
stackoverflow
{ "language": "en", "length": 74, "provenance": "stackexchange_0000F.jsonl.gz:843899", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44476907" }
875be4a15c677d344adf1f8057ded4e1b1b9eba1
Stackoverflow Stackexchange Q: How to Use gRPC with Protocol buffer with Django I am using Django to make an E-commerce website and i want to use gRPC with Protocol Buffer, so, i can serve different client platform to like IOS, Android etc. i want to use gRPC because it is compatible with TensorFlow models to serve with live data of customers or using tensorflow models in productions I just want to know how to use in django, i am new to Django please help. A: There is a gRPC toolkit for Django (django-grpc-framework) that helps you do the following things: * *gRPC server with a development mode (auto-reloader, checks) server *a service class that manages django db connection state services *a generic service that map closely to your db models generics *a simple proto generator based on model proto generation *a simple RPCTestCase testing
Q: How to Use gRPC with Protocol buffer with Django I am using Django to make an E-commerce website and i want to use gRPC with Protocol Buffer, so, i can serve different client platform to like IOS, Android etc. i want to use gRPC because it is compatible with TensorFlow models to serve with live data of customers or using tensorflow models in productions I just want to know how to use in django, i am new to Django please help. A: There is a gRPC toolkit for Django (django-grpc-framework) that helps you do the following things: * *gRPC server with a development mode (auto-reloader, checks) server *a service class that manages django db connection state services *a generic service that map closely to your db models generics *a simple proto generator based on model proto generation *a simple RPCTestCase testing
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:843964", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477115" }
1744db523d4a529ff993fce9619990bc78f6f7a3
Stackoverflow Stackexchange Q: Iterate over json keys with only EJS Using only EJS (in EJS templates in .ejs files for NodeJS), how would I iterate over keys of a JSON object (that's not an array)? I'm looking for something like this: The JSON object like so: the_object = { 1: "belongs to id 1", 3: "belongs to id 3", 12: "belongs to id 12" } Some EJS templating like so: <% for (key, value: the_object) { %> <li>the key is: <%= key %></li> <% } %> To produce something like: *the key is: 1 *the key is: 3 *the key is: 12 Is this possible? A: <% Object.keys(the_object).forEach(function (key) { %> <li>the key is: <%= key %></li> <% }) %>
Q: Iterate over json keys with only EJS Using only EJS (in EJS templates in .ejs files for NodeJS), how would I iterate over keys of a JSON object (that's not an array)? I'm looking for something like this: The JSON object like so: the_object = { 1: "belongs to id 1", 3: "belongs to id 3", 12: "belongs to id 12" } Some EJS templating like so: <% for (key, value: the_object) { %> <li>the key is: <%= key %></li> <% } %> To produce something like: *the key is: 1 *the key is: 3 *the key is: 12 Is this possible? A: <% Object.keys(the_object).forEach(function (key) { %> <li>the key is: <%= key %></li> <% }) %>
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:843968", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477129" }
5f26a245ec0aabb98e680c71fa36b511868c9f12
Stackoverflow Stackexchange Q: How to detect screen lock (Qt5, C++, Windows, OSX) In my Qt5 C++ client, I'm wanting to detect when a user running Windows or OSX has locked the screen, then simultaneously lock my client application. I have yet to come across a Qt5 class that provides this function, so I'm wondering if I'll need to write an OS-specific library. Does anyone have any experience doing something like this? Thanks! A: On windows you can use below code: mywidget.cpp #include "mywidget.h" #include <Windows.h> #include <WtsApi32.h> #include <QDebug> MyWidget::MyWidget(QWidget *parent) : QWidget(parent) { WTSRegisterSessionNotification((HWND)this->winId(), NOTIFY_FOR_THIS_SESSION); } MyWidget::~MyWidget() { WTSUnRegisterSessionNotification((HWND)this->winId()); } bool MyWidget::nativeEvent(const QByteArray &eventType, void *message, long *result) { if (eventType != "windows_generic_MSG") return false; MSG *msg = static_cast<MSG*>(message); switch (msg->message) { case WM_WTSSESSION_CHANGE: qDebug() << "session change: " << msg->wParam; } return false; } project.pro ... LIBS += -lwtsapi32 ... reference1 reference2
Q: How to detect screen lock (Qt5, C++, Windows, OSX) In my Qt5 C++ client, I'm wanting to detect when a user running Windows or OSX has locked the screen, then simultaneously lock my client application. I have yet to come across a Qt5 class that provides this function, so I'm wondering if I'll need to write an OS-specific library. Does anyone have any experience doing something like this? Thanks! A: On windows you can use below code: mywidget.cpp #include "mywidget.h" #include <Windows.h> #include <WtsApi32.h> #include <QDebug> MyWidget::MyWidget(QWidget *parent) : QWidget(parent) { WTSRegisterSessionNotification((HWND)this->winId(), NOTIFY_FOR_THIS_SESSION); } MyWidget::~MyWidget() { WTSUnRegisterSessionNotification((HWND)this->winId()); } bool MyWidget::nativeEvent(const QByteArray &eventType, void *message, long *result) { if (eventType != "windows_generic_MSG") return false; MSG *msg = static_cast<MSG*>(message); switch (msg->message) { case WM_WTSSESSION_CHANGE: qDebug() << "session change: " << msg->wParam; } return false; } project.pro ... LIBS += -lwtsapi32 ... reference1 reference2
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:843982", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477179" }
79481c8ed9ac3a0b07a977cc94f05992e7203111
Stackoverflow Stackexchange Q: The length of labels must equal to the number of rows in the input data I don't know why I'm getting this error! My data training is a sparse matrix. dim(training) > 14407 161 dim(label.train) > 14407 1 xgb.train <- xgb.DMatrix(data = training, label = label.train) > Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) : The length of labels must equal to the number of rows in the input data I have checked my data and: * *label.train is a data.frame *training does not have all zero rows or columns *all values in training are numeric PS. My data is huge so I can't post a reproducible code, just need tips for what might be wrong from those who have experienced this error. A: You're getting the error because your labels are a data.frame. Passing them as a vector or a matrix works for me. vec_y <- mtcars$vs mat_y <- as.matrix(mtcars$vs) df_y <- mtcars[,8,drop=FALSE] #column vs is the 8th column x <- as.matrix(mtcars[,-8]) #column vs is the 8th column #vector labels: works xgboost::xgb.DMatrix(data=x, label=vec_y) #matrix labels: works xgboost::xgb.DMatrix(data=x, label=mat_y) #df labels: doesnt work xgboost::xgb.DMatrix(data=x, label=df_y)
Q: The length of labels must equal to the number of rows in the input data I don't know why I'm getting this error! My data training is a sparse matrix. dim(training) > 14407 161 dim(label.train) > 14407 1 xgb.train <- xgb.DMatrix(data = training, label = label.train) > Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) : The length of labels must equal to the number of rows in the input data I have checked my data and: * *label.train is a data.frame *training does not have all zero rows or columns *all values in training are numeric PS. My data is huge so I can't post a reproducible code, just need tips for what might be wrong from those who have experienced this error. A: You're getting the error because your labels are a data.frame. Passing them as a vector or a matrix works for me. vec_y <- mtcars$vs mat_y <- as.matrix(mtcars$vs) df_y <- mtcars[,8,drop=FALSE] #column vs is the 8th column x <- as.matrix(mtcars[,-8]) #column vs is the 8th column #vector labels: works xgboost::xgb.DMatrix(data=x, label=vec_y) #matrix labels: works xgboost::xgb.DMatrix(data=x, label=mat_y) #df labels: doesnt work xgboost::xgb.DMatrix(data=x, label=df_y) A: It is most likely your other script's data did not have any missing (NA) value. When you sparse (I'm guessing you were trying to one hot encoding columns) a data frame to a matrix, R will automatically remove missing value and hence the error. The best practice is to use "is.na" to replace all nulls to 0.
stackoverflow
{ "language": "en", "length": 242, "provenance": "stackexchange_0000F.jsonl.gz:843997", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477238" }
2cdc4906e5953d2cff4a1e9dc82bd2d2dbc7475c
Stackoverflow Stackexchange Q: Change the color of all nodes in a scene? So this may seem like a stupid question; however, I'll see if anyone has an answer. Is there any way to change the color of all nodes in a scene in swift? For example invert all the colors? I've created a game using SpriteKit and would like to create different themes. Instead of changing every node one by one. I would like to at least do most in one shot. If anyone has any advice that would be greatly appreciated! Thanks! -Matt A: Inside of the scene you want, for node in self.children { // I used spritenode, but you can add as many nodes with color options as you like. guard let snode = node as? SKSpriteNode else { continue } snode.color = .blue } The inversion function would be a separate question I think :P but something like: if snode.color == .black { node.color == .white } But you could probably do this with RGB and math as well.
Q: Change the color of all nodes in a scene? So this may seem like a stupid question; however, I'll see if anyone has an answer. Is there any way to change the color of all nodes in a scene in swift? For example invert all the colors? I've created a game using SpriteKit and would like to create different themes. Instead of changing every node one by one. I would like to at least do most in one shot. If anyone has any advice that would be greatly appreciated! Thanks! -Matt A: Inside of the scene you want, for node in self.children { // I used spritenode, but you can add as many nodes with color options as you like. guard let snode = node as? SKSpriteNode else { continue } snode.color = .blue } The inversion function would be a separate question I think :P but something like: if snode.color == .black { node.color == .white } But you could probably do this with RGB and math as well.
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:843999", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477241" }
6cf91cd8fc0fc2f1ea949bffe50c80aad8e23f5e
Stackoverflow Stackexchange Q: The correct way to delete a variable if it exists I try doing: def create_l(): if 'l' in globals(): l.destroy() l = Listbox(root) This works fine but it returns a syntax warning: Warning (from warnings module): File "C:\Users\User\Desktop\l.py", line 4 l = Listbox(root) SyntaxWarning: name 'l' is used prior to global declaration I am just wondering if there is a way to do this without the syntax warning. A: You should use the global key word when declaring the variable l: global l #declare the variable as global l = 'foo'
Q: The correct way to delete a variable if it exists I try doing: def create_l(): if 'l' in globals(): l.destroy() l = Listbox(root) This works fine but it returns a syntax warning: Warning (from warnings module): File "C:\Users\User\Desktop\l.py", line 4 l = Listbox(root) SyntaxWarning: name 'l' is used prior to global declaration I am just wondering if there is a way to do this without the syntax warning. A: You should use the global key word when declaring the variable l: global l #declare the variable as global l = 'foo' A: Use the del keyword if 'l' in globals(): del l
stackoverflow
{ "language": "en", "length": 103, "provenance": "stackexchange_0000F.jsonl.gz:844005", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477267" }
bbbc92289a70f9ada68d1d8dff13139b6070cd9b
Stackoverflow Stackexchange Q: npm init not working and getting stuck on version So I am using version 8.1.0 of Node.Js and when I call npm init to set up a project it goes to version and stays there. I have tried pressing enter or quitting with ^C but nothing happens. I have waited for over an hour and it hasn't progressed at all. Any idea what I should do? Here is basically what I am seeing: Edit: I tried reinstalling and still didn't work; so I uninstalled version 8.1.0 and installed the user recommended one (6.11.0) and it works fine. I am pretty sure it's a bug in version 8.1.0, but it's the one I need. Edit 2: Oh, I am running this on Windows 10. A: I am having the same problem. However to by-pass and create the package.json file you can use the -y flag and this creates a file with defaults that you can edit later $npm init -y
Q: npm init not working and getting stuck on version So I am using version 8.1.0 of Node.Js and when I call npm init to set up a project it goes to version and stays there. I have tried pressing enter or quitting with ^C but nothing happens. I have waited for over an hour and it hasn't progressed at all. Any idea what I should do? Here is basically what I am seeing: Edit: I tried reinstalling and still didn't work; so I uninstalled version 8.1.0 and installed the user recommended one (6.11.0) and it works fine. I am pretty sure it's a bug in version 8.1.0, but it's the one I need. Edit 2: Oh, I am running this on Windows 10. A: I am having the same problem. However to by-pass and create the package.json file you can use the -y flag and this creates a file with defaults that you can edit later $npm init -y A: As the previous answers say, Its a bug on nodejs v 8.1.0 and the solution is to wait for the new upcoming release or downgrading to previous versions. But,there are some of us who find downgrading kinder annoying and can't wait for that new patched release :)! So the the simple work around without either of the solution to your nodejs is by creating the package.json manually on your project folder. Below is the frame of the file. { "name": "", //name of the app. ex "yourAppName" "version": "", //dafault is 1.0.0 "description": "", // description of the app "dependencies": { "dependencieName": "version" }, //ex "shelljs": "^0.7.0" "devDependencies": {}, //same as the above "scripts": { "scriptName": "path/to/script" }, "repository": { "type": "git", //git is the default "url": "git+https://github.com/yourUserName/yourRepoName" //link to your repo }, "keywords": [], "author": "", //the author, maybe you :) "license": "", //License type "bugs": { "url": "" //ex "https://github.com/yourUserName/yourRepoName/issues" }, } NOTE: You should remove the comments (starting with //) because json config files doesn't support comments by default, otherwise see https://www.npmjs.com/package/json-comments on how to enable config.json comments A: Alright, it seems to be a bug in 8.1.0 and will be fixed in Tuesday's release. https://github.com/nodejs/node/pull/13560#issuecomment-307565172 A: According to what I've read about this issue on GitHub, you can work around it by switching to the earlier Node v8.0.0 and npm v5.0.0 release. This is an issue with Node v8.1.0. The fix for this issue is already in progress and should be implemented in v8.1.1 of Node which releases in a couple of days. Till then, downgrade to the old version and see if that works for you. A: Yes, I also faced this issue, so you can downgrade the node to LTS version. Currently 6.11 version is LTS. It would be easier to downgrade, if you have used a nvm (Node Version Manager) for installing node. Use below NVM commands nvm install 6.11 nvm use 6.11 A: I'm using Window OS and I turn off controlled folder access. I hope It can resolve this problem!
stackoverflow
{ "language": "en", "length": 500, "provenance": "stackexchange_0000F.jsonl.gz:844033", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477365" }
80bff6d487ebd494723fcb7981b1154b5d36a0a8
Stackoverflow Stackexchange Q: Keras - Difference between categorical_accuracy and sparse_categorical_accuracy What is the difference between categorical_accuracy and sparse_categorical_accuracy in Keras? There is no hint in the documentation for these metrics, and by asking Dr. Google, I did not find answers for that either. The source code can be found here: def categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.argmax(y_true, axis=-1), K.argmax(y_pred, axis=-1)), K.floatx()) def sparse_categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.max(y_true, axis=-1), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.floatx()) A: So in categorical_accuracy you need to specify your target (y) as one-hot encoded vector (e.g. in case of 3 classes, when a true class is second class, y should be (0, 1, 0). In sparse_categorical_accuracy you need should only provide an integer of the true class (in the case from previous example - it would be 1 as classes indexing is 0-based).
Q: Keras - Difference between categorical_accuracy and sparse_categorical_accuracy What is the difference between categorical_accuracy and sparse_categorical_accuracy in Keras? There is no hint in the documentation for these metrics, and by asking Dr. Google, I did not find answers for that either. The source code can be found here: def categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.argmax(y_true, axis=-1), K.argmax(y_pred, axis=-1)), K.floatx()) def sparse_categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.max(y_true, axis=-1), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.floatx()) A: So in categorical_accuracy you need to specify your target (y) as one-hot encoded vector (e.g. in case of 3 classes, when a true class is second class, y should be (0, 1, 0). In sparse_categorical_accuracy you need should only provide an integer of the true class (in the case from previous example - it would be 1 as classes indexing is 0-based). A: Looking at the source def categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.argmax(y_true, axis=-1), K.argmax(y_pred, axis=-1)), K.floatx()) def sparse_categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.max(y_true, axis=-1), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.floatx()) categorical_accuracy checks to see if the index of the maximal true value is equal to the index of the maximal predicted value. sparse_categorical_accuracy checks to see if the maximal true value is equal to the index of the maximal predicted value. From Marcin's answer above the categorical_accuracy corresponds to a one-hot encoded vector for y_true. A: The sparse_categorical_accuracy expects sparse targets: [[0], [1], [2]] For instance: import tensorflow as tf sparse = [[0], [1], [2]] logits = [[.8, .1, .1], [.5, .3, .2], [.2, .2, .6]] sparse_cat_acc = tf.metrics.SparseCategoricalAccuracy() sparse_cat_acc(sparse, logits) <tf.Tensor: shape=(), dtype=float64, numpy=0.6666666666666666> categorical_accuracy expects one hot encoded targets: [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]] For instance: onehot = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]] logits = [[.8, .1, .1], [.5, .3, .2], [.2, .2, .6]] cat_acc = tf.metrics.CategoricalAccuracy() cat_acc(sparse, logits) <tf.Tensor: shape=(), dtype=float64, numpy=0.6666666666666666> A: One difference that I just hit is the difference in the name of the metrics. with categorical_accuracy, this worked: mcp_save_acc = ModelCheckpoint('model_' + 'val_acc{val_accuracy:.3f}.hdf5', save_best_only=True, monitor='val_accuracy', mode='max') but after switching to sparse_categorical accuracy, I now need this: mcp_save_acc = ModelCheckpoint('model_' + 'val_acc{val_sparse_categorical_accuracy:.3f}.hdf5', save_best_only=True, monitor='val_sparse_categorical_accuracy', mode='max') even though I still have metrics=['accuracy'] as an argument to my compile() function. I kind of wish val_acc and/or val_accuracy just worked for all keras' inbuilt *_crossentropy losses.
stackoverflow
{ "language": "en", "length": 371, "provenance": "stackexchange_0000F.jsonl.gz:844076", "question_score": "69", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477489" }
4e51d80741bbaf8dd6b2f72a4ac281e25e6196f1
Stackoverflow Stackexchange Q: How to share local changes without git push? I'm using git in my project. Sometimes I need to share my modified changes with my colleagues or to different PC, but I don't want to push those changes. He will take my code and modify something and then will push that code. For now I manually give him file via mail or send in pen drive. I want this to be done via git. Can I do like git commit and then share without git push? A: You can save the changes to a patch file with git diff > /path/to/file.patch This supposes that your changes are unstaged. Use git diff --cached if they are staged. I would not commit them, since your colleague is going to do that and you'll run into conflicts otherwise. You can send this file via mail or whatever, and your colleague can apply those changes with git apply /path/to/file.patch
Q: How to share local changes without git push? I'm using git in my project. Sometimes I need to share my modified changes with my colleagues or to different PC, but I don't want to push those changes. He will take my code and modify something and then will push that code. For now I manually give him file via mail or send in pen drive. I want this to be done via git. Can I do like git commit and then share without git push? A: You can save the changes to a patch file with git diff > /path/to/file.patch This supposes that your changes are unstaged. Use git diff --cached if they are staged. I would not commit them, since your colleague is going to do that and you'll run into conflicts otherwise. You can send this file via mail or whatever, and your colleague can apply those changes with git apply /path/to/file.patch
stackoverflow
{ "language": "en", "length": 155, "provenance": "stackexchange_0000F.jsonl.gz:844083", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477512" }
1b0dc8fa9f42c977c4b044f9ec1d6a0b03ac1506
Stackoverflow Stackexchange Q: How to select opponents for TurnBaseMatches after GMS 11.0.0? getSelectOpponentsIntent(...) was a method games could call to get an opponent selection UI. The output of this was a list of selected Player IDs that you could feed into TurnBasedMatchConfig to create a match. All overloads for this method (and its realtime multiplayer counterparts) are deprecated as of version 11.0.0 of Google Play Services. The deprecation notice doesn't list a replacement and only says vague things about G+ integration going away. Play Games switched to "Gamer IDs" awhile back (which doesn't use G+). It makes sense that the UI for selecting an opponent would cease showing G+ friends/circles... But how are users supposed to select Gamer ID opponents if the only UI for doing so is deprecated? Players don't know their or anyone else's Player ID (it's a long random number). Without this UI or a service that resolves Gamer IDs to Player IDs... it appears the only thing players can do is auto match random opponents and rematch already-created games. A: TurnBasedMultiplayer (the class) was deprecated. It's replacement (TurnBasedMultiplayerClient) has a similar method which isn't deprecated.
Q: How to select opponents for TurnBaseMatches after GMS 11.0.0? getSelectOpponentsIntent(...) was a method games could call to get an opponent selection UI. The output of this was a list of selected Player IDs that you could feed into TurnBasedMatchConfig to create a match. All overloads for this method (and its realtime multiplayer counterparts) are deprecated as of version 11.0.0 of Google Play Services. The deprecation notice doesn't list a replacement and only says vague things about G+ integration going away. Play Games switched to "Gamer IDs" awhile back (which doesn't use G+). It makes sense that the UI for selecting an opponent would cease showing G+ friends/circles... But how are users supposed to select Gamer ID opponents if the only UI for doing so is deprecated? Players don't know their or anyone else's Player ID (it's a long random number). Without this UI or a service that resolves Gamer IDs to Player IDs... it appears the only thing players can do is auto match random opponents and rematch already-created games. A: TurnBasedMultiplayer (the class) was deprecated. It's replacement (TurnBasedMultiplayerClient) has a similar method which isn't deprecated.
stackoverflow
{ "language": "en", "length": 187, "provenance": "stackexchange_0000F.jsonl.gz:844114", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477620" }
c8bd8742a97632bcda18eabf76b4c6713e5ecdae
Stackoverflow Stackexchange Q: Error importing tensorflow. unless you are using bazel, you should not try to import tensorflow from its source directory; See the attached images for my python and tensorflow version. Then I tested out importing tensorflow in cmd window. $Python >>> import tensorflow as tf But I get the following error: Error: Error importing tensorflow. unless you are using bazel, you should not try to import tensorflow from its source directory; please exit the tensorflow source tree, and relaunch your python interpreter from there
Q: Error importing tensorflow. unless you are using bazel, you should not try to import tensorflow from its source directory; See the attached images for my python and tensorflow version. Then I tested out importing tensorflow in cmd window. $Python >>> import tensorflow as tf But I get the following error: Error: Error importing tensorflow. unless you are using bazel, you should not try to import tensorflow from its source directory; please exit the tensorflow source tree, and relaunch your python interpreter from there
stackoverflow
{ "language": "en", "length": 84, "provenance": "stackexchange_0000F.jsonl.gz:844125", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477659" }
41f8a3e381d4147e83e8d91bc4799ac48c05ff0c
Stackoverflow Stackexchange Q: Searchbar xamarin forms I a novice in Xamarin and C# T want to add a dynamic searchbar (mean without pushing the search button) in my content view in order to search in my sqlite database. I cannot figure out why it not working: I have been trying to do the same things like in this tuto but with database but the list cannot display because the app is stopped Here is my method in the database: //SELECT words public List<MyWords> SelectWords(string keyword) { var myword = (from word in conn.Table<MyWords>() where word.Word1.ToLower().Contains(keyword.ToLower()) || word.Word2.ToLower().Contains(keyword.ToLower()) select word); return myword.ToList(); } Here is my method in the class of my contact page: //search on the list view private void SearcMyWords(object sender, EventArgs e) { // var keyword = SearchWords.Text; var words = mywordsdatabase.SelectWords("car"); listWordsView.ItemsSource = words; } Here is my xaml page : <SearchBar x:Name="SearchWords" TextChanged=""/> Thanks in advance. A: You forgot to implement the actual handler for the TextChanged property. Change your XAML like this: <SearchBar x:Name="SearchWords" TextChanged="Handle_TextChanged"/> And add a method in your code-behind, which will probably look something like this: private void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e) { SelectWords(e.NewTextValue); }
Q: Searchbar xamarin forms I a novice in Xamarin and C# T want to add a dynamic searchbar (mean without pushing the search button) in my content view in order to search in my sqlite database. I cannot figure out why it not working: I have been trying to do the same things like in this tuto but with database but the list cannot display because the app is stopped Here is my method in the database: //SELECT words public List<MyWords> SelectWords(string keyword) { var myword = (from word in conn.Table<MyWords>() where word.Word1.ToLower().Contains(keyword.ToLower()) || word.Word2.ToLower().Contains(keyword.ToLower()) select word); return myword.ToList(); } Here is my method in the class of my contact page: //search on the list view private void SearcMyWords(object sender, EventArgs e) { // var keyword = SearchWords.Text; var words = mywordsdatabase.SelectWords("car"); listWordsView.ItemsSource = words; } Here is my xaml page : <SearchBar x:Name="SearchWords" TextChanged=""/> Thanks in advance. A: You forgot to implement the actual handler for the TextChanged property. Change your XAML like this: <SearchBar x:Name="SearchWords" TextChanged="Handle_TextChanged"/> And add a method in your code-behind, which will probably look something like this: private void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e) { SelectWords(e.NewTextValue); }
stackoverflow
{ "language": "en", "length": 191, "provenance": "stackexchange_0000F.jsonl.gz:844130", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477679" }
748114bbabd74360c6888b4e1ea868ed41a406de
Stackoverflow Stackexchange Q: Elegant ES6 way to update state in React The syntax to update state in React has change a lot. I'm trying to find the most simple and elegant way to initiate and update it. Got this RN code: const { quotes } = require('./quotes.json') class QuoteScreen extends Component { state = { QuoteIndex: 0 } render() { return ( <Image ...> <View ...> ... <ButtonNextQuote onPress={() => { this.setState((prevState, props) => { return { QuoteIndex: (prevState.QuoteIndex + 1) % (quotes.length - 1) } }) }} /> </View> </Image> ) } } Would it be possible to reduce the updating of state in the onPress? Would like to avoid calling an anonymous function twice but don't want to reference and bind a handler. Would also like to avoid using the return.. A: I would store the update function in a variable outside the class, e.g. const newState = ({QuoteIndex: i}) => ({QuoteIndex: (i + 1) % nQuotes}); (of course you can chose to define the function in any way you like, maybe "terseness" isn't as important to you anymore if it isn't inlined) And then you can just call this.setState(newState): onPress={() => this.setState(newState)}
Q: Elegant ES6 way to update state in React The syntax to update state in React has change a lot. I'm trying to find the most simple and elegant way to initiate and update it. Got this RN code: const { quotes } = require('./quotes.json') class QuoteScreen extends Component { state = { QuoteIndex: 0 } render() { return ( <Image ...> <View ...> ... <ButtonNextQuote onPress={() => { this.setState((prevState, props) => { return { QuoteIndex: (prevState.QuoteIndex + 1) % (quotes.length - 1) } }) }} /> </View> </Image> ) } } Would it be possible to reduce the updating of state in the onPress? Would like to avoid calling an anonymous function twice but don't want to reference and bind a handler. Would also like to avoid using the return.. A: I would store the update function in a variable outside the class, e.g. const newState = ({QuoteIndex: i}) => ({QuoteIndex: (i + 1) % nQuotes}); (of course you can chose to define the function in any way you like, maybe "terseness" isn't as important to you anymore if it isn't inlined) And then you can just call this.setState(newState): onPress={() => this.setState(newState)} A: Here's how I would do that. I have used object destructuring in the first argument of setState's callback (prevState), and I have used a separate function instead of an anonymous one for performance reasons. Also, please note that I didn't need to manually bind the function to this, because I have used an arrow function for it. const { quotes } = require('./quotes.json') class QuoteScreen extends Component { state = { QuoteIndex: 0 } handleUpdateState = () => { this.setState(({ QuoteIndex }) => ({ QuoteIndex: (QuoteIndex + 1) % (quotes.length - 1) })); } render() { return ( <Image ...> <View ...> ... <ButtonNextQuote onPress={this.handleUpdateState} /> </View> </Image> ) } } A: I think a popular and good way to do this is to * *Use "functional setState" by providing a callback to this.setState to avoid some weird cases in batch state updates *"declare state changes separately from the component classes" so that the functions that get the new state can be reused and tested separately. check this article for a great explanation of this approach featuring tweets by Dan Abramov Example: const { quotes } = require('./quotes.json') // keep pure function outside component to be reusable, testable const getQuoteIndex = ({ QuoteIndex }) => ({ QuoteIndex: (QuoteIndex + 1) % (quotes.length - 1) }) class QuoteScreen extends Component { state = { QuoteIndex: 0 } // arrow function will take care of this binding handlePress = () => { this.setState(getQuoteIndex) } render() { return ( <Image ...> <View ...> ... <ButtonNextQuote onPress={this.handlePress} /> </View> </Image> ) } } A: You'd want to avoid redefining the event handler each time render runs, like others have said. I prefer to pass an object to setState instead of a callback function: _handlePress = () => { this.setState({ QuoteIndex: (this.state.QuoteIndex + 1) % (quotes.length - 1) }); }; onPress={this._handlePress} This is easier to read because it's explicit where the state is coming from. Also, you don't have to keep track of extra callback functions.
stackoverflow
{ "language": "en", "length": 525, "provenance": "stackexchange_0000F.jsonl.gz:844133", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477692" }
d984e6e89314ab42c2958615ff14567a636345e1
Stackoverflow Stackexchange Q: Recursion Ending Too Soon in Javascript Function I am currently learning JavaScript through remaking games from scratch, and my current project is Minesweeper. While trying to create the recursive function that reveals the spaces surrounding a clicked space I have run into the issue of it ending too soon for seemingly no reason. You can read the whole code (so far) here: pastebin.com or refer to just the stand-alone function below: function showAdjacent(block) { if(block.minesNextTo != 0) return; console.log(block.row+','+block.col); block.uncovered = true; block.hidden = false; console.log(block.adjacentBlocks.length); for(i = 0; i < block.adjacentBlocks.length; i++) block.adjacentBlocks[i].hidden = false; for(i = 0; i < block.adjacentBlocks.length; i++) { if(!block.adjacentBlocks[i].uncovered) showAdjacent(block.adjacentBlocks[i]); } } (and yes I know that this function shouldn't only be triggered if a block has zero mines next to it, this is just easier for testing purposes) A: You need to declare i as a local variable: var i; at the top of the function would do it. As it is, it's implicitly global, so the recursive calls mess up the value of i in the parent contexts.
Q: Recursion Ending Too Soon in Javascript Function I am currently learning JavaScript through remaking games from scratch, and my current project is Minesweeper. While trying to create the recursive function that reveals the spaces surrounding a clicked space I have run into the issue of it ending too soon for seemingly no reason. You can read the whole code (so far) here: pastebin.com or refer to just the stand-alone function below: function showAdjacent(block) { if(block.minesNextTo != 0) return; console.log(block.row+','+block.col); block.uncovered = true; block.hidden = false; console.log(block.adjacentBlocks.length); for(i = 0; i < block.adjacentBlocks.length; i++) block.adjacentBlocks[i].hidden = false; for(i = 0; i < block.adjacentBlocks.length; i++) { if(!block.adjacentBlocks[i].uncovered) showAdjacent(block.adjacentBlocks[i]); } } (and yes I know that this function shouldn't only be triggered if a block has zero mines next to it, this is just easier for testing purposes) A: You need to declare i as a local variable: var i; at the top of the function would do it. As it is, it's implicitly global, so the recursive calls mess up the value of i in the parent contexts.
stackoverflow
{ "language": "en", "length": 177, "provenance": "stackexchange_0000F.jsonl.gz:844134", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477697" }
792d843387508e08fcf820ec6fda79713c96f438
Stackoverflow Stackexchange Q: Place Graph on Kivy as a Widget with Button I want to put a graph that self updates. So when I press a Kivy button on my GUI script written with Python and it's supposed to take me to a Screen. The Screen has a graph on a part of the Screen and buttons on the rest of the screen. However, I add the graph and it opens in a separate window. How do I do that? I used the matplotlib library for plotting the graph. I used plt.show() and it opens a different window. A: To prevent matplotlib from stealing the focus of your Window you need to tell it to do so for some strange reason (maybe because of high usage of MPL in IPython notebook?) import matplotlib matplotlib.use('Agg') After those lines the window should stop stealing. The updating on the other hand is something way different and that's why there's garden.graph and garden.matplotlib. If you intend to just draw some simple plots, just use the Graph. If you really need MPL and/or you want to do something complex, use the MPL backend (garden.matplotlib).
Q: Place Graph on Kivy as a Widget with Button I want to put a graph that self updates. So when I press a Kivy button on my GUI script written with Python and it's supposed to take me to a Screen. The Screen has a graph on a part of the Screen and buttons on the rest of the screen. However, I add the graph and it opens in a separate window. How do I do that? I used the matplotlib library for plotting the graph. I used plt.show() and it opens a different window. A: To prevent matplotlib from stealing the focus of your Window you need to tell it to do so for some strange reason (maybe because of high usage of MPL in IPython notebook?) import matplotlib matplotlib.use('Agg') After those lines the window should stop stealing. The updating on the other hand is something way different and that's why there's garden.graph and garden.matplotlib. If you intend to just draw some simple plots, just use the Graph. If you really need MPL and/or you want to do something complex, use the MPL backend (garden.matplotlib).
stackoverflow
{ "language": "en", "length": 187, "provenance": "stackexchange_0000F.jsonl.gz:844135", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477698" }
962feb0c730fc71e805402dbe0022feaf91f409b
Stackoverflow Stackexchange Q: How do you stop inputs going to next input in python? suppose i ask for 2 inputs: input("Age:") Something* input("Name:") But If I do this, then if I put 2 inputs. So If its asking for age and I put "5". Then while the program is doing *something, any inputs I make will go into the slot asking for Name before "Name:" even appears. How do i stop this from happening? A: You could do something like this with the module curses (from this post https://stackoverflow.com/a/33679981/6655211 possible duplicate) input("Age:") import curses stdscr = curses.initscr() curses.noecho() # Something* import time time.sleep(5) curses.endwin() input("Name:")
Q: How do you stop inputs going to next input in python? suppose i ask for 2 inputs: input("Age:") Something* input("Name:") But If I do this, then if I put 2 inputs. So If its asking for age and I put "5". Then while the program is doing *something, any inputs I make will go into the slot asking for Name before "Name:" even appears. How do i stop this from happening? A: You could do something like this with the module curses (from this post https://stackoverflow.com/a/33679981/6655211 possible duplicate) input("Age:") import curses stdscr = curses.initscr() curses.noecho() # Something* import time time.sleep(5) curses.endwin() input("Name:")
stackoverflow
{ "language": "en", "length": 103, "provenance": "stackexchange_0000F.jsonl.gz:844155", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477758" }
37cab57ecd0a0eba1a43c1ed4ad81f7a0cce5add
Stackoverflow Stackexchange Q: ESLint parsing error when using arrow syntax with async I'm using ESLint to analyze my code. The code runs fine, but I get this error from eslint: [eslint] Parsing error: Unexpected token t (parameter) t: any test.serial('set: Handles save error', async t => { // function definition }); Here's .eslintrc.js module.exports = { extends: 'google', parserOptions: { ecmaVersion: 6 } }; A: async/await is an ECMAScript 2017 feature, so if you change ecmaVersion: 8 instead of 6, this should work!
Q: ESLint parsing error when using arrow syntax with async I'm using ESLint to analyze my code. The code runs fine, but I get this error from eslint: [eslint] Parsing error: Unexpected token t (parameter) t: any test.serial('set: Handles save error', async t => { // function definition }); Here's .eslintrc.js module.exports = { extends: 'google', parserOptions: { ecmaVersion: 6 } }; A: async/await is an ECMAScript 2017 feature, so if you change ecmaVersion: 8 instead of 6, this should work! A: I had a similar problem and solve editing the package.json line 5. I removed " ." that's after "eslint" and everything is fine now. A: You may have this error even if you use latest version of ECMAScript if that is the case (like it was with me) the problem may be in your configuration: "space-before-function-paren": [ "error", "never" ] if you have this you should make a change to: "space-before-function-paren": [ "error", { "anonymous": "never", "named": "never", "asyncArrow": "always" } ], You can find this in this issue on GitHub.
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:844161", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477769" }
5aac1abba25d8030a6f1e4c426407eb6a2c3fad3
Stackoverflow Stackexchange Q: Webhook OAuth - How do I exchange a webhook authorization code for an access token? I'm trying to use the oauth approach of adding webhooks to channels within Discord. The workflow is that a user authenticates with my application using OAuth. Then I redirect them to: ApiClient::API_URL.'/oauth2/authorize?client_id='.Discord::appKey().'&scope=webhook.incoming&redirect_uri='.urlencode($webhookCallback->callbackUrl()).'&response_type=code'); The redirect URL works because it does allow the OAuth'd user to choose a server/channel. When you exchange the authorization code for an access token, the token response will contain the webhook object: I'm using the following request to try to convert the authorization code into an access token with no luck: $client = new Client(); $response = $client->post('https://discordapp.com/api/oauth2/token', [ 'headers' => [ 'Accept' => 'application/json' ], 'form_params' => [ 'grant_type' => 'authorization_code', 'client_id' => env('DISCORD_APP_KEY'), 'client_secret' => env('DISCORD_APP_SECRET'), 'redirect_uri' => url('/discord/webhook-authorized'), 'code' => $request->get('code') ], ]); The response I get from the API is: Client error: `POST https://discordapp.com/api/oauth2/token` resulted in a `401 UNAUTHORIZED` response: {"error": "access_denied"} What grant type do I need to complete this request? A: 'grant_type' => 'authorization_code', needed to be 'grant_type' => 'client_credentials',
Q: Webhook OAuth - How do I exchange a webhook authorization code for an access token? I'm trying to use the oauth approach of adding webhooks to channels within Discord. The workflow is that a user authenticates with my application using OAuth. Then I redirect them to: ApiClient::API_URL.'/oauth2/authorize?client_id='.Discord::appKey().'&scope=webhook.incoming&redirect_uri='.urlencode($webhookCallback->callbackUrl()).'&response_type=code'); The redirect URL works because it does allow the OAuth'd user to choose a server/channel. When you exchange the authorization code for an access token, the token response will contain the webhook object: I'm using the following request to try to convert the authorization code into an access token with no luck: $client = new Client(); $response = $client->post('https://discordapp.com/api/oauth2/token', [ 'headers' => [ 'Accept' => 'application/json' ], 'form_params' => [ 'grant_type' => 'authorization_code', 'client_id' => env('DISCORD_APP_KEY'), 'client_secret' => env('DISCORD_APP_SECRET'), 'redirect_uri' => url('/discord/webhook-authorized'), 'code' => $request->get('code') ], ]); The response I get from the API is: Client error: `POST https://discordapp.com/api/oauth2/token` resulted in a `401 UNAUTHORIZED` response: {"error": "access_denied"} What grant type do I need to complete this request? A: 'grant_type' => 'authorization_code', needed to be 'grant_type' => 'client_credentials',
stackoverflow
{ "language": "en", "length": 175, "provenance": "stackexchange_0000F.jsonl.gz:844164", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44477777" }
04f6981ac8f33f5063ffd986166d303978ec5f0a
Stackoverflow Stackexchange Q: How to make zip_longest available in itertools using Python 2.7 When trying to import this function on a Python Jupyter 2.7 nb running on Windows 10, I get this error: I believe I hadn't encountered problems in the past because I was using Python 3. So I wonder if it is just that it is not available in Python 2, or if there is a way of making it work. A: If you don't know which version of python runs the script you can use this trick: try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest # now this works in both python 2 and 3 print(list(zip_longest([1,2,3],[4,5])))
Q: How to make zip_longest available in itertools using Python 2.7 When trying to import this function on a Python Jupyter 2.7 nb running on Windows 10, I get this error: I believe I hadn't encountered problems in the past because I was using Python 3. So I wonder if it is just that it is not available in Python 2, or if there is a way of making it work. A: If you don't know which version of python runs the script you can use this trick: try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest # now this works in both python 2 and 3 print(list(zip_longest([1,2,3],[4,5]))) A: For Python 3, the method is zip_longest: from itertools import zip_longest For Python 2, the method is izip_longest: from itertools import izip_longest
stackoverflow
{ "language": "en", "length": 135, "provenance": "stackexchange_0000F.jsonl.gz:844268", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478119" }
b06f46f10d1742b81464aabd35ba5ada5dad981c
Stackoverflow Stackexchange Q: How to set initial weights in MLPClassifier? I cannot find a way to set the initial weights of the neural network, could someone tell me how please? I am using python package sklearn.neural_network.MLPClassifier. Here is the code for reference: from sklearn.neural_network import MLPClassifier classifier = MLPClassifier(solver="sgd") classifier.fit(X_train, y_train) A: Solution: A working solution is to inherit from MLPClassifier and override the _init_coef method. In the _init_coef write the code to set the initial weights. Then use the new class "MLPClassifierOverride" as in the example below instead of "MLPClassifier" # new class class MLPClassifierOverride(MLPClassifier): # Overriding _init_coef method def _init_coef(self, fan_in, fan_out): if self.activation == 'logistic': init_bound = np.sqrt(2. / (fan_in + fan_out)) elif self.activation in ('identity', 'tanh', 'relu'): init_bound = np.sqrt(6. / (fan_in + fan_out)) else: raise ValueError("Unknown activation function %s" % self.activation) coef_init = ### place your initial values for coef_init here intercept_init = ### place your initial values for intercept_init here return coef_init, intercept_init
Q: How to set initial weights in MLPClassifier? I cannot find a way to set the initial weights of the neural network, could someone tell me how please? I am using python package sklearn.neural_network.MLPClassifier. Here is the code for reference: from sklearn.neural_network import MLPClassifier classifier = MLPClassifier(solver="sgd") classifier.fit(X_train, y_train) A: Solution: A working solution is to inherit from MLPClassifier and override the _init_coef method. In the _init_coef write the code to set the initial weights. Then use the new class "MLPClassifierOverride" as in the example below instead of "MLPClassifier" # new class class MLPClassifierOverride(MLPClassifier): # Overriding _init_coef method def _init_coef(self, fan_in, fan_out): if self.activation == 'logistic': init_bound = np.sqrt(2. / (fan_in + fan_out)) elif self.activation in ('identity', 'tanh', 'relu'): init_bound = np.sqrt(6. / (fan_in + fan_out)) else: raise ValueError("Unknown activation function %s" % self.activation) coef_init = ### place your initial values for coef_init here intercept_init = ### place your initial values for intercept_init here return coef_init, intercept_init A: The docs show you the attributes in use. Attributes: ... coefs_ : list, length n_layers - 1 The ith element in the list represents the weight matrix corresponding to > layer i. intercepts_ : list, length n_layers - 1 The ith element in the list represents the bias vector corresponding to layer > i + 1. Just build your classifier clf=MLPClassifier(solver="sgd") and set coefs_ and intercepts_ before calling clf.fit(). The only remaining question is: does sklearn overwrite your inits? The code looks like: if not hasattr(self, 'coefs_') or (not self.warm_start and not incremental): # First time training the model self._initialize(y, layer_units) This looks to me like it won't replace your given coefs_ (you might check biases too). The packing and unpacking functions further indicates that this should be possible. These are probably used for serialization through pickle internally. A: multilayer_perceptron.py initializes the weights based on the nonlinear function used for hidden layers. If you want to try a different initialization, you can take a look at the function _init_coef here and modify as you desire.
stackoverflow
{ "language": "en", "length": 333, "provenance": "stackexchange_0000F.jsonl.gz:844272", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44478133" }