id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
ad4849c4c4d02e584df64ff1274d4389d1473095
Stackoverflow Stackexchange Q: RxJava2 Observable backpressure recently I realized that I don't understand how RxJava2 backpressure works. I made small test and I expect that it should fail with MissingBackpressureException exception: @Test public void testBackpressureWillFail() { Observable.<Integer>create(e -> { for (int i = 0; i < 10000; i++) { System.out.println("Emit: " + i); e.onNext(i); } e.onComplete(); }) .subscribeOn(Schedulers.newThread()) .observeOn(Schedulers.computation()) .doOnNext(i -> { Thread.sleep(100); System.out.println("Processed:" + i); }) .blockingSubscribe(); } System out shows next: Emit: 0 Emit: 1 Emit: 2 ... Emit: 10000 Processed:0 Processed:1 Processed:2 ... Processed:10000 Why it doesn't produce MissingBackpressureException. I expect that e.onNext(i); will put item into buffer of ObservableObserveOn and after it's size is greater than static final int BUFFER_SIZE = Math.max(16,Integer.getInteger("rx2.buffer-size",128).intValue()); It should throw MissingBackpressureException which doesn't happen. Does the buffer automatically grow? If not where are items stored? A: That's because backpressure moved out to Flowableonly with RxJava2, see here. If you will switch to Flowable with BackpressureStrategy.MISSING you will get the exception. That also means that in your case you indeed have buffer that automatically grows, from observerOn docs: Modifies an ObservableSource to perform its emissions and notifications on a specified Scheduler, asynchronously with an unbounded buffer...
Q: RxJava2 Observable backpressure recently I realized that I don't understand how RxJava2 backpressure works. I made small test and I expect that it should fail with MissingBackpressureException exception: @Test public void testBackpressureWillFail() { Observable.<Integer>create(e -> { for (int i = 0; i < 10000; i++) { System.out.println("Emit: " + i); e.onNext(i); } e.onComplete(); }) .subscribeOn(Schedulers.newThread()) .observeOn(Schedulers.computation()) .doOnNext(i -> { Thread.sleep(100); System.out.println("Processed:" + i); }) .blockingSubscribe(); } System out shows next: Emit: 0 Emit: 1 Emit: 2 ... Emit: 10000 Processed:0 Processed:1 Processed:2 ... Processed:10000 Why it doesn't produce MissingBackpressureException. I expect that e.onNext(i); will put item into buffer of ObservableObserveOn and after it's size is greater than static final int BUFFER_SIZE = Math.max(16,Integer.getInteger("rx2.buffer-size",128).intValue()); It should throw MissingBackpressureException which doesn't happen. Does the buffer automatically grow? If not where are items stored? A: That's because backpressure moved out to Flowableonly with RxJava2, see here. If you will switch to Flowable with BackpressureStrategy.MISSING you will get the exception. That also means that in your case you indeed have buffer that automatically grows, from observerOn docs: Modifies an ObservableSource to perform its emissions and notifications on a specified Scheduler, asynchronously with an unbounded buffer...
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:907141", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674174" }
45a26648f8ac72a903eb7c851ab3e7d4808267f9
Stackoverflow Stackexchange Q: Ansible idempotency issue with unarchive and then modify extracted file In one of the ansible roles we extract some tar.gz file and then we replace one of the extracted files with another one to fix some issue. The problem is when we run ansible again, ansible is extracting the archive back again since the directory content is changed and naturally marking the task changed and also replaces the file again as expected. So we have two "changes" now everytime we run the playbook... How should I handle this issue to keep the operation idempotent? A: Use exclude option to ignore certain paths, see documentation. i.e. - unarchive: src: https://example.com/example.zip dest: /usr/local/bin remote_src: True exclude: bad.config creates might also suit you, unarchive step will not be run if specified path already exists on remote machine
Q: Ansible idempotency issue with unarchive and then modify extracted file In one of the ansible roles we extract some tar.gz file and then we replace one of the extracted files with another one to fix some issue. The problem is when we run ansible again, ansible is extracting the archive back again since the directory content is changed and naturally marking the task changed and also replaces the file again as expected. So we have two "changes" now everytime we run the playbook... How should I handle this issue to keep the operation idempotent? A: Use exclude option to ignore certain paths, see documentation. i.e. - unarchive: src: https://example.com/example.zip dest: /usr/local/bin remote_src: True exclude: bad.config creates might also suit you, unarchive step will not be run if specified path already exists on remote machine
stackoverflow
{ "language": "en", "length": 135, "provenance": "stackexchange_0000F.jsonl.gz:907158", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674245" }
d4933879116f98adfe75b6193bc4d2928ce1757d
Stackoverflow Stackexchange Q: how to use directive @push in blade template laravel I need script only on one page. and it should load after jQuery. I tried in index.blade <script type="text/javascript" src="{{ URL::asset ('js/jquery.js') }}"></script> @push('custom-scripts') <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script> @endpush and then I should use @stack('custom-scripts') in my view? A: You just need to make that the opposite way, @push is meant to be in the child view, which is pushing content to the parent @stack directive. So your index.blade.php should have a: @stack('custom-scripts') And your child view: @push('custom-scripts') <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script> @endpush You can also use @parent directive with @section like this: //index.blade.php @yield('scripts') //child.blade.php @section('scripts') @parent <!-- The rest of your scripts --> @endsection If you need more info I'd recommend you to check the documentation. Hope this helped you.
Q: how to use directive @push in blade template laravel I need script only on one page. and it should load after jQuery. I tried in index.blade <script type="text/javascript" src="{{ URL::asset ('js/jquery.js') }}"></script> @push('custom-scripts') <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script> @endpush and then I should use @stack('custom-scripts') in my view? A: You just need to make that the opposite way, @push is meant to be in the child view, which is pushing content to the parent @stack directive. So your index.blade.php should have a: @stack('custom-scripts') And your child view: @push('custom-scripts') <script type="text/javascript" src="{{ URL::asset ('js/custom-scripts.js') }}"></script> @endpush You can also use @parent directive with @section like this: //index.blade.php @yield('scripts') //child.blade.php @section('scripts') @parent <!-- The rest of your scripts --> @endsection If you need more info I'd recommend you to check the documentation. Hope this helped you. A: Using @once might be also helpful for someone to prevent scripts from being executed more than once. You can define your root view to have a fixed place for scripts that should go at the end of the <head> tag and at the end of the <body> tag: app.blade.php: <html> <head> <title>Website</title> @stack('head-scripts') </head> <body> <main>@yield('content')</main> @stack('body-scripts') </body> </html> home.blade.php: @extends('layouts.app') @section('content') <div>Hello World</div> @push('body-scripts') @once <script src="https://unpkg.com/imask"></script> @endonce @endpush @endsection
stackoverflow
{ "language": "en", "length": 208, "provenance": "stackexchange_0000F.jsonl.gz:907162", "question_score": "32", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674255" }
ad476f6f304dd550bdf7fbc3c5775a035f376ab6
Stackoverflow Stackexchange Q: Java Money - Smallest Unit of currency I have a downstream service (Stripe) which requires I send currency in the smallest currency unit (zero-decimal currency in their docs). I.e. to charge $1 I would send { "currency": "USD", amount: 100 } and to charge ¥100 I would send { "currency": "YEN", amount: 100 } My upstream applications do not want to handle the currency in this way and want to use standard currency formats. Is there a means of transforming javax.money.MonetaryAmount into a zero decimal currency format? Or am I going to have to write the conversions manually? A: I've seen some people use BigDecimal. Here it is as a function. Please write some tests for it :) : public static BigDecimal currencyNoDecimalToDecimal(int amount, String currencyCode) { Currency currency = Currency.getInstance(currencyCode); // ISO 4217 codes BigDecimal bigD = BigDecimal.valueOf(amount); System.out.println("bigD = " + bigD); // bigD = 100 BigDecimal smallD = bigD.movePointLeft(currency.getDefaultFractionDigits()); System.out.println("smallD = " + smallD); // smallD = 1.00 return smallD; } public static void main(String[] args) { int amount = 100; String currencyCode = "USD"; BigDecimal dollars = currencyNoDecimalToDecimal(amount, currencyCode); System.out.println("dollars = "+dollars); }
Q: Java Money - Smallest Unit of currency I have a downstream service (Stripe) which requires I send currency in the smallest currency unit (zero-decimal currency in their docs). I.e. to charge $1 I would send { "currency": "USD", amount: 100 } and to charge ¥100 I would send { "currency": "YEN", amount: 100 } My upstream applications do not want to handle the currency in this way and want to use standard currency formats. Is there a means of transforming javax.money.MonetaryAmount into a zero decimal currency format? Or am I going to have to write the conversions manually? A: I've seen some people use BigDecimal. Here it is as a function. Please write some tests for it :) : public static BigDecimal currencyNoDecimalToDecimal(int amount, String currencyCode) { Currency currency = Currency.getInstance(currencyCode); // ISO 4217 codes BigDecimal bigD = BigDecimal.valueOf(amount); System.out.println("bigD = " + bigD); // bigD = 100 BigDecimal smallD = bigD.movePointLeft(currency.getDefaultFractionDigits()); System.out.println("smallD = " + smallD); // smallD = 1.00 return smallD; } public static void main(String[] args) { int amount = 100; String currencyCode = "USD"; BigDecimal dollars = currencyNoDecimalToDecimal(amount, currencyCode); System.out.println("dollars = "+dollars); }
stackoverflow
{ "language": "en", "length": 188, "provenance": "stackexchange_0000F.jsonl.gz:907172", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674280" }
03418a2d9e3ea9b79b41b84a47077c4c99f57856
Stackoverflow Stackexchange Q: (React-Native) undefined is not a constructor evaluating 'new FormData()' for the past 2 days I struggled with this problem and can't figure it out. I don't understand this error. this is my code: try{ var formData = new FormData(); } catch (error) { console.error('FormData ERROR', error); } and this is the error: 017-06-21 13:49:02.761 [error][tid:com.facebook.React.JavaScript] 'FormData ERROR', { [TypeError: undefined is not a constructor (evaluating 'new FormData()')] line: 98419, column: 36, sourceURL: 'http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false' } Do i have to add support for FormData in ReactNative 0.45.0? please help A: I got into this problem as well and that's because I have imported them on top. If you have done like what I did: import { FormData } from 'react'; or import { FormData } from 'react-native'; Just remove "FormData" from your imports and it will work like magic. FormData doesn't have to be imported for it to be working.
Q: (React-Native) undefined is not a constructor evaluating 'new FormData()' for the past 2 days I struggled with this problem and can't figure it out. I don't understand this error. this is my code: try{ var formData = new FormData(); } catch (error) { console.error('FormData ERROR', error); } and this is the error: 017-06-21 13:49:02.761 [error][tid:com.facebook.React.JavaScript] 'FormData ERROR', { [TypeError: undefined is not a constructor (evaluating 'new FormData()')] line: 98419, column: 36, sourceURL: 'http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false' } Do i have to add support for FormData in ReactNative 0.45.0? please help A: I got into this problem as well and that's because I have imported them on top. If you have done like what I did: import { FormData } from 'react'; or import { FormData } from 'react-native'; Just remove "FormData" from your imports and it will work like magic. FormData doesn't have to be imported for it to be working. A: The error says that you are FormData is undefined. Since it is not part of react native, you probably have to download it from npm. npm install --save form-data Then import it at the top of your file import FormData from 'form-data'; A: if import { FormData } from 'react-native'; didn't help then you can try to import directly: import FormData from 'react-native/Libraries/Network/FormData'; A: I think I got it. First of all, I found something (don't know from where i had these "tips") in my index.ios.js and removed them // const _XHR = GLOBAL.originalXMLHttpRequest ? // GLOBAL.originalXMLHttpRequest : // GLOBAL.XMLHttpRequest // XMLHttpRequest = _XHR; // // FormData = global.originalFormData; Then I found out that my debugger (Chrome or RNDebugger) messed with my network requests and that was bad for multipart image object. (strange?!) finally i got it working with this code: var fdObject = new FormData(); fdObject.append('avatar', {uri: PicturePath, name: 'avatar.jpg', type: 'image/jpg'}); options.method = POST; options.headers['Content-Type'] = 'multipart/form-data'; options.body = fdObject; fetch("http://api.com/post-my-image", options);
stackoverflow
{ "language": "en", "length": 314, "provenance": "stackexchange_0000F.jsonl.gz:907179", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674297" }
716bbbf0d49e8e3d6c727a236349885ac9a75566
Stackoverflow Stackexchange Q: VirtualBox supR3HardenedMainInitRuntime! error I get this error every time i try to launch VBox, after some researches i found that it maybe because installing vbox.deb placed in other folder not in /opt. (i tried many other solution like reinstalling ...). could any one propose other solution to me and/or explain to me how do i make my deb install in /opt folder thank you. VBoxSDL: Error -610 in supR3HardenedMainInitRuntime! VBoxSDL: dlopen("/usr/lib/virtualbox/VBoxRT.so",) failed: <NULL> VBoxSDL: Tip! It may help to reinstall VirtualBox. VirtualBox: Error -610 in supR3HardenedMainInitRuntime! VirtualBox: dlopen("/usr/lib/virtualbox/VBoxRT.so",) failed: <NULL> VirtualBox: Tip! It may help to reinstall VirtualBox. A: Like described at https://www.virtualbox.org/ticket/16759. This fixed my problem (virtualbox 5.1.26r117224, kernel 4.10.0-33) sudo chown root:root /usr sudo chown root:root /usr/lib sudo chown root:root /usr/lib/virtualbox
Q: VirtualBox supR3HardenedMainInitRuntime! error I get this error every time i try to launch VBox, after some researches i found that it maybe because installing vbox.deb placed in other folder not in /opt. (i tried many other solution like reinstalling ...). could any one propose other solution to me and/or explain to me how do i make my deb install in /opt folder thank you. VBoxSDL: Error -610 in supR3HardenedMainInitRuntime! VBoxSDL: dlopen("/usr/lib/virtualbox/VBoxRT.so",) failed: <NULL> VBoxSDL: Tip! It may help to reinstall VirtualBox. VirtualBox: Error -610 in supR3HardenedMainInitRuntime! VirtualBox: dlopen("/usr/lib/virtualbox/VBoxRT.so",) failed: <NULL> VirtualBox: Tip! It may help to reinstall VirtualBox. A: Like described at https://www.virtualbox.org/ticket/16759. This fixed my problem (virtualbox 5.1.26r117224, kernel 4.10.0-33) sudo chown root:root /usr sudo chown root:root /usr/lib sudo chown root:root /usr/lib/virtualbox A: At first,try sudo apt-get update sudo apt-get install --reinstall virtualbox It may not be helpful,then this may give a hand: enter link description here And in the end,you can try to reboot the machine.Is it is not work,then i have no idea.i hope one of them is able to solve you problem. A: https://www.virtualbox.org/ticket/16759 in my machine celticmachine:/var/log# ls -ld /usr drwxrwxr-x 12 998 998 4096 jún 15 01:46 /usr celticmachine:/var/log# ls -ld /usr/lib drwxrwxr-x 172 998 998 28672 jún 26 20:16 /usr/lib celticmachine:/var/log# chown root:root /usr celticmachine:/var/log# chown root:root /usr/lib celticmachine:/var/log# virtualbox And virtualbox started.... (Debian stretch) A: Had the same issue after upgrading to Ubuntu 18.04. apt install --reinstall virtualbox didn't help, here's what worked for me: apt purge virtualbox apt autoclean apt autoremove apt install virtualbox A: This error is not a virtualbox bug, look at this: Ticket #16759 It comes when you install something to /usr manually, and change the permission or ownership of /usr, /usr/lib. So the solution is just to recover them as they used to be: sudo chown root:root /usr sudo chown root:root /usr/lib sudo chown root:root /usr/lib/virtualbox sudo chmod 755 /usr/lib The reference of this answer is here: cannot run virtualbox on ubuntu 16.04 A: My virtualbox failure occurred with the last update made on 16/Mar/2022 usuario-vbox@dell-r730:~$ VBoxHeadless --startvm mysql-vm & [1] 768281 usuario-vbox@dell-r730:~$ VBoxHeadless: Error -1912 in supR3HardenedMainInitRuntime! VBoxHeadless: RTR3InitEx failed with rc=-1912 VBoxHeadless: Tip! It may help to reinstall VirtualBox. ^C [1]+ Exit 1 VBoxHeadless --startvm mysql-vm ... ... They were not turned off from the virtualbox manager. Only from the inside with shutdown -h now I followed the directions above apt remove virtualbox --purge apt autoclean apt autoremove reboot ...the server so that the latest updated kernel is loaded on March 16 along with the other libraries. apt install virtualbox I started the VMs with the commands manually VBoxHeadless --startvm name1-vm & VBoxHeadless --startvm name2-vm & VBoxHeadless --startvm name3-vm & VBoxHeadless --startvm name4-vm & VBoxHeadless --startvm name5-vm & Everything ok was working
stackoverflow
{ "language": "en", "length": 458, "provenance": "stackexchange_0000F.jsonl.gz:907222", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674432" }
7ecfb814ecc311650befb88d8ac8df4ed77812bf
Stackoverflow Stackexchange Q: router.navigate doesn't work I have tried to redirect the page after getting data successfully deleted. So I put the redirect router.navigate inside of the subscribe of the data section. But it's not working and also I have tried with ngZone also nothing happens. And I want to show the success message also. How can I show that? without ngZone: const rid = params['rid']; this.roleSer.deleteRole(rid).subscribe( data => { this.router.navigate(['viewroles']) }, error => { error } ); }); with ngZone: const vrid = this.route.params.subscribe((params: Params) => { const rid = params['rid']; this.roleSer.deleteRole(rid).subscribe( data => { this.zone.run(()=>{ this.router.navigate(['viewroles']) }); }, error => { error } ); }); A: Create one redirect function and use it const vrid = this.route.params.subscribe((params: Params) => { const rid = params['rid']; this.roleSer.deleteRole(rid).subscribe( data => { this.redirect('viewroles'); }, error => { error } ); }); redirect(path): void { this.router.navigate(['/' + path]) }
Q: router.navigate doesn't work I have tried to redirect the page after getting data successfully deleted. So I put the redirect router.navigate inside of the subscribe of the data section. But it's not working and also I have tried with ngZone also nothing happens. And I want to show the success message also. How can I show that? without ngZone: const rid = params['rid']; this.roleSer.deleteRole(rid).subscribe( data => { this.router.navigate(['viewroles']) }, error => { error } ); }); with ngZone: const vrid = this.route.params.subscribe((params: Params) => { const rid = params['rid']; this.roleSer.deleteRole(rid).subscribe( data => { this.zone.run(()=>{ this.router.navigate(['viewroles']) }); }, error => { error } ); }); A: Create one redirect function and use it const vrid = this.route.params.subscribe((params: Params) => { const rid = params['rid']; this.roleSer.deleteRole(rid).subscribe( data => { this.redirect('viewroles'); }, error => { error } ); }); redirect(path): void { this.router.navigate(['/' + path]) }
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:907273", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674587" }
6a8a48e4c2c6f26e5c7130148d371f8698441ce0
Stackoverflow Stackexchange Q: Declare Field as Parameterized List Using java assist We can declare field like following code. evalClass.addField(CtField.make("private java.util.List abc;", evalClass)); How can we declare field List<String> abc using java assist? A: Done little bit research on CtField class. we can set through setGenericSignature. CtField f = new CtField(pool.get(List.class.getCanonicalName()), "abc", evalClass); f.setGenericSignature(getGenericSignature(relatedClass)); evalClass.addField(f); private String getGenericSignature(Class relatedClass) throws BadBytecode { String fieldSignature = "L" + List.class.getCanonicalName().replace(".", "/") + "<L" + String.class.getCanonicalName().replace(".", "/") + ";>;"; return SignatureAttribute.toClassSignature(fieldSignature).encode(); }
Q: Declare Field as Parameterized List Using java assist We can declare field like following code. evalClass.addField(CtField.make("private java.util.List abc;", evalClass)); How can we declare field List<String> abc using java assist? A: Done little bit research on CtField class. we can set through setGenericSignature. CtField f = new CtField(pool.get(List.class.getCanonicalName()), "abc", evalClass); f.setGenericSignature(getGenericSignature(relatedClass)); evalClass.addField(f); private String getGenericSignature(Class relatedClass) throws BadBytecode { String fieldSignature = "L" + List.class.getCanonicalName().replace(".", "/") + "<L" + String.class.getCanonicalName().replace(".", "/") + ";>;"; return SignatureAttribute.toClassSignature(fieldSignature).encode(); } A: First, generics are not supported by Javassist. From the Javassist documentation: Generics The lower-level API of Javassist fully supports generics introduced by Java 5. On the other hand, the higher-level API such as CtClass does not directly support generics. However, this is not a serious problem for bytecode transformation. The generics of Java is implemented by the erasure technique. After compilation, all type parameters are dropped off. For example, suppose that your source code declares a parameterized type Vector: Vector<String> v = new Vector<String>(); String s = v.get(0); The compiled bytecode is equivalent to the following code: Vector v = new Vector(); String s = (String)v.get(0); So when you write a bytecode transformer, you can just drop off all type parameters. Because the compiler embedded in Javassist does not support generics, you must insert an explicit type cast at the caller site if the source code is compiled by Javassist, for example, through CtMethod.make(). No type cast is necessary if the source code is compiled by a normal Java compiler such as javac. So you can basically use the method you wrot in your question in order to add a List without generic specification and that's gonna do the work
stackoverflow
{ "language": "en", "length": 277, "provenance": "stackexchange_0000F.jsonl.gz:907313", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674719" }
e1f81cca8a447cc62bf968c0a1a05de5a2511fe8
Stackoverflow Stackexchange Q: FFmpeg: what does the "global_header" flag do? According to the description, it places global headers in extradata instead of every keyframe. But what's the actual purpose? Is it useful e.g. for streaming? I guess that the resulting video file will be marginally shorter, but more prone to corruption (no redundancy = file unplayable if main header corrupted or only partially downloaded)? Or maybe it somehow improves decoding a little bit? As headers are truly global and cannot change from keyframe to keyframe? Thanks! A: By extradata FFmpeg means out-of-band, as opposed to in-band. The behavior of the flag is format specific. This is useful for headers that are not expected to change because it reduces the overhead. Example: for H.264 in MP4 the SPS and PPS are stored in the avcC atom. For the same H.264 stream in let's say MPEG-TS the sequences are repeated in the bitstream.
Q: FFmpeg: what does the "global_header" flag do? According to the description, it places global headers in extradata instead of every keyframe. But what's the actual purpose? Is it useful e.g. for streaming? I guess that the resulting video file will be marginally shorter, but more prone to corruption (no redundancy = file unplayable if main header corrupted or only partially downloaded)? Or maybe it somehow improves decoding a little bit? As headers are truly global and cannot change from keyframe to keyframe? Thanks! A: By extradata FFmpeg means out-of-band, as opposed to in-band. The behavior of the flag is format specific. This is useful for headers that are not expected to change because it reduces the overhead. Example: for H.264 in MP4 the SPS and PPS are stored in the avcC atom. For the same H.264 stream in let's say MPEG-TS the sequences are repeated in the bitstream.
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:907337", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674791" }
4cdc82a8ce044a6755be5dd07a141d7c14cb1b15
Stackoverflow Stackexchange Q: Apache Arrow Java API Documentation I am looking for useful documentations or examples for the Apache Arrow API. Can anyone point to some useful resources? I was only able to find some blogs and JAVA documentation (which doesn't say much). From what I read, it is a standard in-memory columnar database for fast analytics. Is it possible to load the data to arrow memory and to manipulate it ? A: You should use arrow as a middle man between two applications which need to communicate using passing objects. Arrow isn’t a standalone piece of software but rather a component used to accelerate analytics within a particular system and to allow Arrow-enabled systems to exchange data with low overhead. For example Arrow improves the performance for data movement within a cluster. See tests for examples. @Test public void test() throws Exception { BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE); File testInFile = testFolder.newFile("testIn.arrow"); File testOutFile = testFolder.newFile("testOut.arrow"); writeInput(testInFile, allocator); String[] args = {"-i", testInFile.getAbsolutePath(), "-o", testOutFile.getAbsolutePath()}; int result = new FileRoundtrip(System.out, System.err).run(args); assertEquals(0, result); validateOutput(testOutFile, allocator); } Also Apache Parquet uses it. There are conversion examples from/to arrow objects: MessageType parquet = converter.fromArrow(allTypesArrowSchema).getParquetSchema(); Schema arrow = converter.fromParquet(supportedTypesParquetSchema).getArrowSchema();
Q: Apache Arrow Java API Documentation I am looking for useful documentations or examples for the Apache Arrow API. Can anyone point to some useful resources? I was only able to find some blogs and JAVA documentation (which doesn't say much). From what I read, it is a standard in-memory columnar database for fast analytics. Is it possible to load the data to arrow memory and to manipulate it ? A: You should use arrow as a middle man between two applications which need to communicate using passing objects. Arrow isn’t a standalone piece of software but rather a component used to accelerate analytics within a particular system and to allow Arrow-enabled systems to exchange data with low overhead. For example Arrow improves the performance for data movement within a cluster. See tests for examples. @Test public void test() throws Exception { BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE); File testInFile = testFolder.newFile("testIn.arrow"); File testOutFile = testFolder.newFile("testOut.arrow"); writeInput(testInFile, allocator); String[] args = {"-i", testInFile.getAbsolutePath(), "-o", testOutFile.getAbsolutePath()}; int result = new FileRoundtrip(System.out, System.err).run(args); assertEquals(0, result); validateOutput(testOutFile, allocator); } Also Apache Parquet uses it. There are conversion examples from/to arrow objects: MessageType parquet = converter.fromArrow(allTypesArrowSchema).getParquetSchema(); Schema arrow = converter.fromParquet(supportedTypesParquetSchema).getArrowSchema(); A: They have some basic documentation on how to use Apache Arrow on their site now. Although it could use a bit of filling out.
stackoverflow
{ "language": "en", "length": 220, "provenance": "stackexchange_0000F.jsonl.gz:907348", "question_score": "22", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674818" }
9c14d95c4f76c5fed1b0589c71f0b541b3294534
Stackoverflow Stackexchange Q: how to secure api call from proxy I am working on some app which as API call. while i add proxy in mobile and see response in web debugging tools. I can see my api call parameters and response too. while in others app I cant see this things and it is secured. how can i acheive this? A: Pictures said your API is using non-secure HTTP protocol while others app using HTTPS. The Web API should be performed via HTTPS protocol. HTTPS using SSL/TLS as secure transport layer, it means all data are encrypted before they're online. So, we don't care about any kinds of proxy
Q: how to secure api call from proxy I am working on some app which as API call. while i add proxy in mobile and see response in web debugging tools. I can see my api call parameters and response too. while in others app I cant see this things and it is secured. how can i acheive this? A: Pictures said your API is using non-secure HTTP protocol while others app using HTTPS. The Web API should be performed via HTTPS protocol. HTTPS using SSL/TLS as secure transport layer, it means all data are encrypted before they're online. So, we don't care about any kinds of proxy
stackoverflow
{ "language": "en", "length": 108, "provenance": "stackexchange_0000F.jsonl.gz:907391", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44674980" }
f22daffeb3e11522cf05d6dbcfcca74d96bbea88
Stackoverflow Stackexchange Q: Minimize Console at app startup C# I have a Console Application app, I would like to minimize (not hide permanently) the Console when i run the app, is it possible? also, I am using a timer to run the task every 10 minutes, is it possible to minimize the console every time the app runs? thanks! A: The following code should do the trick. Uses Win32 methods to minimize the console window. I am using Console.ReadLine() to prevent the window closing immediately. internal class Program { [DllImport("User32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool ShowWindow([In] IntPtr hWnd, [In] int nCmdShow); private static void Main(string[] args) { IntPtr handle = Process.GetCurrentProcess().MainWindowHandle; ShowWindow(handle, 6); Console.ReadLine(); } }
Q: Minimize Console at app startup C# I have a Console Application app, I would like to minimize (not hide permanently) the Console when i run the app, is it possible? also, I am using a timer to run the task every 10 minutes, is it possible to minimize the console every time the app runs? thanks! A: The following code should do the trick. Uses Win32 methods to minimize the console window. I am using Console.ReadLine() to prevent the window closing immediately. internal class Program { [DllImport("User32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool ShowWindow([In] IntPtr hWnd, [In] int nCmdShow); private static void Main(string[] args) { IntPtr handle = Process.GetCurrentProcess().MainWindowHandle; ShowWindow(handle, 6); Console.ReadLine(); } }
stackoverflow
{ "language": "en", "length": 121, "provenance": "stackexchange_0000F.jsonl.gz:907413", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675085" }
89d4e74231741c985118fb361a7f58e997031832
Stackoverflow Stackexchange Q: Kingfisher 3.0 iOS swift RoundCornerImageProcessor white background This is the code that I am using to set the user image which works great to actually get and set the image. I get a white outline to the picture. Any idea how to make this transparent? let processor = RoundCornerImageProcessor(cornerRadius: 50) self.userPhoto.backgroundColor = Colors.accent self.userPhoto.kf.setImage(with: url, placeholder: UIImage(named: "ic_camera_alt_48pt"), options: [.processor(processor)]) Example with 50 A: The format of the original image doesn't support transparency (i.e. JPEG). You must convert the image to one that does (i.e. PNG) prior to caching. From the Kingfisher Cheat Sheet: By default (DefaultCacheSerializer), Kingfisher will respect the input image format and try to keep it unchanged. However, there are some exceptions. A common case is that when you using a RoundCornerImageProcessor, you may always want the alpha channel. If your original image is jpg, you may want to set the png serializer instead: let roundCorner = RoundCornerImageProcessor(cornerRadius: 20) imageView.kf.setImage(with: url, options: [.processor(roundCorner), .cacheSerializer(FormatIndicatedCacheSerializer.png)] )
Q: Kingfisher 3.0 iOS swift RoundCornerImageProcessor white background This is the code that I am using to set the user image which works great to actually get and set the image. I get a white outline to the picture. Any idea how to make this transparent? let processor = RoundCornerImageProcessor(cornerRadius: 50) self.userPhoto.backgroundColor = Colors.accent self.userPhoto.kf.setImage(with: url, placeholder: UIImage(named: "ic_camera_alt_48pt"), options: [.processor(processor)]) Example with 50 A: The format of the original image doesn't support transparency (i.e. JPEG). You must convert the image to one that does (i.e. PNG) prior to caching. From the Kingfisher Cheat Sheet: By default (DefaultCacheSerializer), Kingfisher will respect the input image format and try to keep it unchanged. However, there are some exceptions. A common case is that when you using a RoundCornerImageProcessor, you may always want the alpha channel. If your original image is jpg, you may want to set the png serializer instead: let roundCorner = RoundCornerImageProcessor(cornerRadius: 20) imageView.kf.setImage(with: url, options: [.processor(roundCorner), .cacheSerializer(FormatIndicatedCacheSerializer.png)] ) A: You don't need the RoundCornerImageProcessor self.userPhoto.layerCornerRadius = 50 self.userPhoto.clipsToBounds = true self.userPhoto.backgroundColor = Colors.accent self.userPhoto.kf.setImage(with: url, placeholder: UIImage(named: "ic_camera_alt_48pt"))
stackoverflow
{ "language": "en", "length": 179, "provenance": "stackexchange_0000F.jsonl.gz:907420", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675108" }
58e235740a30b0f36e414f1d1820a8fb7d885c92
Stackoverflow Stackexchange Q: I have a .net 4.7 project but I can't add a reference to NetStandard 2.0 i have a project that is a .net 4.7. In the nuget manager, I install the .net standard 2.0 preview in this project, I can see the reference in the solution explorer, but I get an error that DateTime is definied in an assembly that is not referenced, that I have to add the reference to netstandard.dll. I have added manually the reference to the netstandard.dll that I have in the package folder, but then I get the error that the System.boolean and other type are not definied. So I would like to know how I could have a .net 4.7 project that use another project that is .net standard. Thanks. A: Until the automated tooling is shipped in an update to VS 2017 15.3 preview / .net core tooling 2.0.0 preview2, you need to include the NuGet package NETStandard.Library.NETFramework to get netstandard2.0 support in .NET Framework projects.
Q: I have a .net 4.7 project but I can't add a reference to NetStandard 2.0 i have a project that is a .net 4.7. In the nuget manager, I install the .net standard 2.0 preview in this project, I can see the reference in the solution explorer, but I get an error that DateTime is definied in an assembly that is not referenced, that I have to add the reference to netstandard.dll. I have added manually the reference to the netstandard.dll that I have in the package folder, but then I get the error that the System.boolean and other type are not definied. So I would like to know how I could have a .net 4.7 project that use another project that is .net standard. Thanks. A: Until the automated tooling is shipped in an update to VS 2017 15.3 preview / .net core tooling 2.0.0 preview2, you need to include the NuGet package NETStandard.Library.NETFramework to get netstandard2.0 support in .NET Framework projects.
stackoverflow
{ "language": "en", "length": 164, "provenance": "stackexchange_0000F.jsonl.gz:907426", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675135" }
de8559b3ece479526490ecfb6b173fac9c47cfa4
Stackoverflow Stackexchange Q: Display woocommerce variable product price How to display woocommerce variable price for current active variation on single product page? I use the code: <?php global $product; if ($product->is_type( 'simple' )) { ?> <p class="price"><?php echo $product->get_price_html(); ?></p> <?php } ?> <?php if($product->product_type=='variable') { $available_variations = $product->get_available_variations(); $variation_id=$available_variations[0]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation. $variable_product1= new WC_Product_Variation( $variation_id ); $regular_price = $variable_product1 ->regular_price; $sales_price = $variable_product1 ->sale_price; echo $regular_price+$sales_price; } ?> But it shows only lowest variable price instead of currently selected variation's price. How can I display the current price for the active variation? A: <?php global $product; if ($product->is_type( 'simple' )) { ?> <p class="price"><?php echo $product->get_price_html(); ?></p> <?php } ?> <?php if($product->product_type=='variable') { $available_variations = $product->get_available_variations(); $count = count($available_variations)-1; $variation_id=$available_variations[$count]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation. $variable_product1= new WC_Product_Variation( $variation_id ); $regular_price = $variable_product1 ->regular_price; $sales_price = $variable_product1 ->sale_price; echo $regular_price+$sales_price; } ?> try this. This may help you.
Q: Display woocommerce variable product price How to display woocommerce variable price for current active variation on single product page? I use the code: <?php global $product; if ($product->is_type( 'simple' )) { ?> <p class="price"><?php echo $product->get_price_html(); ?></p> <?php } ?> <?php if($product->product_type=='variable') { $available_variations = $product->get_available_variations(); $variation_id=$available_variations[0]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation. $variable_product1= new WC_Product_Variation( $variation_id ); $regular_price = $variable_product1 ->regular_price; $sales_price = $variable_product1 ->sale_price; echo $regular_price+$sales_price; } ?> But it shows only lowest variable price instead of currently selected variation's price. How can I display the current price for the active variation? A: <?php global $product; if ($product->is_type( 'simple' )) { ?> <p class="price"><?php echo $product->get_price_html(); ?></p> <?php } ?> <?php if($product->product_type=='variable') { $available_variations = $product->get_available_variations(); $count = count($available_variations)-1; $variation_id=$available_variations[$count]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation. $variable_product1= new WC_Product_Variation( $variation_id ); $regular_price = $variable_product1 ->regular_price; $sales_price = $variable_product1 ->sale_price; echo $regular_price+$sales_price; } ?> try this. This may help you. A: So, you can just modify \your-theme\woocommerce\single-product\sale-flash.php file Or, your can also use filter. By the way there is more simple solution: if ($product->is_type( 'simple' )) { $sale_price = $product->get_sale_price(); $regular_price = $product->get_regular_price(); } elseif($product->is_type('variable')){ $sale_price = $product->get_variation_sale_price( 'min', true ); $regular_price = $product->get_variation_regular_price( 'max', true ); } $discount = round (($sale_price / $regular_price -1 ) * 100); } Or you can copy this gist https://gist.github.com/sholex/4064fc2b656c0857a78228cf5324b370 A: <?php global $product; if ($product->is_type( 'simple' )) { ?> <p class="price"><?php echo $product->get_price_html(); ?></p> <?php } ?> <?php if($product->product_type=='variable') { $available_variations = $product->get_available_variations(); foreach($available_variations as $key=>$val){ if(trim($val['variation_id'])==**"your selected variant id"**){ $variation_id=$available_variations[$key]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation. } } $variable_product1= new WC_Product_Variation( $variation_id ); $regular_price = $variable_product1 ->regular_price; $sales_price = $variable_product1 ->sale_price; echo $regular_price+$sales_price; } ?> A: add_action( 'woocommerce_before_single_product', 'check_if_variable_first' ); function check_if_variable_first(){ if ( is_product() ) { global $post; $product = wc_get_product( $post->ID ); if ( $product->is_type( 'variable' ) ) { // removing the price of variable products remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 ); // Change location of add_action( 'woocommerce_single_product_summary', 'custom_wc_template_single_price', 10 ); function custom_wc_template_single_price(){ global $product; // Variable product only if($product->is_type('variable')): // Main Price $prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) ); $price = $prices[0] !== $prices[1] ? sprintf( __( 'От: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] ); // Sale Price $prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) ); sort( $prices ); $saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'От: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] ); if ( $price !== $saleprice && $product->is_on_sale() ) { $price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>'; } ?> <style> div.woocommerce-variation-price, div.woocommerce-variation-availability, div.hidden-variable-price { height: 0px !important; overflow:hidden; position:relative; line-height: 0px !important; font-size: 0% !important; } </style> <script> jQuery(document).ready(function($) { $('select').blur( function(){ if( '' != $('input.variation_id').val() ){ $('p.price').html($('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+$('div.woocommerce-variation-availability').html()+'</p>'); console.log($('input.variation_id').val()); } else { $('p.price').html($('div.hidden-variable-price').html()); if($('p.availability')) $('p.availability').remove(); console.log('NULL'); } }); }); </script> <?php echo '<p class="price">'.$price.'</p> <div class="hidden-variable-price" >'.$price.'</div>'; endif; } } } }
stackoverflow
{ "language": "en", "length": 529, "provenance": "stackexchange_0000F.jsonl.gz:907445", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675192" }
89de5fba26795a8dc497908bbce6af0253165bcc
Stackoverflow Stackexchange Q: Compute possible combinations of an equation I've got a template of equations template = (a op b) op c where the available operations op are the following: op = ['+', '-', '/', '*']. What I want to do is to compute all the possible combinations of this equation using the operations op and the parameters a, b and c. e.g. (a + b) + c (a - b) - c (a * b) * c (a / b) / c (a + c) + b (a - c) + b (b * a) - c ... ... ... I had a look at itertools.combinations however I am not quite sure if (or how) I can use this function in this particular context. A: This does what you want: import itertools symbol = ['a', 'b', 'c'] op = ['+', '-', '/', '*'] for symbols in itertools.permutations(symbol): for ops in itertools.product(op, repeat=2): print "(%s %s %s) %s %s" % ( symbols[0], ops[0], symbols[1], ops[1], symbols[2])
Q: Compute possible combinations of an equation I've got a template of equations template = (a op b) op c where the available operations op are the following: op = ['+', '-', '/', '*']. What I want to do is to compute all the possible combinations of this equation using the operations op and the parameters a, b and c. e.g. (a + b) + c (a - b) - c (a * b) * c (a / b) / c (a + c) + b (a - c) + b (b * a) - c ... ... ... I had a look at itertools.combinations however I am not quite sure if (or how) I can use this function in this particular context. A: This does what you want: import itertools symbol = ['a', 'b', 'c'] op = ['+', '-', '/', '*'] for symbols in itertools.permutations(symbol): for ops in itertools.product(op, repeat=2): print "(%s %s %s) %s %s" % ( symbols[0], ops[0], symbols[1], ops[1], symbols[2]) A: You need three things here: * *The permutations of your three variable: (a,b,c), (a,c,b), (b,c,a), etc. *The cartesian product of your operation set with itself: (*, -), (-, +), (+, -), (+, +), etc. *The cartesian product between the variables permutations and the previous product. So, using the glorious itertools: import itertools as it vars = 'abc' ops = '+-/*' vars_permutations = it.permutations(vars) op_permutations = it.product(ops, repeat=2) for var, op in it.product(vars_permutations, op_permutations): print('({} {} {}) {} {}'.format(var[0], op[0], var[1], op[1], var[2]))
stackoverflow
{ "language": "en", "length": 247, "provenance": "stackexchange_0000F.jsonl.gz:907460", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675217" }
afa380630d3c208d68017c7111f3f55b10c31339
Stackoverflow Stackexchange Q: Refresh Chrome policies programmatically? I wrote a Chrome extension, that uses local storage. When I open chrome://policy/ in the browser I can see my extension's data according to the its ID, however, when I change the value manually in the registry it DOES NOT get updated automatically. Instead I have to click on the "Reload policies" button. My extension uses this data and has to be updated. How can I refresh chrome policies from my code? (As if the user would click on the "Reload policies" button.) Thanks! A: For Windows, even if you're just managing the information in the registry and not via GPO, you force the updates to be reflected in Chrome with: gpupdate /force
Q: Refresh Chrome policies programmatically? I wrote a Chrome extension, that uses local storage. When I open chrome://policy/ in the browser I can see my extension's data according to the its ID, however, when I change the value manually in the registry it DOES NOT get updated automatically. Instead I have to click on the "Reload policies" button. My extension uses this data and has to be updated. How can I refresh chrome policies from my code? (As if the user would click on the "Reload policies" button.) Thanks! A: For Windows, even if you're just managing the information in the registry and not via GPO, you force the updates to be reflected in Chrome with: gpupdate /force
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:907469", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675258" }
c020045a0a92f3ea177f0481aff6d65990947ee4
Stackoverflow Stackexchange Q: OTF font not uploded in Wordpress I want to upload the custom fonts in WordPress dashboard. When I try to upload the font file, it is showing the error: Sorry, this file type is not permitted for security reasons. Then I have allowed the font all files by using below code: add_filter('upload_mimes', 'add_custom_upload_mimes'); function add_custom_upload_mimes($existing_mimes) { $existing_mimes['otf'] = 'application/x-font-opentype'; $existing_mimes['woff'] = 'application/x-font-woff'; $existing_mimes['ttf'] = 'application/x-font-ttf'; $existing_mimes['svg'] = 'image/svg+xml'; $existing_mimes['eot'] = 'application/vnd.ms-fontobject'; return $existing_mimes; } Now all type of font get uploaded but when I upload the .otf font it is showing me the same error. Please help me to resolve this issue. Thanks In Advance. A: try using $existing_mimes['otf'] = 'font/otf'; or $existing_mimes['otf'] = 'application/font-sfnt';
Q: OTF font not uploded in Wordpress I want to upload the custom fonts in WordPress dashboard. When I try to upload the font file, it is showing the error: Sorry, this file type is not permitted for security reasons. Then I have allowed the font all files by using below code: add_filter('upload_mimes', 'add_custom_upload_mimes'); function add_custom_upload_mimes($existing_mimes) { $existing_mimes['otf'] = 'application/x-font-opentype'; $existing_mimes['woff'] = 'application/x-font-woff'; $existing_mimes['ttf'] = 'application/x-font-ttf'; $existing_mimes['svg'] = 'image/svg+xml'; $existing_mimes['eot'] = 'application/vnd.ms-fontobject'; return $existing_mimes; } Now all type of font get uploaded but when I upload the .otf font it is showing me the same error. Please help me to resolve this issue. Thanks In Advance. A: try using $existing_mimes['otf'] = 'font/otf'; or $existing_mimes['otf'] = 'application/font-sfnt'; A: It's been a long time since You made this post. But I'm using a plugin called "WP Add Mime Types". And as a value in plugin settings (Settings -> Myme Type Settings) I added this: otf = application/x-font-opentype It's working for me :) A: Blow is the step to resolved this issue. Open the wp-config.php file of your WordPress installation and above the line where it says /* That's all, stop editing! Happy blogging. */ add the following code anywhere: define('ALLOW_UNFILTERED_UPLOADS', true); reference: https://tribulant.com/blog/wordpress/how-to-fix-sorry-this-file-type-is-not-permitted-for-security-reasons/ A: I have used following code, and it's worked properly. add_filter('upload_mimes', 'custom_upload_mimes'); function custom_upload_mimes ( $existing_mimes ) { $existing_mimes['ttf'] = 'application/x-font-ttf'; $existing_mimes['woff'] = 'application/x-font-woff'; $existing_mimes['woff2'] = 'application/x-font-woff2'; $existing_mimes['otf'] = 'application/x-font-otf'; return $existing_mimes; }
stackoverflow
{ "language": "en", "length": 234, "provenance": "stackexchange_0000F.jsonl.gz:907489", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675330" }
df0edbda1d16274617e433227fae165e6a0302f9
Stackoverflow Stackexchange Q: Php - Getting file size with an url I am trying to get a file size of an image from a remote url, I am trying to this like so: $remoteUrl = $file->guid; //remote url example: http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png $fileSize = filesize($remoteUrl); But, I get: filesize(): stat failed for http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png A: You can use HTTP headers to find the size of the object. The PHP function get_headers() can get them: $headers = get_headers('http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png', true); echo $headers['Content-Length']; This way you can avoid downloading the entire file. You also have access to all other headers, such as $headers['Content-Type'], which can come in handy if you are dealing with images (documentation).
Q: Php - Getting file size with an url I am trying to get a file size of an image from a remote url, I am trying to this like so: $remoteUrl = $file->guid; //remote url example: http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png $fileSize = filesize($remoteUrl); But, I get: filesize(): stat failed for http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png A: You can use HTTP headers to find the size of the object. The PHP function get_headers() can get them: $headers = get_headers('http://myApp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png', true); echo $headers['Content-Length']; This way you can avoid downloading the entire file. You also have access to all other headers, such as $headers['Content-Type'], which can come in handy if you are dealing with images (documentation). A: That error usually means the supplied URL does not return a valid image. When I try to visit http://myapp/wp-content/uploads/2017/05/Screen-Shot-2017-05-08-at-10.35.54.png it does not show an image in my browser. Double check that the returned URL from $file->guid; is correct. A: You will need to try a different method, the http:// stream wrapper does not support stat() which is needed for the filesize() function. This question has some options you might use, using curl to make a HEAD request and inspect the Content-Length header.
stackoverflow
{ "language": "en", "length": 190, "provenance": "stackexchange_0000F.jsonl.gz:907496", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675350" }
cd08a419154daaa857afb9841c8077de4ba67238
Stackoverflow Stackexchange Q: ERROR Error: No provider for JwtHelper I'm new to Angular2 and i'm using jwthelper to encode the jwt token and extract the details. import { Injectable } from '@angular/core'; import { JwtHelper } from 'angular2-jwt'; @Injectable() export class SessionService { constructor(private jwtHelper: JwtHelper){} getUser(){ var token = JSON.parse(localStorage.getItem('currentUser')); return this.jwtHelper.decodeToken(token.token); } } Couldn't find a solution for the following error and show me what is incorrect here. ERROR Error: No provider for JwtHelper! A: This is because you are trying to inject JwtHelper in the constructor of your component/service. This is done only for providers. According to using jwthelper in components section, you have to create a new object and use it. In your service, constructor(){} //remove from constructor. getUser(){ let jwtHelper: JwtHelper = new JwtHelper(); var token = JSON.parse(localStorage.getItem('currentUser')); return this.jwtHelper.decodeToken(token.token); }
Q: ERROR Error: No provider for JwtHelper I'm new to Angular2 and i'm using jwthelper to encode the jwt token and extract the details. import { Injectable } from '@angular/core'; import { JwtHelper } from 'angular2-jwt'; @Injectable() export class SessionService { constructor(private jwtHelper: JwtHelper){} getUser(){ var token = JSON.parse(localStorage.getItem('currentUser')); return this.jwtHelper.decodeToken(token.token); } } Couldn't find a solution for the following error and show me what is incorrect here. ERROR Error: No provider for JwtHelper! A: This is because you are trying to inject JwtHelper in the constructor of your component/service. This is done only for providers. According to using jwthelper in components section, you have to create a new object and use it. In your service, constructor(){} //remove from constructor. getUser(){ let jwtHelper: JwtHelper = new JwtHelper(); var token = JSON.parse(localStorage.getItem('currentUser')); return this.jwtHelper.decodeToken(token.token); }
stackoverflow
{ "language": "en", "length": 134, "provenance": "stackexchange_0000F.jsonl.gz:907503", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675373" }
412ea6e29f1d35f30d91e0abe95356da4b87766e
Stackoverflow Stackexchange Q: How to send and configure APN Auth Key (.p8 file) in VB.Net Im facing it difficulty in iOS as well as VB.Net Not able to find any solutions since yesterday, I am posting it here. Finding it hard to configure. Any help would be greatful!! A: you can use this reference link if you have a curl and openssl with Homebrew version. Other link to run on Node JS code has all steps of creating the Apple Push Notification Authentication Key and setting up a local server. To run Node JS code for sending push notification link Let me know if you face any issue.
Q: How to send and configure APN Auth Key (.p8 file) in VB.Net Im facing it difficulty in iOS as well as VB.Net Not able to find any solutions since yesterday, I am posting it here. Finding it hard to configure. Any help would be greatful!! A: you can use this reference link if you have a curl and openssl with Homebrew version. Other link to run on Node JS code has all steps of creating the Apple Push Notification Authentication Key and setting up a local server. To run Node JS code for sending push notification link Let me know if you face any issue.
stackoverflow
{ "language": "en", "length": 106, "provenance": "stackexchange_0000F.jsonl.gz:907513", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675399" }
3c821146dddb66a04bbf82d134ddcc68915c3471
Stackoverflow Stackexchange Q: How to get ordered type of Map from method Collectors.groupingBy I need to separate list of data into different lists by type, for this purpose I use construction Map<String,List<Dish>> dishMap = menu.stream() .collect(Collectors.groupingBy(Dish::getType)); but How can I get LinkedHashMap instead HashMap from method "Collectors.groupingBy". I found some data in javadoc but I can`t get what I must to do with this method: Map<String,List<Dish>> dishMap = menu.stream().collect(Collectors.groupingBy( Dish::getType, LinkedHashMap::new, ????)); what should I place in the third argument in method "groupingBy" to get what I need? A: You should use the toList Collector: Map<String,List<Dish>> dishMap = menu.stream().collect(Collectors.groupingBy( Dish::getType, LinkedHashMap::new, Collectors.toList()));
Q: How to get ordered type of Map from method Collectors.groupingBy I need to separate list of data into different lists by type, for this purpose I use construction Map<String,List<Dish>> dishMap = menu.stream() .collect(Collectors.groupingBy(Dish::getType)); but How can I get LinkedHashMap instead HashMap from method "Collectors.groupingBy". I found some data in javadoc but I can`t get what I must to do with this method: Map<String,List<Dish>> dishMap = menu.stream().collect(Collectors.groupingBy( Dish::getType, LinkedHashMap::new, ????)); what should I place in the third argument in method "groupingBy" to get what I need? A: You should use the toList Collector: Map<String,List<Dish>> dishMap = menu.stream().collect(Collectors.groupingBy( Dish::getType, LinkedHashMap::new, Collectors.toList()));
stackoverflow
{ "language": "en", "length": 100, "provenance": "stackexchange_0000F.jsonl.gz:907527", "question_score": "20", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675454" }
3c5ecb426d65d06ecbd4a8f13751fbce5d02ee6d
Stackoverflow Stackexchange Q: input[type="submit" i] - What is "i" and this syntax While inspecting an element in Chrome I stumbled across this: input[type="submit" i]:active It's part of Chrome's user agent stylesheet. I've been doing web development since 2002 and I've never seen or noticed this before. It doesn't even seem to match what I thought the syntax was. Is this specific to Chrome? Is there W3C documentation on it? Upon trying to mess with it, it didn't seem to be behave any differently than writing this: input[type="submit"]:active I've been actively searching the web and have had zero luck finding anything. If anyone knows, I'd appreciate an answer. P.S. The only thing I could think of is that it meant, "internal," though I simply don't know.
Q: input[type="submit" i] - What is "i" and this syntax While inspecting an element in Chrome I stumbled across this: input[type="submit" i]:active It's part of Chrome's user agent stylesheet. I've been doing web development since 2002 and I've never seen or noticed this before. It doesn't even seem to match what I thought the syntax was. Is this specific to Chrome? Is there W3C documentation on it? Upon trying to mess with it, it didn't seem to be behave any differently than writing this: input[type="submit"]:active I've been actively searching the web and have had zero luck finding anything. If anyone knows, I'd appreciate an answer. P.S. The only thing I could think of is that it meant, "internal," though I simply don't know.
stackoverflow
{ "language": "en", "length": 123, "provenance": "stackexchange_0000F.jsonl.gz:907532", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675476" }
6b81369b19473a360b0a7c5232a88953d5415c23
Stackoverflow Stackexchange Q: How to show md-error in material select box in angular 2? I am using reactive forms for validation in my angular 2 project. I want to highlight the fields that are invalid when 'submit' is pressed. I have achieved this in input tag by using md-Error but i am not able to do it in md-Select. Can anybody help? Screenshot: http://i.imgur.com/uOQbwaZ.png This is an example of md-select that i am using: <md-select placeholder="Listing Type" formControlName='listingType' required > <md-option *ngFor="let type of listType" [value]="type"> {{ type }} </md-option> </md-select> This is the md-input that i am using: <md-input-container class="more-width"> <input mdInput formControlName='price' required placeholder="Price"> <md-error>Please Enter Price</md-error> </md-input-container> This is the Validation that i am applying this.listingForm = this.fb.group({ propertyType: ['', Validators.required] }) A: You can show the red line below the box, but no error messages as of right now. I think it's a feature that will come soon. Issue on Github
Q: How to show md-error in material select box in angular 2? I am using reactive forms for validation in my angular 2 project. I want to highlight the fields that are invalid when 'submit' is pressed. I have achieved this in input tag by using md-Error but i am not able to do it in md-Select. Can anybody help? Screenshot: http://i.imgur.com/uOQbwaZ.png This is an example of md-select that i am using: <md-select placeholder="Listing Type" formControlName='listingType' required > <md-option *ngFor="let type of listType" [value]="type"> {{ type }} </md-option> </md-select> This is the md-input that i am using: <md-input-container class="more-width"> <input mdInput formControlName='price' required placeholder="Price"> <md-error>Please Enter Price</md-error> </md-input-container> This is the Validation that i am applying this.listingForm = this.fb.group({ propertyType: ['', Validators.required] }) A: You can show the red line below the box, but no error messages as of right now. I think it's a feature that will come soon. Issue on Github A: you can find a good example of this validating an email address in the angular material documentation here. A: This error has now been resolved. You just need to place the mat-error outside the mat-select and inside the mat-form-field. Here is an example <mat-form-field appearance="fill"> <mat-label>Favorite animal</mat-label> <mat-select [formControl]="animalControl" required> <mat-option>--</mat-option> <mat-option *ngFor="let animal of animals" [value]="animal"> {{animal.name}} </mat-option> </mat-select> <mat-error *ngIf="animalControl.hasError('required')">Please choose an animal</mat-error> </mat-form-field> For detail you can check the following link Error Messages in Angular form fields
stackoverflow
{ "language": "en", "length": 234, "provenance": "stackexchange_0000F.jsonl.gz:907545", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675540" }
aa8203035d91a1c4f663a5a45568ec79fedc4e4e
Stackoverflow Stackexchange Q: Django widget override template I am new at django. I want to create a custom widget. forms.py: from project.widgets import MultiChoiceFilterWidget class CustomSearchForm(FacetedSearchForm): TEST_COLORS = [ u"Blau", u"Rot", u"Gelb" ] color = forms.MultipleChoiceField( label=_("Color"), choices=[(x, x) for x in TEST_COLORS], widget=MultiChoiceFilterWidget, required=False) widget.py: class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple): template_name = 'project/widgets/filter.html' option_template_name = 'ptoject/widgets/filter_option.html' project/widgets/filter.html: <h1>TEST</h1> But it doesn't render the new template, instead it still renders the old way. Can you give me some tips? A: If you only need to change the templates, redefining a complete widget is tedious for nothing. Since the widget is passed to the field as an instance, you can instanciate the base widget you want to use and change the templates afterward. class CustomSearchForm(FacetedSearchForm): TEST_COLORS = [ u"Blau", u"Rot", u"Gelb" ] color = forms.MultipleChoiceField( label=_("Color"), choices=[(x, x) for x in TEST_COLORS], widget=forms.widgets.CheckboxSelectMultiple, required=False) color.widget.template_name = 'project/widgets/filter.html' color.widget.option_template_name = 'project/widgets/filter_option.html' If you need to pass custom data to your templates, then you will have to create a custom widget.
Q: Django widget override template I am new at django. I want to create a custom widget. forms.py: from project.widgets import MultiChoiceFilterWidget class CustomSearchForm(FacetedSearchForm): TEST_COLORS = [ u"Blau", u"Rot", u"Gelb" ] color = forms.MultipleChoiceField( label=_("Color"), choices=[(x, x) for x in TEST_COLORS], widget=MultiChoiceFilterWidget, required=False) widget.py: class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple): template_name = 'project/widgets/filter.html' option_template_name = 'ptoject/widgets/filter_option.html' project/widgets/filter.html: <h1>TEST</h1> But it doesn't render the new template, instead it still renders the old way. Can you give me some tips? A: If you only need to change the templates, redefining a complete widget is tedious for nothing. Since the widget is passed to the field as an instance, you can instanciate the base widget you want to use and change the templates afterward. class CustomSearchForm(FacetedSearchForm): TEST_COLORS = [ u"Blau", u"Rot", u"Gelb" ] color = forms.MultipleChoiceField( label=_("Color"), choices=[(x, x) for x in TEST_COLORS], widget=forms.widgets.CheckboxSelectMultiple, required=False) color.widget.template_name = 'project/widgets/filter.html' color.widget.option_template_name = 'project/widgets/filter_option.html' If you need to pass custom data to your templates, then you will have to create a custom widget. A: You will have to do the below steps to render your new widget template: 1) Add 'django.forms' to your INSTALLED_APPS; 2) Add FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' to your settings.py. More details : https://docs.djangoproject.com/en/2.0/ref/forms/renderers/#django.forms.renderers.TemplatesSetting A: Django version < 1.11: The widget must implement the render method in order to render a different template: from django.utils.safestring import mark_safe from django.template.loader import render_to_string class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple): template_name = 'project/widgets/filter.html' def render(self, data): ... Do stuff with data ... return mark_safe(render_to_string(self.template_name)) Django version 1.11: In the renderer's documentation, we can find the following: New in Django 1.11: In older versions, widgets are rendered using Python. All APIs described in this document are new. And by having a look at the widget source code and specifically on how the Input widget extends the Widget class, we can see that you would only need to customize your widget as follows: class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple): template_name = 'project/widgets/filter.html' Which is what you have already.
stackoverflow
{ "language": "en", "length": 317, "provenance": "stackexchange_0000F.jsonl.gz:907546", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675550" }
b5177b24fbb3848d19c1491b73ab813cdbfd2763
Stackoverflow Stackexchange Q: "Server.ScriptTimeout" in asp.net core In previous version of ASP.NET we could use "Server.ScriptTimeout" in controllers t ospecify timeout. How can it be done now in ASP.NET Core? For example, I know that my page will require around 3-4 minutes to be run. Is it possible to avoid timeouts?
Q: "Server.ScriptTimeout" in asp.net core In previous version of ASP.NET we could use "Server.ScriptTimeout" in controllers t ospecify timeout. How can it be done now in ASP.NET Core? For example, I know that my page will require around 3-4 minutes to be run. Is it possible to avoid timeouts?
stackoverflow
{ "language": "en", "length": 49, "provenance": "stackexchange_0000F.jsonl.gz:907562", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675589" }
7c649c13c908216f076ffcd93e4b82abcab638e4
Stackoverflow Stackexchange Q: Character after hyphen affects string.compare I would expect "2-" and "22" to always compare the same way, but changing the 3rd character changes the sort order. string.Compare("2-1","22-", StringComparison.CurrentCulture) //-1 string.Compare("2-2","22-", StringComparison.CurrentCulture) //1 What on earth is happening here? Our culture is en-US by the way. A: As per the documentation: Character sets include ignorable characters. The Compare(String, String, StringComparison) method does not consider such characters when it performs a culture-sensitive comparison. To recognize ignorable characters in your comparison, supply a value of StringComparison.Ordinal or OrdinalIgnoreCase for the comparisonType parameter. In your case, the hyphen is an ignorable character. In this case it means that the middle hyphen isn't taken into account. That means it actually compares 21 and 22 to 22-, which will evaluate to -1 and 1 respectively.
Q: Character after hyphen affects string.compare I would expect "2-" and "22" to always compare the same way, but changing the 3rd character changes the sort order. string.Compare("2-1","22-", StringComparison.CurrentCulture) //-1 string.Compare("2-2","22-", StringComparison.CurrentCulture) //1 What on earth is happening here? Our culture is en-US by the way. A: As per the documentation: Character sets include ignorable characters. The Compare(String, String, StringComparison) method does not consider such characters when it performs a culture-sensitive comparison. To recognize ignorable characters in your comparison, supply a value of StringComparison.Ordinal or OrdinalIgnoreCase for the comparisonType parameter. In your case, the hyphen is an ignorable character. In this case it means that the middle hyphen isn't taken into account. That means it actually compares 21 and 22 to 22-, which will evaluate to -1 and 1 respectively.
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:907621", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44675770" }
8feff2ec479c7907b9929aed520aa97fe4e60c1d
Stackoverflow Stackexchange Q: update or delete on table "x" violates foreign key constraint "fk_rails_5a7b40847a" on table "x" I am building a rails app (5.1.1) that has the equivalent of posts and comments linked to them. Everything seems to be working just fine but when I try to delete a post that has comments I get this error: PG::ForeignKeyViolation: ERROR: update or delete on table "posts" violates foreign key constraint "fk_rails_5a7b40847a" on table "comments" DETAIL: Key (id)=(3) is still referenced from table "comments". : DELETE FROM "posts" WHERE "prototypes"."id" = $1" The error seems pretty straight forward but I'm really new to rails and postgresql so I'm looking for some help on that! A: It depends what you want to do with the post's comments on its deletion. In case you want to delete them on cascade, for example: post.rb has_many :comments, dependent: :destroy
Q: update or delete on table "x" violates foreign key constraint "fk_rails_5a7b40847a" on table "x" I am building a rails app (5.1.1) that has the equivalent of posts and comments linked to them. Everything seems to be working just fine but when I try to delete a post that has comments I get this error: PG::ForeignKeyViolation: ERROR: update or delete on table "posts" violates foreign key constraint "fk_rails_5a7b40847a" on table "comments" DETAIL: Key (id)=(3) is still referenced from table "comments". : DELETE FROM "posts" WHERE "prototypes"."id" = $1" The error seems pretty straight forward but I'm really new to rails and postgresql so I'm looking for some help on that! A: It depends what you want to do with the post's comments on its deletion. In case you want to delete them on cascade, for example: post.rb has_many :comments, dependent: :destroy A: Update the below line in your Post model as below has_many :comments, dependent: :destroy You have to mention dependent: :destroy in your Post model. So when any post get to deleted by post.destroy, It deletes the all dependent records of Comment model. Hope this will resolve your issue A: It's because you have a constraint in your database. I presume that the foreign key post_id in table comments must exist in the associated table posts. That is certainly because you specify the foreign key relation in the migration with rails g model Comment post:references. You have to specify what to do with associated models on deletion : class Post < ActiveRecord::Base has_many :comments, dependent: :destroy # destroy associated comments end Then call method post.destroy instead of post.delete on your record See has_many for other options
stackoverflow
{ "language": "en", "length": 277, "provenance": "stackexchange_0000F.jsonl.gz:907729", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676095" }
4eee73b4f7c63f38ffa0ed961a369ea3ddef4479
Stackoverflow Stackexchange Q: Failed to find build tools revision After updating Android studio version to 2.2.2 i face this error for all build tools versions. even i installed some of theme from android studio again but didn't work. I tried all other tools versions. Failed to find build tools revision Update it works good with classpath 'com.android.tools.build:gradle:2.1.0' but with gradle:2.2.3 still got error. A: First, try cleaning and rebuilding your project. You can find Clean project in Build tab. If it doesn't work, use SDK Manager to install build tools version you want. Match build.gradle file to the version installed. For example, if 26.0.0 version is installed than change your build.gradle file to match the following: android { buildToolsVersion "26.0.0" ... } Check documentation for more information. Also, check offical gradle release notes and check if you have correct versions for all programs. Upgrading Android Studio might help.
Q: Failed to find build tools revision After updating Android studio version to 2.2.2 i face this error for all build tools versions. even i installed some of theme from android studio again but didn't work. I tried all other tools versions. Failed to find build tools revision Update it works good with classpath 'com.android.tools.build:gradle:2.1.0' but with gradle:2.2.3 still got error. A: First, try cleaning and rebuilding your project. You can find Clean project in Build tab. If it doesn't work, use SDK Manager to install build tools version you want. Match build.gradle file to the version installed. For example, if 26.0.0 version is installed than change your build.gradle file to match the following: android { buildToolsVersion "26.0.0" ... } Check documentation for more information. Also, check offical gradle release notes and check if you have correct versions for all programs. Upgrading Android Studio might help. A: Go to your project right click on project and than select open module setting than in module section select your app and then build tools revision and then select your build version
stackoverflow
{ "language": "en", "length": 179, "provenance": "stackexchange_0000F.jsonl.gz:907735", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676128" }
e9847f704efd67f8a1685b96de11c393289ca73f
Stackoverflow Stackexchange Q: Google App Engine Deploy Error Code 9 All, I'm attempting to deploy a Google App Engine. I've gotten as far as this, but I'm not sure how to proceed. Updating service [default]... ......failed. ERROR: (gcloud.app.deploy) Error Response: [9] The App Engine service account does not exist for "[my-project]". It appears that I need to create a service account for the app engine, but I'm not sure what variables it needs. Thanks! A: The problem is that I had deleted the "App Engine default service account". I was able to re-add the account using this page. On the right side of the page is a tool to "Try the API". For the appsId enter the project to be repaired and then click 'Execute'. The tool will walk you through a series of steps and at the end repair the project.
Q: Google App Engine Deploy Error Code 9 All, I'm attempting to deploy a Google App Engine. I've gotten as far as this, but I'm not sure how to proceed. Updating service [default]... ......failed. ERROR: (gcloud.app.deploy) Error Response: [9] The App Engine service account does not exist for "[my-project]". It appears that I need to create a service account for the app engine, but I'm not sure what variables it needs. Thanks! A: The problem is that I had deleted the "App Engine default service account". I was able to re-add the account using this page. On the right side of the page is a tool to "Try the API". For the appsId enter the project to be repaired and then click 'Execute'. The tool will walk you through a series of steps and at the end repair the project.
stackoverflow
{ "language": "en", "length": 140, "provenance": "stackexchange_0000F.jsonl.gz:907772", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676231" }
695ab10b426d4a69efb3872552f4fed1ded96e40
Stackoverflow Stackexchange Q: Plain Javascript: event.target : Get the next Sibling, & the first Child I have an HTML table and have set up event listeners for each row: var greyHeadings = document.querySelectorAll(".grey"); console.log(greyHeadings); greyHeadings.forEach(function(greyHeading){ greyHeading.addEventListener('click', function(e){ displayDescription(e, greyHeading); }); }); The function which is called ( displayDescription ) is the following one: function displayDescription(e, greyHeading){ var desc = e.target.parentNode.nextSibling.firstChild; console.log(desc); } It does get me the correct target, but it seems that nextSibiling.firstChild does not work. I need to get to the next row (so, the sibling), and find the first td (so, the first Child), so i can add a active class to it, -in case you're wondering. I have also created a jsfiddle: https://jsfiddle.net/7vpzLfke/ I am a beginner, so an explanation which is a little bit more detailed would be greatly appreciated! A: You will have to use nextElementSibling instead of nextSibling, since nextElementSibling always returns an HTML Element. More on that here
Q: Plain Javascript: event.target : Get the next Sibling, & the first Child I have an HTML table and have set up event listeners for each row: var greyHeadings = document.querySelectorAll(".grey"); console.log(greyHeadings); greyHeadings.forEach(function(greyHeading){ greyHeading.addEventListener('click', function(e){ displayDescription(e, greyHeading); }); }); The function which is called ( displayDescription ) is the following one: function displayDescription(e, greyHeading){ var desc = e.target.parentNode.nextSibling.firstChild; console.log(desc); } It does get me the correct target, but it seems that nextSibiling.firstChild does not work. I need to get to the next row (so, the sibling), and find the first td (so, the first Child), so i can add a active class to it, -in case you're wondering. I have also created a jsfiddle: https://jsfiddle.net/7vpzLfke/ I am a beginner, so an explanation which is a little bit more detailed would be greatly appreciated! A: You will have to use nextElementSibling instead of nextSibling, since nextElementSibling always returns an HTML Element. More on that here
stackoverflow
{ "language": "en", "length": 154, "provenance": "stackexchange_0000F.jsonl.gz:907789", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676281" }
30512f724a1f42cdbc69bc0d4cd8e0df3e78ed6b
Stackoverflow Stackexchange Q: How to mock object which create within the test method? I have ContextListener which inject in ServletContext object for work with database. And this DBJoint object create in method which test: @WebListener public class ContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { final ServletContext servletContext = servletContextEvent.getServletContext(); final DBJoint joint = new DBJointHandler( "database_scripts", "authentication_database"); servletContext.setAttribute("db", joint); } } For testing servletContext.setAttribute("db", joint); I need DBJoint joint for send in setAttribute. My test: @Test public void whenThen() { final ServletContextEvent event = mock(ServletContextEvent.class); final ServletContext context = mock(ServletContext.class); when(event.getServletContext()).thenReturn(context); final ContextListener listener = new ContextListener(); listener.contextInitialized(event); DBJoint joint = ..?// how to mocking this? verify(context).setAttribute("db", joint); } * *Testing for servletContext.setAttribute("db", joint); is possibly? *If answer "yes", how. Thank You. A: You can mock constructor by using power mock. Try this DBJointHandler joint = new DBJointHandler("database_scripts", "authentication_database"); try { PowerMockito.whenNew(DBJointHandler.class).withArguments("database_scripts", "authentication_database").thenReturn(joint); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
Q: How to mock object which create within the test method? I have ContextListener which inject in ServletContext object for work with database. And this DBJoint object create in method which test: @WebListener public class ContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { final ServletContext servletContext = servletContextEvent.getServletContext(); final DBJoint joint = new DBJointHandler( "database_scripts", "authentication_database"); servletContext.setAttribute("db", joint); } } For testing servletContext.setAttribute("db", joint); I need DBJoint joint for send in setAttribute. My test: @Test public void whenThen() { final ServletContextEvent event = mock(ServletContextEvent.class); final ServletContext context = mock(ServletContext.class); when(event.getServletContext()).thenReturn(context); final ContextListener listener = new ContextListener(); listener.contextInitialized(event); DBJoint joint = ..?// how to mocking this? verify(context).setAttribute("db", joint); } * *Testing for servletContext.setAttribute("db", joint); is possibly? *If answer "yes", how. Thank You. A: You can mock constructor by using power mock. Try this DBJointHandler joint = new DBJointHandler("database_scripts", "authentication_database"); try { PowerMockito.whenNew(DBJointHandler.class).withArguments("database_scripts", "authentication_database").thenReturn(joint); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } A: First you need to understand that your servletContext object is a mocked object and not a real object. The joint object is real and you don't need to mock. You can possibly test servletContext.setAttribute("db", joint); using mockito verify verify(servletContext).setAttribute(eq("db"), any(DBJoint.class));
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:907792", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676287" }
3390291361746549e27befdd929284bb62b68f3e
Stackoverflow Stackexchange Q: Java get context url in spring service without HttpServletRequest In my spring webservice I'm trying to get the url of my application like "http://localhost:8080/mycontext". My service does not contain any HttpServletRequest var, so I can I get it ? A: You can get the current request via the RequestContextHolder like: ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest req = sra.getRequest(); req.getContextPath(); req.getPathInfo(); Or you can just inject it via Spring into your service: private @Autowired HttpServletRequest request;
Q: Java get context url in spring service without HttpServletRequest In my spring webservice I'm trying to get the url of my application like "http://localhost:8080/mycontext". My service does not contain any HttpServletRequest var, so I can I get it ? A: You can get the current request via the RequestContextHolder like: ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest req = sra.getRequest(); req.getContextPath(); req.getPathInfo(); Or you can just inject it via Spring into your service: private @Autowired HttpServletRequest request;
stackoverflow
{ "language": "en", "length": 76, "provenance": "stackexchange_0000F.jsonl.gz:907808", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676335" }
659b02eaca07a0725de41106bd9bc2a1c188df04
Stackoverflow Stackexchange Q: How to wrap quotes around variable value in bash? I have a variable test=value.txt I am using test as $test which gives me value.txt I want result as 'value.txt' How can I achieve this? Edit: Above is just an example of the task I am trying to achieve. I can't change variable value. A: Assignment using string: test="'value.txt'" echo "$test" 'value.txt' Assignment using variable: var=value.txt test="'$var'" echo "$test" 'value.txt'
Q: How to wrap quotes around variable value in bash? I have a variable test=value.txt I am using test as $test which gives me value.txt I want result as 'value.txt' How can I achieve this? Edit: Above is just an example of the task I am trying to achieve. I can't change variable value. A: Assignment using string: test="'value.txt'" echo "$test" 'value.txt' Assignment using variable: var=value.txt test="'$var'" echo "$test" 'value.txt' A: Try something like this: test="'value.txt'" or this: test=\'value.txt\' A: test=aaa test="'$test'" echo $test output: 'aaa'
stackoverflow
{ "language": "en", "length": 86, "provenance": "stackexchange_0000F.jsonl.gz:907814", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676356" }
abdc68b56719423fcee770fb960a625a10e4935c
Stackoverflow Stackexchange Q: Firebase dashboard can't see full server key When looking at my server key in the Firebase dashboard, the server key is cut off and I'm not sure how to see the entire string: The Legacy server key has a copy button I can use, but the new server key does not. How can I copy or see my full new server key? A: Just left click on the Server key label and press Tab key. There you will see a Copy option. Click it and you now will have the key
Q: Firebase dashboard can't see full server key When looking at my server key in the Firebase dashboard, the server key is cut off and I'm not sure how to see the entire string: The Legacy server key has a copy button I can use, but the new server key does not. How can I copy or see my full new server key? A: Just left click on the Server key label and press Tab key. There you will see a Copy option. Click it and you now will have the key
stackoverflow
{ "language": "en", "length": 92, "provenance": "stackexchange_0000F.jsonl.gz:907821", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676388" }
685e2820a5ee9b1cff6b0b26e26ff41a149c32e7
Stackoverflow Stackexchange Q: Should namelists be avoided in Fortran and if so what is the recommended alternative? I often use the namelist feature for flexible input of parameter lists to FORTRAN programmes, but the other day when searching to remind myself of their use I came across this statement: It (namelist language extension to f77) has now been included in the Fortran 90 language. However, NAMELIST is a poorly designed feature and should be avoided whenever possible. I was just wondering * *if this is a generally held view? *if yes, why is this the case? *what the suggested alternative is for parameter input? (I of course use netcdf for gridded data file input, I'm thinking of run-time parameter settings here). A: There is no mention of namelist inefficiency and poor design whatsoever in the canonical book of Metcalf et al.: Modern Fortran Explained. https://books.google.com/books?id=V7UVDAAAQBAJ&lpg=PP1&pg=PA197#v=onepage&q=namelist%20I/O&f=false To the contrary, I believe namelists -- especially with the added enhancements in Fortran 2003 and 2008 -- are quite useful and flexible method of data I/O.
Q: Should namelists be avoided in Fortran and if so what is the recommended alternative? I often use the namelist feature for flexible input of parameter lists to FORTRAN programmes, but the other day when searching to remind myself of their use I came across this statement: It (namelist language extension to f77) has now been included in the Fortran 90 language. However, NAMELIST is a poorly designed feature and should be avoided whenever possible. I was just wondering * *if this is a generally held view? *if yes, why is this the case? *what the suggested alternative is for parameter input? (I of course use netcdf for gridded data file input, I'm thinking of run-time parameter settings here). A: There is no mention of namelist inefficiency and poor design whatsoever in the canonical book of Metcalf et al.: Modern Fortran Explained. https://books.google.com/books?id=V7UVDAAAQBAJ&lpg=PP1&pg=PA197#v=onepage&q=namelist%20I/O&f=false To the contrary, I believe namelists -- especially with the added enhancements in Fortran 2003 and 2008 -- are quite useful and flexible method of data I/O.
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:907828", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676414" }
170c5653f1b5e92e803734112c14e675b96ca118
Stackoverflow Stackexchange Q: multiple consumers in a single queue in ActiveMQ I have tried single consumer and producer it works fine , as well as the multiple consumers with sinlge producer . But what i really want to know , is it really possible to have multiple consumers in a single queue in ActiveMQ.
Q: multiple consumers in a single queue in ActiveMQ I have tried single consumer and producer it works fine , as well as the multiple consumers with sinlge producer . But what i really want to know , is it really possible to have multiple consumers in a single queue in ActiveMQ.
stackoverflow
{ "language": "en", "length": 52, "provenance": "stackexchange_0000F.jsonl.gz:907835", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676451" }
4d925dd608e0e2d1ca117e8e0e12b76dccebab90
Stackoverflow Stackexchange Q: How to make quality gate pass, although new plugins are added? I added two plugins to SonarQube version 6.3.0.19869 (css and web). Now all my projects fail on their quality gate. How can I get it to pass for the first time? I can't fix all old errors now. I want to fix only new issues. A: Version 6.3 included functionality to backdate new issues raised on old code by rules that are newly added to your previously applied profile. However, that functionality still misses some cases (SONAR-8737), and yours appears to be one of them.
Q: How to make quality gate pass, although new plugins are added? I added two plugins to SonarQube version 6.3.0.19869 (css and web). Now all my projects fail on their quality gate. How can I get it to pass for the first time? I can't fix all old errors now. I want to fix only new issues. A: Version 6.3 included functionality to backdate new issues raised on old code by rules that are newly added to your previously applied profile. However, that functionality still misses some cases (SONAR-8737), and yours appears to be one of them. A: Go to http://yourserver:port/issues and try to filter out exactly those issues, that you do not want to handle for the moment (probably using the "Language" or "Creation Date" filters are a good start). Then do a "Bulk Change" (link on top of the page) to get all of these issues out of your project's quality gate. Depending on your quality gate, this might mean to change the status of the issues from "open" to "confirmed", change their severity, or similar. Since this approach really depends on the quality gate configuration, it does not work in all cases.
stackoverflow
{ "language": "en", "length": 195, "provenance": "stackexchange_0000F.jsonl.gz:907844", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676481" }
d3210bbfffb514a2536d00e884d0821c570af768
Stackoverflow Stackexchange Q: ng-pattern for alphanumeric and all special symbol characters In input, I need to allow alphanumeric and all special symbol character. I am using the following pattern. Unfortunatelly, it is not working. ng-pattern="/^[ A-Za-z0-9_@./#$=!%^)(]:*;?/\,}{'|<>[&+-]*$/" A: You missed to escape all the characters that should be excaped with \. The following may work: ng-pattern="/^[A-Za-z0-9_@.#$=!%^)(\]:\*;\?\/\,}{'\|<>\[&\+-]*$/" Note that it could be simplified to: ng-pattern="/^[A-z\d_@.#$=!%^)(\]:\*;\?\/\,}{'\|<>\[&\+-]*$/" Test it on regex101
Q: ng-pattern for alphanumeric and all special symbol characters In input, I need to allow alphanumeric and all special symbol character. I am using the following pattern. Unfortunatelly, it is not working. ng-pattern="/^[ A-Za-z0-9_@./#$=!%^)(]:*;?/\,}{'|<>[&+-]*$/" A: You missed to escape all the characters that should be excaped with \. The following may work: ng-pattern="/^[A-Za-z0-9_@.#$=!%^)(\]:\*;\?\/\,}{'\|<>\[&\+-]*$/" Note that it could be simplified to: ng-pattern="/^[A-z\d_@.#$=!%^)(\]:\*;\?\/\,}{'\|<>\[&\+-]*$/" Test it on regex101
stackoverflow
{ "language": "en", "length": 65, "provenance": "stackexchange_0000F.jsonl.gz:907852", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676495" }
3a63e84ea793637d81e24411911f6e110341a49c
Stackoverflow Stackexchange Q: R bnlearn eval inside function I am using the bnlearn package in R to train a Bayesian network. I have troubles with the following code (slightly modified bnlearn example code): library(bnlearn) data(learning.test) fitted = bn.fit(hc(learning.test), learning.test) myfuncBN=function(){ var = names(learning.test) obs = 2 str = paste("(", names(learning.test)[-3], "=='", sapply(learning.test[obs,-3], as.character), "')", sep = "", collapse = " & ") str2 = paste("(", names(learning.test)[3], "=='", as.character(learning.test[obs, 3]), "')", sep = "") cpquery(fitted, eval(parse(text = str2)), eval(parse(text = str))) } myfuncBN() This code throws the error: Error during wrapup: cannot coerce type 'closure' to vector of type 'character' It works however if str and str2 are defined outside the function myfuncBN(). Does anyone know the reason for this? A: Here is a solution to the problem: library(bnlearn) data(learning.test) fitted = bn.fit(hc(learning.test), learning.test) myfuncBN=function() { vars = names(learning.test) obs = 2 str1 = paste("(", vars[-3], "=='", sapply(learning.test[obs,-3], as.character), "')", sep = "", collapse = " & ") str2 = paste("(", vars[3], "=='", as.character(learning.test[obs, 3]), "')", sep = "") eval(parse(text=paste("cpquery(fitted,",str2,",",str1,")"))) } set.seed(1) myfuncBN() # [1] 0.05940594 This value is equal to the result given by: set.seed(1) cpquery(fitted, event=(C=="c"), evidence=((A=="b") & (B=="a") & (D=="a") & (E=="b") & (F=="b"))) # [1] 0.05940594
Q: R bnlearn eval inside function I am using the bnlearn package in R to train a Bayesian network. I have troubles with the following code (slightly modified bnlearn example code): library(bnlearn) data(learning.test) fitted = bn.fit(hc(learning.test), learning.test) myfuncBN=function(){ var = names(learning.test) obs = 2 str = paste("(", names(learning.test)[-3], "=='", sapply(learning.test[obs,-3], as.character), "')", sep = "", collapse = " & ") str2 = paste("(", names(learning.test)[3], "=='", as.character(learning.test[obs, 3]), "')", sep = "") cpquery(fitted, eval(parse(text = str2)), eval(parse(text = str))) } myfuncBN() This code throws the error: Error during wrapup: cannot coerce type 'closure' to vector of type 'character' It works however if str and str2 are defined outside the function myfuncBN(). Does anyone know the reason for this? A: Here is a solution to the problem: library(bnlearn) data(learning.test) fitted = bn.fit(hc(learning.test), learning.test) myfuncBN=function() { vars = names(learning.test) obs = 2 str1 = paste("(", vars[-3], "=='", sapply(learning.test[obs,-3], as.character), "')", sep = "", collapse = " & ") str2 = paste("(", vars[3], "=='", as.character(learning.test[obs, 3]), "')", sep = "") eval(parse(text=paste("cpquery(fitted,",str2,",",str1,")"))) } set.seed(1) myfuncBN() # [1] 0.05940594 This value is equal to the result given by: set.seed(1) cpquery(fitted, event=(C=="c"), evidence=((A=="b") & (B=="a") & (D=="a") & (E=="b") & (F=="b"))) # [1] 0.05940594
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:907856", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676501" }
54e5bd53aba0da695d8415b62e86bbf3c3d6693d
Stackoverflow Stackexchange Q: How to send json data in POST request using C# I want to send json data in POST request using C#. I have tried few ways but facing lot of issues . I need to request using request body as raw json from string and json data from json file. How can i send request using these two data forms. Ex: For authentication request body in json --> {"Username":"myusername","Password":"pass"} For other APIs request body should retrieved from external json file. A: This works for me. var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = new JavaScriptSerializer().Serialize(new { Username = "myusername", Password = "password" }); streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); }
Q: How to send json data in POST request using C# I want to send json data in POST request using C#. I have tried few ways but facing lot of issues . I need to request using request body as raw json from string and json data from json file. How can i send request using these two data forms. Ex: For authentication request body in json --> {"Username":"myusername","Password":"pass"} For other APIs request body should retrieved from external json file. A: This works for me. var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = new JavaScriptSerializer().Serialize(new { Username = "myusername", Password = "password" }); streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); } A: You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient: using (var client = new HttpClient()) { // This would be the like http://www.uber.com client.BaseAddress = new Uri("Base Address/URL Address"); // serialize your json using newtonsoft json serializer then add it to the StringContent var content = new StringContent(YourJson, Encoding.UTF8, "application/json") // method address would be like api/callUber:SomePort for example var result = await client.PostAsync("Method Address", content); string resultContent = await result.Content.ReadAsStringAsync(); } A: You can do it with HttpWebRequest: var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = new JavaScriptSerializer().Serialize(new { Username = "myusername", Password = "pass" }); streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); }
stackoverflow
{ "language": "en", "length": 284, "provenance": "stackexchange_0000F.jsonl.gz:907885", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676611" }
8bfc54e220d57af9ea3f533513e5a351d5d15ca0
Stackoverflow Stackexchange Q: Get the sum which is greater than 0 or less than 0 using MySQL I have a MySQL query that will get the sum of the amount in my column. What I found out is that there are also negative values in my data. I want to separate the sum of positive values and negative values. Can you help me on this? I tried this query... but its giving me a Invalid use of group function. Here's my query: SELECT sum(AMOUNT) from deposit where type = 42 and sum(AMOUNT) > 0 A: I found the solution which was posted by someone earlier but unfortunately he deleted it(i dont know why) Thanks to that person. :) I tried to consider the Having clause but its giving me a wrong result. SELECT sum(CASE WHEN AMOUNT > 0 THEN AMOUNT ELSE 0 END) as Positive, sum(CASE WHEN AMOUNT < 0 THEN AMOUNT ELSE 0 END) as Negative from deposit where type = 42
Q: Get the sum which is greater than 0 or less than 0 using MySQL I have a MySQL query that will get the sum of the amount in my column. What I found out is that there are also negative values in my data. I want to separate the sum of positive values and negative values. Can you help me on this? I tried this query... but its giving me a Invalid use of group function. Here's my query: SELECT sum(AMOUNT) from deposit where type = 42 and sum(AMOUNT) > 0 A: I found the solution which was posted by someone earlier but unfortunately he deleted it(i dont know why) Thanks to that person. :) I tried to consider the Having clause but its giving me a wrong result. SELECT sum(CASE WHEN AMOUNT > 0 THEN AMOUNT ELSE 0 END) as Positive, sum(CASE WHEN AMOUNT < 0 THEN AMOUNT ELSE 0 END) as Negative from deposit where type = 42 A: Whenever you have a condition on an aggregate, use having: SELECT sum(AMOUNT) from deposit where type = 42 having sum(AMOUNT) > 0 Or if you are only interested in summing the positive values, then don't put the condition on the sum, but on the individual amount: SELECT sum(AMOUNT) from deposit where type = 42 and amount > 0 A: Use having SELECT sum(AMOUNT) from deposit where type = 42 and amount > 0 having sum(AMOUNT) > 0 A: You could also use a subselect: SELECT s FROM ( SELECT SUM(amount) s FROM deposit WHERE type = 42 ) R WHERE s > 0; See also: https://en.wikipedia.org/wiki/Having_(SQL) A: For this type of situation we have aggregate functions having in mysql. 1) If you want to get greater than zero; SELECT sum(AMOUNT) from deposit where type = 42 having sum(AMOUNT) > 0 2) If you want to get less than zero; SELECT sum(AMOUNT) from deposit where type = 42 having sum(AMOUNT) < 0 If you want both in one result you can use subquery.
stackoverflow
{ "language": "en", "length": 334, "provenance": "stackexchange_0000F.jsonl.gz:907911", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676690" }
c23c575ab02dd989d2cd01619299f7d192d95ebe
Stackoverflow Stackexchange Q: Papa Parse incorect column type I have one column with for example 5/5 value and when i exporting this data to csv file result is date format (5-MAY). How can i change column type in config object? here is example data var data = [{count:'5/5'},{count:'23/5'}];
Q: Papa Parse incorect column type I have one column with for example 5/5 value and when i exporting this data to csv file result is date format (5-MAY). How can i change column type in config object? here is example data var data = [{count:'5/5'},{count:'23/5'}];
stackoverflow
{ "language": "en", "length": 46, "provenance": "stackexchange_0000F.jsonl.gz:907934", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676762" }
6f974faa86f09185430b4cfaba5539ec71183870
Stackoverflow Stackexchange Q: How to get the user friends list using LinkedIn? I tried bellow code but it's not working. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; [manager GET:[NSString stringWithFormat:@"https://api.linkedin.com/v1/people/~/connections:(picture-url,first-name,last-name,id,industry,positions:(company:(name),title),specialties,date-of-birth,interests,languages,siteStandardProfileRequest)?oauth2_access_token=%@&format=json",accessToken] parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) { NSLog(@"%@",responseObject); } failure:^(NSURLSessionTask *operation, NSError *error) { NSLog(@"Fail"); }]; After hitting this api i get bellow responce. Please help me how to get the linkedin friends list. <error> <status>403</status> <timestamp>1498049304917</timestamp> <request-id>G6GU8W51BY</request-id> <error-code>0</error-code> <message>Access to connections denied</message> </error> A: Update: LinkedIn has restricted their open API access, and to get the properties of user friends list no longer works. The Connections API is only for LinkedIn partners now. On February 12th 2015 Linkedin announced a series of changes in their developer program. These changes have now begun to take effect and will be rolled out to the entire LinkedIn application base between May 12th - May 19th, 2015. You can see more details here
Q: How to get the user friends list using LinkedIn? I tried bellow code but it's not working. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; [manager GET:[NSString stringWithFormat:@"https://api.linkedin.com/v1/people/~/connections:(picture-url,first-name,last-name,id,industry,positions:(company:(name),title),specialties,date-of-birth,interests,languages,siteStandardProfileRequest)?oauth2_access_token=%@&format=json",accessToken] parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) { NSLog(@"%@",responseObject); } failure:^(NSURLSessionTask *operation, NSError *error) { NSLog(@"Fail"); }]; After hitting this api i get bellow responce. Please help me how to get the linkedin friends list. <error> <status>403</status> <timestamp>1498049304917</timestamp> <request-id>G6GU8W51BY</request-id> <error-code>0</error-code> <message>Access to connections denied</message> </error> A: Update: LinkedIn has restricted their open API access, and to get the properties of user friends list no longer works. The Connections API is only for LinkedIn partners now. On February 12th 2015 Linkedin announced a series of changes in their developer program. These changes have now begun to take effect and will be rolled out to the entire LinkedIn application base between May 12th - May 19th, 2015. You can see more details here
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:907941", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676795" }
685120b3ac902a2cf86484c2cc2647b5e3a101d8
Stackoverflow Stackexchange Q: ClassCastException after applying PathProperties I'm trying to apply some PathProperties to my Finders but I keep getting this error : [ClassCastException: java.util.ArrayList cannot be cast to com.avaje.ebean.bean.BeanCollection] It only happens when I have a List<...> called in my PathProperties like so : PathProperties pathProperties = PathProperties.parse("(*,historique(*))"); List<Devi> test = Devi.find.apply(pathProperties).findList(); Where my Finder is defined like this : public static Finder<String,Devi> find = new Finder<String,Devi>(Devi.class); Here, the object Devi is full of public variables, that I am able to call without any issue (the PathProperties "(*)" works), but when I try to access a List of objects inside this object (here, public List<Histo> historique), it won't work. I tried, and I'm also able to access an object within the object, as long as it's not a List. I'm kinda lost here, I don't know what I did wrong. A: According to https://github.com/ebean-orm/ebean/issues/591 , this is a bug triggered by initializing the ArrayList. Without the initialization it will apparently work.
Q: ClassCastException after applying PathProperties I'm trying to apply some PathProperties to my Finders but I keep getting this error : [ClassCastException: java.util.ArrayList cannot be cast to com.avaje.ebean.bean.BeanCollection] It only happens when I have a List<...> called in my PathProperties like so : PathProperties pathProperties = PathProperties.parse("(*,historique(*))"); List<Devi> test = Devi.find.apply(pathProperties).findList(); Where my Finder is defined like this : public static Finder<String,Devi> find = new Finder<String,Devi>(Devi.class); Here, the object Devi is full of public variables, that I am able to call without any issue (the PathProperties "(*)" works), but when I try to access a List of objects inside this object (here, public List<Histo> historique), it won't work. I tried, and I'm also able to access an object within the object, as long as it's not a List. I'm kinda lost here, I don't know what I did wrong. A: According to https://github.com/ebean-orm/ebean/issues/591 , this is a bug triggered by initializing the ArrayList. Without the initialization it will apparently work.
stackoverflow
{ "language": "en", "length": 160, "provenance": "stackexchange_0000F.jsonl.gz:907964", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676894" }
7d0565e75abb4e8fe7ed26760234a894d93000b7
Stackoverflow Stackexchange Q: How to make a button redirect to another page in React I have a component which has in its Class.propTypes a function onClick: onClick: PropTypes.func In another component I'm using this component multiple times to populate a page. Each of these components have a title which when clicked should redirect to another page. The problem I have is that it doesn't work when I click on it. It does nothing. This is the render of the main component: render() { return ( <Class title={account.AccountName} onClick={() => "mySite/accountview?id=" + account.AccountName} > </Class> ... ); } What should I add to onClick to make it work? A: You need use React Router. With Link: <Link to={`/mySite/accountview?id=${account.AccountName}`}>something</Link> With onClick: <button onClick={() => hashHistory.push(`/mySite/accountview?id=${account.AccountName}`)}></button> You can use hashHistory or browserHistory :D
Q: How to make a button redirect to another page in React I have a component which has in its Class.propTypes a function onClick: onClick: PropTypes.func In another component I'm using this component multiple times to populate a page. Each of these components have a title which when clicked should redirect to another page. The problem I have is that it doesn't work when I click on it. It does nothing. This is the render of the main component: render() { return ( <Class title={account.AccountName} onClick={() => "mySite/accountview?id=" + account.AccountName} > </Class> ... ); } What should I add to onClick to make it work? A: You need use React Router. With Link: <Link to={`/mySite/accountview?id=${account.AccountName}`}>something</Link> With onClick: <button onClick={() => hashHistory.push(`/mySite/accountview?id=${account.AccountName}`)}></button> You can use hashHistory or browserHistory :D
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:907969", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44676907" }
e49c14870315dc7c5fafcc8a710611b752a63322
Stackoverflow Stackexchange Q: Visual Studio keep expanding things * *I collapse a project in Project Explorer. Save, close Visual Studio, reopen the solution, everything is expanded. *I collapse a method, or a region, or a comment, or whatever other piece of code. Save, close Visual Studio, reopen the solution, reopen the file, everything is expanded. *I collapse some XAML. Save, close Visual Studio, reopen the solution, reopen the file, everything is expanded. At first I was using Visual Studio 2015 and I had not this problem. Then it started behaving this way. Then I uninstalled VS2015, and then installed VS2017. It keeps doing it. It doesn't happens with all the solutions or projects, by the way, and it's not consistent. In some cases it only expands all projects in the Project Explorer, in other cases it expands everything. Any idea? What could it be? A: Do you have check "Track Active Item in Solution Explorer" (Tools -> Options -> Projects and Solutions)? If it's on, Solution Explorer will expand folders.
Q: Visual Studio keep expanding things * *I collapse a project in Project Explorer. Save, close Visual Studio, reopen the solution, everything is expanded. *I collapse a method, or a region, or a comment, or whatever other piece of code. Save, close Visual Studio, reopen the solution, reopen the file, everything is expanded. *I collapse some XAML. Save, close Visual Studio, reopen the solution, reopen the file, everything is expanded. At first I was using Visual Studio 2015 and I had not this problem. Then it started behaving this way. Then I uninstalled VS2015, and then installed VS2017. It keeps doing it. It doesn't happens with all the solutions or projects, by the way, and it's not consistent. In some cases it only expands all projects in the Project Explorer, in other cases it expands everything. Any idea? What could it be? A: Do you have check "Track Active Item in Solution Explorer" (Tools -> Options -> Projects and Solutions)? If it's on, Solution Explorer will expand folders.
stackoverflow
{ "language": "en", "length": 168, "provenance": "stackexchange_0000F.jsonl.gz:908024", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677067" }
4a30b2aa90ee065d74c2de07c69924a24f372ab1
Stackoverflow Stackexchange Q: Restore marker initial position and zoom level in Leaflet In Leaflet, I am trying to create a function that restores the initial position and zoom level of a layer containing coordinates. The code below function refresh() { map.fitBounds(coordLayer.getBounds(); } centers the marker but is zoomed in to the maxZoom I had set: var map = L.map('map').setView([lat, lon], 6); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' { maxZoom: 13, minZoom: 2, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }).addTo(map); The default zoom level on page refresh is 6, but I don't know how to create a function that centers the marker at zoom level 6. A: Found a simple solution after reading the Documentation: function refresh() { map.setView([lat, lon], 6); }
Q: Restore marker initial position and zoom level in Leaflet In Leaflet, I am trying to create a function that restores the initial position and zoom level of a layer containing coordinates. The code below function refresh() { map.fitBounds(coordLayer.getBounds(); } centers the marker but is zoomed in to the maxZoom I had set: var map = L.map('map').setView([lat, lon], 6); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' { maxZoom: 13, minZoom: 2, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }).addTo(map); The default zoom level on page refresh is 6, but I don't know how to create a function that centers the marker at zoom level 6. A: Found a simple solution after reading the Documentation: function refresh() { map.setView([lat, lon], 6); } A: With this var you can set your Default Initial Zoom Level and this getter should work on this. Is this the answer you've been searching for?
stackoverflow
{ "language": "en", "length": 139, "provenance": "stackexchange_0000F.jsonl.gz:908042", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677113" }
644d891350071351025c8763eb2ad24bfee083ea
Stackoverflow Stackexchange Q: Call to undefined function sqlsrv_connect() - Troubleshooting System Information CMS: Wordpress Web Server: XAMPP PHP Version: 5.5.30 MS Management Studio 17 Goal Establish MSSQL Database connection using PHP What has been done * *Downloaded SQLSRV Drivers *Copied files php_pdo_sqlsrv_55_nts.dll and php_pdo_sqlsrv_55_ts.dll to the directory C:\xampp\php\ext *Added the following lines to the dynamic extensions part in the php.ini file: extension=php_pdo_sqlsrv_55_ts.dll and extension=php_pdo_sqlsrv_55_nts.dll *Restarted Web Server *Confirmed sqlsrv is listed in phpinfo() Code $serverName = "technology-pc\sqlexpress"; // The connection will be attempted using Windows Authentication. $connectionInfo = array( "Database"=>"example_db"); $conn = sqlsrv_connect($serverName, $connectionInfo); if( $conn ) { echo "Connection established.<br />"; } else { echo "Connection could not be established.<br />"; die( print_r( sqlsrv_errors(), true)); } Error Call to undefined function sqlsrv_connect() A: You have added the PDO variant of SQLSRV drivers to the extension list, but have not added the base drivers php_sqlsrv_55_ts.dll. Add to the php.ini: extension=php_sqlsrv_55_ts.dll or extension=php_sqlsrv_55_nts.dll Also, you really should be using either the Thread-Safe (_ts.dll) or Non-Thread-Safe (_nts.dll) versions of the driver, not both. I believe that, as you are using an Apache Server, you should be using the Thread-Safe versions. So you php.ini should have: extension=php_sqlsrv_55_ts.dll extension=php_pdo_sqlsrv_55_ts.dll
Q: Call to undefined function sqlsrv_connect() - Troubleshooting System Information CMS: Wordpress Web Server: XAMPP PHP Version: 5.5.30 MS Management Studio 17 Goal Establish MSSQL Database connection using PHP What has been done * *Downloaded SQLSRV Drivers *Copied files php_pdo_sqlsrv_55_nts.dll and php_pdo_sqlsrv_55_ts.dll to the directory C:\xampp\php\ext *Added the following lines to the dynamic extensions part in the php.ini file: extension=php_pdo_sqlsrv_55_ts.dll and extension=php_pdo_sqlsrv_55_nts.dll *Restarted Web Server *Confirmed sqlsrv is listed in phpinfo() Code $serverName = "technology-pc\sqlexpress"; // The connection will be attempted using Windows Authentication. $connectionInfo = array( "Database"=>"example_db"); $conn = sqlsrv_connect($serverName, $connectionInfo); if( $conn ) { echo "Connection established.<br />"; } else { echo "Connection could not be established.<br />"; die( print_r( sqlsrv_errors(), true)); } Error Call to undefined function sqlsrv_connect() A: You have added the PDO variant of SQLSRV drivers to the extension list, but have not added the base drivers php_sqlsrv_55_ts.dll. Add to the php.ini: extension=php_sqlsrv_55_ts.dll or extension=php_sqlsrv_55_nts.dll Also, you really should be using either the Thread-Safe (_ts.dll) or Non-Thread-Safe (_nts.dll) versions of the driver, not both. I believe that, as you are using an Apache Server, you should be using the Thread-Safe versions. So you php.ini should have: extension=php_sqlsrv_55_ts.dll extension=php_pdo_sqlsrv_55_ts.dll A: You probably edited the wrong php.ini file. Check the right php.ini file with php info. You can use this script: <?php echo phpinfo(); ?> Or if you have CLI access type php -i to get the info listed. Check for the right path of your php.ini file. A: Try below code to connect mssql database $server = 'dburl.com\MSSQLSERVER, 1433'; $username = 'uname'; $password = 'password'; $connectionInfo = array( "Database"=>$database, "UID"=>$username, "PWD"=>$password,"ReturnDatesAsStrings"=>true); $conn = sqlsrv_connect( $server, $connectionInfo);
stackoverflow
{ "language": "en", "length": 270, "provenance": "stackexchange_0000F.jsonl.gz:908141", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677399" }
ebb353546b915f0ebeec27c8f9fe6eb421d918d6
Stackoverflow Stackexchange Q: React can't set state I'm working in React and trying to fill a ImageGrid with data from a API. There is no problem with getting the data but somehow I cant set my state with the responseData I can show the data while I get the response from the API but I can't set my state... componentWillMount() { this.state = { content: '' }; this.loadContent(); } loadContent() { ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => { console.log("Data is here",responseData); //<---------- HERE this.setState({ content: responseData }); }) console.log("Data is not here",this.state.content); //<---------- HERE } Here I get the data: class ApiService { static getTweets() { return fetch("https://MyURL", { method: 'get' }) .then((resp) => resp.json()) .then(function(data) { return data; }).catch(function(error) { console.log(error);// Error :( }); } } export default ApiService; A: You have async issue: both fetch and setState are async. loadContent() { ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => { console.log("Data is here",responseData); //<---------- HERE this.setState({ content: responseData }, () => { // only now the state was updated console.log("Data is here", this.state.content); }); // even the nest line runs to early console.log("Data is not here",this.state.content); }) // the next line runs to early console.log("Data is not here",this.state.content); }
Q: React can't set state I'm working in React and trying to fill a ImageGrid with data from a API. There is no problem with getting the data but somehow I cant set my state with the responseData I can show the data while I get the response from the API but I can't set my state... componentWillMount() { this.state = { content: '' }; this.loadContent(); } loadContent() { ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => { console.log("Data is here",responseData); //<---------- HERE this.setState({ content: responseData }); }) console.log("Data is not here",this.state.content); //<---------- HERE } Here I get the data: class ApiService { static getTweets() { return fetch("https://MyURL", { method: 'get' }) .then((resp) => resp.json()) .then(function(data) { return data; }).catch(function(error) { console.log(error);// Error :( }); } } export default ApiService; A: You have async issue: both fetch and setState are async. loadContent() { ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => { console.log("Data is here",responseData); //<---------- HERE this.setState({ content: responseData }, () => { // only now the state was updated console.log("Data is here", this.state.content); }); // even the nest line runs to early console.log("Data is not here",this.state.content); }) // the next line runs to early console.log("Data is not here",this.state.content); } A: You want to use the set state callback as state is not set instantly. loadContent() { ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => { console.log("Data is here",responseData); //<---------- HERE this.setState({ content: responseData }, () => { console.log("Data is here",this.state.content); //<---------- HERE ); }) } A: You need to implement componentDidUpdate. Don't rely on the promises to know when your component has updated. React's life-cycle will worry about that after the system has updated. See below. From that point you can easily do something like componentDidUpdate(prevProps, prevState) { if(prevState.content !== this.state.content) { console.log('I have new content!', this.state.content); } } Also, you can ignore that if statement if you only have one setState() call in your component. So the short version is as follows: componentDidUpdate(prevProps, prevState) { console.log('I have new content!', this.state.content); }
stackoverflow
{ "language": "en", "length": 316, "provenance": "stackexchange_0000F.jsonl.gz:908154", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677440" }
a603e2b5a9d5dbf612540ca369fb5dd1b08ce2a4
Stackoverflow Stackexchange Q: How do you save a snippet of code in SAS Studio as an abbreviation? In SAS Studio, is it possible to save a snippet of code, such as a header, as an abbreviation so you can pull-up the code in future programs without having to type the whole thing in again? This can be achieved is SAS EG by selecting "Program > Add Abbreviation Macro", does SAS Studio have a similar option? A: The Snippet functionality is available in SAS Studio from version 3.1 on-wards. Full details are on SAS support site here. To create your own snippet: * *Open your .sas file in SAS Studio and select the code that you want to save as a snippet. *On the Code tab, click Add to My Snippets button. The Add to My Snippets dialog box appears. *Enter a name for the snippet and click Save. This snippet is now available from the My Snippets folder.
Q: How do you save a snippet of code in SAS Studio as an abbreviation? In SAS Studio, is it possible to save a snippet of code, such as a header, as an abbreviation so you can pull-up the code in future programs without having to type the whole thing in again? This can be achieved is SAS EG by selecting "Program > Add Abbreviation Macro", does SAS Studio have a similar option? A: The Snippet functionality is available in SAS Studio from version 3.1 on-wards. Full details are on SAS support site here. To create your own snippet: * *Open your .sas file in SAS Studio and select the code that you want to save as a snippet. *On the Code tab, click Add to My Snippets button. The Add to My Snippets dialog box appears. *Enter a name for the snippet and click Save. This snippet is now available from the My Snippets folder.
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:908155", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677441" }
7776428b44a1c488266a1c2c3fa2509aaef998b4
Stackoverflow Stackexchange Q: Why do the impression counts on the AdSense app and on the site apps.AdMob.com differ? I am using admob in my app to show advertising. To check the impressions I am using AdSense app and set with my AdMob account. When I check the impressions count on site apps.admob.com and on app AdSense impression count differ. Its almost double on AdSense app. What is the reason behind that? A: I am seeing the same behavior. Adsense report: Admob report: It seems that Admob shows adsense when it has no admob ads to show. but still it is a mystery tome why this is not indicated explicitly in the Admob website.
Q: Why do the impression counts on the AdSense app and on the site apps.AdMob.com differ? I am using admob in my app to show advertising. To check the impressions I am using AdSense app and set with my AdMob account. When I check the impressions count on site apps.admob.com and on app AdSense impression count differ. Its almost double on AdSense app. What is the reason behind that? A: I am seeing the same behavior. Adsense report: Admob report: It seems that Admob shows adsense when it has no admob ads to show. but still it is a mystery tome why this is not indicated explicitly in the Admob website. A: For future reference what Adsense calls impressions Admob calls it Requests. Adsense impression is counted for each ad request where at least one ad has begun to download to the user's device. But Adsence doesn't know if the ad really shows. In the other hand Admob knows when ads have been shown, and it is call Admob impression.
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:908160", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677464" }
6d8aee5e94da0165093510f210232feebfe0cc44
Stackoverflow Stackexchange Q: Jenkins doesnt build project with firebase I have an android project whicj was previously built in jenkins successfully. But when I added firebase to the project, jenkins stopped building the project. The error text is as follows. Could not find com.google.firebase:firebase-core:11.0.1. Required by: project :data > Could not find com.google.firebase:firebase-config:11.0.1. Required by: project :data > Could not find com.google.firebase:firebase-messaging:11.0.1. Required by: project :data So, what is the problem? Thanks. A: Run following on your server running jenkins (Google Repository artifacts need to be udpated). android update sdk --no-ui
Q: Jenkins doesnt build project with firebase I have an android project whicj was previously built in jenkins successfully. But when I added firebase to the project, jenkins stopped building the project. The error text is as follows. Could not find com.google.firebase:firebase-core:11.0.1. Required by: project :data > Could not find com.google.firebase:firebase-config:11.0.1. Required by: project :data > Could not find com.google.firebase:firebase-messaging:11.0.1. Required by: project :data So, what is the problem? Thanks. A: Run following on your server running jenkins (Google Repository artifacts need to be udpated). android update sdk --no-ui
stackoverflow
{ "language": "en", "length": 89, "provenance": "stackexchange_0000F.jsonl.gz:908167", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677485" }
59d0f3140dcb7ad66e26336086b94af797ddec8c
Stackoverflow Stackexchange Q: How to measure the speed of a python function I usually write codes(functions) on www.codefights.com as a competitor.So speed is one of the important part of the code . How can i measure the speed of a certain code in python language whether it is the lambda function or a def function . A: You can use it in ipython and use the %time to see the allocation time needed for the execution of the function : In [1]: def function(a,b): ...: return a+b ...: In [2]: %time function(1, 2) CPU times: user 5 µs, sys: 0 ns, total: 5 µs Wall time: 9.06 µs Out[2]: 3
Q: How to measure the speed of a python function I usually write codes(functions) on www.codefights.com as a competitor.So speed is one of the important part of the code . How can i measure the speed of a certain code in python language whether it is the lambda function or a def function . A: You can use it in ipython and use the %time to see the allocation time needed for the execution of the function : In [1]: def function(a,b): ...: return a+b ...: In [2]: %time function(1, 2) CPU times: user 5 µs, sys: 0 ns, total: 5 µs Wall time: 9.06 µs Out[2]: 3 A: I usually rely on the following when I need to measure the execution time of some very specific piece of code: https://docs.python.org/3/library/time.html def howLong(): startTime = time.time() time.sleep(3) print("Time to wake up, ~3 seconds have passed!") endTime = time.time() howMuchTime = endTime - startTime print(str(howMuchTime) + " sec") if __name__ == '__main__': import time howLong() Result Time to wake up, ~3 seconds have passed! 3.013692855834961 sec A: In 3 Step ;) Step 1: install line_profiler pip install line_profiler Step 2: Add @profile to your code: from time import sleep @profile def so_slow(bar): sleep(5) return bar if __name__ == "__main__": so_slow(5) Step 3: Test your code: kernprof -l -v your_code.py Result Wrote profile results to your_code.py.lprof Timer unit: 1e-06 s Total time: 5.00283 s File: your_code.py Function: so_slow at line 4 Line # Hits Time Per Hit % Time Line Contents ============================================================== 4 @profile 5 def so_slow(bar): 6 1 5002830 5002830.0 100.0 sleep(5) 7 1 2 2.0 0.0 return bar memory_profiler You can use memory_profiler too, Install it, add profile and call it: pip install memory_profiler python -m memory_profiler your_code.py Result: Filename: your_code.py Line # Mem usage Increment Line Contents ================================================ 4 21.289 MiB 0.000 MiB @profile 5 def so_slow(bar): 6 21.289 MiB 0.000 MiB sleep(5) 7 21.289 MiB 0.000 MiB return bar Update: You can use objgraph to find memory leak or draw a graph of your code: from time import sleep import objgraph x = [1] objgraph.show_backrefs([x], filename='sample-backref-graph.png') def so_slow(bar): sleep(5) return bar if __name__ == "__main__": so_slow(5) Result: Reference : A guide to analyzing Python performance A: Have a look at the timeit module in pythons standard libaray: https://docs.python.org/2/library/timeit.html >>> import timeit >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 0.8187260627746582 >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) 0.7288308143615723 >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000) 0.5858950614929199 To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement: def test(): """Stupid test function""" L = [] for i in range(100): L.append(i) if __name__ == '__main__': import timeit print(timeit.timeit("test()", setup="from __main__ import test")) A: For instance: import timeit def a(): return 1+1 print timeit.timeit(a, number=1000000)
stackoverflow
{ "language": "en", "length": 461, "provenance": "stackexchange_0000F.jsonl.gz:908205", "question_score": "20", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677606" }
bb3903812bdddfdb59a4e8a1b0d4fd4c316b8b0f
Stackoverflow Stackexchange Q: check if date column contains all the hours in each year I frequently need to download hourly historic data from a website in the following format ` date A B C 2011/01/01 00:00 100 200 300 2011/01/01 01:00 105 210 330 ..... 2012/12/31 23:00 200 400 500' some issue i'm having is that the online data some times misses couple hours/days per year. I need to check how many and which dates are missing to decide is the data is usable. I normally just do df.groupby(by = df['date'].dt.yr)['dt'].count() and see if each year has 8760 (8784 for leap years) and check which days are missing manually. I wonder if anyone has had similar problem and knows how to write a piece of code to tell me which year is missing how many hours and which hours are missing. A: Use asfreq and difference df.asfreq('H').index.difference(df.index) DatetimeIndex(['2011-01-01 02:00:00', '2011-01-01 03:00:00', '2011-01-01 04:00:00', '2011-01-01 05:00:00', '2011-01-01 06:00:00', '2011-01-01 07:00:00', '2011-01-01 08:00:00', '2011-01-01 09:00:00', '2011-01-01 10:00:00', '2011-01-01 11:00:00', ... '2012-12-31 13:00:00', '2012-12-31 14:00:00', '2012-12-31 15:00:00', '2012-12-31 16:00:00', '2012-12-31 17:00:00', '2012-12-31 18:00:00', '2012-12-31 19:00:00', '2012-12-31 20:00:00', '2012-12-31 21:00:00', '2012-12-31 22:00:00'], dtype='datetime64[ns]', name='date', length=17541, freq='H')
Q: check if date column contains all the hours in each year I frequently need to download hourly historic data from a website in the following format ` date A B C 2011/01/01 00:00 100 200 300 2011/01/01 01:00 105 210 330 ..... 2012/12/31 23:00 200 400 500' some issue i'm having is that the online data some times misses couple hours/days per year. I need to check how many and which dates are missing to decide is the data is usable. I normally just do df.groupby(by = df['date'].dt.yr)['dt'].count() and see if each year has 8760 (8784 for leap years) and check which days are missing manually. I wonder if anyone has had similar problem and knows how to write a piece of code to tell me which year is missing how many hours and which hours are missing. A: Use asfreq and difference df.asfreq('H').index.difference(df.index) DatetimeIndex(['2011-01-01 02:00:00', '2011-01-01 03:00:00', '2011-01-01 04:00:00', '2011-01-01 05:00:00', '2011-01-01 06:00:00', '2011-01-01 07:00:00', '2011-01-01 08:00:00', '2011-01-01 09:00:00', '2011-01-01 10:00:00', '2011-01-01 11:00:00', ... '2012-12-31 13:00:00', '2012-12-31 14:00:00', '2012-12-31 15:00:00', '2012-12-31 16:00:00', '2012-12-31 17:00:00', '2012-12-31 18:00:00', '2012-12-31 19:00:00', '2012-12-31 20:00:00', '2012-12-31 21:00:00', '2012-12-31 22:00:00'], dtype='datetime64[ns]', name='date', length=17541, freq='H')
stackoverflow
{ "language": "en", "length": 190, "provenance": "stackexchange_0000F.jsonl.gz:908227", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677676" }
eefaa5216c3447987af22c1dec8b57d6d8fd6f06
Stackoverflow Stackexchange Q: Alfresco Create User From Filter By taking reference from this post and I am successful in authenticating the user. But this post does not authenticate new users that are not present in alfresco. I have also explored SSOAuthenticationFilter.java to find how alfresco creates user when external authentication subsystem is used but not able figure out how the creation of user takes place in the mentioned subsystem. It would be great if anyone could provide the way to create and authenticate user that are not present in alfresco. A: Which version of Alfresco do you use ? Recent version provide a similar function, please take a look to : http://docs.alfresco.com/community/concepts/auth-basics.html The only thing you need to need is define the header name in your global properties files. About the new user creation, in Alfresco behaviour it's based on the synchronization.syncWhenMissingPeopleLogIn properties : http://docs.alfresco.com/community/concepts/sync-props.html When an unknown user try to loggin Alfresco will trigger a synchronization. Y.
Q: Alfresco Create User From Filter By taking reference from this post and I am successful in authenticating the user. But this post does not authenticate new users that are not present in alfresco. I have also explored SSOAuthenticationFilter.java to find how alfresco creates user when external authentication subsystem is used but not able figure out how the creation of user takes place in the mentioned subsystem. It would be great if anyone could provide the way to create and authenticate user that are not present in alfresco. A: Which version of Alfresco do you use ? Recent version provide a similar function, please take a look to : http://docs.alfresco.com/community/concepts/auth-basics.html The only thing you need to need is define the header name in your global properties files. About the new user creation, in Alfresco behaviour it's based on the synchronization.syncWhenMissingPeopleLogIn properties : http://docs.alfresco.com/community/concepts/sync-props.html When an unknown user try to loggin Alfresco will trigger a synchronization. Y.
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:908239", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677739" }
983738f7d88ea02556a4293ebcf6f832104142b4
Stackoverflow Stackexchange Q: Custom Claim with Boolean type I'm using Visual Studio 2015 to create an ASP.NET MVC 5 app. I'm using the Identity framework to add claims to a user after authentication. It's easy enough to add claims based on the built-in ClaimTypes, but I'm having challenges adding a custom claim that's a Boolean. I've created this static class to hold my custom claim types: public static class CustomClaimTypes { public static readonly string IsEmployee = "http://example.com/claims/isemployee"; } Then I try to add a custom claim to the ClaimsIdentity object: userIdentity.AddClaim(new Claim(CustomClaimTypes.IsEmployee, isEmployee)); It gives this error on the line above: cannot convert from 'bool?' to 'System.Security.Claims.ClaimsIdentity' All the examples that I'm finding are adding strings. How do you add a bool, int, or other type? Thanks. A: You can also pass valueType as third parameter. userIdentity.AddClaim( new Claim(CustomClaimTypes.IsEmployee, isEmployee.ToString(), ClaimValueTypes.Boolean)); so on front end you will get bool type value instead of string.
Q: Custom Claim with Boolean type I'm using Visual Studio 2015 to create an ASP.NET MVC 5 app. I'm using the Identity framework to add claims to a user after authentication. It's easy enough to add claims based on the built-in ClaimTypes, but I'm having challenges adding a custom claim that's a Boolean. I've created this static class to hold my custom claim types: public static class CustomClaimTypes { public static readonly string IsEmployee = "http://example.com/claims/isemployee"; } Then I try to add a custom claim to the ClaimsIdentity object: userIdentity.AddClaim(new Claim(CustomClaimTypes.IsEmployee, isEmployee)); It gives this error on the line above: cannot convert from 'bool?' to 'System.Security.Claims.ClaimsIdentity' All the examples that I'm finding are adding strings. How do you add a bool, int, or other type? Thanks. A: You can also pass valueType as third parameter. userIdentity.AddClaim( new Claim(CustomClaimTypes.IsEmployee, isEmployee.ToString(), ClaimValueTypes.Boolean)); so on front end you will get bool type value instead of string. A: The claims can only be represented as strings. Any numbers, booleans, guids, whatever all have to be strings when added to the claims collection. So ToString() it. userIdentity.AddClaim( new Claim(CustomClaimTypes.IsEmployee, isEmployee.GetValueOrDefault(false).ToString())); A: To get the correct type you want in the response, you need to overload TokenEndpointResponse public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context) { foreach (var item in context.Identity.Claims) { object value; if (item.ValueType.Contains("boolean")) value = bool.Parse(item.Value); else value = item.Value; context.AdditionalResponseParameters.Add(item.Type, value); } return base.TokenEndpointResponse(context); } of course after specifying the ClaimValueTypes as mentioned in previous answers, otherwise it will identify all fields as string type.
stackoverflow
{ "language": "en", "length": 250, "provenance": "stackexchange_0000F.jsonl.gz:908254", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677784" }
5e675e23b5f1db8df968ca56dab0543ad5f54388
Stackoverflow Stackexchange Q: Rvalue to lvalue conversion? Why it is not possible to convert rvalues to lvalues? It is possible to do a conversion in the opposite direction though. Technically rvalues do have a memory address, isn't it? A: It is rather straightforward to write a template function unmove(), that does the opposite of std::move(): template<class T> T& unmove(T&& t) { return t; } Please note that, according to the standard since C++11: a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference. So it is safe to use unmove() within a single full expression, but after the expression has been fully evaluated, the temporaries go away. My common use for unmove() is to call functions / methods, that return values through references, when I don't need those values.
Q: Rvalue to lvalue conversion? Why it is not possible to convert rvalues to lvalues? It is possible to do a conversion in the opposite direction though. Technically rvalues do have a memory address, isn't it? A: It is rather straightforward to write a template function unmove(), that does the opposite of std::move(): template<class T> T& unmove(T&& t) { return t; } Please note that, according to the standard since C++11: a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference. So it is safe to use unmove() within a single full expression, but after the expression has been fully evaluated, the temporaries go away. My common use for unmove() is to call functions / methods, that return values through references, when I don't need those values. A: You can: int&& x = 3; x is now an lvalue. A so called 'rvalue-reference' can bind to a temporary, but anything with a name is an lvalue, so you need to forward<>() it if you need it's rvalueness back. Note that by binding a temporary to a rvalue-reference (or a const reference) you extend its lifetime. Technically a cast is possible, but not recommended, since temporaries have short lifetime, so you typically get a dangling reference. A: Correct an anwer above. int&& x = 3; x is 'rvalue-reference'. See https://www.tutorialspoint.com/What-is-double-address-operator-and-and-in-Cplusplus
stackoverflow
{ "language": "en", "length": 248, "provenance": "stackexchange_0000F.jsonl.gz:908264", "question_score": "19", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677825" }
955b978d8662950b8ced4e3ddebed5dc0332a5e6
Stackoverflow Stackexchange Q: New line for ngbpopover text I am using angular 2 and ng bootstrap popover feature. Following is my html. I have infoIconText variable that has some new line \n character. However I am still unable to see the new line when I see the popover text. How can I style the popover text? Any suggestions? <i class="fa fa-info-circle" ngbPopover="{{infoIconText}}" triggers="mouseenter:mouseleave" aria-hidden="true"></i> My infoIconText is as follows: this.infoIconText = "This is line 1." + "\nThis is line2"; A: I was able to solve this issue by creating a template and referencing that template. <ng-template #popContent>Line1<br>Line2</ng-template> <i class="fa fa-info-circle info-icon-background popover-content" [ngbPopover]="popContent" placement="top" triggers="mouseenter:mouseleave" aria-hidden="true"></i>
Q: New line for ngbpopover text I am using angular 2 and ng bootstrap popover feature. Following is my html. I have infoIconText variable that has some new line \n character. However I am still unable to see the new line when I see the popover text. How can I style the popover text? Any suggestions? <i class="fa fa-info-circle" ngbPopover="{{infoIconText}}" triggers="mouseenter:mouseleave" aria-hidden="true"></i> My infoIconText is as follows: this.infoIconText = "This is line 1." + "\nThis is line2"; A: I was able to solve this issue by creating a template and referencing that template. <ng-template #popContent>Line1<br>Line2</ng-template> <i class="fa fa-info-circle info-icon-background popover-content" [ngbPopover]="popContent" placement="top" triggers="mouseenter:mouseleave" aria-hidden="true"></i>
stackoverflow
{ "language": "en", "length": 104, "provenance": "stackexchange_0000F.jsonl.gz:908267", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44677834" }
024986e27288efa8511fd0ccfefd888bcaef6a8f
Stackoverflow Stackexchange Q: Angular Firebase Database Querying This is my .ts file import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; @Component({ selector: 'app-candidate-reg-success', templateUrl: './candidate-reg-success.component.html', styleUrls: ['./candidate-reg-success.component.css'] }) export class CandidateRegSuccessComponent implements OnInit { constructor() { debugger; const rootRef=firebase.database.ref(); const mail=rootRef.child('candidates_list').orderByChild('email').equalTo('[email protected]'); console.log(mail); } ngOnInit() { } } I am trying to query the user from candidates_list table which has the email address [email protected]. But I am unable to console it. It shows a error like Property 'ref' does not exist on type 'typeof database'. Any solution to query angular firebase database? A: you need to inject the AngularFirebaseData in constructor and change the code and try again import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; @Component({ selector: 'app-candidate-reg-success', templateUrl: './candidate-reg-success.component.html', styleUrls: ['./candidate-reg-success.component.css'] }) export class CandidateRegSuccessComponent implements OnInit { constructor(public db: AngularFireDatabase) { debugger; db.list('/candidates_list', ref => ref.orderByChild('email').equalTo('[email protected]')); } ngOnInit() { }}
Q: Angular Firebase Database Querying This is my .ts file import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; @Component({ selector: 'app-candidate-reg-success', templateUrl: './candidate-reg-success.component.html', styleUrls: ['./candidate-reg-success.component.css'] }) export class CandidateRegSuccessComponent implements OnInit { constructor() { debugger; const rootRef=firebase.database.ref(); const mail=rootRef.child('candidates_list').orderByChild('email').equalTo('[email protected]'); console.log(mail); } ngOnInit() { } } I am trying to query the user from candidates_list table which has the email address [email protected]. But I am unable to console it. It shows a error like Property 'ref' does not exist on type 'typeof database'. Any solution to query angular firebase database? A: you need to inject the AngularFirebaseData in constructor and change the code and try again import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; @Component({ selector: 'app-candidate-reg-success', templateUrl: './candidate-reg-success.component.html', styleUrls: ['./candidate-reg-success.component.css'] }) export class CandidateRegSuccessComponent implements OnInit { constructor(public db: AngularFireDatabase) { debugger; db.list('/candidates_list', ref => ref.orderByChild('email').equalTo('[email protected]')); } ngOnInit() { }}
stackoverflow
{ "language": "en", "length": 154, "provenance": "stackexchange_0000F.jsonl.gz:908322", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678017" }
5427fbd917978c43a77708b5b8f670dae5ed9b86
Stackoverflow Stackexchange Q: How to use the Google satellite view as tile in leaflet with R Many questions seem similar to mine, I could not however find a fitting answer for R. So far, I use the awesome R leaflet (and ggmap) package that way: library(ggmap) library(leaflet) coord <-geocode('New York') map.city <- leaflet() %>% addTiles('http://{s}.tile.thunderforest.com/transport/{z}/{x}/{y}.png?apikey=68c4cd328d3b484091812a76fae093fd') %>% setView(coord$lon, coord$lat, zoom = 11) But what if I want as a map the Google satellite? I went through this post https://stackoverflow.com/questions/9394190/leaflet-map-api-with-google-satellite-layer#= but don't understand how to use the googleSat function defined there. A: To use the actual Google Maps (which comes with satellite view) you can use my googleway package library(googleway) apiKey <- 'your_api_key' mapKey <- 'your_map_key' newYork <- google_geocode(address = "New York", key = apiKey) google_map(location = as.numeric(newYork$results$geometry$location), key = mapKey) The vignette has more examples of what you can do with the maps.
Q: How to use the Google satellite view as tile in leaflet with R Many questions seem similar to mine, I could not however find a fitting answer for R. So far, I use the awesome R leaflet (and ggmap) package that way: library(ggmap) library(leaflet) coord <-geocode('New York') map.city <- leaflet() %>% addTiles('http://{s}.tile.thunderforest.com/transport/{z}/{x}/{y}.png?apikey=68c4cd328d3b484091812a76fae093fd') %>% setView(coord$lon, coord$lat, zoom = 11) But what if I want as a map the Google satellite? I went through this post https://stackoverflow.com/questions/9394190/leaflet-map-api-with-google-satellite-layer#= but don't understand how to use the googleSat function defined there. A: To use the actual Google Maps (which comes with satellite view) you can use my googleway package library(googleway) apiKey <- 'your_api_key' mapKey <- 'your_map_key' newYork <- google_geocode(address = "New York", key = apiKey) google_map(location = as.numeric(newYork$results$geometry$location), key = mapKey) The vignette has more examples of what you can do with the maps. A: If it has to be google satellite imagery you could use the googleway package. If other satellite imagery is ok, you can use "Esri.WorlImagery" with or without "CartoDB.PositronOnlyLabels" in leaflet: library(ggmap) library(leaflet) coord <-geocode('New York') map.city <- leaflet() %>% addProviderTiles('Esri.WorldImagery') %>% setView(coord$lon, coord$lat, zoom = 11) map.city %>% addProviderTiles("CartoDB.PositronOnlyLabels")
stackoverflow
{ "language": "en", "length": 190, "provenance": "stackexchange_0000F.jsonl.gz:908327", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678039" }
7384cf0698d1d1c33016542f6abeb225a901c7ac
Stackoverflow Stackexchange Q: named docker volume not updating using docker-compose I'm trying to have one service to build my client side and then share it to the server using a named volume. Every time I do a docker-compose up --build I want the client side to build and update the named volume clientapp:. How do I do that? docker-compose.yml version: '2' volumes: clientapp: services: database: image: mongo:3.4 volumes: - /data/db - /var/lib/mongodb - /var/log/mongodb client: build: ./client volumes: - clientapp:/usr/src/app/client server: build: ./server ports: - "3000:3000" environment: - DB_1_PORT_27017_TCP_ADDR=database volumes: - clientapp:/usr/src/app/client depends_on: - client - database client Dockerfile FROM node:6 ENV NPM_CONFIG_LOGLEVEL warn RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY package.json /usr/src/app RUN npm install COPY . /usr/src/app # builds my application into /client CMD ["npm", "build"] A: Imagine you shared your src folder like this : ... volumes: - ./my_src:/path/to/docker/src ... What worked for me is to chown the my_src folder : chown $USER:$USER -R my_src It turned out some files were created by root and couldn't be modified by docker. Hope it helps !
Q: named docker volume not updating using docker-compose I'm trying to have one service to build my client side and then share it to the server using a named volume. Every time I do a docker-compose up --build I want the client side to build and update the named volume clientapp:. How do I do that? docker-compose.yml version: '2' volumes: clientapp: services: database: image: mongo:3.4 volumes: - /data/db - /var/lib/mongodb - /var/log/mongodb client: build: ./client volumes: - clientapp:/usr/src/app/client server: build: ./server ports: - "3000:3000" environment: - DB_1_PORT_27017_TCP_ADDR=database volumes: - clientapp:/usr/src/app/client depends_on: - client - database client Dockerfile FROM node:6 ENV NPM_CONFIG_LOGLEVEL warn RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY package.json /usr/src/app RUN npm install COPY . /usr/src/app # builds my application into /client CMD ["npm", "build"] A: Imagine you shared your src folder like this : ... volumes: - ./my_src:/path/to/docker/src ... What worked for me is to chown the my_src folder : chown $USER:$USER -R my_src It turned out some files were created by root and couldn't be modified by docker. Hope it helps ! A: By definition, a volume is the persistent directories that docker won't touch other than to perform an initial creation when they are empty. If this is your code, it probably shouldn't be a volume. With that said, you can: * *Delete the volume between runs with docker-compose down -v and it will be recreated and initialized on the next docker-compose up -d. *Change your container startup scripts to copy the files from some other directory in the image to the volume location on startup. *Get rid of the volume and include the code directly in the image. I'd recommend the latter.
stackoverflow
{ "language": "en", "length": 277, "provenance": "stackexchange_0000F.jsonl.gz:908329", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678042" }
a6067b4d0372c24029a94a3fb2ec1637d99542e8
Stackoverflow Stackexchange Q: Docker and Chromium net::ERR_NETWORK_CHANGED I have an AngularJS application that does an ajax call but it results in a chromium error: net::ERR_NETWORK_CHANGED I tried to disable any adapters that I don't need. I have multiple ones and multiple dockers containers running. I disabled ipv6 on each adapter. I don't use any proxy and use default Chromium browser without any addon nor browser profile. Disabled Wifi interface, only using ethernet. Any idea how to fix this? A: I was constantly getting ERR_NETWORK_CHANGED. This is what finally worked for my current browsers: Chromium, Opera and FlashPeak Slimjet. sudo service docker stop The following actions did not solve my issue: * *Checked modem, router, and cables to isolate the issue. *Disabled IPv6 from my wired Network *Commands: sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1 sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1 After I stopped Docker, I am not getting any more console errors. I hope this can help someone saving hours of annoying troubleshooting. Ron.
Q: Docker and Chromium net::ERR_NETWORK_CHANGED I have an AngularJS application that does an ajax call but it results in a chromium error: net::ERR_NETWORK_CHANGED I tried to disable any adapters that I don't need. I have multiple ones and multiple dockers containers running. I disabled ipv6 on each adapter. I don't use any proxy and use default Chromium browser without any addon nor browser profile. Disabled Wifi interface, only using ethernet. Any idea how to fix this? A: I was constantly getting ERR_NETWORK_CHANGED. This is what finally worked for my current browsers: Chromium, Opera and FlashPeak Slimjet. sudo service docker stop The following actions did not solve my issue: * *Checked modem, router, and cables to isolate the issue. *Disabled IPv6 from my wired Network *Commands: sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1 sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1 After I stopped Docker, I am not getting any more console errors. I hope this can help someone saving hours of annoying troubleshooting. Ron. A: sudo service docker stop But this is not a solution because I need docker in my daily work. So I found out that docker networks cause this problem docker network prune helped me Or try to delete one by one except of none, bridge, host A: Based on the original answers, I want to go into more detail what fixed it in my case. Stopping the docker service sudo service docker stop in my case fixed the issue. The underlying issue one of my docker-compose setups having restart=always. Unfortunatly I had a bug causing a container to terminate and restart. This restart caused the network change. It is determinable by running docker ps and noticing the container restarted. I fixed the problem and ran docker-compose down for my docker compose setup. Both actions would fix it independently. Furthermore a Bugreport for chromium exists regarding this issue, but it has the state wontfix.
stackoverflow
{ "language": "en", "length": 310, "provenance": "stackexchange_0000F.jsonl.gz:908365", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678168" }
3765170af7ac1dabd31467480bc7f4ed55545700
Stackoverflow Stackexchange Q: Python + OpenCV - Copying an image to some directory I would like to copy some images to some directory, rather than cv2.imwrite the images. The reason is that when I use cv2.imwrite in OpenCV, I get images that are larger than the original ones, apart from that I can see that some images are being rotated. Would that be possible in Python + OpenCV, since I don't want any operation to be made on the original image, which cv2.imwrite seems to be doing? Thanks. A: You don't need opencv to do this. You can use the shutil library. import shutil shutil.copyfile('path/to/1.jpg', 'new/path/to/1.jpg') Note that the destination path must specify the filename too. If you don't want this, you can use shutil.copy2 which lets you specify a directory as the destination. shutil.copy2('path/to/1.jpg', 'new/path/to/dir')
Q: Python + OpenCV - Copying an image to some directory I would like to copy some images to some directory, rather than cv2.imwrite the images. The reason is that when I use cv2.imwrite in OpenCV, I get images that are larger than the original ones, apart from that I can see that some images are being rotated. Would that be possible in Python + OpenCV, since I don't want any operation to be made on the original image, which cv2.imwrite seems to be doing? Thanks. A: You don't need opencv to do this. You can use the shutil library. import shutil shutil.copyfile('path/to/1.jpg', 'new/path/to/1.jpg') Note that the destination path must specify the filename too. If you don't want this, you can use shutil.copy2 which lets you specify a directory as the destination. shutil.copy2('path/to/1.jpg', 'new/path/to/dir')
stackoverflow
{ "language": "en", "length": 134, "provenance": "stackexchange_0000F.jsonl.gz:908388", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678258" }
a62b1b9523f9e8e281818d831bbb6bcff7f81704
Stackoverflow Stackexchange Q: Constexpr for creating objects I'm trying to figure out if there is a performance gain of creating objects with constexpr instead of normally. Here is the code snippet for constexpr. class Rect { const int a; const float b; public: constexpr Rect(const int a,const float b) : a(a),b(b){} }; int main() { constexpr Rect rect = Rect(1,2.0f); } And without constexpr. class Rect { int a; float b; public: Rect(int a, float b) : a(a),b(b){} }; int main() { Rect rect = Rect(1,2.0f); } I was expecting there will be a lot less code for constexpr since the memory should be initialized at compile-time. Am I using constexpr properly? And if that is not true, can you use constexpr to create the objects at compile-time and then use them without any runtime overhead? Thanks! A: It turned out that I had some headers included which were responsible for the similarity of the code. The answer is that there is a big difference between both cases. When compiling without optimizations, there is a substantial difference in the generated code... -cdhowie
Q: Constexpr for creating objects I'm trying to figure out if there is a performance gain of creating objects with constexpr instead of normally. Here is the code snippet for constexpr. class Rect { const int a; const float b; public: constexpr Rect(const int a,const float b) : a(a),b(b){} }; int main() { constexpr Rect rect = Rect(1,2.0f); } And without constexpr. class Rect { int a; float b; public: Rect(int a, float b) : a(a),b(b){} }; int main() { Rect rect = Rect(1,2.0f); } I was expecting there will be a lot less code for constexpr since the memory should be initialized at compile-time. Am I using constexpr properly? And if that is not true, can you use constexpr to create the objects at compile-time and then use them without any runtime overhead? Thanks! A: It turned out that I had some headers included which were responsible for the similarity of the code. The answer is that there is a big difference between both cases. When compiling without optimizations, there is a substantial difference in the generated code... -cdhowie
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:908395", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678277" }
23b08a5c9ff76d3847d2a8199d1681be741d0cfa
Stackoverflow Stackexchange Q: Xamarin.Forms: Press back button from code Is there a way in Xamarin.Forms to press the back button from code? I tried to call OnBackButtonPressed and SendBackButtonPressed but this does not work. The OnBackButtonPressed Event is called but the back action does not perform. Call OnBackButtonPressed: if (_currentQuestionnaireGroup != null) await RefreshDataAsync(); else { App.QuestionnaireOverviewPage.IsDirty = true; this.OnBackButtonPressed(); } Event: protected override bool OnBackButtonPressed() { if (_questionnaireHandler != null) App.QuestionnaireOverviewPage.IsDirty = true; return true; } A: Sorry for the poor english In your Event, change return true; for return base.OnBackButtonPressed();. When you return true, the action 'back' is canceled at device.
Q: Xamarin.Forms: Press back button from code Is there a way in Xamarin.Forms to press the back button from code? I tried to call OnBackButtonPressed and SendBackButtonPressed but this does not work. The OnBackButtonPressed Event is called but the back action does not perform. Call OnBackButtonPressed: if (_currentQuestionnaireGroup != null) await RefreshDataAsync(); else { App.QuestionnaireOverviewPage.IsDirty = true; this.OnBackButtonPressed(); } Event: protected override bool OnBackButtonPressed() { if (_questionnaireHandler != null) App.QuestionnaireOverviewPage.IsDirty = true; return true; } A: Sorry for the poor english In your Event, change return true; for return base.OnBackButtonPressed();. When you return true, the action 'back' is canceled at device.
stackoverflow
{ "language": "en", "length": 101, "provenance": "stackexchange_0000F.jsonl.gz:908426", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678364" }
522f6fe57554f2935f43629b7e89643680698bb0
Stackoverflow Stackexchange Q: Disable warning "Access can be package-private" for @Transactional methods I have several public methods annotated with @Transactional and IntelliJ shows the warning that they can be package-private or private. @Transactional public void doSomething() { ///body } Since methods annotated with @Transactional should be public, how can I disable in IntelliJ this inspection/warning only for those methods? A: Sadly, it isn't possible to make all methods annotated with @Transactional clear the warning, although it is possible to add @SuppressWarnings("WeakerAccess") to make the warning go away.Alternatively, you can disable this inspection altogether in IntelliJ IDEA by going to File→Settings→Editor→Inspections. In the list show in this view you will want to navigate through the subcategories: Java→Declaration redundancy and uncheck the checkbox called "Declaration access can be weaker" that will be available then. If you wish to disable this for future projects, choose the profile "Default" from the dropdown menu labelled "Profile", otherwise, just do this for "Project Default".
Q: Disable warning "Access can be package-private" for @Transactional methods I have several public methods annotated with @Transactional and IntelliJ shows the warning that they can be package-private or private. @Transactional public void doSomething() { ///body } Since methods annotated with @Transactional should be public, how can I disable in IntelliJ this inspection/warning only for those methods? A: Sadly, it isn't possible to make all methods annotated with @Transactional clear the warning, although it is possible to add @SuppressWarnings("WeakerAccess") to make the warning go away.Alternatively, you can disable this inspection altogether in IntelliJ IDEA by going to File→Settings→Editor→Inspections. In the list show in this view you will want to navigate through the subcategories: Java→Declaration redundancy and uncheck the checkbox called "Declaration access can be weaker" that will be available then. If you wish to disable this for future projects, choose the profile "Default" from the dropdown menu labelled "Profile", otherwise, just do this for "Project Default".
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:908520", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678629" }
d4d8ac21bd67c8159166c0ea646db9f615b9889e
Stackoverflow Stackexchange Q: Theano 0.10: Can not use cuDNN on context None: cannot compile with cuDNN I just updated theano to 0.10 version with pip: pip install --no-deps git+https://github.com/Theano/Theano.git#egg=Theano But it cannot be imported successfully, with the error message as follows: Can not use cuDNN on context None: cannot compile with cuDNN. We got this error: c:\users\yl~1\appdata\local\temp\try_flags_jbgv_m.c:4:19:   fatal error: cudnn.h: No such file or directory compilation terminated.    Mapped name None to device cuda: GeForce 940M (0000:01:00.0) I haven't configured theano to use cudnn. I feel theano should works without it. My .theanorc is: Without the .theanorc file, theano works fine. I have also posted this issue at: https://github.com/Theano/Theano/issues/6063#issuecomment-310064365 The best solution I have is to bypass cudnn by add in the .theanorc: [dnn] enabled = False but at the price of the decreased computation speed
Q: Theano 0.10: Can not use cuDNN on context None: cannot compile with cuDNN I just updated theano to 0.10 version with pip: pip install --no-deps git+https://github.com/Theano/Theano.git#egg=Theano But it cannot be imported successfully, with the error message as follows: Can not use cuDNN on context None: cannot compile with cuDNN. We got this error: c:\users\yl~1\appdata\local\temp\try_flags_jbgv_m.c:4:19:   fatal error: cudnn.h: No such file or directory compilation terminated.    Mapped name None to device cuda: GeForce 940M (0000:01:00.0) I haven't configured theano to use cudnn. I feel theano should works without it. My .theanorc is: Without the .theanorc file, theano works fine. I have also posted this issue at: https://github.com/Theano/Theano/issues/6063#issuecomment-310064365 The best solution I have is to bypass cudnn by add in the .theanorc: [dnn] enabled = False but at the price of the decreased computation speed
stackoverflow
{ "language": "en", "length": 133, "provenance": "stackexchange_0000F.jsonl.gz:908540", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678689" }
7e6452455f8fce751dc33434ba2a0dc575515ed4
Stackoverflow Stackexchange Q: Kafka multiple topic consume consumer.subscribe(Pattern.compile(".*"),new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection<TopicPartition> clctn) { } @Override public void onPartitionsAssigned(Collection<TopicPartition> clctn) { } }); How to consume all topics with regex in apache/kafka? I tried above code, but it didn't work. A: For regex use the following signature KafkaConsumer.subscribe(Pattern pattern, ConsumerRebalanceListener listener) E.g. the following code snippet enables the consumer to listen to all topics with prefix my_topics_ ConsumerRebalanceListener listener = new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection<TopicPartition> arg0) { // Don't need it now. } @Override public void onPartitionsAssigned(Collection<TopicPartition> arg0) { // Don't need it now. } }; pattern = Pattern.compile("my_topics_.*"); kafkaConsumer.subscribe(pattern, listener);
Q: Kafka multiple topic consume consumer.subscribe(Pattern.compile(".*"),new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection<TopicPartition> clctn) { } @Override public void onPartitionsAssigned(Collection<TopicPartition> clctn) { } }); How to consume all topics with regex in apache/kafka? I tried above code, but it didn't work. A: For regex use the following signature KafkaConsumer.subscribe(Pattern pattern, ConsumerRebalanceListener listener) E.g. the following code snippet enables the consumer to listen to all topics with prefix my_topics_ ConsumerRebalanceListener listener = new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection<TopicPartition> arg0) { // Don't need it now. } @Override public void onPartitionsAssigned(Collection<TopicPartition> arg0) { // Don't need it now. } }; pattern = Pattern.compile("my_topics_.*"); kafkaConsumer.subscribe(pattern, listener);
stackoverflow
{ "language": "en", "length": 103, "provenance": "stackexchange_0000F.jsonl.gz:908546", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678708" }
79374ca34da5fd954c7cdf08511057c2638528e2
Stackoverflow Stackexchange Q: How to reason or make inferences in Neo4j? I created a semantic Graph in Neo4j. Is there any possibility to use an OWL reasoner in Neo4j? Or any inference engine? Though it has been mentioned here i can't find any solution or API for this. Thankful for any advice! A: Maybe you want to see this: click here I quoted this from that link: Your main task if you want to use reasoners over a neo4j database is going to be to suck data out of neo4j, and format it as a set of RDF triples. You can then put those RDF triples into a Jena Model. When you have that jena model in memory, you can use existing jena APIs to use reasoners with that model
Q: How to reason or make inferences in Neo4j? I created a semantic Graph in Neo4j. Is there any possibility to use an OWL reasoner in Neo4j? Or any inference engine? Though it has been mentioned here i can't find any solution or API for this. Thankful for any advice! A: Maybe you want to see this: click here I quoted this from that link: Your main task if you want to use reasoners over a neo4j database is going to be to suck data out of neo4j, and format it as a set of RDF triples. You can then put those RDF triples into a Jena Model. When you have that jena model in memory, you can use existing jena APIs to use reasoners with that model A: My research in this area in progress, please watch here to see latest article draft, there is special section Inference on graph. I'm looking on neo4j -> Prolog -> neo4j approach: (a)-[b]->(c) graph can be expressed as b(a,c) predicate, so export your .db into .pl and query in SWI Prolog for example. But the most complex thing: how to do some (direct) reasoning for backward import into neo4j. I'm thinking about applying YieldProlog with direct traversal over neo4j db using BOLT prolotocol. I plan to add special mods for Yield method to specially process labels and attributes of graph elements, so my knowledge bases going to be described is neo4j databases by design. A: If you're looking for practical inference over graph data you should take a look at TypeDB, it has a reasoning engine built in. You can define your reasoning logic using rules in TypeQL. P.S. I work for Vaticle, the company who builds TypeDB ;)
stackoverflow
{ "language": "en", "length": 287, "provenance": "stackexchange_0000F.jsonl.gz:908568", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678792" }
34a34b9e97efc311e3d035bce2fd77405b71c6e0
Stackoverflow Stackexchange Q: Wildcard in JsonPath I am parsing a JSON like below: jobs1: [ { request: { body: { jobID: "79ceeeff-53b9-4645-80bd-95dfca6fe1e9", ... jobs2: [ { request: { body: { jobID: "60e7c286-f936-4f96-87bc-6bd55f107514", And looking for a way to use wildcards in the JSON path. I am using the RestAssured framework in Java. After executing the code like below: List<String> ids = get("/state/").path("*.request.body.jobID"); System.out.println(ids); I expect to get: [79ceeeff-53b9-4645-80bd-95dfca6fe1e9, 60e7c286-f936-4f96-87bc-6bd55f107514] But instead I get an exception: java.lang.IllegalArgumentException: Invalid JSON expression: Script1.groovy: 1: unexpected token: *. @ line 1, column 27. *.request.body.jobID ^ I have looked through these tutorials, but nothing seemed to work for me: https://github.com/json-path/JsonPath http://goessner.net/articles/JsonPath How do I correctly use the wildcards in JsonPath? A: GOTO http://jsonpath.herokuapp.com/ And give input like green box in the given image. Your pattern should be like below *.[*].request.body.jobID Your JSON should be like below { jobs1: [{ request: { body: { jobID: "79ceeeff-53b9-4645-80bd-95dfca6fe1e9" } } } ], jobs2: [{ request: { body: { jobID: "60e7c286-f936-4f96-87bc-6bd55f107514" } } } ] } Your will get result like below [ "79ceeeff-53b9-4645-80bd-95dfca6fe1e9", "60e7c286-f936-4f96-87bc-6bd55f107514" ]
Q: Wildcard in JsonPath I am parsing a JSON like below: jobs1: [ { request: { body: { jobID: "79ceeeff-53b9-4645-80bd-95dfca6fe1e9", ... jobs2: [ { request: { body: { jobID: "60e7c286-f936-4f96-87bc-6bd55f107514", And looking for a way to use wildcards in the JSON path. I am using the RestAssured framework in Java. After executing the code like below: List<String> ids = get("/state/").path("*.request.body.jobID"); System.out.println(ids); I expect to get: [79ceeeff-53b9-4645-80bd-95dfca6fe1e9, 60e7c286-f936-4f96-87bc-6bd55f107514] But instead I get an exception: java.lang.IllegalArgumentException: Invalid JSON expression: Script1.groovy: 1: unexpected token: *. @ line 1, column 27. *.request.body.jobID ^ I have looked through these tutorials, but nothing seemed to work for me: https://github.com/json-path/JsonPath http://goessner.net/articles/JsonPath How do I correctly use the wildcards in JsonPath? A: GOTO http://jsonpath.herokuapp.com/ And give input like green box in the given image. Your pattern should be like below *.[*].request.body.jobID Your JSON should be like below { jobs1: [{ request: { body: { jobID: "79ceeeff-53b9-4645-80bd-95dfca6fe1e9" } } } ], jobs2: [{ request: { body: { jobID: "60e7c286-f936-4f96-87bc-6bd55f107514" } } } ] } Your will get result like below [ "79ceeeff-53b9-4645-80bd-95dfca6fe1e9", "60e7c286-f936-4f96-87bc-6bd55f107514" ] A: *.[*].request.body.jobID this will extract the jobID's alone like below [ "79ceeeff-53b9-4645-80bd-95dfca6fe1e9", "60e7c286-f936-4f96-87bc-6bd55f107514" ] A: Do you really need wildcards here? This seems to be able to retrieve what you expect: ..request.body.jobID Or even simpler: ..jobID
stackoverflow
{ "language": "en", "length": 211, "provenance": "stackexchange_0000F.jsonl.gz:908570", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678797" }
cc4edafc998a98f7274353dc733f84be3ff9aec1
Stackoverflow Stackexchange Q: How to transpose dataframe columns into rows in pandas I have below dataframe and want to transpose the columns aftr 3rd column into rows. Please help on this. df: country year perc data1 data2 data3 IN 2015 hjk 75 81 96 US 2015 KTM 100 289 632 Results: country year perc TransposedColumn Value IN 2015 hjk data1 75 IN 2015 hjk data2 81 IN 2015 hjk data3 96 US 2015 KTM data1 100 US 2015 KTM data2 289 US 2015 KTM data3 632 A: use melt: df.melt(id_vars=['country','year','perc']) older versions of Pandas: pd.melt(df, id_vars=['country','year','perc']) Output: country year perc variable value 0 IN 2015 hjk data1 75 1 US 2015 KTM data1 100 2 IN 2015 hjk data2 81 3 US 2015 KTM data2 289 4 IN 2015 hjk data3 96 5 US 2015 KTM data3 632 Option #2 df.set_index(['country','year','perc']).stack().reset_index() Output: country year perc level_3 0 0 IN 2015 hjk data1 75 1 IN 2015 hjk data2 81 2 IN 2015 hjk data3 96 3 US 2015 KTM data1 100 4 US 2015 KTM data2 289 5 US 2015 KTM data3 632
Q: How to transpose dataframe columns into rows in pandas I have below dataframe and want to transpose the columns aftr 3rd column into rows. Please help on this. df: country year perc data1 data2 data3 IN 2015 hjk 75 81 96 US 2015 KTM 100 289 632 Results: country year perc TransposedColumn Value IN 2015 hjk data1 75 IN 2015 hjk data2 81 IN 2015 hjk data3 96 US 2015 KTM data1 100 US 2015 KTM data2 289 US 2015 KTM data3 632 A: use melt: df.melt(id_vars=['country','year','perc']) older versions of Pandas: pd.melt(df, id_vars=['country','year','perc']) Output: country year perc variable value 0 IN 2015 hjk data1 75 1 US 2015 KTM data1 100 2 IN 2015 hjk data2 81 3 US 2015 KTM data2 289 4 IN 2015 hjk data3 96 5 US 2015 KTM data3 632 Option #2 df.set_index(['country','year','perc']).stack().reset_index() Output: country year perc level_3 0 0 IN 2015 hjk data1 75 1 IN 2015 hjk data2 81 2 IN 2015 hjk data3 96 3 US 2015 KTM data1 100 4 US 2015 KTM data2 289 5 US 2015 KTM data3 632
stackoverflow
{ "language": "en", "length": 181, "provenance": "stackexchange_0000F.jsonl.gz:908580", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678829" }
63d178c501975cc50aa9b51c23ab54d21a509a07
Stackoverflow Stackexchange Q: How to handle media queries in HTML emails in Gmail? I send responsive HTML emails with my website, with media queries, but in Gmail / Inbox, max-width in the media query refers to the browser viewport, instead of the HTML email. So, on every other mail client, my emails switch to mobile display under 600px, in Gmail / Inbox, this comportement is broken. Do you have a solution to make the media query take as viewport the mail viewport instead of the browser viewport ? A: * *Recommended approach: <meta name=viewport content="width=device-width, initial-scale=1"> *Avoid minimum-scale, maximum-scale, user-scalable.
Q: How to handle media queries in HTML emails in Gmail? I send responsive HTML emails with my website, with media queries, but in Gmail / Inbox, max-width in the media query refers to the browser viewport, instead of the HTML email. So, on every other mail client, my emails switch to mobile display under 600px, in Gmail / Inbox, this comportement is broken. Do you have a solution to make the media query take as viewport the mail viewport instead of the browser viewport ? A: * *Recommended approach: <meta name=viewport content="width=device-width, initial-scale=1"> *Avoid minimum-scale, maximum-scale, user-scalable.
stackoverflow
{ "language": "en", "length": 98, "provenance": "stackexchange_0000F.jsonl.gz:908611", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678920" }
3cd521fa10d4caceb6d88417f17aa4612ac8d2cf
Stackoverflow Stackexchange Q: Permanent mount volume via sshfs Sierra I am trying to permanently mount a volume via sshfs on mac. I have tried to follow the instructions in how-to-get-automount-and-sshfs-osxfuse-working-with-yosemite (Although I have Sierra, I couldn't find instructions for it so I thought to give it a try with Yosemite instructions). However I get stuck at this step: If you do not see mount_sshfs, then you need to do this step. This is a critical step because it is easily forgotten and may create headaches. sudo ln -s $(which sshfs) /sbin/mount_sshfs. Here is the error: $ sudo ln -s $(which sshfs) /sbin/mount_sshfs ln: /sbin/mount_sshfs: Operation not permitted I couldn't find the way to solve this. A: Apple protects some critical folders by "System Integrity Protection (SIP)", you can temporarily disable it with the instructions given here https://apple.stackexchange.com/questions/208478/how-do-i-disable-system-integrity-protection-sip-aka-rootless-on-macos-os-x
Q: Permanent mount volume via sshfs Sierra I am trying to permanently mount a volume via sshfs on mac. I have tried to follow the instructions in how-to-get-automount-and-sshfs-osxfuse-working-with-yosemite (Although I have Sierra, I couldn't find instructions for it so I thought to give it a try with Yosemite instructions). However I get stuck at this step: If you do not see mount_sshfs, then you need to do this step. This is a critical step because it is easily forgotten and may create headaches. sudo ln -s $(which sshfs) /sbin/mount_sshfs. Here is the error: $ sudo ln -s $(which sshfs) /sbin/mount_sshfs ln: /sbin/mount_sshfs: Operation not permitted I couldn't find the way to solve this. A: Apple protects some critical folders by "System Integrity Protection (SIP)", you can temporarily disable it with the instructions given here https://apple.stackexchange.com/questions/208478/how-do-i-disable-system-integrity-protection-sip-aka-rootless-on-macos-os-x
stackoverflow
{ "language": "en", "length": 135, "provenance": "stackexchange_0000F.jsonl.gz:908626", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678957" }
d1da7fbb0352fa6fb116fba509921c393f8c37c1
Stackoverflow Stackexchange Q: From SKLearn to Keras - What is the difference? I'm trying to go from SKLearn to Keras in order to make specific improvements to my models. However, I can't get the same performance I had with my SKLearn model : mlp = MLPClassifier( solver='adam', activation='relu', beta_1=0.9, beta_2=0.999, learning_rate='constant', alpha=0, hidden_layer_sizes=(238,), max_iter=300 ) dev_score(mlp) Gives ~0.65 score everytime Here is my corresponding Keras code : def build_model(alpha): level_moreargs = {'kernel_regularizer':l2(alpha), 'kernel_initializer': 'glorot_uniform'} model = Sequential() model.add(Dense(units=238, input_dim=X.shape[1], **level_moreargs)) model.add(Activation('relu')) model.add(Dense(units=class_names.shape[0], **level_moreargs)) # output model.add(Activation('softmax')) model.compile(loss=keras.losses.categorical_crossentropy, # like sklearn optimizer=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0), metrics=['accuracy']) return model k_dnn = KerasClassifier(build_fn=build_model, epochs=300, batch_size=200, validation_data=None, shuffle=True, alpha=0.5, verbose=0) dev_score(k_dnn) From looking at the documentation (and digging into SKLearn code), this should correspond exactly to the same thing. However, I get ~0.5 accuracy when I run this model, which is very bad. And if I set alpha to 0, SKLearn's score barely changes (0.63), while Keras's goes random from 0.2 to 0.4. What is the difference between these models ? Why is Keras, although being supposed to be better than SKLearn, outperformed by so far here ? What's my mistake ? Thanks,
Q: From SKLearn to Keras - What is the difference? I'm trying to go from SKLearn to Keras in order to make specific improvements to my models. However, I can't get the same performance I had with my SKLearn model : mlp = MLPClassifier( solver='adam', activation='relu', beta_1=0.9, beta_2=0.999, learning_rate='constant', alpha=0, hidden_layer_sizes=(238,), max_iter=300 ) dev_score(mlp) Gives ~0.65 score everytime Here is my corresponding Keras code : def build_model(alpha): level_moreargs = {'kernel_regularizer':l2(alpha), 'kernel_initializer': 'glorot_uniform'} model = Sequential() model.add(Dense(units=238, input_dim=X.shape[1], **level_moreargs)) model.add(Activation('relu')) model.add(Dense(units=class_names.shape[0], **level_moreargs)) # output model.add(Activation('softmax')) model.compile(loss=keras.losses.categorical_crossentropy, # like sklearn optimizer=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0), metrics=['accuracy']) return model k_dnn = KerasClassifier(build_fn=build_model, epochs=300, batch_size=200, validation_data=None, shuffle=True, alpha=0.5, verbose=0) dev_score(k_dnn) From looking at the documentation (and digging into SKLearn code), this should correspond exactly to the same thing. However, I get ~0.5 accuracy when I run this model, which is very bad. And if I set alpha to 0, SKLearn's score barely changes (0.63), while Keras's goes random from 0.2 to 0.4. What is the difference between these models ? Why is Keras, although being supposed to be better than SKLearn, outperformed by so far here ? What's my mistake ? Thanks,
stackoverflow
{ "language": "en", "length": 188, "provenance": "stackexchange_0000F.jsonl.gz:908630", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678966" }
b63ede6be2adbf69832f3b1cbe185cf970badce1
Stackoverflow Stackexchange Q: Add active class to child element I am beginner with Vue.js (and bootstrap-vue) and I want to create tabs (like here) <b-nav class="nav-tabs"> <b-nav-item v-bind:active=true v-bind:class="{ active : tab === 1 }" v-on:click="tab = 1">Link 1</b-nav-item> <b-nav-item v-bind:class="{ active : tab === 2}" v-on:click="tab = 2">Link 2</b-nav-item> <b-nav-item v-bind:class="{ active : tab === 3}" v-on:click="tab = 3">Link 3</b-nav-item> </b-nav> But when I click on second link it doesn't change active=true (and active=false on first button). I tried v-on:click:active=true but it doesn't work. It works fine with tabs, but not with navs (e.g. https://bootstrap-vue.github.io/docs/components/tabs). Any idea? Added: Vue code: import Vue from 'vue'; import BootstrapVue from 'bootstrap-vue' Vue.use(BootstrapVue); new Vue({ el: '#app', data: { tab: 1 }, }); A: Not familiar with bootstrap-vue, but I just did a bit of toying in their playground, and what you need to bind is the active property, bootstrap takes cares of the styles from that. In other words, this seems to work: <b-nav class="nav-tabs"> <b-nav-item :active="tab === 1" @click="tab = 1">Link 1</b-nav-item> <b-nav-item :active="tab === 2" @click="tab = 2">Link 2</b-nav-item> <b-nav-item :active="tab === 3" @click="tab = 3">Link 3</b-nav-item> </b-nav>
Q: Add active class to child element I am beginner with Vue.js (and bootstrap-vue) and I want to create tabs (like here) <b-nav class="nav-tabs"> <b-nav-item v-bind:active=true v-bind:class="{ active : tab === 1 }" v-on:click="tab = 1">Link 1</b-nav-item> <b-nav-item v-bind:class="{ active : tab === 2}" v-on:click="tab = 2">Link 2</b-nav-item> <b-nav-item v-bind:class="{ active : tab === 3}" v-on:click="tab = 3">Link 3</b-nav-item> </b-nav> But when I click on second link it doesn't change active=true (and active=false on first button). I tried v-on:click:active=true but it doesn't work. It works fine with tabs, but not with navs (e.g. https://bootstrap-vue.github.io/docs/components/tabs). Any idea? Added: Vue code: import Vue from 'vue'; import BootstrapVue from 'bootstrap-vue' Vue.use(BootstrapVue); new Vue({ el: '#app', data: { tab: 1 }, }); A: Not familiar with bootstrap-vue, but I just did a bit of toying in their playground, and what you need to bind is the active property, bootstrap takes cares of the styles from that. In other words, this seems to work: <b-nav class="nav-tabs"> <b-nav-item :active="tab === 1" @click="tab = 1">Link 1</b-nav-item> <b-nav-item :active="tab === 2" @click="tab = 2">Link 2</b-nav-item> <b-nav-item :active="tab === 3" @click="tab = 3">Link 3</b-nav-item> </b-nav> A: First of all you might need to add quotation marks in v-bind:active="true"but here is the general fiddle. I am not using bootstrap-vue component, but it shouldn't be that difficult A: you can proceed like this <b-nav class="nav-tabs"> <b-nav-item exact-active-class="active" to="/link-1">Link 1</b-nav-item> <b-nav-item exact-active-class="active" to="/link-2">Link 2</b-nav-item> <b-nav-item exact-active-class="active" to="/link-3">Link 3</b-nav-item> </b-nav> property exact-active-class: <router-link> prop: Configure the active CSS class applied when the link is active with exact match. Typically you will want to set this to class name 'active'
stackoverflow
{ "language": "en", "length": 266, "provenance": "stackexchange_0000F.jsonl.gz:908636", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44678993" }
f431e1148fa881dbba322497a7651c81664498d0
Stackoverflow Stackexchange Q: React-Native: How to increase space between text and underline I have followed styles: const styles = StyleSheet.create({ title: { textDecorationLine: 'underline', textDecorationStyle: 'solid', textDecorationColor: '#000' } }); and it creates the underline for my content into some Text component. But it seems that this underline is too close to the text decorated with it. Can I increase this distance in some how? Thank you for helping! A: * *Wrap your Text in a View that has a style containing borderBottomWidth: 1 or whatever you want the thickness to be. *Give your Text a lineHeight to adjust the spacing between the border and the content. If you have multiple lines of text, then using paddingBottom would also work. Simple as that really. Bear in mind the View border will stretch to include any padding on the View itself.
Q: React-Native: How to increase space between text and underline I have followed styles: const styles = StyleSheet.create({ title: { textDecorationLine: 'underline', textDecorationStyle: 'solid', textDecorationColor: '#000' } }); and it creates the underline for my content into some Text component. But it seems that this underline is too close to the text decorated with it. Can I increase this distance in some how? Thank you for helping! A: * *Wrap your Text in a View that has a style containing borderBottomWidth: 1 or whatever you want the thickness to be. *Give your Text a lineHeight to adjust the spacing between the border and the content. If you have multiple lines of text, then using paddingBottom would also work. Simple as that really. Bear in mind the View border will stretch to include any padding on the View itself. A: As of now that is not possible in React Native, cause it is also not supported in web apps i.e Css. Link here But there is a work around to this. Create react View wrapper over the Text you want to adjust the underline. And then add borderBottomWidth to View and adjust the distance of underline from Text paddingBottom. const styles = StyleSheet.create({ viewStyle : { borderBottomWidth: 10, // whatever width you want of underline } title: { paddingBottom: 4, // Adjust the distance from your text view. } }); Add the viewStyle to your parentView. Hope that helps! A: According to me, the best possible way to do this is to add a <View /> (without content) after the <Text> and give top-border as you want your underline to be. For example: <Text style={{ color: 'blue' }}>Categories</Text> <View style={{ height: 0, // height is '0' so that the view will not occupy space width: 100, // as much as you want to 'Stretch' the underline borderTopColor: 'blue', borderTopWidth: 2, // 'Thickness' of the underline marginTop: 15 . // 'Gap' between the content & the underline }} /> REMEMBER: This will work if the parent of your Text has flexDirection: 'column' (which is default value). But if it has flexDirection: 'row', wrap both the Text & View (i.e. underline) in another view like <View>...</View> so the items will be arranged in a column. A: How to give space between text and decoration line in react-native. Refer the attached image 1 with bottom border width and 2 is decoration line
stackoverflow
{ "language": "en", "length": 398, "provenance": "stackexchange_0000F.jsonl.gz:908693", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679155" }
5beeb797cd6da8634147407889e2d8931bacd5cc
Stackoverflow Stackexchange Q: RandomForest IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices I am working with sklearn on RandomForestClassifier: class RandomForest(RandomForestClassifier): def fit(self, x, y): self.unique_train_y, y_classes = transform_y_vectors_in_classes(y) return RandomForestClassifier.fit(self, x, y_classes) def predict(self, x): y_classes = RandomForestClassifier.predict(self, x) predictions = transform_classes_in_y_vectors(y_classes, self.unique_train_y) return predictions def transform_classes_in_y_vectors(y_classes, unique_train_y): cyr = [unique_train_y[predicted_index] for predicted_index in y_classes] predictions = np.array(float(cyr)) return predictions I got this Error message: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices A: It seems that y_classes holds values that are not valid indices. When you try to get access into unique_train_y with predicted_index than you get the exception as predicted_index is not what you think it is. Try to execute the following code: cyr = [unique_train_y[predicted_index] for predicted_index in range(len(y_classes))] # assuming unique_train_y is a list and predicted_index should be integer.
Q: RandomForest IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices I am working with sklearn on RandomForestClassifier: class RandomForest(RandomForestClassifier): def fit(self, x, y): self.unique_train_y, y_classes = transform_y_vectors_in_classes(y) return RandomForestClassifier.fit(self, x, y_classes) def predict(self, x): y_classes = RandomForestClassifier.predict(self, x) predictions = transform_classes_in_y_vectors(y_classes, self.unique_train_y) return predictions def transform_classes_in_y_vectors(y_classes, unique_train_y): cyr = [unique_train_y[predicted_index] for predicted_index in y_classes] predictions = np.array(float(cyr)) return predictions I got this Error message: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices A: It seems that y_classes holds values that are not valid indices. When you try to get access into unique_train_y with predicted_index than you get the exception as predicted_index is not what you think it is. Try to execute the following code: cyr = [unique_train_y[predicted_index] for predicted_index in range(len(y_classes))] # assuming unique_train_y is a list and predicted_index should be integer.
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:908695", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679165" }
4768a30c263062ddf226f85c6cbdcbe809ba7e95
Stackoverflow Stackexchange Q: Change behaviour of help text in django form globally I want to take advantage of the default help text in django, but I don't like the way it's handled. I want to have: <tr><label>djangolab</label><input>djangoinput</input><span>djangohelp></span><span class='onhovershowhelp'>?</span> The last element is not provided by default. CSS on hover on '?' will change visibility for the help text span from hidden to visible. I want things to work out of the box so '{{form}}' will display as I want for any model form. So I want globally: * *Help text span by default with some attributes(z=1, hidden) *Add another span to form row. I don't want to do this for every model form/field etc, use loops in the template and manually build this etc... A: Got it. Have all forms inherit something like this (that _html_output call is the hidden implementation detail taken directly from django's source code): import django.forms class GenericForm(django.forms.ModelForm): def as_table(self): return self._html_output( normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', error_row='<tr><td colspan="2">%s</td></tr>', row_ender='</td></tr>', help_text_html='<a class="helptext">?<span>%s</span></a>', errors_on_separate_row=False) return html And some CSS to accompany this: .helptext { margin: 5px; color: blue; } a.helptext span { display:none; width: 30em; text-align: justify; z-index:1; } a.helptext:hover span { display:inline; position:absolute; background:#ffffff; border:1px solid #cccccc; color:#6c6c6c; }
Q: Change behaviour of help text in django form globally I want to take advantage of the default help text in django, but I don't like the way it's handled. I want to have: <tr><label>djangolab</label><input>djangoinput</input><span>djangohelp></span><span class='onhovershowhelp'>?</span> The last element is not provided by default. CSS on hover on '?' will change visibility for the help text span from hidden to visible. I want things to work out of the box so '{{form}}' will display as I want for any model form. So I want globally: * *Help text span by default with some attributes(z=1, hidden) *Add another span to form row. I don't want to do this for every model form/field etc, use loops in the template and manually build this etc... A: Got it. Have all forms inherit something like this (that _html_output call is the hidden implementation detail taken directly from django's source code): import django.forms class GenericForm(django.forms.ModelForm): def as_table(self): return self._html_output( normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', error_row='<tr><td colspan="2">%s</td></tr>', row_ender='</td></tr>', help_text_html='<a class="helptext">?<span>%s</span></a>', errors_on_separate_row=False) return html And some CSS to accompany this: .helptext { margin: 5px; color: blue; } a.helptext span { display:none; width: 30em; text-align: justify; z-index:1; } a.helptext:hover span { display:inline; position:absolute; background:#ffffff; border:1px solid #cccccc; color:#6c6c6c; }
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:908713", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679205" }
91edb799e17ba73fadf2db70e4fd35f4cc8074af
Stackoverflow Stackexchange Q: QwtPlot - Multiple Y Axis I use QwtPlot 6.1.3. Is there any way to display multiple curves, sharing a single X axis, but each one with its own Y axis ? I didn't find anything in the documentation, and my Google searchs didn't return anything usefull (just some hacks) Something similar to this : Thanks A: Qwt doesn't supports multiple axis attached to the same Canvas, it has however a fork that supports: https://sourceforge.net/p/qwt/code/HEAD/tree/branches/qwt-6.1-multiaxes/
Q: QwtPlot - Multiple Y Axis I use QwtPlot 6.1.3. Is there any way to display multiple curves, sharing a single X axis, but each one with its own Y axis ? I didn't find anything in the documentation, and my Google searchs didn't return anything usefull (just some hacks) Something similar to this : Thanks A: Qwt doesn't supports multiple axis attached to the same Canvas, it has however a fork that supports: https://sourceforge.net/p/qwt/code/HEAD/tree/branches/qwt-6.1-multiaxes/
stackoverflow
{ "language": "en", "length": 75, "provenance": "stackexchange_0000F.jsonl.gz:908734", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679281" }
b22300c54fcfb11ae3971ea3d241faa7b7799772
Stackoverflow Stackexchange Q: Docker how to use boolean value on spec.container.env.value Is there a way to pass a boolean value for spec.container.env.value ? I want to override, with helm, a boolean env variables in a docker parent image (https://github.com/APSL/docker-thumbor) : UPLOAD_ENABLED I made a simpler test If you try the following yaml : apiVersion: v1 kind: Pod metadata: name: envar-demo labels: purpose: demonstrate-envars spec: containers: - name: envar-demo-container image: gcr.io/google-samples/node-hello:1.0 env: - name: DEMO_GREETING value: true And try to create it with kubernetes, you got the following error : kubectl create -f envars.yaml the error : error: error validating "envars.yaml": error validating data: expected type string, for field spec.containers[0].env[0].value, got bool; if you choose to ignore these errors, turn validation off with --validate=false with validate=false Error from server (BadRequest): error when creating "envars.yaml": Pod in version "v1" cannot be handled as a Pod: [pos 192]: json: expect char '"' but got char 't' It doesn't work with integer values too A: Try escaping the value. The below worked for me: - name: DEMO_GREETING value: "'true'"
Q: Docker how to use boolean value on spec.container.env.value Is there a way to pass a boolean value for spec.container.env.value ? I want to override, with helm, a boolean env variables in a docker parent image (https://github.com/APSL/docker-thumbor) : UPLOAD_ENABLED I made a simpler test If you try the following yaml : apiVersion: v1 kind: Pod metadata: name: envar-demo labels: purpose: demonstrate-envars spec: containers: - name: envar-demo-container image: gcr.io/google-samples/node-hello:1.0 env: - name: DEMO_GREETING value: true And try to create it with kubernetes, you got the following error : kubectl create -f envars.yaml the error : error: error validating "envars.yaml": error validating data: expected type string, for field spec.containers[0].env[0].value, got bool; if you choose to ignore these errors, turn validation off with --validate=false with validate=false Error from server (BadRequest): error when creating "envars.yaml": Pod in version "v1" cannot be handled as a Pod: [pos 192]: json: expect char '"' but got char 't' It doesn't work with integer values too A: Try escaping the value. The below worked for me: - name: DEMO_GREETING value: "'true'" A: This works for me. In my example, one is hardcoded, and the other comes from an env var. env: - name: MY_BOOLEAN value: 'true' - name: MY_BOOLEAN2 value: '${MY_BOOLEAN2_ENV_VAR}' So basically, I wrap single quotes around everything, just in case. WARNING: Dont use hyphens in your env var names, that will not work... A: if you are the helm chart implementer, just quote it data: # VNC_ONLY: {{ .Values.vncOnly }} <-- Wrong VNC_ONLY: "{{ .Values.vncOnly }}" # <-- Correct A: spec.container.env.value is defined as string. see here: https://kubernetes.io/docs/api-reference/v1.6/#envvar-v1-core You'd have to cast/convert/coerse to boolean in your container when using this value A: From command line you can also use --set-string instead of --set and you will be able to pass value without escaping for instance: --set-string "env.my-setting=False"
stackoverflow
{ "language": "en", "length": 301, "provenance": "stackexchange_0000F.jsonl.gz:908751", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679343" }
a73ae41058a638c0eddbeea2891ac256325b24a3
Stackoverflow Stackexchange Q: O notation of a Loop for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { O(1); } } here the func is n * (n+1) / 2 but what if the outerloop condition is i < log(n)? I have problems with loops that relates on each other. A: You just have to count the total number of iterations: 1 + 2 + 3 + .. + n - 1 = n * (n - 1) / 2 as you correctly inferred. When you replace n with log(n), just do the same in the final formula, which then becomes log(n) * (log(n)+1) / 2, or in Big-O notation, O((log(n))^2).
Q: O notation of a Loop for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { O(1); } } here the func is n * (n+1) / 2 but what if the outerloop condition is i < log(n)? I have problems with loops that relates on each other. A: You just have to count the total number of iterations: 1 + 2 + 3 + .. + n - 1 = n * (n - 1) / 2 as you correctly inferred. When you replace n with log(n), just do the same in the final formula, which then becomes log(n) * (log(n)+1) / 2, or in Big-O notation, O((log(n))^2). A: If the condition of the outer loop is changed to i < log(n) then the overall complexity of the nested two-loop construct changes from O(n2) to O(log(n)2) You can show this with a simple substitution k = log(n), because the complexity of the loop in terms of k is O(k2). Reversing the substitution yields O(log(n)2). A: For nested for loops (when using the O notation, ofc) you can multiply the worst-case scenario of all of them. If the first loop goes to x and you have a nested loop going to i (i being at worst-case x) then you have a run-time complexity of O(x^2)
stackoverflow
{ "language": "en", "length": 223, "provenance": "stackexchange_0000F.jsonl.gz:908771", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679398" }
d37e0aa01ad1c1185bebd7abd7840e5cf85e641d
Stackoverflow Stackexchange Q: ModuleNotFoundError: No module named 'tensorflow.tensorboard.tensorboard' There seems to be a problem with recent TensorFlow build. The TensorBoard visualization tool would not run when it is compiled from sources to use with GPU. The error is as follows: $ tensorboard Traceback (most recent call last): File "/home/gpu/anaconda3/envs/tensorflow/bin/tensorboard", line 7, in <module> from tensorflow.tensorboard.tensorboard import main ModuleNotFoundError: No module named 'tensorflow.tensorboard.tensorboard' Specs of system: Ubuntu 16.04, NVIDIA GTX 1070, cuda-8.0, cudnn 6.0. Installed using Bazel from sources as described here: https://www.tensorflow.org/install/install_sources Installed into fresh anaconda3 environment 'tensorflow', environment is activated when performing command. Would appreciate any help! A: After some trial and error, I have solved this issue by adapting the file tensorboard-script.py in path/to/conda/envs/myenv/Scripts (Windows) as follows: if __name__ == '__main__': import sys #import tensorflow.tensorboard.tensorboard import tensorboard.main #sys.exit(tensorflow.tensorboard.tensorboard.main()) sys.exit(tensorboard.main.main()) Now I can invoke tensorboard as expected: tensorboard --logdir=log/ --port 6006
Q: ModuleNotFoundError: No module named 'tensorflow.tensorboard.tensorboard' There seems to be a problem with recent TensorFlow build. The TensorBoard visualization tool would not run when it is compiled from sources to use with GPU. The error is as follows: $ tensorboard Traceback (most recent call last): File "/home/gpu/anaconda3/envs/tensorflow/bin/tensorboard", line 7, in <module> from tensorflow.tensorboard.tensorboard import main ModuleNotFoundError: No module named 'tensorflow.tensorboard.tensorboard' Specs of system: Ubuntu 16.04, NVIDIA GTX 1070, cuda-8.0, cudnn 6.0. Installed using Bazel from sources as described here: https://www.tensorflow.org/install/install_sources Installed into fresh anaconda3 environment 'tensorflow', environment is activated when performing command. Would appreciate any help! A: After some trial and error, I have solved this issue by adapting the file tensorboard-script.py in path/to/conda/envs/myenv/Scripts (Windows) as follows: if __name__ == '__main__': import sys #import tensorflow.tensorboard.tensorboard import tensorboard.main #sys.exit(tensorflow.tensorboard.tensorboard.main()) sys.exit(tensorboard.main.main()) Now I can invoke tensorboard as expected: tensorboard --logdir=log/ --port 6006 A: An easy fix: python -m tensorboard.main --logdir=/path/to/logs A: Okay, I've found a solution that works and also received some explanation from tensorflower on github. There might be an issue with tensorboard when compiling tensorflow from sources because tensorboard is now removed to a separate repo and is not a part of tensorflow. The tensorflower said the docs will be updated eventually, but I figured a workaround for the impatient (like myself). Edit tensorboard file inside tensorflow/bin (/home/gpu/anaconda3/envs/tensorflow/bin/tensorboard in my case) and replace from tensorflow.tensorboard.tensorboard import main by from tensorflow.tensorboard.main import * Now tensorboard should run from console as usual. A: Tensorboard ships with tensorflow. If you are unable to run using tensorboard command, try below approach. tensorboard.py might have been moved to different directory. Try searching for tensorboard.py in the tensorbard directory where tensorflow is installed. Go to the path and use following line for visualization: python tensorboard.py --logdir=path A: You should priorly launch pip install tensorflow.tensorboard
stackoverflow
{ "language": "en", "length": 298, "provenance": "stackexchange_0000F.jsonl.gz:908782", "question_score": "16", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679439" }
51ff387edb6d7712b711681dc5d01f83cf41c524
Stackoverflow Stackexchange Q: office-js window focus Writing an Add-in for Excel 2016 desktop application using the javascript API, I ran into the following problem: After opening and the dismissing a dialog window using Office.context.ui.displayDialogAsync and subsequently dialog.close() The Taskpane takes focus from the main excel window meaning that I cannot move the cursor to a new cell using the arrow keys before using the mouse to give the main window focus again. After having spent ages trying to solve this one, I got hold of a Microsoft rep. who told me that it cannot be done.
Q: office-js window focus Writing an Add-in for Excel 2016 desktop application using the javascript API, I ran into the following problem: After opening and the dismissing a dialog window using Office.context.ui.displayDialogAsync and subsequently dialog.close() The Taskpane takes focus from the main excel window meaning that I cannot move the cursor to a new cell using the arrow keys before using the mouse to give the main window focus again. After having spent ages trying to solve this one, I got hold of a Microsoft rep. who told me that it cannot be done.
stackoverflow
{ "language": "en", "length": 94, "provenance": "stackexchange_0000F.jsonl.gz:908787", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679445" }
0dd0ce52380c6a9df6a0daf6ee939566a937a85f
Stackoverflow Stackexchange Q: How do I access an attribute from a counted resource within another resource? I'm using Terraform to script an AWS build. I'm spinning up a number of instances across multiple availability zones, in this example, 2: resource "aws_instance" "myinstance" { count = 2 ami = "${var.myamiid}" instance_type = "${var.instancetype}" availability_zone = "${data.aws_availability_zones.all.names[count.index]}" # other details omitted for brevity } I now need to assign an Elastic IP to these instances, so that I can rebuild the instances in the future without their IP address changing. The below shows what I'd like to do: resource "aws_eip" "elastic_ips" { count = 2 instance = "${aws_instance.myinstance[count.index].id}" vpc = true } But this errors with: expected "}" but found "." I've also tried using lookup: instance = "${lookup(aws_instance.sbc, count.index).id}" but that fails with the same error. How can I go about attaching Elastic IPs to these instances? A: A bit more playing around and I've found the answer - you can index into the "splat" syntax: instance = "${aws_instance.myinstance.*.id[count.index]}"
Q: How do I access an attribute from a counted resource within another resource? I'm using Terraform to script an AWS build. I'm spinning up a number of instances across multiple availability zones, in this example, 2: resource "aws_instance" "myinstance" { count = 2 ami = "${var.myamiid}" instance_type = "${var.instancetype}" availability_zone = "${data.aws_availability_zones.all.names[count.index]}" # other details omitted for brevity } I now need to assign an Elastic IP to these instances, so that I can rebuild the instances in the future without their IP address changing. The below shows what I'd like to do: resource "aws_eip" "elastic_ips" { count = 2 instance = "${aws_instance.myinstance[count.index].id}" vpc = true } But this errors with: expected "}" but found "." I've also tried using lookup: instance = "${lookup(aws_instance.sbc, count.index).id}" but that fails with the same error. How can I go about attaching Elastic IPs to these instances? A: A bit more playing around and I've found the answer - you can index into the "splat" syntax: instance = "${aws_instance.myinstance.*.id[count.index]}" A: This works for me, instance = aws_instance.myinstance.*.id A: Please go through terraform interpolation - element list index element(list, index) - Returns a single element from a list at the given index. If the index is greater than the number of elements, this function will wrap using a standard mod algorithm. This function only works on flat lists. Examples: element(aws_subnet.foo.*.id, count.index) So in your case, the code will be: instance = "${element(aws_instance.myinstance.*.id, count.index}" A: Other answers already pointed out that counted elements must be accessed via indexes. I like to add that I encountered the error Because aws_instance.some-resource has "count" set, its attributes must be accessed on specific instances. although I had already fixed that particular line. The error kept showing up, mentioning a line with some code segment that was not even present any longer in my code. I was able to resolve this by fixing all places where I had not accessed a specific instance (which were also mentioned in other errors). In my case, an output section was not adapted previously. Only then all errors disappeared all of a sudden. A: try using aws_instance.jserver[count.index].id e.g. of ec2 instance and volume attachment is resource "aws_instance" "jserver"{ count=3 } resource "aws_volume_attachment" "j_ebs_att" { count = 3 ... instance_id = aws_instance.jserver[count.index].id } A: I know you are using older version of terraform but I still want to add just in case someone is struggling with the same issue with terraform 0.12. For terraform version 11 the syntax is totally different from version v12. As you can see it's only the interpolation that should be removed. From your syntax and the various response provided. version 11: instance = "${aws_instance.myinstance.*.id[count.index]}" version 12 instance = aws_instance.myinstance.*.id[count.index]
stackoverflow
{ "language": "en", "length": 449, "provenance": "stackexchange_0000F.jsonl.gz:908792", "question_score": "14", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679456" }
91cce857acff5104d27a59c3334ab9f8fc0f2091
Stackoverflow Stackexchange Q: On click stopPropagation while keeping bootstrap collapse behavior I have a bootstrap list-group-item with a badge as follows: <a class="list-group-item list-group-item-action" href="#" revision="211147" id="commit0"> <span class="badge collapsed" id="badge0" data-toggle="collapse" data-target="#ul0" > changed files:1 </span> <ul class="list-group changed-files-list collapse" id="ul0" aria-expanded="false" style="height: 0px;"> <li class="list-group-item changed-file"> release.groovy </li> </ul> </a> It contains a collapsed ul that is targeted by the badge. At the same time, when clicked, the a element is selected(as it is part of a list-group with multiple selection possible). I try to insert this bit of code: $('.badge').on('click', function(e){ //$('#'+this.id).click(); e.stopPropagation(); }); so that when clicking on the badge the a element is not selected. If I use this code the ul element is not being shown. I guess bootstrap uses the on click function and so it has something to do with my function overriding the bootstrap one. How can I stop propagation while keeping the collapse behavior? A: I found the solution by using bootstrap's collapse function: $('.badge').click( function(e){ $('#ul'+this.id.substring(5)).collapse("toggle"); e.stopPropagation(); });
Q: On click stopPropagation while keeping bootstrap collapse behavior I have a bootstrap list-group-item with a badge as follows: <a class="list-group-item list-group-item-action" href="#" revision="211147" id="commit0"> <span class="badge collapsed" id="badge0" data-toggle="collapse" data-target="#ul0" > changed files:1 </span> <ul class="list-group changed-files-list collapse" id="ul0" aria-expanded="false" style="height: 0px;"> <li class="list-group-item changed-file"> release.groovy </li> </ul> </a> It contains a collapsed ul that is targeted by the badge. At the same time, when clicked, the a element is selected(as it is part of a list-group with multiple selection possible). I try to insert this bit of code: $('.badge').on('click', function(e){ //$('#'+this.id).click(); e.stopPropagation(); }); so that when clicking on the badge the a element is not selected. If I use this code the ul element is not being shown. I guess bootstrap uses the on click function and so it has something to do with my function overriding the bootstrap one. How can I stop propagation while keeping the collapse behavior? A: I found the solution by using bootstrap's collapse function: $('.badge').click( function(e){ $('#ul'+this.id.substring(5)).collapse("toggle"); e.stopPropagation(); });
stackoverflow
{ "language": "en", "length": 167, "provenance": "stackexchange_0000F.jsonl.gz:908899", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679778" }
8da313ec6e36a2b8841edc143ed326b397ead191
Stackoverflow Stackexchange Q: How to execute a MySQL function in a Knex query? I have a BINARY field in my table which I usually grab like this: SELECT HEX(users.id) AS id FROM users WHERE username = ? I recently started using Knex because I need to be able to dynamically generate WHERE clauses from objects. Here's what I tried: knex('users').select('HEX(users.id) AS id)').where(filter); Here's the query it generates: select `HEX(users`.`id)` as `id` .... And then I tried this: knex('users').select('HEX(`users`.`id`) AS id').where(filter); And it comes up with this: select `HEX(``users```.```id``)` as `id` .... How do I execute HEX() without it being mistaken for a column name? A: With knex letting to do quoting of identifiers it would look like this: knex('users').select(knex.raw('HEX(??) AS id', ['users.id'])).where(filter);
Q: How to execute a MySQL function in a Knex query? I have a BINARY field in my table which I usually grab like this: SELECT HEX(users.id) AS id FROM users WHERE username = ? I recently started using Knex because I need to be able to dynamically generate WHERE clauses from objects. Here's what I tried: knex('users').select('HEX(users.id) AS id)').where(filter); Here's the query it generates: select `HEX(users`.`id)` as `id` .... And then I tried this: knex('users').select('HEX(`users`.`id`) AS id').where(filter); And it comes up with this: select `HEX(``users```.```id``)` as `id` .... How do I execute HEX() without it being mistaken for a column name? A: With knex letting to do quoting of identifiers it would look like this: knex('users').select(knex.raw('HEX(??) AS id', ['users.id'])).where(filter); A: I've found a solution. I have to use raw() function. So my query builder will look like this: knex('users').select(knex.raw('HEX(`users`.`id`) AS id')).where(filter);
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:908921", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679846" }
8038f591df4eaf4deb07b4f134720f97917a0c0d
Stackoverflow Stackexchange Q: Rotated elements overlap each other Is there a way to fix this, when I rotate 2 elements, they overlap each other because the width and height don't swap. Thank you https://jsfiddle.net/aez4uc3u/ a { display: block; transform: rotate(-90deg); } <div> <a href="#">This is the first link</a> <a href="#">This is the second link</a> </div> A: Rotate the parent. a { display: block } div { transform: rotate(-90deg); } <div> <a href="#">This is the first link</a> <a href="#">This is the second link</a> </div> Positioning the div as you might like will take additional transforms and, perhaps, adjusting the transform-origin property. You shoud also be aware that transform is purely visual. It does not actually affect the positioning or margins of elements.
Q: Rotated elements overlap each other Is there a way to fix this, when I rotate 2 elements, they overlap each other because the width and height don't swap. Thank you https://jsfiddle.net/aez4uc3u/ a { display: block; transform: rotate(-90deg); } <div> <a href="#">This is the first link</a> <a href="#">This is the second link</a> </div> A: Rotate the parent. a { display: block } div { transform: rotate(-90deg); } <div> <a href="#">This is the first link</a> <a href="#">This is the second link</a> </div> Positioning the div as you might like will take additional transforms and, perhaps, adjusting the transform-origin property. You shoud also be aware that transform is purely visual. It does not actually affect the positioning or margins of elements. A: Rotate the container and display the childs as inline-block seems to do the trick. .container { transform: rotate(-90deg); } .container a { display:inline-block; margin: 0 5px; } <div class="container"> <a href="#">This is the first link</a> <a href="#">This is the second link</a> </div>
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:908931", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679871" }
52c2dfac12a84e10cf6ab768b8f65f74e4dfb53b
Stackoverflow Stackexchange Q: Different random number generation between OS in R I'm getting slightly different random numbers depending on the OS (Mac vs Linux): set.seed(890458, kind="Mersenne-Twister", normal.kind="Inversion") print(rlnorm(1504)[1504], digits=22) sessionInfo() Linux: > set.seed(890458, kind="Mersenne-Twister", normal.kind="Inversion") > print(rlnorm(1504)[1504], digits=22) [1] 2.732876214731374542311 > sessionInfo() R version 3.4.0 (2017-04-21) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Debian GNU/Linux 9 (stretch) Matrix products: default BLAS: /usr/lib/libblas/libblas.so.3.7.0 LAPACK: /usr/lib/lapack/liblapack.so.3.7.0 locale: [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 [7] LC_PAPER=en_US.UTF-8 LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] compiler_3.4.0 tools_3.4.0 digest_0.6.12 Mac: > set.seed(890458, kind="Mersenne-Twister", normal.kind="Inversion") > print(rlnorm(1504)[1504], digits=22) [1] 2.732876214731374098221 > sessionInfo() R version 3.4.0 (2017-04-21) Platform: x86_64-apple-darwin15.6.0 (64-bit) Running under: macOS Sierra 10.12.5 Matrix products: default BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib locale: [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] compiler_3.4.0 digest_0.6.12 Is this expected? Is there anyway to guarantee reproducibility across platforms? It also happens with rnorm rather than rlnorm but with higher numbers.
Q: Different random number generation between OS in R I'm getting slightly different random numbers depending on the OS (Mac vs Linux): set.seed(890458, kind="Mersenne-Twister", normal.kind="Inversion") print(rlnorm(1504)[1504], digits=22) sessionInfo() Linux: > set.seed(890458, kind="Mersenne-Twister", normal.kind="Inversion") > print(rlnorm(1504)[1504], digits=22) [1] 2.732876214731374542311 > sessionInfo() R version 3.4.0 (2017-04-21) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Debian GNU/Linux 9 (stretch) Matrix products: default BLAS: /usr/lib/libblas/libblas.so.3.7.0 LAPACK: /usr/lib/lapack/liblapack.so.3.7.0 locale: [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 [7] LC_PAPER=en_US.UTF-8 LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] compiler_3.4.0 tools_3.4.0 digest_0.6.12 Mac: > set.seed(890458, kind="Mersenne-Twister", normal.kind="Inversion") > print(rlnorm(1504)[1504], digits=22) [1] 2.732876214731374098221 > sessionInfo() R version 3.4.0 (2017-04-21) Platform: x86_64-apple-darwin15.6.0 (64-bit) Running under: macOS Sierra 10.12.5 Matrix products: default BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib locale: [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] compiler_3.4.0 digest_0.6.12 Is this expected? Is there anyway to guarantee reproducibility across platforms? It also happens with rnorm rather than rlnorm but with higher numbers.
stackoverflow
{ "language": "en", "length": 179, "provenance": "stackexchange_0000F.jsonl.gz:908969", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44679984" }
59e74a324f4a2cb419131bb2087f122e9debde61
Stackoverflow Stackexchange Q: What's the difference between git stash save and git stash push? When should I use git stash save instead of git stash push and vice-versa? A: git stash save accepts a single non-option argument — the stash message. git stash push accepts the message with option -m and accepts a list of files to stash as arguments.
Q: What's the difference between git stash save and git stash push? When should I use git stash save instead of git stash push and vice-versa? A: git stash save accepts a single non-option argument — the stash message. git stash push accepts the message with option -m and accepts a list of files to stash as arguments. A: Just to be clear, starting Git 2.15/2.16 (Q1 2018), git stash save has been deprecated in favour of git stash push (though git stash save is still available for the time being). See commit c0c0c82, commit fd2ebf1, commit db37745 (22 Oct 2017) by Thomas Gummerer (tgummerer). (Merged by Junio C Hamano -- gitster -- in commit 40f1293, 06 Nov 2017) stash: mark "git stash save" deprecated in the man page 'git stash push' fixes a historical wart in the interface of 'git stash save'. As 'git stash push' has all functionality of 'git stash save', with a nicer, more consistent user interface deprecate 'git stash save'. stash: remove now superfluos help for "stash push" With the 'git stash save' interface, it was easily possible for users to try to add a message which would start with "-", which 'git stash save' would interpret as a command line argument, and fail. For this case we added some extra help on how to create a stash with a message starting with "-". For 'stash push', messages are passed with the -m flag, avoiding this potential pitfall. Now only pathspecs starting with "-" would have to be distinguished from command line parameters by using "-- --<pathspec>". This is fairly common in the git command line interface, and we don't try to guess what the users wanted in the other cases. Because this way of passing pathspecs is quite common in other git commands, and we don't provide any extra help there, do the same in the error message for 'git stash push'. With Git 2.18 (Q2 2018), the command line completion (in contrib/) has been taught that "git stash save" has been deprecated ("git stash push" is the preferred spelling in the new world) and does not offer it as a possible completion candidate when "git stash push" can be. See commit df70b19, commit 0eb5a4f (19 Apr 2018) by Thomas Gummerer (tgummerer). (Merged by Junio C Hamano -- gitster -- in commit 79d92b1, 08 May 2018) completion: make stash -p and alias for stash push -p We define 'git stash -p' as an alias for 'git stash push -p' in the manpage. Do the same in the completion script, so all options that can be given to 'git stash push' are being completed when the user is using 'git stash -p --<tab>'. Currently the only additional option the user will get is '--message', but there may be more in the future. The command line completion script (in contrib/) tried to complete "git stash -p" as if it were "git stash push -p", but it was too aggressive and also affected "git stash show -p", which has been corrected With Git 2.28 (Q3 2020). See commit fffd0cf (21 May 2020) by Ville Skyttä (scop). (Merged by Junio C Hamano -- gitster -- in commit a8ecd01, 09 Jun 2020) completion: don't override given stash subcommand with -p Signed-off-by: Ville Skyttä df70b190 ("completion: make stash -p and alias for stash push -p", 2018-04-20, Git v2.18.0-rc0 -- merge listed in batch #5) wanted to make sure "git stash -p <TAB>" offers the same completion as "git stash push -p <TAB>", but it did so by forcing the $subcommand to be "push" whenever then "-p" option is found on the command line. This harms any subcommand that can take the "-p" option --- even when the subcommand is explicitly given, e.g. "git stash show -p", the code added by the change would overwrite the $subcommand the user gave us. Fix it by making sure that the defaulting to "push" happens only when there is no $subcommand given yet. A: The push command is intended to always be used over the save command, as it is more flexible and uses more conventional command line arguments. The save command is deprecated for these reasons. Replacement The push option was introduced in 2.13.0 in order to provide the command line arguments in a more conventional way than save does. The rationale for this change was documented in the commit messages which added the command to Git: f5727e2: Introduce a new git stash push verb in addition to git stash save. The push verb is used to transition from the current command line arguments to a more conventional way, in which the message is given as an argument to the -m option. This allows us to have pathspecs at the end of the command line arguments like other Git commands do, so that the user can say which subset of paths to stash (and leave others behind). c0c0c82: With the 'git stash save' interface, it was easily possible for users to try to add a message which would start with "-", which 'git stash save' would interpret as a command line argument, and fail. […] For 'stash push', messages are passed with the -m flag, avoiding this potential pitfall. Now only pathspecs starting with "-" would have to be distinguished from command line parameters by using "-- --<pathspec>". This is fairly common in the git command line interface, and we don't try to guess what the users wanted in the other cases. fd2ebf1: 'git stash push' has all functionality of 'git stash save', with a nicer, more consistent user interface Deprecation The save command was officially deprecated in the 2.16.0 release of Git: "git stash save" has been deprecated in favour of "git stash push". The deprecation of save is explained in its documentation: save [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-u|--include-untracked] [-a|--all] [-q|--quiet] [<message>] This option is deprecated in favour of git stash push. It differs from "stash push" in that it cannot take pathspec. Instead, all non-option arguments are concatenated to form the stash message. Short form In addition to the standard form of the command, push has a short form whereby "push" is omitted from the stash command. The save command has no such equivalent. Per the documentation: For quickly making a snapshot, you can omit "push". In this mode, non-option arguments are not allowed to prevent a misspelled subcommand from making an unwanted stash entry. The two exceptions to this are stash -p which acts as alias for stash push -p and pathspec elements, which are allowed after a double hyphen -- for disambiguation. git stash git stash -p Command comparison From reading through the documentation, I think this should be a fairly complete comparison of the two commands: push save git stash push git stash save git stash push -m <message> git stash save <message> or git stash save -m <message> git stash push -m <message> (message starting with "-") git stash save -m <message> git stash push [--] <pathspec>…​ N/A (not possible) git stash push --pathspec-from-file=<file> N/A (not possible) git stash git stash save git stash -p git stash save -p git stash -- <pathspec>…​ N/A (not possible) As shown in this comparison, the notable changes between save and push are: * *A partial stash can be created using pathspecs using push, but not save. The pathspec can be provided either as inline arguments or by using --. *The message can be provided as an inline argument with save, but must be provided by -m in push
stackoverflow
{ "language": "en", "length": 1247, "provenance": "stackexchange_0000F.jsonl.gz:908989", "question_score": "92", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680028" }
88556544fb5926ae8fcb61a1e158d2731564cd60
Stackoverflow Stackexchange Q: How to import font-awesome in node.js to use in react.js? I am working with node.js and react.js. I already imported my own css file like so: import React from 'react'; import Modal from 'react-modal'; import './../App.css'; this works fine, but when I try to add font-awesome like so: import './src/font-awesome-4.7.0/css/font-awesome.css' then it doesn't work. Am I doing something wrong? Or is there maybe another way? A: Here's how i did it entirely in the front end react side: * *Include font awesome inside the <head> tag <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> *Install react-fontawesome npm install --save react-fontawesome *Import the file and use it in your react components import FontAwesome from 'react-fontawesome'; // ..rest of your code <FontAwesome name="linkedin" size="2x"/>
Q: How to import font-awesome in node.js to use in react.js? I am working with node.js and react.js. I already imported my own css file like so: import React from 'react'; import Modal from 'react-modal'; import './../App.css'; this works fine, but when I try to add font-awesome like so: import './src/font-awesome-4.7.0/css/font-awesome.css' then it doesn't work. Am I doing something wrong? Or is there maybe another way? A: Here's how i did it entirely in the front end react side: * *Include font awesome inside the <head> tag <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> *Install react-fontawesome npm install --save react-fontawesome *Import the file and use it in your react components import FontAwesome from 'react-fontawesome'; // ..rest of your code <FontAwesome name="linkedin" size="2x"/>
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:908993", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680038" }
8a055e9e982ae059fd601908c152b532936df11e
Stackoverflow Stackexchange Q: Elasticsearch delimited payload token filter I am trying to use delimited_payload_filter for text field but no luck heres my requests : PUT /myIndex { "settings": { "analysis" : { "analyzer" : { "kuku" : { "tokenizer" : "standard", "filter" : ["delimited_payload_filter"] } } } }, "mappings": { "calls" : { "properties": { "text": { "type" : "text", "analyzer" : "kuku" } } } } } } Then I add the following doc: PUT /myIndex/calls/1 { "text" : "the|1 quick|2 fox|3" } I expect that if I will do the following query I will get a hit but i didnt. GET /myIndex/calls/_search { "query": { "match_phrase": { "text": "quick fox" } } } A: Change tokenizer to something other than "standard" like "whitespace". The "standard" is tokenizing the text and stripping the "|" delimiter before the delimited_payload filter has a chance to work on it.
Q: Elasticsearch delimited payload token filter I am trying to use delimited_payload_filter for text field but no luck heres my requests : PUT /myIndex { "settings": { "analysis" : { "analyzer" : { "kuku" : { "tokenizer" : "standard", "filter" : ["delimited_payload_filter"] } } } }, "mappings": { "calls" : { "properties": { "text": { "type" : "text", "analyzer" : "kuku" } } } } } } Then I add the following doc: PUT /myIndex/calls/1 { "text" : "the|1 quick|2 fox|3" } I expect that if I will do the following query I will get a hit but i didnt. GET /myIndex/calls/_search { "query": { "match_phrase": { "text": "quick fox" } } } A: Change tokenizer to something other than "standard" like "whitespace". The "standard" is tokenizing the text and stripping the "|" delimiter before the delimited_payload filter has a chance to work on it.
stackoverflow
{ "language": "en", "length": 145, "provenance": "stackexchange_0000F.jsonl.gz:909011", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680120" }
faa0197bc83485be5b6b0d26b9802c16004e4aba
Stackoverflow Stackexchange Q: Pandas skipping lines (stop warnings from showing) I am reading a CSV file in Python this way using Pandas: data = pd.read_csv('file1.csv', error_bad_lines=False) I am getting: Skipping line 6: expected 4 fields, saw 6 How do I stop this warnings from showing up? A: From the docs: warn_bad_lines : boolean, default True If error_bad_lines is False, and warn_bad_lines is True, a warning for each “bad line” will be output. So set warn_bad_lines=False data = pd.read_csv('file1.csv', error_bad_lines=False, warn_bad_lines=False)
Q: Pandas skipping lines (stop warnings from showing) I am reading a CSV file in Python this way using Pandas: data = pd.read_csv('file1.csv', error_bad_lines=False) I am getting: Skipping line 6: expected 4 fields, saw 6 How do I stop this warnings from showing up? A: From the docs: warn_bad_lines : boolean, default True If error_bad_lines is False, and warn_bad_lines is True, a warning for each “bad line” will be output. So set warn_bad_lines=False data = pd.read_csv('file1.csv', error_bad_lines=False, warn_bad_lines=False) A: From the docs: data = pd.read_csv('file1.csv', error_bad_lines=False, warn_bad_lines=False)
stackoverflow
{ "language": "en", "length": 87, "provenance": "stackexchange_0000F.jsonl.gz:909016", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680141" }
367e871feaa03b29d0696ffd19c0fb3238878f24
Stackoverflow Stackexchange Q: MS.Win32.Penimc.UnsafeNativeMethods Visual Studio 2015 and Sql Server Management Studio 2012 I am getting the following error after patch KB3186497 was installed on my machine. A: Microsoft Forums This worked for me: Visual Studio 2015 * *Find the devenv.exe.config file. It is located in the folder <VS Install Location>\Common7\IDE. *Copy devenv.exe.config to a non-protected folder, for example your Documents folder, and then create a backup copy of devenv.exe.config. *Open devenv.exe.config, and modify the <AppContextSwitchOverrides> element to add Switch.System.Windows.Input.Stylus.DisableStylusAndTouchSupport=true SSMS 2012 * *Find the Ssms.exe.config file. It is located in the folder <SSMS Install Location>\Tools\Binn\ManagementStudio\. *Copy Ssms.exe.config to a non-protected folder, for example your Documents folder, and then create a backup copy of Ssms.exe.config. *Open Ssms.exe.config, and add the element <AppContextSwitchOverrides value="Switch.System.Windows.Input.Stylus.DisableStylusAndTouchSupport=true" /> above the element <assemblyBinding> in <runtime>
Q: MS.Win32.Penimc.UnsafeNativeMethods Visual Studio 2015 and Sql Server Management Studio 2012 I am getting the following error after patch KB3186497 was installed on my machine. A: Microsoft Forums This worked for me: Visual Studio 2015 * *Find the devenv.exe.config file. It is located in the folder <VS Install Location>\Common7\IDE. *Copy devenv.exe.config to a non-protected folder, for example your Documents folder, and then create a backup copy of devenv.exe.config. *Open devenv.exe.config, and modify the <AppContextSwitchOverrides> element to add Switch.System.Windows.Input.Stylus.DisableStylusAndTouchSupport=true SSMS 2012 * *Find the Ssms.exe.config file. It is located in the folder <SSMS Install Location>\Tools\Binn\ManagementStudio\. *Copy Ssms.exe.config to a non-protected folder, for example your Documents folder, and then create a backup copy of Ssms.exe.config. *Open Ssms.exe.config, and add the element <AppContextSwitchOverrides value="Switch.System.Windows.Input.Stylus.DisableStylusAndTouchSupport=true" /> above the element <assemblyBinding> in <runtime> A: I faced a similar issue and the culprit was Microsoft .Net 4.7 Framework. I had to uninstall 4.7 and then installed 4.6 version. Now it works fine.
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:909075", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680294" }
31ebb2c2c2bcc5acc9e7417627ace7694cfac75e
Stackoverflow Stackexchange Q: Cannot find module 'react/lib/ReactComponentTreeHook' from 'ReactDebugTool.js' I'm trying to get Jest to run a snapshot test of my React app. The versions from my package.json: "react": "15.6.1", "react-dom": "15.6.1", "react-test-renderer": "15.6.1", I can't get past this error: ● Test suite failed to run Cannot find module 'react/lib/ReactComponentTreeHook' from 'ReactDebugTool.js' at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17) at Object.<anonymous> (node_modules/react-test-renderer/lib/ReactDebugTool.js:16:30) I have tried removing and reinstalling my node_modules dir and I've verified that the path to my component is correct but still get this same error. My test looks like this: import React from 'react'; import renderer from 'react-test-renderer'; import { Section } from '../../app/views/containers/section'; it('renders correctly', () => { const section = renderer.create( <Section key="1" section="finance"/> ).toJSON(); expect(section).toMatchSnapshot(); }); What am I doing wrong? A: On 0.47.0 Still had errors with the accepted answer had to do the following: "react-dom": "^16.0.0-beta.5", "react-test-renderer": "16.0.0-alpha.12", enzyme will work with the above changes but any sort of simulation will not, disabled taps until they support.
Q: Cannot find module 'react/lib/ReactComponentTreeHook' from 'ReactDebugTool.js' I'm trying to get Jest to run a snapshot test of my React app. The versions from my package.json: "react": "15.6.1", "react-dom": "15.6.1", "react-test-renderer": "15.6.1", I can't get past this error: ● Test suite failed to run Cannot find module 'react/lib/ReactComponentTreeHook' from 'ReactDebugTool.js' at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17) at Object.<anonymous> (node_modules/react-test-renderer/lib/ReactDebugTool.js:16:30) I have tried removing and reinstalling my node_modules dir and I've verified that the path to my component is correct but still get this same error. My test looks like this: import React from 'react'; import renderer from 'react-test-renderer'; import { Section } from '../../app/views/containers/section'; it('renders correctly', () => { const section = renderer.create( <Section key="1" section="finance"/> ).toJSON(); expect(section).toMatchSnapshot(); }); What am I doing wrong? A: On 0.47.0 Still had errors with the accepted answer had to do the following: "react-dom": "^16.0.0-beta.5", "react-test-renderer": "16.0.0-alpha.12", enzyme will work with the above changes but any sort of simulation will not, disabled taps until they support. A: While upgrading to React 16.0.0, I did notice that you do need to upgrade react-dom to 16.0.0 and it works flawless! A: Ran into the similar problem last week, we have a React-Native project that has recently upgraded to: "react-native": "0.45.1" "react": "16.0.0-alpha.12" "jest": "20.0.4" "react-test-renderer": "15.5.4" and then we try to run our Jest tests and we saw the same issue as you mentioned above. Then we realized there is a cutting edge version of the react-test-renderer and we tried that one out: "react-test-renderer": "^16.0.0-alpha.12", And now the issue is no longer there. A: The package named "storyshots" (link to the old package for reference) is deprecated and replaced by "@storybook/addon-storyshots" at the time of writing (2022), see official documentation
stackoverflow
{ "language": "en", "length": 281, "provenance": "stackexchange_0000F.jsonl.gz:909121", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680414" }
954b3dc071b1c47c50798f458fc1e15c10a69a6c
Stackoverflow Stackexchange Q: IntelliJ IDEA debugger is too slow to start on macOS IntelliJ IDEA debugger is too slow on my new MacBook Pro 13 inch TouchBar model (late 2016). It has an i5 2.9ghz (6th Gen) and 8 GB ram. Is there something wrong with processing power or is something else wrong? On my pc (i5 4670k, 8gb) the same version runs fine. A: Agree with CrazyCoder. There is an easier way for obtaining/modifying hostname instead of using the github repo. * *In system preference, click sharing 2. Click edit in the popup window. In my case, the hostname is MacBook.local. 3. sudo vi /etc/hosts
Q: IntelliJ IDEA debugger is too slow to start on macOS IntelliJ IDEA debugger is too slow on my new MacBook Pro 13 inch TouchBar model (late 2016). It has an i5 2.9ghz (6th Gen) and 8 GB ram. Is there something wrong with processing power or is something else wrong? On my pc (i5 4670k, 8gb) the same version runs fine. A: Agree with CrazyCoder. There is an easier way for obtaining/modifying hostname instead of using the github repo. * *In system preference, click sharing 2. Click edit in the popup window. In my case, the hostname is MacBook.local. 3. sudo vi /etc/hosts A: You may have a problem with DNS, see the following answer: git clone https://github.com/thoeni/inetTester java -jar ./bin/inetTester.jar Find the hostname that's output from the .jar. sudo nano /etc/hosts and add these two entries. 127.0.0.1 <output-host-name>.local ::1 <output-host-name>.local A: I would like to add one more case. If we have a number of method breakpoints, then the Intellij will run extremely slow.
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:909131", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680463" }
213a598cb02add79f344fcd95c2ced9493c29bc5
Stackoverflow Stackexchange Q: Obtain root directory of multi-module maven project from a Mojo I'm developing a maven plugin, and I need to obtain the root directory of multi-module project. With mavenProject.getBuild().getDirectory() I can get the path to directory of current module, alright. So thought I'd try to get root MavenProject, but with getRootProject() defined as below, getRootProject().getBuild().getDirectory() returns "${project.basedir}" (literally that String value... which I don't know how to resolve, and even if I did resolve it it would resolve to current module, which is not what I want). @Parameter(defaultValue = "${project}", readonly = true) private MavenProject mavenProject; // ... private MavenProject getRootProject() { MavenProject project = mavenProject; while (project.getParent() != null) { project = project.getParent(); } return project; } How do I get (resolved & absolute) path to root module? A: Thanks to this answer which deals with the same issue from a different perspective (not from a Mojo), I found a solution: Add the following field to my Mojo: @Parameter(defaultValue = "${session}", readonly = true) private MavenSession mavenSession; Then use it this way: mavenSession.getExecutionRootDirectory()
Q: Obtain root directory of multi-module maven project from a Mojo I'm developing a maven plugin, and I need to obtain the root directory of multi-module project. With mavenProject.getBuild().getDirectory() I can get the path to directory of current module, alright. So thought I'd try to get root MavenProject, but with getRootProject() defined as below, getRootProject().getBuild().getDirectory() returns "${project.basedir}" (literally that String value... which I don't know how to resolve, and even if I did resolve it it would resolve to current module, which is not what I want). @Parameter(defaultValue = "${project}", readonly = true) private MavenProject mavenProject; // ... private MavenProject getRootProject() { MavenProject project = mavenProject; while (project.getParent() != null) { project = project.getParent(); } return project; } How do I get (resolved & absolute) path to root module? A: Thanks to this answer which deals with the same issue from a different perspective (not from a Mojo), I found a solution: Add the following field to my Mojo: @Parameter(defaultValue = "${session}", readonly = true) private MavenSession mavenSession; Then use it this way: mavenSession.getExecutionRootDirectory()
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:909135", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680469" }
5e001b85ee3e4cc02ce4ac9a453c2460bbf05577
Stackoverflow Stackexchange Q: Set offset or initial position for a cell in a collection view I want to add some space before the first cell in a collection view, something like an offset, my collection view has a horizontal scroll position. Here is my current collection view: It has a leading constraint of 35, what I want is the cell to start at an "x" position of 35 but with the ability to scroll full width like in this: Is there a way to create that initial offset in a collection view using Swift 3? A: Swift 5 / Xcode 11 Thanks Alexander Spirichev. Based on his answer, you can also set the left inset to 35 points programmatically: let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 8 layout.sectionInset = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 0) collectionView.setCollectionViewLayout(layout, animated: false)
Q: Set offset or initial position for a cell in a collection view I want to add some space before the first cell in a collection view, something like an offset, my collection view has a horizontal scroll position. Here is my current collection view: It has a leading constraint of 35, what I want is the cell to start at an "x" position of 35 but with the ability to scroll full width like in this: Is there a way to create that initial offset in a collection view using Swift 3? A: Swift 5 / Xcode 11 Thanks Alexander Spirichev. Based on his answer, you can also set the left inset to 35 points programmatically: let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 8 layout.sectionInset = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 0) collectionView.setCollectionViewLayout(layout, animated: false) A: You could just set Section Insets for Collection View Flow Layout without code. A: You need to set contentInset - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{ return UIEdgeInsetsMake(top, left, bottom, right); } you can see in detail here A: You can set space before the initial cell in collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) as follow: if (indexPath.row == 0 || indexPath.row == 1) { // Set value according to user requirements cell.frame.origin.y = 10 } A: A bit late to the party here, but I came across a couple solutions The right way (scroll to first cell): https://coderwall.com/p/e-ajeq/uicollectionview-set-initial-contentoffset Simple hacky way: I add in a transparent "spacer" cell to the first item to offset the rest of the cells. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) if (indexPath.row == 0) { cell.backgroundColor = UIColor.white return cell } cell.backgroundColor = UIColor.green return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if (indexPath.row == 0){ //spacer return CGSize(width:6, height:50) } return CGSize(width: 50, height: 50) } A: If you only want the cells in that section to have the padding, then use sectionInset from UICollectionViewFlowLayout as suggested in the other answers. But from what I can guess you're probably fine with instead setting contentInsets on the collection view itself (inherited from UIScrollView)
stackoverflow
{ "language": "en", "length": 367, "provenance": "stackexchange_0000F.jsonl.gz:909150", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680503" }
8351d065918178e09186f12b7125ddfccd788bf9
Stackoverflow Stackexchange Q: Preventing new line in textarea I'm working on a chat feature (using Vue) and am using a textarea for my input so the overflow wraps and is more readable for users writing longer messages. Unfortunately, when the user keys down enter and submits, the cursor moves to a new line before submitting, making the UX feel off. Any ideas for how I could disable the newline on submit using vanilla Javascript? As you can see, I've tried adding a replace() function but to no avail. My textarea: <textarea id="btn-input" type="text" class="input-group_input" rows="4" placeholder="Type your message here..." v-model="body" @keydown.enter="postReply()"> </textarea> My submit method: postReply() { this.$http.post('/api/chat/' + this.session.id + '/replies', { body: this.body }).then((response) => { this.body.replace(/(\r\n|\n|\r)/gm,''); this.body = ''; this.replies.unshift(response.data); }).catch((error) => { }) }, A: Use @keydown.enter.prevent="postReply". This will prevent the default action of the enter key, which is to created a newline, but still call your method.
Q: Preventing new line in textarea I'm working on a chat feature (using Vue) and am using a textarea for my input so the overflow wraps and is more readable for users writing longer messages. Unfortunately, when the user keys down enter and submits, the cursor moves to a new line before submitting, making the UX feel off. Any ideas for how I could disable the newline on submit using vanilla Javascript? As you can see, I've tried adding a replace() function but to no avail. My textarea: <textarea id="btn-input" type="text" class="input-group_input" rows="4" placeholder="Type your message here..." v-model="body" @keydown.enter="postReply()"> </textarea> My submit method: postReply() { this.$http.post('/api/chat/' + this.session.id + '/replies', { body: this.body }).then((response) => { this.body.replace(/(\r\n|\n|\r)/gm,''); this.body = ''; this.replies.unshift(response.data); }).catch((error) => { }) }, A: Use @keydown.enter.prevent="postReply". This will prevent the default action of the enter key, which is to created a newline, but still call your method.
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:909189", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680638" }
207d4b354cc829d666c46e4784953f600fd96ea4
Stackoverflow Stackexchange Q: Coalescing aggregate of fields in postgres I'm trying to group by a name field, but with a 'coalescing aggregate' of the other values a row might have. Here's the data: name | jurisdiction | db_from ------------|-----------------|---------------- my station NULL 2017-06-21 8:01 my station my jurisdiction 2017-06-21 8:00 my station old data 2017-06-21 7:59 I want to wind up with: name | jurisdiction ------------|----------------- my station my jurisdiction Here's what I've come up with: WITH _stations AS ( SELECT * FROM config.stations x ORDER BY x.db_from DESC )SELECT x."name", (array_remove(array_agg(x.jurisdiction), NULL))[1] as jurisdiction FROM _stations x GROUP BY x."name"; Some of the values of the jurisdiction fields may be null and I'm trying to take the most recent one that's not null. I know I shouldn't be relying on the order of the CTE, but it seems to be working for now. A: It took me a bit if digging to find this so I hope it helps. Let me know if this isn't the best way to solve the problem: SELECT x."name", (array_remove(array_agg(x.jurisdiction ORDER BY x.db_from DESC), NULL))[1] as jurisdiction FROM config.stations x GROUP BY x."name"
Q: Coalescing aggregate of fields in postgres I'm trying to group by a name field, but with a 'coalescing aggregate' of the other values a row might have. Here's the data: name | jurisdiction | db_from ------------|-----------------|---------------- my station NULL 2017-06-21 8:01 my station my jurisdiction 2017-06-21 8:00 my station old data 2017-06-21 7:59 I want to wind up with: name | jurisdiction ------------|----------------- my station my jurisdiction Here's what I've come up with: WITH _stations AS ( SELECT * FROM config.stations x ORDER BY x.db_from DESC )SELECT x."name", (array_remove(array_agg(x.jurisdiction), NULL))[1] as jurisdiction FROM _stations x GROUP BY x."name"; Some of the values of the jurisdiction fields may be null and I'm trying to take the most recent one that's not null. I know I shouldn't be relying on the order of the CTE, but it seems to be working for now. A: It took me a bit if digging to find this so I hope it helps. Let me know if this isn't the best way to solve the problem: SELECT x."name", (array_remove(array_agg(x.jurisdiction ORDER BY x.db_from DESC), NULL))[1] as jurisdiction FROM config.stations x GROUP BY x."name" A: select distinct on (x."name") * from _stations x where x.jurisdiction is not null order by x."name", x.db_from desc https://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT
stackoverflow
{ "language": "en", "length": 207, "provenance": "stackexchange_0000F.jsonl.gz:909213", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44680699" }