id
stringlengths 40
40
| text
stringlengths 29
2.03k
| original_text
stringlengths 3
154k
| subdomain
stringclasses 20
values | metadata
dict |
---|---|---|---|---|
baae8fcba516a0fe3a2213d7ee45e637b1a2a990
|
Stackoverflow Stackexchange
Q: Julia macros: @__FILE__ @__LINE__ in macro This code:
macro FL(message)
return @sprintf("%s:%d | %s", @__FILE__, @__LINE__, message) # line 2
end
println(@FL("m")) # line 4
prints fl.jl:2 | m. How can I make it print fl.jl:4 | m?
A: The following will work in the current Julia nightly:
macro FL(message)
return :(@sprintf("%s:%d | %s", $(string(__source__.file)), $(__source__.line), $(esc(message)))) # line 2
end
println(@FL("m")) # line 4
This was made possible by the following implementation pull request. It is not possible in any officially released version, unfortunately.
|
Q: Julia macros: @__FILE__ @__LINE__ in macro This code:
macro FL(message)
return @sprintf("%s:%d | %s", @__FILE__, @__LINE__, message) # line 2
end
println(@FL("m")) # line 4
prints fl.jl:2 | m. How can I make it print fl.jl:4 | m?
A: The following will work in the current Julia nightly:
macro FL(message)
return :(@sprintf("%s:%d | %s", $(string(__source__.file)), $(__source__.line), $(esc(message)))) # line 2
end
println(@FL("m")) # line 4
This was made possible by the following implementation pull request. It is not possible in any officially released version, unfortunately.
A: Though there may be more elegant ways to do this, if you don't want this to block your progress on other fronts, why not just pass the line number to the macro...
macro FL(message, line)
return @sprintf("%s:%d | %s", @__FILE__, line, message)
end
println(@FL("m", @__LINE__))
|
stackoverflow
|
{
"language": "en",
"length": 132,
"provenance": "stackexchange_0000F.jsonl.gz:836427",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44453579"
}
|
ba980b72273a65e5b5b6292e2f394756e2b8f409
|
Stackoverflow Stackexchange
Q: Adapt width div with transform rotate and change text I have a problem with a specific style. I have a string "Historic" in a div with CSS transform rotate, positioned on a specific part of sibling div. If I change the string by "Historique" (for i18n), the div move.
I wish the div keep at the same place when string has changed. Thank you for answers.
#main {
margin: 50px;
position: relative;
width: 300px;
background: #eee;
border: thin solid #bbb;
}
#tag {
position: absolute;
left: -36px;
padding: 5px;
font-size: 9px;
transform: rotate(-90deg);
background: red;
color: white;
bottom: 15px;
text-transform: uppercase;
max-height: 20px;
}
.content {
display: flex;
position: relative;
padding: 20px;
}
<div id="main">
<div id="tag">Historic</div>
<div class="content">a</div>
<div class="content">b</div>
<div class="content">c</div>
</div>
A: I got it working by changing the tag class to read like this.
Note the transform-origin option.
transform-origin: left top 0;
position: absolute;
left: -21px;
padding: 5px;
font-size: 9px;
transform: rotate(-90deg);
background: red;
color: white;
bottom: -20px;
text-transform: uppercase;
max-height: 20px;
|
Q: Adapt width div with transform rotate and change text I have a problem with a specific style. I have a string "Historic" in a div with CSS transform rotate, positioned on a specific part of sibling div. If I change the string by "Historique" (for i18n), the div move.
I wish the div keep at the same place when string has changed. Thank you for answers.
#main {
margin: 50px;
position: relative;
width: 300px;
background: #eee;
border: thin solid #bbb;
}
#tag {
position: absolute;
left: -36px;
padding: 5px;
font-size: 9px;
transform: rotate(-90deg);
background: red;
color: white;
bottom: 15px;
text-transform: uppercase;
max-height: 20px;
}
.content {
display: flex;
position: relative;
padding: 20px;
}
<div id="main">
<div id="tag">Historic</div>
<div class="content">a</div>
<div class="content">b</div>
<div class="content">c</div>
</div>
A: I got it working by changing the tag class to read like this.
Note the transform-origin option.
transform-origin: left top 0;
position: absolute;
left: -21px;
padding: 5px;
font-size: 9px;
transform: rotate(-90deg);
background: red;
color: white;
bottom: -20px;
text-transform: uppercase;
max-height: 20px;
|
stackoverflow
|
{
"language": "en",
"length": 167,
"provenance": "stackexchange_0000F.jsonl.gz:836430",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44453587"
}
|
9d3ea2aa0c38e3f810894ea1d6237373a0d0413d
|
Stackoverflow Stackexchange
Q: Custom query with querydsl and jpa Is it possible to write custom queries with query dsl?
e.g. (self outer join)
SELECT test1.SURNAME, test2.SURNAME
FROM Test test1
LEFT OUTER JOIN Test test2 ON test1.SUPERVISOR_WARRANT_NUMBER = test2.WARRANT_NUMBER
WHERE test1.SURNAME LIKE '%Your name%';
So I would like to do above with
@Repository
public interface Test <TestModel> , QueryDslPredicateExecutor<TestModel> {
@Override
@Query("SELECT test FROM Test") /*do outer self join in Query*/
Page<TestModel> findAll(Predicate prdct, Pageable pgbl);
}
The exception I get with above code is:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter with that position [1] did not exist; nested exception is java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
If above is not possible, what would be the best approach in java to write dynamic queries (with various joins) with paging?
|
Q: Custom query with querydsl and jpa Is it possible to write custom queries with query dsl?
e.g. (self outer join)
SELECT test1.SURNAME, test2.SURNAME
FROM Test test1
LEFT OUTER JOIN Test test2 ON test1.SUPERVISOR_WARRANT_NUMBER = test2.WARRANT_NUMBER
WHERE test1.SURNAME LIKE '%Your name%';
So I would like to do above with
@Repository
public interface Test <TestModel> , QueryDslPredicateExecutor<TestModel> {
@Override
@Query("SELECT test FROM Test") /*do outer self join in Query*/
Page<TestModel> findAll(Predicate prdct, Pageable pgbl);
}
The exception I get with above code is:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter with that position [1] did not exist; nested exception is java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
If above is not possible, what would be the best approach in java to write dynamic queries (with various joins) with paging?
|
stackoverflow
|
{
"language": "en",
"length": 125,
"provenance": "stackexchange_0000F.jsonl.gz:836519",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44453890"
}
|
dbdaad5791fd80f207d6dc32914292e75f63f20b
|
Stackoverflow Stackexchange
Q: Android Studio DDMS can't open /data folder in an emulator phone I recently created an Emulator device with Android Studio,but only to find that I can't open the /data/data folder to get the sqlite db file.The folder just can't open,I have tried to use shell scirpt to chmod the /data directory,but it says the su command not found.
The Emulator
Can't open!
Is there anyone has the same problem? Or I have to root the Emulator?
But it's an Emulator! I just think it's kind of inconvenient to root a Emulator!
A: Even after running Android Studio as administrator if you can't access data/data folder, try using API 23 or lower for you emulator device.
|
Q: Android Studio DDMS can't open /data folder in an emulator phone I recently created an Emulator device with Android Studio,but only to find that I can't open the /data/data folder to get the sqlite db file.The folder just can't open,I have tried to use shell scirpt to chmod the /data directory,but it says the su command not found.
The Emulator
Can't open!
Is there anyone has the same problem? Or I have to root the Emulator?
But it's an Emulator! I just think it's kind of inconvenient to root a Emulator!
A: Even after running Android Studio as administrator if you can't access data/data folder, try using API 23 or lower for you emulator device.
A: Update
Can't remember whether it's from Android Studio 3.0 or later but if you have downloaded AS 3.3+, you'll find the tab on bottom right corner called Device File Explorer, which lets you to see and easily get the data of your app without rooting.
Opening as Administrator didn't help but rooting the phone did worked, and no I'm not lowering my SDK version.
Open cmd and go to C:\Users\{User}\AppData\Local\Android\Sdk\platform-tools or to the folder location and type cmd at the address bar.
Whether you're super user or not can be determined by $:
C:\{User}\...\platform-tools>adb shell
generic_x86:/ $ exit
To have su/root privileges type adb root and exit:
C:\{User}\...\platform-tools>adb root
generic_x86:/ # exit
Next run the Android Device Monitor to extract the data.
To turn off root type adb unroot.
A: Using Android Studio 3.1.2 and DDMS is no longer available under the Tool options. Instead Android Studio has the "Device File Explorer" tab available on the bottom right (I know why put it there).
Click on the "Device File Explorer" tab and select the Android Device you want to explore. To actually access the files, make sure USB Debugging is turned on in the AVD.
If that doesn't work, you'll need to use Terminal panel.
*
*Change the folder permission through adb shell (using chmod command)
*Pull the file using
"adb pull". See example:
C:\Users\B\AppData\Local\Android\sdk\platform-tools> adb pull /data/data/com.example.b.expensewatcher/databases/myexpenses.db
/data/data/com.example.b.expensewatcher/databases/myexpenses.db: 1 file pulled. 3.3 MB/s (24576 bytes in 0.007s)
For more details on changing folder permissions see: https://www.dev2qa.com/android-device-monitor-cannot-open-data-folder-resolve-method/
A: open DDMS with administrator previlledges. Had same issue and it solved it.
Fastest means to doing this is opening android studio with administrator previledges and opening DDMS from there.
otherwise, have a look at this link Android device monitor
A: Instead of rooting your android phone, you can access the data folder from android studio by opening 'device file explorer' which is to the bottom right corner of your IDE.
Open 'data>data>packagename>databases' you can save the database files but this will be in the encrypted form. You can directly access it from the file explorer on your PC.
Install DB Browser for SQLite and select option 'open database.'
Connect your android device and enable 'File Transfer'. Go to the directory where your android studio has been installed i.e., in my case documents. Then,
C:\Users\prana\Documents\AndroidStudio\DeviceExplorer\xiaomi-redmi_note_4-164594b\data\data\com.android.packagename\databases
You can find your databases here.
Hope it helps!
A: Use adb to root the emulator device. Once that is done, you will have permission to access the data\data folder
adb shell
su
The adb tool will be present in Users\\AppData\Local\Android\sdk1\platform-tools
Open cmd, change directory to above folder and enter the above code
Restart Android device monitor (if needed)
|
stackoverflow
|
{
"language": "en",
"length": 558,
"provenance": "stackexchange_0000F.jsonl.gz:836532",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44453922"
}
|
bdebaec06ad5feb85916b7f27b66f4694ce34fc3
|
Stackoverflow Stackexchange
Q: What's the difference between "arm-linux-user" and "armeb-linux-user"? When compile QEMU from source code, I find in file configure, option --target-list supports arm-linux-user and **armeb-linux-user". I know xx-linux-user is for User Emulation. What is the difference between "arm-linux-user" and "armeb-linux-user"?
A: armeb-linux-user is for big-endian Linux ARM binaries, and arm-linux-user is for little-endian ARM binaries. If you don't know you want big-endian then you don't want it. (The usual setup for user-mode QEMU uses the host-kernel's binfmt-misc support so it can automatically pick the right -linux-user QEMU binary to run for the guest executable anyway.)
|
Q: What's the difference between "arm-linux-user" and "armeb-linux-user"? When compile QEMU from source code, I find in file configure, option --target-list supports arm-linux-user and **armeb-linux-user". I know xx-linux-user is for User Emulation. What is the difference between "arm-linux-user" and "armeb-linux-user"?
A: armeb-linux-user is for big-endian Linux ARM binaries, and arm-linux-user is for little-endian ARM binaries. If you don't know you want big-endian then you don't want it. (The usual setup for user-mode QEMU uses the host-kernel's binfmt-misc support so it can automatically pick the right -linux-user QEMU binary to run for the guest executable anyway.)
|
stackoverflow
|
{
"language": "en",
"length": 95,
"provenance": "stackexchange_0000F.jsonl.gz:836577",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454063"
}
|
b4d1034bc22634346dbf23ba92c188048c66062a
|
Stackoverflow Stackexchange
Q: Angular Renderer2 remove listener Is it possible to remove listeners with the new angular 4 renderer?
here is the interface:
abstract listen(target: 'window' | 'document' | 'body' | any, eventName: string, callback: (event: any) => boolean | void): () => void;
In the renderer v1 listen and listenGlobal returns a Function, but this one returns void.
Is it an issue? If not, how can I remove a listener?
A: There is no difference with Renderer:
import { Renderer2 } from '@angular/core';
export class MyComponent {
listenerFn: () => void;
constructor(private renderer: Renderer2) {}
ngOnInit() {
this.listenerFn = this.renderer.listen(document, 'mousemove', () => console.log('move'));
}
ngOnDestroy() {
if (this.listenerFn) {
this.listenerFn();
}
}
}
|
Q: Angular Renderer2 remove listener Is it possible to remove listeners with the new angular 4 renderer?
here is the interface:
abstract listen(target: 'window' | 'document' | 'body' | any, eventName: string, callback: (event: any) => boolean | void): () => void;
In the renderer v1 listen and listenGlobal returns a Function, but this one returns void.
Is it an issue? If not, how can I remove a listener?
A: There is no difference with Renderer:
import { Renderer2 } from '@angular/core';
export class MyComponent {
listenerFn: () => void;
constructor(private renderer: Renderer2) {}
ngOnInit() {
this.listenerFn = this.renderer.listen(document, 'mousemove', () => console.log('move'));
}
ngOnDestroy() {
if (this.listenerFn) {
this.listenerFn();
}
}
}
A: You could also use the fromEventPattern function from rxjs.
private createOnClickObservable(renderer: Renderer2) {
let removeClickEventListener: () => void;
const createClickEventListener = (
handler: (e: Event) => boolean | void
) => {
removeClickEventListener = renderer.listen("document", "click", handler);
};
this.onClick$ = fromEventPattern<Event>(createClickEventListener, () =>
removeClickEventListener()
).pipe(takeUntil(this._destroy$));
}
just use/subscribe to it as expected
myMouseService.onClick$.subscribe((e: Event) => {
console.log("CLICK", e);
});
and dont worry about destroying, it will be handled by rxjs during closing the observable!
live-demo: https://stackblitz.com/edit/angular-so4?file=src%2Fapp%2Fmy-mouse.service.ts
see another answer, to explore more details: Is it possible to use HostListener in a Service? Or how to use DOM events in an Angular service?
A: It’s easier to put the result of the Renderer.listen handler in a variable:
listener: any;
this.listener = this.renderer.listen('body', 'mousemove', (event) => {
console.log(event);
});
and when the cancel event occurs, call the variable with empty parameters
this.renderer.listen('body', 'mouseup', (event) => {
this.listener();
});
|
stackoverflow
|
{
"language": "en",
"length": 260,
"provenance": "stackexchange_0000F.jsonl.gz:836627",
"question_score": "26",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454203"
}
|
6f30f4705f35a47a22dc57b9fc965cb90298acfa
|
Stackoverflow Stackexchange
Q: Object attributes in robot framework Lets say i have a python class like:
class MyObject:
def __init__(self, name=""):
self.name = name
def print_attr(self):
return vars(self)
def __str__(self):
return self.name
and RF script like:
*** Settings ***
Variables mine.py
*** Test Cases ***
Example
${DOG}= Set Variable ${MyObject("dog")}
${CAT}= Set Variable ${MyObject("cat")}
${MyObject.does_it_fly}= Set Variable nope
${CAT.does_it_fly}= Set Variable yeeep
When I Log ${DOG.print_attr()} and Log ${CAT.print_attr()} I get the results, respectively:
{'name':'dog'}
{'does_it_fly':'yeeep', 'name':'cat'}
But when I Log ${DOG.does_it_fly} I get the nope.
My question is, why the "does_it_fly" attribute does not show in "DOG" object attributes, but when I'm checking it individually, it appears?
Is there a way to show all the class attributes? What I'm I doing/assuming wrong?
I tried to check the class attributes with the __dict__, dir, vars (example below) but the result is the same - only "name" is shown. (I guess it's because the function is checking what is written in the .py file physically):
def class_attr():
return MyObject().__dict__
EDIT:
Actually, dir(self) instead of vars(self) does print all the attributes of DOG object, but it also includes methods.
|
Q: Object attributes in robot framework Lets say i have a python class like:
class MyObject:
def __init__(self, name=""):
self.name = name
def print_attr(self):
return vars(self)
def __str__(self):
return self.name
and RF script like:
*** Settings ***
Variables mine.py
*** Test Cases ***
Example
${DOG}= Set Variable ${MyObject("dog")}
${CAT}= Set Variable ${MyObject("cat")}
${MyObject.does_it_fly}= Set Variable nope
${CAT.does_it_fly}= Set Variable yeeep
When I Log ${DOG.print_attr()} and Log ${CAT.print_attr()} I get the results, respectively:
{'name':'dog'}
{'does_it_fly':'yeeep', 'name':'cat'}
But when I Log ${DOG.does_it_fly} I get the nope.
My question is, why the "does_it_fly" attribute does not show in "DOG" object attributes, but when I'm checking it individually, it appears?
Is there a way to show all the class attributes? What I'm I doing/assuming wrong?
I tried to check the class attributes with the __dict__, dir, vars (example below) but the result is the same - only "name" is shown. (I guess it's because the function is checking what is written in the .py file physically):
def class_attr():
return MyObject().__dict__
EDIT:
Actually, dir(self) instead of vars(self) does print all the attributes of DOG object, but it also includes methods.
|
stackoverflow
|
{
"language": "en",
"length": 185,
"provenance": "stackexchange_0000F.jsonl.gz:836632",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454233"
}
|
a22273c351dfae454ddf35e5767c32092375b4c0
|
Stackoverflow Stackexchange
Q: Does C have a CPAN-like system? Does C have an online code/lib sharing system,
like CPAN for Perl, pip for python, gem for ruby?
If not, Does C for GNU/Linux have one?
Thanks!
A: No.
In GNU/Linux, the C language is basically "the system language"; the kernel and many important parts of the operating system are written in it. Therefore, the system package manager is used to manage C dependencies.
Look for packages named lib*-dev, where the * is the actual name of the package.
For instance there's lib32readline-dev which is the development version of the readline library.
|
Q: Does C have a CPAN-like system? Does C have an online code/lib sharing system,
like CPAN for Perl, pip for python, gem for ruby?
If not, Does C for GNU/Linux have one?
Thanks!
A: No.
In GNU/Linux, the C language is basically "the system language"; the kernel and many important parts of the operating system are written in it. Therefore, the system package manager is used to manage C dependencies.
Look for packages named lib*-dev, where the * is the actual name of the package.
For instance there's lib32readline-dev which is the development version of the readline library.
A: Not an official one. But clibs looks promising and it seems to be quite popular:
https://github.com/clibs/clib
|
stackoverflow
|
{
"language": "en",
"length": 116,
"provenance": "stackexchange_0000F.jsonl.gz:836675",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454396"
}
|
b893ab1e11187e302c1be28b8a2650042ca38b6a
|
Stackoverflow Stackexchange
Q: check connection jpype - java Is there a way to check the connection between jpype and java other than a print statement?
I have installed jpype in anaconda (Windows 10 64bit, anaconda python27 (64bit) and jpype from the anaconda cloud). I can import jpype and create javaclasses and javaojects. However, when I try to get a print statement nothing happens and I can't figure out why.
from jpype import *
getDefaultJVMPath()
Out[2]: u'C:\\Program Files\\Java\\jre1.8.0_131\\bin\\server\\jvm.dll'
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("JPYPE WORKS !")
No print statement
javaPackage = JPackage("java.lang")
javaClass = javaPackage.String
javaObject = javaClass("Hello, Jpype")
javaObject
Out[8]: <jpype._jclass.java.lang.String at 0xc1b8b70>
java.lang.System.out.println(javaObject)
No print statement
The getDefaultJVMPath() is correct. But I can't get the connection with the jvm to work and I can't figure out where it goes wrong.
Any suggestions?
A: That's the case when you're using Jupyter Notebook. It works well if you're executing it in Python console or by using a .py file. If you're wondering why it worked for getDefaultJVMPath(), here is why
type(getDefaultJVMPath())
returns 'str'. But
type(java.lang.System.out.println("JPYPE WORKS !"))
returns 'NoneType'
Hope that helps!
|
Q: check connection jpype - java Is there a way to check the connection between jpype and java other than a print statement?
I have installed jpype in anaconda (Windows 10 64bit, anaconda python27 (64bit) and jpype from the anaconda cloud). I can import jpype and create javaclasses and javaojects. However, when I try to get a print statement nothing happens and I can't figure out why.
from jpype import *
getDefaultJVMPath()
Out[2]: u'C:\\Program Files\\Java\\jre1.8.0_131\\bin\\server\\jvm.dll'
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("JPYPE WORKS !")
No print statement
javaPackage = JPackage("java.lang")
javaClass = javaPackage.String
javaObject = javaClass("Hello, Jpype")
javaObject
Out[8]: <jpype._jclass.java.lang.String at 0xc1b8b70>
java.lang.System.out.println(javaObject)
No print statement
The getDefaultJVMPath() is correct. But I can't get the connection with the jvm to work and I can't figure out where it goes wrong.
Any suggestions?
A: That's the case when you're using Jupyter Notebook. It works well if you're executing it in Python console or by using a .py file. If you're wondering why it worked for getDefaultJVMPath(), here is why
type(getDefaultJVMPath())
returns 'str'. But
type(java.lang.System.out.println("JPYPE WORKS !"))
returns 'NoneType'
Hope that helps!
|
stackoverflow
|
{
"language": "en",
"length": 176,
"provenance": "stackexchange_0000F.jsonl.gz:836728",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454533"
}
|
67706d77aa927955838b7385f4a6fb2b109918ea
|
Stackoverflow Stackexchange
Q: C++ Move Semantics I have this example:
Widget* makeWidget(int a, int b) {
if (a > b) {
return new Widget(a);
}
else {
return new Widget(b);
}
}
Isn't that the same like Moving the return values, because you just pass the reference and not a copy? Why do I end Moving Constructor/Assignemnt ?
Greetings
A:
Why do I end Moving Constructor/Assignemnt ?
In your function:
Widget* makeWidget(int a, int b);
You are returning a Widget * (i.e.: a pointer to Widget) no move of an object takes place here at all.
Isn't that the same like Moving the return values, because you just pass the reference and not a copy?
It is not the same in terms of semantics, because by moving you always return an object.
By moving you are actually not copying, but moving the data from the move-from object (i.e.: the object being moved) to the move-to object (i.e.: the object being constructed or assigned to by means of the move constructor or move assignment operator, respectively).
|
Q: C++ Move Semantics I have this example:
Widget* makeWidget(int a, int b) {
if (a > b) {
return new Widget(a);
}
else {
return new Widget(b);
}
}
Isn't that the same like Moving the return values, because you just pass the reference and not a copy? Why do I end Moving Constructor/Assignemnt ?
Greetings
A:
Why do I end Moving Constructor/Assignemnt ?
In your function:
Widget* makeWidget(int a, int b);
You are returning a Widget * (i.e.: a pointer to Widget) no move of an object takes place here at all.
Isn't that the same like Moving the return values, because you just pass the reference and not a copy?
It is not the same in terms of semantics, because by moving you always return an object.
By moving you are actually not copying, but moving the data from the move-from object (i.e.: the object being moved) to the move-to object (i.e.: the object being constructed or assigned to by means of the move constructor or move assignment operator, respectively).
A: Depends on what you compare it with. If you've replaced the return type with unique_ptr<Widget>, you'd use the move constructor to achieve clear ownership semantics.
Compared to plain Widget return, if you did that you'd also achieve non-nullability.
In your case no move is performed, but you also don't have any benefits. You return something that can be null with no ownership specification. Without a move constructor you can either do that, or be forced to copy to maintain proper semantics and guarantees. Move constructors allow you to have that cake and eat it, too.
|
stackoverflow
|
{
"language": "en",
"length": 269,
"provenance": "stackexchange_0000F.jsonl.gz:836730",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454537"
}
|
1a07bc6b861b44058f472b66250dd16a91131816
|
Stackoverflow Stackexchange
Q: How to import project's R in Live Template automatically? I'm trying to create a live template for Fragment's onCreateView(). This is my template now:
After using it, R wants to be manually imported.
How can I import application's R by default? Or can I somehow get the project package name with a groovy script and write it before R like $PACKAGE_NAME$.R.layout.$LAYOUT_NAME$ to make it work?
A: Enabling the "Add unambiguous imports on the fly" in File -> Settings -> Editor -> General -> Auto Import -> Java might solve your issue since it will automatically import the R class on the fly, and the need to manually import it will disappear.
|
Q: How to import project's R in Live Template automatically? I'm trying to create a live template for Fragment's onCreateView(). This is my template now:
After using it, R wants to be manually imported.
How can I import application's R by default? Or can I somehow get the project package name with a groovy script and write it before R like $PACKAGE_NAME$.R.layout.$LAYOUT_NAME$ to make it work?
A: Enabling the "Add unambiguous imports on the fly" in File -> Settings -> Editor -> General -> Auto Import -> Java might solve your issue since it will automatically import the R class on the fly, and the need to manually import it will disappear.
|
stackoverflow
|
{
"language": "en",
"length": 112,
"provenance": "stackexchange_0000F.jsonl.gz:836748",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454573"
}
|
562c226fb2737deedd16d17911952f084ce58c0f
|
Stackoverflow Stackexchange
Q: Yeoman - V5 is not a function? Hi I have just followed this tutorial link step by step, I am making an angular App, it works fine, but i am getting this error in console V5 is not a function Although the app works fine. I am attaching the exact steps which i took and also a screen shot of my console.
A: Try to install npm and nodejs again with bower, make sure you have the compatible versions with your application.
|
Q: Yeoman - V5 is not a function? Hi I have just followed this tutorial link step by step, I am making an angular App, it works fine, but i am getting this error in console V5 is not a function Although the app works fine. I am attaching the exact steps which i took and also a screen shot of my console.
A: Try to install npm and nodejs again with bower, make sure you have the compatible versions with your application.
|
stackoverflow
|
{
"language": "en",
"length": 83,
"provenance": "stackexchange_0000F.jsonl.gz:836760",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454611"
}
|
bb4c215ddf621d9758670d58f69ed1198dc40306
|
Stackoverflow Stackexchange
Q: Does use of lambda in Android in Activity cause a memory leak? I'm watching this presentation, and at 13:42 they say that using lambda in the way:
api.getEvents()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(() -> loadingIndication.show())
.doOnUnsubscribe(() -> loadingIndication.hide())
.subscribe(...);
causes View to leak.
Can you explain how the leak works in this case? Does the leak appear depending on how we compile the code and what class we put the RxJava code (e.g. in Activity, in Application, in Service)?
A: This causes a leak because lambdas are no different from anonymous inner classes where they will have an implicit reference to the current class where they're called, in this case it the Activity. So this piece of code actually has reference to your Activity.
api.getEvents()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(() -> loadingIndication.show())
.doOnUnsubscribe(() -> loadingIndication.hide())
.subscribe(events -> {}, throwable -> {});
I haven't had the time to checkout the video but there is a way to handle this kind of possible memory leak by using CompositeDisposable and adding the Disposable returned from the above code through compositeDisposable.add() and calling compositeDisposable.clear() on your Activity's onDestroy().
|
Q: Does use of lambda in Android in Activity cause a memory leak? I'm watching this presentation, and at 13:42 they say that using lambda in the way:
api.getEvents()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(() -> loadingIndication.show())
.doOnUnsubscribe(() -> loadingIndication.hide())
.subscribe(...);
causes View to leak.
Can you explain how the leak works in this case? Does the leak appear depending on how we compile the code and what class we put the RxJava code (e.g. in Activity, in Application, in Service)?
A: This causes a leak because lambdas are no different from anonymous inner classes where they will have an implicit reference to the current class where they're called, in this case it the Activity. So this piece of code actually has reference to your Activity.
api.getEvents()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(() -> loadingIndication.show())
.doOnUnsubscribe(() -> loadingIndication.hide())
.subscribe(events -> {}, throwable -> {});
I haven't had the time to checkout the video but there is a way to handle this kind of possible memory leak by using CompositeDisposable and adding the Disposable returned from the above code through compositeDisposable.add() and calling compositeDisposable.clear() on your Activity's onDestroy().
|
stackoverflow
|
{
"language": "en",
"length": 181,
"provenance": "stackexchange_0000F.jsonl.gz:836761",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454615"
}
|
a14868f8a3fc507301c08d26a1cbff325856e957
|
Stackoverflow Stackexchange
Q: Use prxmatch to match strings ending in a certain character Match strings ending in certain character
I am trying to get create a new variable which indicates if a string ends with a certain character.
Below is what I have tried, but when this code is run, the variable ending_in_e is all zeros. I would expect that names like "Alice" and "Jane" would be matched by the code below, but they are not:
proc sql;
select *,
case
when prxmatch("/e$/",name) then 1
else 0
end as ending_in_e
from sashelp.class
;quit;
A: You should account for the fact that, in SAS, strings are of char type and spaces are added up to the string end if the actual value is shorter than the buffer.
Either trim the string:
prxmatch("/e$/",trim(name))
Or add a whitespace pattern:
prxmatch("/e\s*$/",name)
^^^
to match 0 or more whitespaces.
|
Q: Use prxmatch to match strings ending in a certain character Match strings ending in certain character
I am trying to get create a new variable which indicates if a string ends with a certain character.
Below is what I have tried, but when this code is run, the variable ending_in_e is all zeros. I would expect that names like "Alice" and "Jane" would be matched by the code below, but they are not:
proc sql;
select *,
case
when prxmatch("/e$/",name) then 1
else 0
end as ending_in_e
from sashelp.class
;quit;
A: You should account for the fact that, in SAS, strings are of char type and spaces are added up to the string end if the actual value is shorter than the buffer.
Either trim the string:
prxmatch("/e$/",trim(name))
Or add a whitespace pattern:
prxmatch("/e\s*$/",name)
^^^
to match 0 or more whitespaces.
A: SAS character variables are fixed length. So you either need to trim the trailing spaces or include them in your regular expression.
Regular expressions are powerful, but they might be confusing to some. For such a simple pattern it might be clearer to use simpler functions.
proc print data=sashelp.class ;
where char(name,length(name))='e';
run;
|
stackoverflow
|
{
"language": "en",
"length": 196,
"provenance": "stackexchange_0000F.jsonl.gz:836788",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454709"
}
|
d1ecd4a8c678322b7bdf1bebf659061a68822935
|
Stackoverflow Stackexchange
Q: Add location and weather information to HealthKit Workout Session I am working on an app where HealthKit is used and HKWorkout sessions are created and added to the HealthKit store.
Now after I finished an outdoor activity with Apple's native Workout app on the Watch, (like Open Water Swimming), when I then open this workout on the Activity App on my iPhone, it tells me the location where I started the activity and the weather conditions at the time.
I've been reading through the HealthKit documentation but I could not find any API to add this information from my app to the HKWorkoutSession.
Is it possible for developers to add this to a HKWorkout, and if so: how?
A: To add weather details to your app's workouts, you must specify values for the HKMetadataKeyWeatherCondition, HKMetadataKeyWeatherTemperature, or HKMetadataKeyWeatherHumidity metadata keys on the saved HKWorkout. See the metadata keys reference for more information.
There is no API to specify a general location for the workout. However, in watchOS 4.0 your app can now save an HKWorkoutRoute alongside an HKWorkout to provide a map of the route the user took (documentation).
|
Q: Add location and weather information to HealthKit Workout Session I am working on an app where HealthKit is used and HKWorkout sessions are created and added to the HealthKit store.
Now after I finished an outdoor activity with Apple's native Workout app on the Watch, (like Open Water Swimming), when I then open this workout on the Activity App on my iPhone, it tells me the location where I started the activity and the weather conditions at the time.
I've been reading through the HealthKit documentation but I could not find any API to add this information from my app to the HKWorkoutSession.
Is it possible for developers to add this to a HKWorkout, and if so: how?
A: To add weather details to your app's workouts, you must specify values for the HKMetadataKeyWeatherCondition, HKMetadataKeyWeatherTemperature, or HKMetadataKeyWeatherHumidity metadata keys on the saved HKWorkout. See the metadata keys reference for more information.
There is no API to specify a general location for the workout. However, in watchOS 4.0 your app can now save an HKWorkoutRoute alongside an HKWorkout to provide a map of the route the user took (documentation).
|
stackoverflow
|
{
"language": "en",
"length": 189,
"provenance": "stackexchange_0000F.jsonl.gz:836790",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454721"
}
|
a93720eb1cd5ee58e830edd96808a5116f457954
|
Stackoverflow Stackexchange
Q: InfluxDB storage size on disk All I want is simply to know how much space my InfluxDB database takes on my HDD. The stats() command gives me dozens of numbers but I don't know which one shows what I want.
A: Stats output does not contain that information. The size of the directory structure on disk will give that info.
du -sh /var/lib/influxdb/data/<db name>
Where /var/lib/influxdb/data is the data directory defined in influxdb.conf.
|
Q: InfluxDB storage size on disk All I want is simply to know how much space my InfluxDB database takes on my HDD. The stats() command gives me dozens of numbers but I don't know which one shows what I want.
A: Stats output does not contain that information. The size of the directory structure on disk will give that info.
du -sh /var/lib/influxdb/data/<db name>
Where /var/lib/influxdb/data is the data directory defined in influxdb.conf.
A: In InfluxDB v1.x, you can use following command to find out the disk usage of database, measurement and even shards:
influx_inspect report-disk -detailed /var/lib/influxdb/data/
In InfluxDB v2.x, you could take advantage of the internal stats as following:
from(bucket: "yourBucket")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r["_measurement"] == "storage_shard_disk_size")
|> filter(fn: (r) => r["_field"] == "gauge")
|> last()
It will show you the size of each database.
A: For InfluxDB 2.0 on MacOS - (for me at least) - the location is ~/.influxdbv2/engine.
Running "du -sh *" will show you the disk usage.
A: Also check .influxdb in your user's home directory.
If you already run influxd, you can check which file descriptors it keeps open:
$ pgrep -a influxd
<influxd PID> <full command path>
$ ls -l /proc/<influxd PID>/fd
For example, I have an influxd from a prebuilt package influxdb-1.8.6_linux_amd64.tar.gz. It is simply unpacked in /home/me/bin/ and runs as a user command. There is neither /var/lib/influxdb/ nor /etc/influxdb/influxdb.conf. There is ~/bin/influxdb-1.8.6-1/etc/influxdb/influxdb.conf, but it is not actually used. However, the list of file descriptors in /proc/<PID>/fd shows that it keeps several files opened under:
/home/me/.influxdb/data
/home/me/.influxdb/data/<my_db_name>/_series
/home/me/.influxdb/wal/<my_db_name>/
But do not take this for granted, I am not an influxdb expert. Notice that 1.8 is an old version, there might be some tricks in other versions.
|
stackoverflow
|
{
"language": "en",
"length": 292,
"provenance": "stackexchange_0000F.jsonl.gz:836833",
"question_score": "46",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454836"
}
|
73e5968f889919f6643835d73049539828cc9e9d
|
Stackoverflow Stackexchange
Q: How to setup WOW.js in Angular 2 and 4? I am trying to get WOW.js working in my Angular project but it is not working yet. I am not using webpack so I think the next thread is not answering my question: How to use WOW.js in Angular 2 Webpack?.
The steps that I took until now:
*
*I installed the wow.js module.
npm install wowjs
*I added the wowjs files to '.angular-cli.json'.
"styles": [
"../node_modules/wowjs/css/libs/animate.css" ],
"scripts": [
"../node_modules/wowjs/dist/wow.js"
]
3.Then I added a wow effect to one of my headers.
<h1 class="wow slideInLeft" data-wow-duration="2s">Wow effect!</h1>
*And the next thing I did was rebuilding and serving my project.
ng build
ng serve
*There is no wow effect yet. Does somebody know what I have to do yet?
A: You will need to initialise WOW for your component.
In the component where you plan on using WOW, import the script
import { WOW } from 'wowjs/dist/wow.min';
then in your class with the Angular method ngAfterViewInit
class ngAfterViewInit(){
new WOW().init();
}
|
Q: How to setup WOW.js in Angular 2 and 4? I am trying to get WOW.js working in my Angular project but it is not working yet. I am not using webpack so I think the next thread is not answering my question: How to use WOW.js in Angular 2 Webpack?.
The steps that I took until now:
*
*I installed the wow.js module.
npm install wowjs
*I added the wowjs files to '.angular-cli.json'.
"styles": [
"../node_modules/wowjs/css/libs/animate.css" ],
"scripts": [
"../node_modules/wowjs/dist/wow.js"
]
3.Then I added a wow effect to one of my headers.
<h1 class="wow slideInLeft" data-wow-duration="2s">Wow effect!</h1>
*And the next thing I did was rebuilding and serving my project.
ng build
ng serve
*There is no wow effect yet. Does somebody know what I have to do yet?
A: You will need to initialise WOW for your component.
In the component where you plan on using WOW, import the script
import { WOW } from 'wowjs/dist/wow.min';
then in your class with the Angular method ngAfterViewInit
class ngAfterViewInit(){
new WOW().init();
}
|
stackoverflow
|
{
"language": "en",
"length": 171,
"provenance": "stackexchange_0000F.jsonl.gz:836838",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44454855"
}
|
f1ad96a634d82f018c231e874128fab1ffeeb6ce
|
Stackoverflow Stackexchange
Q: Creating a new project in Android studio-Kotlin error I am very new to Kotlin and I am creating a new project that supports Kotlin in Android Studio 3.0 canary.
This project is having two issues.
*
*The R file is not getting resolved
*The package name must be a '.' separated identifier list
What should I do now?
Thanks in advance.
A: This happens when you use a domain name with ".in" or any 2 character TLD in domain name while creating the project. This should be resolved if you create with a 3 character TLD domain name. Otherwise you can use as in_.xyz
|
Q: Creating a new project in Android studio-Kotlin error I am very new to Kotlin and I am creating a new project that supports Kotlin in Android Studio 3.0 canary.
This project is having two issues.
*
*The R file is not getting resolved
*The package name must be a '.' separated identifier list
What should I do now?
Thanks in advance.
A: This happens when you use a domain name with ".in" or any 2 character TLD in domain name while creating the project. This should be resolved if you create with a 3 character TLD domain name. Otherwise you can use as in_.xyz
A: I assume you are using one of Kotlin keywords in your package name.
To fix compilation error just surround the Keywords like in ,as,is with Grave accent ( ` ). E.g.
`is`.package.name,
`in`.company.app
Hope, it'll help you.
|
stackoverflow
|
{
"language": "en",
"length": 143,
"provenance": "stackexchange_0000F.jsonl.gz:836890",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455008"
}
|
306ef5ff9809e0571bef88b1735f0f2dcf228898
|
Stackoverflow Stackexchange
Q: This project references NuGet package(s) that are missing on this computer. In my Visual studio 2015 update 3, I am experiencing bellow error when copied the solution folder to another windows machine.
Error This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build**Microsoft.Net.Compilers.props.**
I verified the NuGet Package Manager for the project, everything that marked as "missing" has a green tick next to it, including Microsoft.Net.Compilers.
A: solved the issue by removing below mentioned code segment from .csproj file
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
|
Q: This project references NuGet package(s) that are missing on this computer. In my Visual studio 2015 update 3, I am experiencing bellow error when copied the solution folder to another windows machine.
Error This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build**Microsoft.Net.Compilers.props.**
I verified the NuGet Package Manager for the project, everything that marked as "missing" has a green tick next to it, including Microsoft.Net.Compilers.
A: solved the issue by removing below mentioned code segment from .csproj file
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
|
stackoverflow
|
{
"language": "en",
"length": 137,
"provenance": "stackexchange_0000F.jsonl.gz:836891",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455011"
}
|
2247ed8d55d711f0f0ee2dabf39ce6be3d469f4f
|
Stackoverflow Stackexchange
Q: Random Custom Font rendering issue with react-native IOS Webview I tried every trick on the book I know. But When I jump to quickly from one webview to another the custom font get lost and does not render anymore.
I have a font inside the native code and a @font-face fallback on the css part:
Logging from XCode:
Nea: (
"Nea-Bold",
"Nea-Regular"
)
From the css file:
$PLANET-FONT-FAMILY-BLACK: "Nea-Bold", "Nea Bold", "neaboldwebfont", "Avenir LT Std 85 Heavy", "Arial";
$PLANET-FONT-FAMILY-BOOK: "Nea-Regular", "Nea Regular", "nearegularwebfont", "Avenir LT Std 85 Roman", "Arial";
/* Fonts */
@font-face {
font-family: 'Nea Bold';
font-style: normal;
font-weight: normal;
src: url("../../../../../assets/fonts/nea/nea-bold-webfont.svg#neabold") format("svg"),
url("../../../../../assets/fonts/nea/nea-bold-webfont.ttf") format("truetype"),
url("../../../../../assets/fonts/nea/nea-bold-webfont.eot") format("opentype"),
url("../../../../../assets/fonts/nea/nea-bold-webfont.woff") format("woff");
}
@font-face {
font-family: 'Nea Regular';
font-style: normal;
font-weight: normal;
src: url("../../../../../assets/fonts/nea/nea-regular-webfont.svg#nearegular") format("svg"),
url("../../../../../assets/fonts/nea/nea-regular-webfont.ttf") format("truetype"),
url("../../../../../assets/fonts/nea/nea-regular-webfont.eot") format("opentype"),
url("../../../../../assets/fonts/nea/nea-regular-webfont.woff") format("woff");
}
It works most of the time unless, I reload the webview too fast. What I am doing wrong ?
|
Q: Random Custom Font rendering issue with react-native IOS Webview I tried every trick on the book I know. But When I jump to quickly from one webview to another the custom font get lost and does not render anymore.
I have a font inside the native code and a @font-face fallback on the css part:
Logging from XCode:
Nea: (
"Nea-Bold",
"Nea-Regular"
)
From the css file:
$PLANET-FONT-FAMILY-BLACK: "Nea-Bold", "Nea Bold", "neaboldwebfont", "Avenir LT Std 85 Heavy", "Arial";
$PLANET-FONT-FAMILY-BOOK: "Nea-Regular", "Nea Regular", "nearegularwebfont", "Avenir LT Std 85 Roman", "Arial";
/* Fonts */
@font-face {
font-family: 'Nea Bold';
font-style: normal;
font-weight: normal;
src: url("../../../../../assets/fonts/nea/nea-bold-webfont.svg#neabold") format("svg"),
url("../../../../../assets/fonts/nea/nea-bold-webfont.ttf") format("truetype"),
url("../../../../../assets/fonts/nea/nea-bold-webfont.eot") format("opentype"),
url("../../../../../assets/fonts/nea/nea-bold-webfont.woff") format("woff");
}
@font-face {
font-family: 'Nea Regular';
font-style: normal;
font-weight: normal;
src: url("../../../../../assets/fonts/nea/nea-regular-webfont.svg#nearegular") format("svg"),
url("../../../../../assets/fonts/nea/nea-regular-webfont.ttf") format("truetype"),
url("../../../../../assets/fonts/nea/nea-regular-webfont.eot") format("opentype"),
url("../../../../../assets/fonts/nea/nea-regular-webfont.woff") format("woff");
}
It works most of the time unless, I reload the webview too fast. What I am doing wrong ?
|
stackoverflow
|
{
"language": "en",
"length": 150,
"provenance": "stackexchange_0000F.jsonl.gz:836912",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455063"
}
|
becd10c113660ffb8402e61bfbb7a24c11b15426
|
Stackoverflow Stackexchange
Q: Using Spring Boot application to pull key value pairs from Spring Cloud Consul After referencing this link, I am able to pull down value from config/application/key1
The code are as follows:
@SpringBootApplication
@EnableAutoConfiguration
@EnableDiscoveryClient
@RestController
@EnableConfigurationProperties
public class Application {
@Autowired
private Environment env;
@RequestMapping("/")
public String home() {
return env.getProperty("keys");
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
*
*However, may I ask how to access key1 value in the path of config/application/keys/key1 (one level deeper)?
*And if there is the repetition in the like config/application.key1 and config/software/key1, how can I choose which one to pull down?
|
Q: Using Spring Boot application to pull key value pairs from Spring Cloud Consul After referencing this link, I am able to pull down value from config/application/key1
The code are as follows:
@SpringBootApplication
@EnableAutoConfiguration
@EnableDiscoveryClient
@RestController
@EnableConfigurationProperties
public class Application {
@Autowired
private Environment env;
@RequestMapping("/")
public String home() {
return env.getProperty("keys");
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
*
*However, may I ask how to access key1 value in the path of config/application/keys/key1 (one level deeper)?
*And if there is the repetition in the like config/application.key1 and config/software/key1, how can I choose which one to pull down?
|
stackoverflow
|
{
"language": "en",
"length": 102,
"provenance": "stackexchange_0000F.jsonl.gz:836927",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455113"
}
|
7b2775f779280e1c721ea1242882eec9b2fc8ca6
|
Stackoverflow Stackexchange
Q: How Can I use AR.js in Ionic Framework? I am able to use the code on chrome browser but the code does not seem to work on Ionic. https://github.com/jeromeetienne/AR.js
Or is their any other open source AR technology that I can use for Ionic. EzarTech isn't powerful enough for my application.
|
Q: How Can I use AR.js in Ionic Framework? I am able to use the code on chrome browser but the code does not seem to work on Ionic. https://github.com/jeromeetienne/AR.js
Or is their any other open source AR technology that I can use for Ionic. EzarTech isn't powerful enough for my application.
|
stackoverflow
|
{
"language": "en",
"length": 52,
"provenance": "stackexchange_0000F.jsonl.gz:836950",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455183"
}
|
43cc694894085742d3ef14b9b93ca2fb5a496dfc
|
Stackoverflow Stackexchange
Q: Convert nil []byte variable to string doesn't panic. Why not? package main
import ("fmt")
func main() {
var bts []byte =nil
fmt.Println("the result :", string(bts)) // why not panic ?
// the result :
}
https://play.golang.org/p/dzRzzKvUyd
A: Because zero value of a slice (nil) acts like a zero-length slice. E.g. you also can declare a slice variable and then append to it in a loop:
// Filter returns a new slice holding only
// the elements of s that satisfy f()
func Filter(s []int, fn func(int) bool) []int {
var p []int // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
More details can be found here: https://blog.golang.org/go-slices-usage-and-internals
|
Q: Convert nil []byte variable to string doesn't panic. Why not? package main
import ("fmt")
func main() {
var bts []byte =nil
fmt.Println("the result :", string(bts)) // why not panic ?
// the result :
}
https://play.golang.org/p/dzRzzKvUyd
A: Because zero value of a slice (nil) acts like a zero-length slice. E.g. you also can declare a slice variable and then append to it in a loop:
// Filter returns a new slice holding only
// the elements of s that satisfy f()
func Filter(s []int, fn func(int) bool) []int {
var p []int // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
More details can be found here: https://blog.golang.org/go-slices-usage-and-internals
A: In general for any type that can be nil you can generate whatever string representation you like! It's because when implementing fmt.Stringer interface (see here) - or any function on a type that can be nil - you can have a nil for receiver value. In other words you can call methods on nil objects in contrast with OOP languages. In this sample code, you'll see ʕ◔ϖ◔ʔ hey nilo! for a nil value of the second type, but BOO DATA!!! :: Hi! :) when you have an element inside (it prints just the first element as a sample code).
And again keep in mind nil is typed in go.
|
stackoverflow
|
{
"language": "en",
"length": 232,
"provenance": "stackexchange_0000F.jsonl.gz:836958",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455197"
}
|
8f22b8934d4de4b3d2500328a6c0d6b89f471876
|
Stackoverflow Stackexchange
Q: JAVA_HOME is not defined correctly in Groovy I install groovy in ubuntu and when i run groovy command in terminal i saw the bellowing error:
groovy: JAVA_HOME is not defined correctly, can
not execute: /usr/local/java/jdk1.8.0_20/bin/java
what should i do to solve this?
A: You should take the whole directory where java is installed and also add java home in PATH variable, for example:
export JAVA_HOME=/usr/java/jdk1.8.0_31
export PATH=$JAVA_HOME/bin:$PATH
For verification purpose you can also run below commands,
echo $PATH
java -version
|
Q: JAVA_HOME is not defined correctly in Groovy I install groovy in ubuntu and when i run groovy command in terminal i saw the bellowing error:
groovy: JAVA_HOME is not defined correctly, can
not execute: /usr/local/java/jdk1.8.0_20/bin/java
what should i do to solve this?
A: You should take the whole directory where java is installed and also add java home in PATH variable, for example:
export JAVA_HOME=/usr/java/jdk1.8.0_31
export PATH=$JAVA_HOME/bin:$PATH
For verification purpose you can also run below commands,
echo $PATH
java -version
A: Updating JAVA_HOME or PATH environment variables is ok for individual users, but to fix it system-wide, just create the missing symlink. For me, it went like this:
$ groovy --version
groovy: JAVA_HOME not defined, can't execute: /usr/lib/jvm/default-java/bin/java
$ cd /usr/lib/jvm
$ ls -log
lrwxrwxrwx 1 20 Nov 1 14:17 java-1.8.0-openjdk-amd64 -> java-8-openjdk-amd64
drwxr-xr-x 7 4096 Feb 3 02:36 java-8-openjdk-amd64
$ sudo ln -s java-8-openjdk-amd64/ default-java
$ groovy --version
Groovy Version: 2.4.8 JVM: 1.8.0_151 Vendor: Oracle Corporation OS: Linux
|
stackoverflow
|
{
"language": "en",
"length": 160,
"provenance": "stackexchange_0000F.jsonl.gz:836967",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455220"
}
|
74ce7d6427e76e3b15136662c1ffaaf9130940f7
|
Stackoverflow Stackexchange
Q: Install pip3 package using ansible instead of pip2 I am trying to setup a Django project in vagrant using ansible. I have used the following code for installing the pip packages:
- name: Setup Virtualenv
pip: virtualenv={{ virtualenv_path }} virtualenv_python=python3 requirements={{ virtualenv_path }}/requirements.txt
I need to use python3 for the django project and even though I have explicitly mentioned to use python3, it is installing the pip packages via pip2. I have ensured that python3 is installed on the virtual machine.
Please, help me install the packages via pip3.
A: Had the same issue. There is workaround with usage executable:
- name: Install and upgrade pip
pip:
name: pip
extra_args: --upgrade
executable: pip3
|
Q: Install pip3 package using ansible instead of pip2 I am trying to setup a Django project in vagrant using ansible. I have used the following code for installing the pip packages:
- name: Setup Virtualenv
pip: virtualenv={{ virtualenv_path }} virtualenv_python=python3 requirements={{ virtualenv_path }}/requirements.txt
I need to use python3 for the django project and even though I have explicitly mentioned to use python3, it is installing the pip packages via pip2. I have ensured that python3 is installed on the virtual machine.
Please, help me install the packages via pip3.
A: Had the same issue. There is workaround with usage executable:
- name: Install and upgrade pip
pip:
name: pip
extra_args: --upgrade
executable: pip3
A: Try to use executable option. Excerpt from pip module doc:
executable (added in 1.3)
The explicit executable or a pathname to the executable to be used to run pip for a specific version of Python installed in the system. For example pip-3.3, if there are both Python 2.7 and 3.3 installations in the system and you want to run pip for the Python 3.3 installation. It cannot be specified together with the 'virtualenv' parameter (added in 2.1). By default, it will take the appropriate version for the python interpreter use by ansible, e.g. pip3 on python 3, and pip2 or pip on python 2.
Update:
To combine virtualenv path and alternative executable, use virtualenv_command like this:
- pip:
virtualenv: /tmp/py3
virtualenv_command: /usr/bin/python3 -m venv
name: boto
Absolute path is required for virtualenv_command.
|
stackoverflow
|
{
"language": "en",
"length": 247,
"provenance": "stackexchange_0000F.jsonl.gz:836971",
"question_score": "20",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455240"
}
|
4fb94f7a673a83035ccb7aa0c8d7eef33fc216e5
|
Stackoverflow Stackexchange
Q: How to specify --recurse-submodules strategy in SmartGit for git fetch SmartGit is explicitly using the submodule update strategy no. How can I overwrite it to use the strategy on-demand?
Executed command by SmartGit:
git.exe fetch --progress --prune --recurse-submodules=no origin
I tried to overwrite the fetch command with an alias:
git config --global alias.fetch 'git fetch --recurse-submodules=on-demand'
I see no changes in SmartGit's log window.
A: As of SmartGit 17, it's not possible to change --recurse-submodules= strategy. However, in the Repository|Settings, on Pull tab, you can configure to Always fetch new commits, tags and branches from submodule.
|
Q: How to specify --recurse-submodules strategy in SmartGit for git fetch SmartGit is explicitly using the submodule update strategy no. How can I overwrite it to use the strategy on-demand?
Executed command by SmartGit:
git.exe fetch --progress --prune --recurse-submodules=no origin
I tried to overwrite the fetch command with an alias:
git config --global alias.fetch 'git fetch --recurse-submodules=on-demand'
I see no changes in SmartGit's log window.
A: As of SmartGit 17, it's not possible to change --recurse-submodules= strategy. However, in the Repository|Settings, on Pull tab, you can configure to Always fetch new commits, tags and branches from submodule.
|
stackoverflow
|
{
"language": "en",
"length": 97,
"provenance": "stackexchange_0000F.jsonl.gz:836986",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455270"
}
|
91aa9427c003d3e837508d808cd45a2dbf7648cc
|
Stackoverflow Stackexchange
Q: Call to php function syslog in docker container dosn't work i'm trying to dockerize my php application. I have a container for NGINX and PHP-FPM.
My application writes some log data to the syslog via the PHP openlog and syslog functions like this:
openlog("myapp.test", LOG_ODELAY | LOG_CONS, LOG_LOCAL5);
syslog(LOG_INFO, "This is a test");
closelog();
My docker daemon is configured to use the syslog driver:
{
"graph": "/storage/docker-service",
"storage-driver": "overlay",
"log-driver": "syslog",
"log-opts": {
"syslog-address": "tcp://SERVER_IP:514",
"syslog-facility": "local5"
}
}
(SERVER_IP is the IPv4 address of my server)
I start my docker container with docker-compose and only set the log-tag with the logging options for each container.
NGINX is configured to log to the syslog:
error_log syslog:server=SERVER_IP,facility=local5,tag=nginx debug;
access_log syslog:server=SERVER_IP,facility=local5,tag=nginx;
PHP-FPM the same:
error_log = syslog
syslog.ident = php-fpm
syslog.facility = local5
The logs from NGINX and PHP-FPM are shown correctly in the servers syslog. But the log messages created with the php functions never appear.
What is the problem here? Think using the docker syslog driver catches all syslog messages within the containers?
Any suggestion how to fix this?
|
Q: Call to php function syslog in docker container dosn't work i'm trying to dockerize my php application. I have a container for NGINX and PHP-FPM.
My application writes some log data to the syslog via the PHP openlog and syslog functions like this:
openlog("myapp.test", LOG_ODELAY | LOG_CONS, LOG_LOCAL5);
syslog(LOG_INFO, "This is a test");
closelog();
My docker daemon is configured to use the syslog driver:
{
"graph": "/storage/docker-service",
"storage-driver": "overlay",
"log-driver": "syslog",
"log-opts": {
"syslog-address": "tcp://SERVER_IP:514",
"syslog-facility": "local5"
}
}
(SERVER_IP is the IPv4 address of my server)
I start my docker container with docker-compose and only set the log-tag with the logging options for each container.
NGINX is configured to log to the syslog:
error_log syslog:server=SERVER_IP,facility=local5,tag=nginx debug;
access_log syslog:server=SERVER_IP,facility=local5,tag=nginx;
PHP-FPM the same:
error_log = syslog
syslog.ident = php-fpm
syslog.facility = local5
The logs from NGINX and PHP-FPM are shown correctly in the servers syslog. But the log messages created with the php functions never appear.
What is the problem here? Think using the docker syslog driver catches all syslog messages within the containers?
Any suggestion how to fix this?
|
stackoverflow
|
{
"language": "en",
"length": 180,
"provenance": "stackexchange_0000F.jsonl.gz:837033",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455409"
}
|
14b0eac5786b379315dbee54325a072c4ec8d107
|
Stackoverflow Stackexchange
Q: Android SDK installed but not found I'm installing an environment for an Ionic project on Windows 10. I downloaded Android studio and installed SDK in
C:\Users\user\AppData\Local\Android\sdk
My system variable ANDROID_HOME=C:\Users\user\AppData\Local\Android\sdk
Executed OK:
ionic platform add android
But :
$ ionic run android
Running command: "C:\Program Files\nodejs\node.exe" C:\Users\KGE\SVN\trunk\sagaMobile\hooks\after_prepare\010_add_platform_class.js C:/Users/KGE/SVN/trunk/sagaMobile
add to body class: platform-android
Error: Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.
I tried to find a solution for 2 days but nothing works. If you have any ideas ...
EDIT:
I use Git bash for input. I have the same with CMD, even as admin.
EDIT 2:
Solved by removing and reinstall of the whole project
|
Q: Android SDK installed but not found I'm installing an environment for an Ionic project on Windows 10. I downloaded Android studio and installed SDK in
C:\Users\user\AppData\Local\Android\sdk
My system variable ANDROID_HOME=C:\Users\user\AppData\Local\Android\sdk
Executed OK:
ionic platform add android
But :
$ ionic run android
Running command: "C:\Program Files\nodejs\node.exe" C:\Users\KGE\SVN\trunk\sagaMobile\hooks\after_prepare\010_add_platform_class.js C:/Users/KGE/SVN/trunk/sagaMobile
add to body class: platform-android
Error: Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.
I tried to find a solution for 2 days but nothing works. If you have any ideas ...
EDIT:
I use Git bash for input. I have the same with CMD, even as admin.
EDIT 2:
Solved by removing and reinstall of the whole project
|
stackoverflow
|
{
"language": "en",
"length": 123,
"provenance": "stackexchange_0000F.jsonl.gz:837038",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455431"
}
|
bdbb1b3601e2bb79839e4609bd91738e09c22313
|
Stackoverflow Stackexchange
Q: Flatten values of every key in python I have a dictionary like this:
migration_dict = {'30005': ['key42750','key43119', 'key44103', ['key333'],
['key444'], ['keyxx']], '30003': ['key43220', 'key42244','key42230',
['keyzz'], ['kehh']]}
How can I flatten the values of every key in order to have something like this:
migration_dict = {'30005': ['key42750','key43119', 'key44103', 'key333',
'key444', 'keyxx'], '30003': ['key43220', 'key42244','key42230',
'keyzz', 'kehh']}
A: You can write a recursive function to flatten the value lists and use it in a dictionary comprehension to build a new dictionary:
def flatten(lst):
for x in lst:
if isinstance(x, list):
for y in flatten(x): # yield from flatten(...) in Python 3
yield y #
else:
yield x
migration_dict = {k: list(flatten(v)) for k, v in dct.items()}
print(migration_dict)
# {'30005': ['key42750', 'key43119', 'key44103', 'key333', 'key444', 'keyxx'], '30003': ['key43220', 'key42244', 'key42230', 'keyzz', 'kehh']}
It handles any nesting depth in the dict value lists.
|
Q: Flatten values of every key in python I have a dictionary like this:
migration_dict = {'30005': ['key42750','key43119', 'key44103', ['key333'],
['key444'], ['keyxx']], '30003': ['key43220', 'key42244','key42230',
['keyzz'], ['kehh']]}
How can I flatten the values of every key in order to have something like this:
migration_dict = {'30005': ['key42750','key43119', 'key44103', 'key333',
'key444', 'keyxx'], '30003': ['key43220', 'key42244','key42230',
'keyzz', 'kehh']}
A: You can write a recursive function to flatten the value lists and use it in a dictionary comprehension to build a new dictionary:
def flatten(lst):
for x in lst:
if isinstance(x, list):
for y in flatten(x): # yield from flatten(...) in Python 3
yield y #
else:
yield x
migration_dict = {k: list(flatten(v)) for k, v in dct.items()}
print(migration_dict)
# {'30005': ['key42750', 'key43119', 'key44103', 'key333', 'key444', 'keyxx'], '30003': ['key43220', 'key42244', 'key42230', 'keyzz', 'kehh']}
It handles any nesting depth in the dict value lists.
A: for key in migration_dict:
for i in migration_dict[key]:
if type(i) == list:
migration_dict[key].remove(i)
for element in i:
migration_dict[key].append(element)
Now this loop should do it. Note however, that this works only if the inner list doesn't have more lists within it. If it does then you might have to make a recursive function that flattens it out for you.
A: If you don't mind using an 3rd party extension, you could use iteration_utilities.deepflatten1 and a dict-comprehension:
>>> from iteration_utilities import deepflatten
>>> {key: list(deepflatten(value, ignore=str)) for key, value in migration_dict.items()}
{'30003': ['key43220', 'key42244', 'key42230', 'keyzz', 'kehh'],
'30005': ['key42750', 'key43119', 'key44103', 'key333', 'key444', 'keyxx']}
This flattens all iterable items in your values (except strings).
1 Disclaimer: I'm the author of that library
A: Heres a oneliner:
Consider this dict, same structure:
m = {'a': ['k1', 'k2', 'k3', ['k4'], ['k5'], ['k6']],
'b': ['k1', 'k2', 'k3', ['k4'], ['k5'], ['k6']]}
import itertools
d = {k:list(itertools.chain.from_iterable(itertools.repeat(x,1) if isinstance(x, str) else x for x in v)) for k,v in m.iteritems()}
{'a': ['k1', 'k2', 'k3', 'k4', 'k5', 'k6'],
'b': ['k1', 'k2', 'k3', 'k4', 'k5', 'k6']}
You could also use a 3rd party library more-iterools,
t = {k: list(more_itertools.collapse(v, base_type=str)) for k,v in m.iteritems()}
{'a': ['k1', 'k2', 'k3', 'k4', 'k5', 'k6'],
'b': ['k1', 'k2', 'k3', 'k4', 'k5', 'k6']}
A: If its important to have flat values in your dictionary, maybe you could create a function that gets rid of all the (multi-dimensional)lists before adding them to the dictionary?
def flatten_values(value):
if type(value) == list:
for i in value:
return i
Hope this helps, couldnt make this into a comment, because i don't have enough rep ;)
|
stackoverflow
|
{
"language": "en",
"length": 408,
"provenance": "stackexchange_0000F.jsonl.gz:837061",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455503"
}
|
aafd5bf5f6c8f8e5a8e980b0de817e9a2da78b2a
|
Stackoverflow Stackexchange
Q: WARNING: PDF write support was not found on the class path Please friends I am encountering this difficulty viewing a pdf file, it is given the error below
org.icepdf.core.pobjects.Document
WARNING: PDF write support was not found on the class path
Jun 09, 2017 8:32:10 AM org.icepdf.core.pobjects.Catalog
Below is my code
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.icepdf.ri.common.ComponentKeyBinding;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
/**
*
* @author LabaPc
*/
public class viewPDF {
public viewPDF() {
}
public void displayPDF(JPanel viewerComponentPanel, String filePath) {
// build a controller
SwingController controller = new SwingController();
// Build a SwingViewFactory configured with the controller
SwingViewBuilder factory = new SwingViewBuilder(controller);
// Use the factory to build a JPanel that is pre-configured
//with a complete, active Viewer UI.
viewerComponentPanel = factory.buildViewerPanel();
// add copy keyboard command
ComponentKeyBinding.install(controller, viewerComponentPanel);
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
controller.openDocument(filePath);
}
}
Below is the method that calls the code above
public void viewFile(){
String canonicalPath = tempFileHolder.get(scriptName);
viewPDF vw = new viewPDF();
vw.displayPDF(jPanelGrader,canonicalPath);
}
A: That' not an error, just a warning. Usually because the open-source version of icepdf is missing the write support, only core and viewer.
|
Q: WARNING: PDF write support was not found on the class path Please friends I am encountering this difficulty viewing a pdf file, it is given the error below
org.icepdf.core.pobjects.Document
WARNING: PDF write support was not found on the class path
Jun 09, 2017 8:32:10 AM org.icepdf.core.pobjects.Catalog
Below is my code
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.icepdf.ri.common.ComponentKeyBinding;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
/**
*
* @author LabaPc
*/
public class viewPDF {
public viewPDF() {
}
public void displayPDF(JPanel viewerComponentPanel, String filePath) {
// build a controller
SwingController controller = new SwingController();
// Build a SwingViewFactory configured with the controller
SwingViewBuilder factory = new SwingViewBuilder(controller);
// Use the factory to build a JPanel that is pre-configured
//with a complete, active Viewer UI.
viewerComponentPanel = factory.buildViewerPanel();
// add copy keyboard command
ComponentKeyBinding.install(controller, viewerComponentPanel);
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
controller.openDocument(filePath);
}
}
Below is the method that calls the code above
public void viewFile(){
String canonicalPath = tempFileHolder.get(scriptName);
viewPDF vw = new viewPDF();
vw.displayPDF(jPanelGrader,canonicalPath);
}
A: That' not an error, just a warning. Usually because the open-source version of icepdf is missing the write support, only core and viewer.
|
stackoverflow
|
{
"language": "en",
"length": 194,
"provenance": "stackexchange_0000F.jsonl.gz:837078",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455556"
}
|
80aebb300789cd2cfa0e39c4ea3d424680fc0bfe
|
Stackoverflow Stackexchange
Q: Nested List Iterator. Program doesn't terminates Below is my program.
public class NewClass {
public static void main(String[] args) {
List<String> cars = new ArrayList<String>();
cars.add("Maruti");
cars.add("Hundai");
cars.add("Polo");
Iterator<String> literate1 = cars.iterator();
while (literate1.hasNext()){
System.out.println(literate1.next());
literate1.remove();
Iterator<String> literate2 = cars.iterator();
while (literate2.hasNext()){
}
}
}
}
Output
Maruti
Just after printing this result, program doesn't terminates. Can you explain what is going on?
A: literate2.hasNext() always returns true. So while loop will never end.
|
Q: Nested List Iterator. Program doesn't terminates Below is my program.
public class NewClass {
public static void main(String[] args) {
List<String> cars = new ArrayList<String>();
cars.add("Maruti");
cars.add("Hundai");
cars.add("Polo");
Iterator<String> literate1 = cars.iterator();
while (literate1.hasNext()){
System.out.println(literate1.next());
literate1.remove();
Iterator<String> literate2 = cars.iterator();
while (literate2.hasNext()){
}
}
}
}
Output
Maruti
Just after printing this result, program doesn't terminates. Can you explain what is going on?
A: literate2.hasNext() always returns true. So while loop will never end.
A: Please check the below code. It will work.
List<String> cars = new ArrayList<String>();
cars.add("Maruti");
cars.add("Hundai");
cars.add("Polo");
Iterator<String> literate1 = cars.iterator();
while (literate1.hasNext()) {
System.out.println(literate1.next());
}
In your code, the inner while loop has the condition literate2.hasNext(). It's actually returning true all the time. For that reason, it's creating an infinite loop.
A: while (literate2.hasNext()){
}
Infinite loop right there. Until you call next(), hasNext() will always return true if there are more items.
|
stackoverflow
|
{
"language": "en",
"length": 149,
"provenance": "stackexchange_0000F.jsonl.gz:837082",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455567"
}
|
bb6d4aa765e34dbf484b9bc8a0ad6107c3612750
|
Stackoverflow Stackexchange
Q: Using @Spy and @Autowired together I have a Service Class with 3 methods, Service class is also using some @Autowired annotations.
Out of 3 methods, I want to mock two methods but use real method for 3rd one.
Problem is:
*
*If I am using @Autowired with @Spy, all three real method implementation is being called.
*If I am using @Spy only, call to real method is return with Null pointer as there is no initialisation of Autowired objects.
A: I know about these two options:
*
*Use @SpyBean annotation from spring-boot-test as the only annotation
@Autowired
@InjectMocks
private ProductController productController;
@SpyBean
private ProductService productServiceSpy;
*Use Java reflection to "autowire" the spy object, e.g. ReflectionTestUtils
@Autowired
private ProductController productController;
@Autowired
private ProductService productService;
@Before
public void setUp() {
ProductService productServiceSpy = Mockito.spy(productService);
ReflectionTestUtils.setField(productController, "productService", productServiceSpy);
}
|
Q: Using @Spy and @Autowired together I have a Service Class with 3 methods, Service class is also using some @Autowired annotations.
Out of 3 methods, I want to mock two methods but use real method for 3rd one.
Problem is:
*
*If I am using @Autowired with @Spy, all three real method implementation is being called.
*If I am using @Spy only, call to real method is return with Null pointer as there is no initialisation of Autowired objects.
A: I know about these two options:
*
*Use @SpyBean annotation from spring-boot-test as the only annotation
@Autowired
@InjectMocks
private ProductController productController;
@SpyBean
private ProductService productServiceSpy;
*Use Java reflection to "autowire" the spy object, e.g. ReflectionTestUtils
@Autowired
private ProductController productController;
@Autowired
private ProductService productService;
@Before
public void setUp() {
ProductService productServiceSpy = Mockito.spy(productService);
ReflectionTestUtils.setField(productController, "productService", productServiceSpy);
}
A: Using @Spy together with @Autowired works until you want to verify interaction between that spy and a different component that spy is injected into. What I found to work for me was the following approach found at https://dzone.com/articles/how-to-mock-spring-bean-version-2
@Configuration
public class AddressServiceTestConfiguration {
@Bean
@Primary
public AddressService addressServiceSpy(AddressService addressService) {
return Mockito.spy(addressService);
}
}
This turns your autowired component into a spy object, which will be used by your service and can be verified in your tests.
A: I have a similar problem and we fixed using @SpyBean and @Autowired together:
@SpyBean
@Autowired
ClosedInvoiceEventHandler closedInvoiceEventHandler;
A: I was surprised myself but it does work for us. We have plenty places like:
@Spy
@Autowired
private FeatureService featureService;
I think I know why you are facing this problem. It's not about injection, it's about when(bloMock.doSomeStuff()).thenReturn(1) vs doReturn(1).when(bloMock).doSomeStuff().
See: http://www.stevenschwenke.de/spyingWithMockito
The very important difference is that the first option will actually
call the doSomeStuff()- method while the second will not. Both will
cause doSomeStuff() to return the desired 1.
A: UPDATE 20220509-203459
For TestNg User,
Add this to the test class
@TestExecutionListeners(listeners = MockitoTestExecutionListener.class)
and extends AbstractTransactionalTestNGSpringContextTests
then @SpyBean will work.
Two choices are given in this Answer
Howerver, I met problems.
*
*Use @SpyBean annotation from spring-boot-test as the only annotation
This seems a good idea but only for junit users. I am using TestNg in my tests.
I have not found a way to make @SpyBean work well with TestNg.
*Use Java reflection to "autowire" the spy object, e.g. ReflectionTestUtils
The beans autowired seem all have final methods, because spring have already proxy them and make methods final. So Mockito.spy a autowired bean maybe impossible.
Indeed, i tried and got a exception:
invalid use of argument matchers 0 matchers expected 1 recorded
I didnot find reason myself but i saw explanation from here
So, the only approach left is https://stackoverflow.com/a/55148514/12133207
I am not sure if it does work, I will try.
-- tried,not work. maybe because the method parameter is also spring proxied. The methods are alse final.
|
stackoverflow
|
{
"language": "en",
"length": 475,
"provenance": "stackexchange_0000F.jsonl.gz:837083",
"question_score": "48",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455572"
}
|
9bb2dc34765ed8514ab8cf15f63beafdb1d7d4b9
|
Stackoverflow Stackexchange
Q: XDebug halts execution on caught-exceptions I'm using VSCode + PHP Debug extension, and when I debug my application, the script execution is halted on any exception, even if it has been caught.
Extension: https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug
{
"version": "0.2.0",
"configurations": [
{
"name": "Listen for XDebug",
"type": "php",
"request": "launch",
"port": 9000
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 9000
}
]
}
XDebug settings
xdebug.remote_autostart=1
xdebug.remote_enable=1
xdebug.show_exception_trace=0
A: I also had the same issue Xdebug being stopped at pretty much everything it goes through.
If you go to the Debug panel of VS Code and at the bottom check for the Breakpoints section. Disable Notices, Exceptions, Everything and Warnings (or whatever suits you best).
I basically keep the aforementioned 4 settings unticked so that it will only stop at my breakpoints.
Screenshot of the settings: Imgur (Unfortunately, SO's image uploading plugin doesn't seem to work for me!)
Hope this helps :)
|
Q: XDebug halts execution on caught-exceptions I'm using VSCode + PHP Debug extension, and when I debug my application, the script execution is halted on any exception, even if it has been caught.
Extension: https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug
{
"version": "0.2.0",
"configurations": [
{
"name": "Listen for XDebug",
"type": "php",
"request": "launch",
"port": 9000
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 9000
}
]
}
XDebug settings
xdebug.remote_autostart=1
xdebug.remote_enable=1
xdebug.show_exception_trace=0
A: I also had the same issue Xdebug being stopped at pretty much everything it goes through.
If you go to the Debug panel of VS Code and at the bottom check for the Breakpoints section. Disable Notices, Exceptions, Everything and Warnings (or whatever suits you best).
I basically keep the aforementioned 4 settings unticked so that it will only stop at my breakpoints.
Screenshot of the settings: Imgur (Unfortunately, SO's image uploading plugin doesn't seem to work for me!)
Hope this helps :)
|
stackoverflow
|
{
"language": "en",
"length": 160,
"provenance": "stackexchange_0000F.jsonl.gz:837087",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455584"
}
|
92d4de324bcc87dd0a52b063dc29c9b43ad511df
|
Stackoverflow Stackexchange
Q: no match for 'operator='(operand type are 'std::vector' and 'int' I'm new to c++ and I'm learning about vector. I wrote a basic code to see how it works but i get the following errors.
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
C:\Users\Sohit\Desktop\Comparator\vectors.cpp||In function 'int main()':|
C:\Users\Sohit\Desktop\Comparator\vectors.cpp|7|error: 'void operator=(const int&)' must be a nonstatic member function|
C:\Users\Sohit\Desktop\Comparator\vectors.cpp|10|error: no match for 'operator=' (operand types are 'std::vector' and 'int')|
no match for 'operator='(operand type are 'std::vector' and 'int'
please help
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v[100];
for(int i=0;i<100;i++)
v[i]=i+1;
int Count=v.size();
std::cout<<Count;
bool is_nonempty=!v.empty();
cout<<is_nonempty;
vector<int>v2;
for(int i=0;i<100;i++)
v2.push_back(i*i);
int count2 = v2.size();
cout<<count2;
v.resize(200);
for(int i=100;i<200;i++)
v[i]=i*i*i;
v.resize(200);
for(int i=100;i<200;i++)
v2.push_back(i*i*i);
vector<int> v3=v2;
v.clear();
v(20,"unknown");
int n,m;
cin>>n>>m;
vector< vector<int> > Matrix(n,vector<int>(m,-1));
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cout<<Matrix[i][j];
return 0;
}
A: The following:
vector<int> v[100];
...declares 100 vectors of int with size 0, so when you do:
v[i] = i+1;
v[i] is the ith vector, so you try to assign i + 1 which is a int to v[i] which is vector.
If you want a single vector of size 100, the correct syntax is:
vector<int> v(100);
|
Q: no match for 'operator='(operand type are 'std::vector' and 'int' I'm new to c++ and I'm learning about vector. I wrote a basic code to see how it works but i get the following errors.
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
C:\Users\Sohit\Desktop\Comparator\vectors.cpp||In function 'int main()':|
C:\Users\Sohit\Desktop\Comparator\vectors.cpp|7|error: 'void operator=(const int&)' must be a nonstatic member function|
C:\Users\Sohit\Desktop\Comparator\vectors.cpp|10|error: no match for 'operator=' (operand types are 'std::vector' and 'int')|
no match for 'operator='(operand type are 'std::vector' and 'int'
please help
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v[100];
for(int i=0;i<100;i++)
v[i]=i+1;
int Count=v.size();
std::cout<<Count;
bool is_nonempty=!v.empty();
cout<<is_nonempty;
vector<int>v2;
for(int i=0;i<100;i++)
v2.push_back(i*i);
int count2 = v2.size();
cout<<count2;
v.resize(200);
for(int i=100;i<200;i++)
v[i]=i*i*i;
v.resize(200);
for(int i=100;i<200;i++)
v2.push_back(i*i*i);
vector<int> v3=v2;
v.clear();
v(20,"unknown");
int n,m;
cin>>n>>m;
vector< vector<int> > Matrix(n,vector<int>(m,-1));
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cout<<Matrix[i][j];
return 0;
}
A: The following:
vector<int> v[100];
...declares 100 vectors of int with size 0, so when you do:
v[i] = i+1;
v[i] is the ith vector, so you try to assign i + 1 which is a int to v[i] which is vector.
If you want a single vector of size 100, the correct syntax is:
vector<int> v(100);
|
stackoverflow
|
{
"language": "en",
"length": 194,
"provenance": "stackexchange_0000F.jsonl.gz:837116",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455669"
}
|
12e6fbbacef3c330f3c30bfc51b82beeeefea69c
|
Stackoverflow Stackexchange
Q: Angular2 plugin for SonarQube 6.x I am new with Sonar and I have recently installed SonarQube 6.3
I couldnt find any plugin for AngularJS neither Angular2.
Is there any way to have an Angular scanner? Any plans to release one for SonarQube 6.X?
Thanks a lot
A: There are plenty of plugins on GitHub.
For example:
*
*sonar-web-frontend-plugin for many front end technologies including AngularJS and TypeScript but is a bit old. It analyzes the scanners' reports.
*SonarTsPlugin for TypeScript and so Angular 2. It directly performs an analysis.
*SonarTS is the official SonarSource plugin for TypeScript.
|
Q: Angular2 plugin for SonarQube 6.x I am new with Sonar and I have recently installed SonarQube 6.3
I couldnt find any plugin for AngularJS neither Angular2.
Is there any way to have an Angular scanner? Any plans to release one for SonarQube 6.X?
Thanks a lot
A: There are plenty of plugins on GitHub.
For example:
*
*sonar-web-frontend-plugin for many front end technologies including AngularJS and TypeScript but is a bit old. It analyzes the scanners' reports.
*SonarTsPlugin for TypeScript and so Angular 2. It directly performs an analysis.
*SonarTS is the official SonarSource plugin for TypeScript.
|
stackoverflow
|
{
"language": "en",
"length": 98,
"provenance": "stackexchange_0000F.jsonl.gz:837131",
"question_score": "19",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455713"
}
|
7983ddd571898c7642ec15cc9eb38ed32f4a5c60
|
Stackoverflow Stackexchange
Q: Docker-compose specify config file I'm new to docker and now I want to use docker-compose. I would like to provide the docker-compose.yml script the config file with host/port, maybe credentials and other cassandra configuration.
DockerHub link.
How to specify it in the compose script:
cassandra:
image: bitnami/cassandra:latest
A: You can do it using Docker compose environment variables(https://docs.docker.com/compose/environment-variables/#substituting-environment-variables-in-compose-files). You can also specify a separate environment file with environment variables.
|
Q: Docker-compose specify config file I'm new to docker and now I want to use docker-compose. I would like to provide the docker-compose.yml script the config file with host/port, maybe credentials and other cassandra configuration.
DockerHub link.
How to specify it in the compose script:
cassandra:
image: bitnami/cassandra:latest
A: You can do it using Docker compose environment variables(https://docs.docker.com/compose/environment-variables/#substituting-environment-variables-in-compose-files). You can also specify a separate environment file with environment variables.
A: Apparently, including a file outside of the scope of the image build, such as a config file, has been a major point of discussion (and perhaps some tension) between the community and the folks at Docker. A lot of the developers in that linked issue recommended adding config files in a folder as a volume (unfortunately, you cannot add an individual file).
It would look something like:
volumes:
- ./config_folder:./config_folder
Where config_folder would be at the root of your project, at the same level as the Dockerfile.
A: If Docker compose environment cannot solved your problem, you should create a new image from the original image with COPY to override the file.
Dockerfile:
From orginal_image:xxx
COPY local_conffile in_image_dir/conf_dir/
|
stackoverflow
|
{
"language": "en",
"length": 188,
"provenance": "stackexchange_0000F.jsonl.gz:837162",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455821"
}
|
f6c326332a8667ac16473531168cff13990eae32
|
Stackoverflow Stackexchange
Q: How to get Order key for creating custom order return url in WooCommerce This is the code that I am using to get a custom Order return URL:
global $woocommerce;
$test_order = new WC_Order($order_id);
$test_order_key = $test_order->order_key;
$returnURL = site_url().'/checkout/order-received/7140/'.$test_order_key;
The example URL that I need is: http://www.example.com/checkout/order-received/[order_number]/key=[wc-order-key]
How do I get [wc-order-key]?
Thanks.
A: There is 2 ways to get the order key:
1) From an instance of WC_Order object class using the method get_order_key(), this way:
// Get an instance of the WC_Order object
$order_obj = WC_get_order($order_id);
// Get the order key
$order_key = $test_order->get_order_key();
$returnURL = site_url().'/checkout/order-received/'.$order_id.'/'.$order_key;
2) Using the WordPress get_post_meta() function from the $order_id, this way:
// Get the order key
$order_key = get_post_meta( $order_id, '_order_key', true);
$returnURL = site_url().'/checkout/order-received/'.$order_id.'/'.$order_key;
The Order number is the Order ID in general…
|
Q: How to get Order key for creating custom order return url in WooCommerce This is the code that I am using to get a custom Order return URL:
global $woocommerce;
$test_order = new WC_Order($order_id);
$test_order_key = $test_order->order_key;
$returnURL = site_url().'/checkout/order-received/7140/'.$test_order_key;
The example URL that I need is: http://www.example.com/checkout/order-received/[order_number]/key=[wc-order-key]
How do I get [wc-order-key]?
Thanks.
A: There is 2 ways to get the order key:
1) From an instance of WC_Order object class using the method get_order_key(), this way:
// Get an instance of the WC_Order object
$order_obj = WC_get_order($order_id);
// Get the order key
$order_key = $test_order->get_order_key();
$returnURL = site_url().'/checkout/order-received/'.$order_id.'/'.$order_key;
2) Using the WordPress get_post_meta() function from the $order_id, this way:
// Get the order key
$order_key = get_post_meta( $order_id, '_order_key', true);
$returnURL = site_url().'/checkout/order-received/'.$order_id.'/'.$order_key;
The Order number is the Order ID in general…
|
stackoverflow
|
{
"language": "en",
"length": 135,
"provenance": "stackexchange_0000F.jsonl.gz:837170",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455859"
}
|
c3d962d74af381819e9005580b9dfe69e4974baa
|
Stackoverflow Stackexchange
Q: Spring security login page - images i'm a newbie. I'm trying to developp a webapp using Spring.
I have a custom login page where i want to insert an image. How can i do? I've red all of the questions on SO but no one worked for me...
I don't know why i can't see the image.
This is my project structure :
- src/main/resources
- images
-logo.png
+ static
- template
-login.html
that's the image in login.html:
<img src="/resources/images/logo.png" align="left" />
could be better using thymeleaf taglib th:?
that's securityConfig :
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
A: Your request to get the image will be blocked because the user is not authenticated. You have to whitelist the URLs to your static resources (Javascript files, images, CSS files etc).
This will work:
@Override
protected void configure(HttpSecurity http) throws Exception {
String[] staticResources = {
"/css/**",
"/images/**",
"/fonts/**",
"/scripts/**",
};
http
.authorizeRequests()
.antMatchers(staticResources).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
Also, my folder structure is:
/src/main/resources/static/images/...
/src/main/resources/static/scripts/...
My code works for this setup.
|
Q: Spring security login page - images i'm a newbie. I'm trying to developp a webapp using Spring.
I have a custom login page where i want to insert an image. How can i do? I've red all of the questions on SO but no one worked for me...
I don't know why i can't see the image.
This is my project structure :
- src/main/resources
- images
-logo.png
+ static
- template
-login.html
that's the image in login.html:
<img src="/resources/images/logo.png" align="left" />
could be better using thymeleaf taglib th:?
that's securityConfig :
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
A: Your request to get the image will be blocked because the user is not authenticated. You have to whitelist the URLs to your static resources (Javascript files, images, CSS files etc).
This will work:
@Override
protected void configure(HttpSecurity http) throws Exception {
String[] staticResources = {
"/css/**",
"/images/**",
"/fonts/**",
"/scripts/**",
};
http
.authorizeRequests()
.antMatchers(staticResources).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
Also, my folder structure is:
/src/main/resources/static/images/...
/src/main/resources/static/scripts/...
My code works for this setup.
A: You should hold your images under static folder it's default directory for resources. For example move images folder there and modify HTML:
<img src="images/logo.png" align="left" />
or this if you want append some variables in image's path:
<img th:src="images/logo.png" align="left" />
|
stackoverflow
|
{
"language": "en",
"length": 229,
"provenance": "stackexchange_0000F.jsonl.gz:837188",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455900"
}
|
e300df2dba16c063e0f828b6c2d15a767e6f2fcc
|
Stackoverflow Stackexchange
Q: Getting Windows Build Number programmatically Using C#, how can I get the Windows build number or OS Build number as shown in the About window? This is different from the version number: for Windows 10 Creator Update, the Build Number would be 1703 and the OS Build would be 15063.296.
I can't find anything relevant in Environment.OSVersion and this linked question (Getting Windows OS version programmatically) is only about getting the version number (10 in this case)
A: The following gets the Build number:
Environment.OSVersion.Version.Build
|
Q: Getting Windows Build Number programmatically Using C#, how can I get the Windows build number or OS Build number as shown in the About window? This is different from the version number: for Windows 10 Creator Update, the Build Number would be 1703 and the OS Build would be 15063.296.
I can't find anything relevant in Environment.OSVersion and this linked question (Getting Windows OS version programmatically) is only about getting the version number (10 in this case)
A: The following gets the Build number:
Environment.OSVersion.Version.Build
|
stackoverflow
|
{
"language": "en",
"length": 86,
"provenance": "stackexchange_0000F.jsonl.gz:837198",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455928"
}
|
9b9c93e6a0d13dd4654dc9871f385886ea619b15
|
Stackoverflow Stackexchange
Q: How to change WebKit macro to false from CSS or JS The new WebKit feature for loading large images asynchronously introduced in Safari Tech Preview 26 causes mjpg-streamer webcam based streams to flicker, the boolean property that defaults to true, largeImageAsyncDecodingEnabled, causes this issue. Link to the property definition
I am trying to find a way to set this property to false on the html page with CSS or JS. Is this even possible? Or is there another way to do it?
This is for OctoPrint running OctoPi for a 3D printer server. I found through trial and error, any image over 453x453 px is loaded asynchronously and causes the flicker to happen; it's akin to an annoying strobe light effect. I am using a resolution of 1280x720 for the webcam, and there is no issue before tech preview 26.
Thank you for the help!
A: The issue has now been fixed in Safari Tech Preview 37. https://trac.webkit.org/changeset/219876/webkit/
|
Q: How to change WebKit macro to false from CSS or JS The new WebKit feature for loading large images asynchronously introduced in Safari Tech Preview 26 causes mjpg-streamer webcam based streams to flicker, the boolean property that defaults to true, largeImageAsyncDecodingEnabled, causes this issue. Link to the property definition
I am trying to find a way to set this property to false on the html page with CSS or JS. Is this even possible? Or is there another way to do it?
This is for OctoPrint running OctoPi for a 3D printer server. I found through trial and error, any image over 453x453 px is loaded asynchronously and causes the flicker to happen; it's akin to an annoying strobe light effect. I am using a resolution of 1280x720 for the webcam, and there is no issue before tech preview 26.
Thank you for the help!
A: The issue has now been fixed in Safari Tech Preview 37. https://trac.webkit.org/changeset/219876/webkit/
A: You can't override the macro. But you may force the rest of the page to load after the image loaded.
By using CSS/JS? Why? Use plain HTML
There is a link rel preload markup exists. Read more here on W3C
The important parts are
The preload keyword on link elements provides a declarative fetch primitive that addresses the above use case of initiating an early fetch and separating fetching from resource execution. As such, preload keyword serves as a low-level primitive that enables applications to build custom resource loading and execution behaviors without hiding resources from the user agent and incurring delayed resource fetching penalties.
How to achieve that
<!-- preload stylesheet resource via declarative markup -->
<link rel="preload" href="url" as="image">
<!-- or, preload stylesheet resource via JavaScript -->
<script>
var res = document.createElement("link");
res.rel = "preload";
res.as = "image";
res.href = "url";
document.head.appendChild(res);
</script>
If the load was successful, queue a task to fire a simple event named load at the link element. Otherwise, queue a task to fire a simple event named error at the link element.
if a resource is fetched via a preload link and the response contains a no-cache directive, the fetched response is retained by the user agent and is made immediately available when fetched with a matching same navigation request at a later time
Update
Based on comments discussion we hade,
You have 2 options.
1. Try to change the img tag to video since the issue only affect img tag.
Use the following code for that
$(document).ready(function(){
var newTag=$('img')[0].cloneNode(true);
newTag = $(newTag).wrap("<video></video>")[0].parentNode;
newTag = $(newTag).wrap("<div></div>")[0];
newTag = newTag.parentNode.innerHTML;
newTag = newTag.replace("img","source");
$('img').replaceWith(newTag);
});
*Force the user to choose another browser. That is if you detected it is Safari tech preview 26 by using window.userAgent, then navigate them to another page saying that this version of browser is not supported because of compatibility issues. Please downgrade/ choose another browser. - note that this may be temporary. Since it is a known issue(the flickering), they will provide a fix in the future.
Special thanks to To markdown for converting HTML to Markdown within fraction of seconds (I don't have any affiliation)
A: I can't see any client side hack that won't turn into a full blown construction. You might be able to hack around it, but reporting it to WebKit seems to be the best way forward.
WebKit-bug 170640 is what stopped largeImageAsyncDecodingEnabled from being enabled. It was also causing a flickering. Once that was fixed, they enabled it by default. This however suggest that there is still an issue.
HTTP headers retrieved from GitHub
This might be helpful if anyone decides to submit a bug report to WebKit.
The standard header is the following
mjpg-streamer/mjpg-streamer-experimental/plugins/output_http/httpd.h
#define STD_HEADER "Connection: close\r\n" \
"Server: MJPG-Streamer/0.2\r\n" \
"Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0\r\n" \
"Pragma: no-cache\r\n" \
"Expires: Mon, 3 Jan 2000 12:34:56 GMT\r\n"
Then for the actual stream of images:
mjpg-streamer-experimental/plugins/output_http/httpd.c#L466
sprintf(buffer, "HTTP/1.0 200 OK\r\n" \
"Access-Control-Allow-Origin: *\r\n" \
STD_HEADER \
"Content-Type: multipart/x-mixed-replace;boundary=" BOUNDARY "\r\n" \
"\r\n" \
"--" BOUNDARY "\r\n");
On a small note, there already seems to be a settings/toggle in WebKit to enable and/or disable the largeImageAsyncDecodingEnabled, check it out here. I doubt this is accessible through Safari's UI tho, and doesn't solve the issue without user interaction.
|
stackoverflow
|
{
"language": "en",
"length": 706,
"provenance": "stackexchange_0000F.jsonl.gz:837207",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455954"
}
|
779f0637a90e195817c6de3d162d3d3c012e1ee5
|
Stackoverflow Stackexchange
Q: Resetting byte[] buffer to zeros? In the following code for sockets, I declare a byte buffer and listen for client messages in a loop:
// Create some buffer
byte[] buffer = new byte[512];
while (true)
{
// Listen for messages from Client
int length = socket.getInputStream().read(buffer);
if (length != -1)
System.out.println(new String(buffer));
else
break;
// Reset buffer here to zeros?
}
Each time I'd require to reset the contents of buffer to receive a new message. What's the proper way to do this?
A: You don't need to reset the buffer, you need to a String constructor that does not go past the end of the part of the buffer that has the bytes received:
if (length != -1) {
System.out.println(new String(buffer, 0, length));
}
Now your code will work even if the buffer is dirty.
Note: For better portability pass the desired Charset to String constructor. Otherwise the String you construct may not match the string that has been transmitted to you through the socket.
|
Q: Resetting byte[] buffer to zeros? In the following code for sockets, I declare a byte buffer and listen for client messages in a loop:
// Create some buffer
byte[] buffer = new byte[512];
while (true)
{
// Listen for messages from Client
int length = socket.getInputStream().read(buffer);
if (length != -1)
System.out.println(new String(buffer));
else
break;
// Reset buffer here to zeros?
}
Each time I'd require to reset the contents of buffer to receive a new message. What's the proper way to do this?
A: You don't need to reset the buffer, you need to a String constructor that does not go past the end of the part of the buffer that has the bytes received:
if (length != -1) {
System.out.println(new String(buffer, 0, length));
}
Now your code will work even if the buffer is dirty.
Note: For better portability pass the desired Charset to String constructor. Otherwise the String you construct may not match the string that has been transmitted to you through the socket.
A: Agree with dasblinkenlight answers, but to answer the question itself (how to reset an array), you can use Arrays.fill to set a value to every cell
byte[] array = new byte[10];
Arrays.fill(array, (byte)0);
|
stackoverflow
|
{
"language": "en",
"length": 201,
"provenance": "stackexchange_0000F.jsonl.gz:837217",
"question_score": "12",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455987"
}
|
87bf713f9f49caecde9d5448be87a0f970941ac0
|
Stackoverflow Stackexchange
Q: Kingfisher can't setImage for UIButton code is:
let url = URL(string: (user?.avatar)!)!
print(url.absoluteString)
let resource = ImageResource(downloadURL: url, cacheKey: "my_avatar")
testUIButton.kf.setImage(with: resource, for:.normal)
The result is testUIButton display TintColor,No Image will be displayed.
A: Try To Set UIButton Type Custom. This works for me.
let btnCustom = UIButton(type: .custom)
if let imgURL = URL(string: imgURLString) {
btnCustom.kf.setImage(with: imgURL, for: .normal)
} else {
btnCustom.setImage(UIImage(named: "img_user"), for: .normal)
}
btnCustom.cornerRadius = 15
btnCustom.clipsToBounds = true
btnCustom.addTarget(self, action: #selector(self.customAction)), for: .touchUpInside)
view.addSubview(btnCustom)
|
Q: Kingfisher can't setImage for UIButton code is:
let url = URL(string: (user?.avatar)!)!
print(url.absoluteString)
let resource = ImageResource(downloadURL: url, cacheKey: "my_avatar")
testUIButton.kf.setImage(with: resource, for:.normal)
The result is testUIButton display TintColor,No Image will be displayed.
A: Try To Set UIButton Type Custom. This works for me.
let btnCustom = UIButton(type: .custom)
if let imgURL = URL(string: imgURLString) {
btnCustom.kf.setImage(with: imgURL, for: .normal)
} else {
btnCustom.setImage(UIImage(named: "img_user"), for: .normal)
}
btnCustom.cornerRadius = 15
btnCustom.clipsToBounds = true
btnCustom.addTarget(self, action: #selector(self.customAction)), for: .touchUpInside)
view.addSubview(btnCustom)
A: Final result is we must set a placeholder image for ImageButton.It seems to be same as in Android dev envrionment.
A: Try to use modifier as below:
let modifier = AnyImageModifier { return $0.withRenderingMode(.alwaysOriginal) }
button.kf.setImage(with: url, for: .normal, placeholder: nil, options: [.imageModifier(modifier)], progressBlock: nil, completionHandler: nil)
|
stackoverflow
|
{
"language": "en",
"length": 129,
"provenance": "stackexchange_0000F.jsonl.gz:837222",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44455993"
}
|
5a29399f4ab8423cdcefdfd519405a0cf8643409
|
Stackoverflow Stackexchange
Q: IDistributedCache Removing keys I've recently started using the sql version of IDistributedCache on a dotnet core web api.
How would you remove/invalidate a set of keys for say a specific user?
I.e: I structured the keys to follow this convention:
/users/{userId}/Key1
/users/{userId}/Key2
/users/{userId}/Section/Key3
I cannot find any method to remove all keys starting with: /users/{userId}
How do you remove more than one item from the IDistributedCache at a time?
A: Removing via SQL statement is not a good solution because the webapp process performs some kind of lock. For example, I had to manually stop after three minutes and half the following simple query Delete from SqlSession with only two records.
So I ended up this way: I retrieve data with a simple query like
Select Id from SqlSession where Id like 'MyIdGroup%'
or with Entity framework
var cacheElementsToDelete = await _dbContext.SQLSessions
.Where(a => a.Id.StartsWith("MyIdGroup"))
.ToListAsync();
Then I use the method of the IDistributedCache to remove each item
foreach (var item in cacheElementsToDelete)
{
await _cache.RemoveAsync(item.Id);
}
|
Q: IDistributedCache Removing keys I've recently started using the sql version of IDistributedCache on a dotnet core web api.
How would you remove/invalidate a set of keys for say a specific user?
I.e: I structured the keys to follow this convention:
/users/{userId}/Key1
/users/{userId}/Key2
/users/{userId}/Section/Key3
I cannot find any method to remove all keys starting with: /users/{userId}
How do you remove more than one item from the IDistributedCache at a time?
A: Removing via SQL statement is not a good solution because the webapp process performs some kind of lock. For example, I had to manually stop after three minutes and half the following simple query Delete from SqlSession with only two records.
So I ended up this way: I retrieve data with a simple query like
Select Id from SqlSession where Id like 'MyIdGroup%'
or with Entity framework
var cacheElementsToDelete = await _dbContext.SQLSessions
.Where(a => a.Id.StartsWith("MyIdGroup"))
.ToListAsync();
Then I use the method of the IDistributedCache to remove each item
foreach (var item in cacheElementsToDelete)
{
await _cache.RemoveAsync(item.Id);
}
|
stackoverflow
|
{
"language": "en",
"length": 168,
"provenance": "stackexchange_0000F.jsonl.gz:837226",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456001"
}
|
e45f28cc3d9dc5b89cfad0778367934a23fd5d25
|
Stackoverflow Stackexchange
Q: Android NDK Error. Not able to build the project I am getting the following specified error,
E:\SDK\ndk-bundle\build\core\setup-app-platform.mk
Error:(115) *** Android NDK: Aborting . Stop.
Error:Execution failed for task ':un7zip:compileReleaseNdk'.
com.android.ide.common.process.ProcessException: Error while executing process E:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=E:\appRizort\RizortCardboard\un7zip\build\intermediates\ndk\release\Android.mk APP_PLATFORM=android-25 NDK_OUT=E:\appRizort\RizortCardboard\un7zip\build\intermediates\ndk\release\obj NDK_LIBS_OUT=E:\appRizort\RizortCardboard\un7zip\build\intermediates\ndk\release\lib APP_ABI=armeabi-v7a,armeabi,x86,arm64-v8a}
A: Your NDK_PROJECT_PATH is null, if your path to the project folder contains white-space, it may cause this issue.
|
Q: Android NDK Error. Not able to build the project I am getting the following specified error,
E:\SDK\ndk-bundle\build\core\setup-app-platform.mk
Error:(115) *** Android NDK: Aborting . Stop.
Error:Execution failed for task ':un7zip:compileReleaseNdk'.
com.android.ide.common.process.ProcessException: Error while executing process E:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=E:\appRizort\RizortCardboard\un7zip\build\intermediates\ndk\release\Android.mk APP_PLATFORM=android-25 NDK_OUT=E:\appRizort\RizortCardboard\un7zip\build\intermediates\ndk\release\obj NDK_LIBS_OUT=E:\appRizort\RizortCardboard\un7zip\build\intermediates\ndk\release\lib APP_ABI=armeabi-v7a,armeabi,x86,arm64-v8a}
A: Your NDK_PROJECT_PATH is null, if your path to the project folder contains white-space, it may cause this issue.
A: APP_PLATFORM that you specify when you build the native part of your project with NDK is very important. The story is described at length in the NDK guide:
This variable contains the minimum Android platform version you want to support. For example, a value of android-15 specifies that your library uses APIs that are not available below Android 4.0.3 (API level 15) and can't be used on devices running a lower platform version. For a complete list of platform names and corresponding Android system images, see Android NDK Native APIs.
Instead of changing this flag directly, you should set the minSdkVersion property in the defaultConfig or productFlavors blocks of your module-level build.gradle file. This makes sure your library is used only by apps installed on devices running an adequate version of Android. The ndk-build toolchain uses the following logic to choose the minimum platform version for your library based the ABI you're building and the minSdkVersion you specify:
*
*If there exists a platform version for the ABI equal to minSdkVersion, ndk-build uses that version.
*Otherwise, if there exists platform versions lower than minSdkVersion for the ABI, ndk-build uses the highest of those platform versions. This is a reasonable choice because a missing platform version typically means that there were no changes to the native platform APIs since the previous available version.
*Otherwise, ndk-build uses the next available platform version higher than minSdkVersion.
NDK does not have separate android-25 platform. You can choose android-24 or (with r15 beta), android-26, if your minimal supported platform is O. If your minSdkVersion is less, or if in doubt, choose lower platform for NDK, because NDK platforms are upwards-compatible.
|
stackoverflow
|
{
"language": "en",
"length": 339,
"provenance": "stackexchange_0000F.jsonl.gz:837230",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456011"
}
|
313c688625cb16d5dc204f8629ccf03e81cf91dd
|
Stackoverflow Stackexchange
Q: How to understand errors(combined) at Google Spanner Monitor? Google Spanner monitor provides helpful information about databases and instance. Operation per seconds view contains errors(combined) measure that is not clear for me.
How to understand errors(combined)?
A: You can make a dashboard in Stackdriver (https://app.google.stackdriver.com) that will break down the errors slightly. We're working on a resources page for Cloud Spanner right now that will actually break them down by error code, but before that, you can go to Resources > Metrics Explorer and filter by response status:
You'll occasionally get error responses using the Cloud Spanner API; FAILED_PRECONDITION is somewhat common if you have a lot of transactions happening simultaneously that invalidate other transactions.
|
Q: How to understand errors(combined) at Google Spanner Monitor? Google Spanner monitor provides helpful information about databases and instance. Operation per seconds view contains errors(combined) measure that is not clear for me.
How to understand errors(combined)?
A: You can make a dashboard in Stackdriver (https://app.google.stackdriver.com) that will break down the errors slightly. We're working on a resources page for Cloud Spanner right now that will actually break them down by error code, but before that, you can go to Resources > Metrics Explorer and filter by response status:
You'll occasionally get error responses using the Cloud Spanner API; FAILED_PRECONDITION is somewhat common if you have a lot of transactions happening simultaneously that invalidate other transactions.
|
stackoverflow
|
{
"language": "en",
"length": 115,
"provenance": "stackexchange_0000F.jsonl.gz:837231",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456015"
}
|
88b1d99695480d49de6ddb1a65c9f56b31488875
|
Stackoverflow Stackexchange
Q: Laravel; how make setLocale permanent? I've my home route
Route::get('/', 'HomeController@index')->name('home');
And a specific route to change language
Route::get('/setLocale/{locale}', 'HomeController@setLocale')->name('setLocale');
In HomeController->setLocale($locale) I check if $locale is a valid locale, then simply do
\App::setLocale($locale);
Then redirect to home.
Here, in HomeController->index() I verify locale using
$locale = \App::getLocale();
The problem is that after user CHANGES the locale, the app set the new locale, redirect, but the locale detected is still the DEFAULT locale, not the new one setup by the user.
How / where / when can I make persistent the change to app locale?
I thinked Laravel was setting a locale cookies or something when using setLocale and re-reading it when using getLocale but now I think it's not this the way Laravel works.
I ask, again: how can I set app locale so that is preserved after page change?
A: setlocale only works for the current request. If you want the value to be remembered, you will have to set a cookie manualy.
I recommend using a middleware to do this.
|
Q: Laravel; how make setLocale permanent? I've my home route
Route::get('/', 'HomeController@index')->name('home');
And a specific route to change language
Route::get('/setLocale/{locale}', 'HomeController@setLocale')->name('setLocale');
In HomeController->setLocale($locale) I check if $locale is a valid locale, then simply do
\App::setLocale($locale);
Then redirect to home.
Here, in HomeController->index() I verify locale using
$locale = \App::getLocale();
The problem is that after user CHANGES the locale, the app set the new locale, redirect, but the locale detected is still the DEFAULT locale, not the new one setup by the user.
How / where / when can I make persistent the change to app locale?
I thinked Laravel was setting a locale cookies or something when using setLocale and re-reading it when using getLocale but now I think it's not this the way Laravel works.
I ask, again: how can I set app locale so that is preserved after page change?
A: setlocale only works for the current request. If you want the value to be remembered, you will have to set a cookie manualy.
I recommend using a middleware to do this.
A: I did that by using a middleware. Here's my code:
LanguageMiddleware:
public function handle($request, Closure $next)
{
if(session()->has('locale'))
app()->setLocale(session('locale'));
else
app()->setLocale(config('app.locale'));
return $next($request);
}
remember to register your middleware :)
The users are able to change the language, with a simple GET-Route:
Route::get('/lang/{key}', function ($key) {
session()->put('locale', $key);
return redirect()->back();
});
Hopefully that helps you :)
Apparently, there are some changes in Laravel 7.0!
If you are using the code above, please change from a BeforeMiddleware to a AfterMiddleware! (see https://laravel.com/docs/7.x/middleware)
If you don't do this, the value of session('locale') will always be null!
|
stackoverflow
|
{
"language": "en",
"length": 269,
"provenance": "stackexchange_0000F.jsonl.gz:837235",
"question_score": "12",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456027"
}
|
a19c2f5c53b1c3d49e2c7886ffe60904e389ef2c
|
Stackoverflow Stackexchange
Q: Is there a findall in Scala maps? In a Scala Map, how do I get all keys in a Map that have the same value?
For example in my Map I have 3 keys which have the value 27
Eg:
large -> 27
indispensable -> 27
most -> 27
I tried
val adj1value = htAdjId.find(_._2 == value1).getOrElse(default)._1
but that gives me only the first key "large" (as is the definition of find). I searched a lot but I am not able to find a "findall" function. Does it exist in Scala? If not, can someone please advice me on how to solve this problem?
A: You can filter the collection and extract all keys using keys:
val map = Map("h" -> 27, "b" -> 2, "c" -> 27)
map.filter { case (key, value) => value == 27 }.keys
Yields
res0: Iterable[String] = Set(h, c)
Though I'd argue that if you need to iterate the entire Map each time, perhaps it isn't the right data structure to begin with, perhaps a List[(String, Int)] will suffice and save the overhead incurred by using a Map.
|
Q: Is there a findall in Scala maps? In a Scala Map, how do I get all keys in a Map that have the same value?
For example in my Map I have 3 keys which have the value 27
Eg:
large -> 27
indispensable -> 27
most -> 27
I tried
val adj1value = htAdjId.find(_._2 == value1).getOrElse(default)._1
but that gives me only the first key "large" (as is the definition of find). I searched a lot but I am not able to find a "findall" function. Does it exist in Scala? If not, can someone please advice me on how to solve this problem?
A: You can filter the collection and extract all keys using keys:
val map = Map("h" -> 27, "b" -> 2, "c" -> 27)
map.filter { case (key, value) => value == 27 }.keys
Yields
res0: Iterable[String] = Set(h, c)
Though I'd argue that if you need to iterate the entire Map each time, perhaps it isn't the right data structure to begin with, perhaps a List[(String, Int)] will suffice and save the overhead incurred by using a Map.
A: You can treat the map as a Iterable[K,V] then groupBy the value like this..
@ Map(
"large" -> 27,
"indispensable" -> 27,
"most" -> 27
).groupBy(_._2).mapValues(_.keys)
res4: Map[Int, Iterable[String]] = Map(27 -> Set(
"large",
"indispensable",
"most"))
A: [answered by a friend of mine offline] Hashmaps are usually built to do only the forward lookup efficiently. Unless you know that the underlying data structure used in the hashmap supports this, you probably don't want to do this "reverse lookup" because it will be very inefficient.
Consider putting your data into a bi-directional map or "bi-map" from the start if you are going to access it in both directions. OR, use two hashmaps: one in regular direction, one inverted (values become keys, keys become values) OR use different data structure altogether.
i.e two maps is a good idea if the map is large or you're going to be doing this kind of check a lot. Otherwise try filter instead of find
|
stackoverflow
|
{
"language": "en",
"length": 344,
"provenance": "stackexchange_0000F.jsonl.gz:837255",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456083"
}
|
04978be6ac245cdde4ce4856f37ba107a2283e28
|
Stackoverflow Stackexchange
Q: How to serialize a C# DateTime as a Javascript Date using Web API In MVC, you can do something like this:
public ActionResult Index()
{
return Json(new List<DateTime> { DateTime.Parse("19/02/2017") },
JsonRequestBehavior.AllowGet);
}
And the returned value is ["\/Date(1487458800000)\/"], which is a Javascript Date object.
However, using WebAPI like this:
public IEnumerable<DateTime> Get()
{
return new List<DateTime> { DateTime.Parse("19/02/2017") };
}
The returned value is <dateTime>2017-02-19T00:00:00</dateTime>
Is there any way that I can serialize a DateTime as a Javascript Date object using WebApi?
A: If you change your Accept header on your request to application/json you get:
["2017-06-09T08:14:13.7729697-03:00"]
Try with a tool like Postman.
In angular, you can do something like:
var config = { headers: {
'Accept': 'application/json',
}
};
$http.get("/api/values", config);
|
Q: How to serialize a C# DateTime as a Javascript Date using Web API In MVC, you can do something like this:
public ActionResult Index()
{
return Json(new List<DateTime> { DateTime.Parse("19/02/2017") },
JsonRequestBehavior.AllowGet);
}
And the returned value is ["\/Date(1487458800000)\/"], which is a Javascript Date object.
However, using WebAPI like this:
public IEnumerable<DateTime> Get()
{
return new List<DateTime> { DateTime.Parse("19/02/2017") };
}
The returned value is <dateTime>2017-02-19T00:00:00</dateTime>
Is there any way that I can serialize a DateTime as a Javascript Date object using WebApi?
A: If you change your Accept header on your request to application/json you get:
["2017-06-09T08:14:13.7729697-03:00"]
Try with a tool like Postman.
In angular, you can do something like:
var config = { headers: {
'Accept': 'application/json',
}
};
$http.get("/api/values", config);
A: You can use that format with JavaScript though:
var myDate = new Date("2017-02-19T00:00:00");
|
stackoverflow
|
{
"language": "en",
"length": 138,
"provenance": "stackexchange_0000F.jsonl.gz:837256",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456084"
}
|
763354ad9ef232895450c601a9e3b075186e41b8
|
Stackoverflow Stackexchange
Q: Web Speech API has "Network Error" I'm using Web Speech API to recognize user voice. Recently I meet the Error that I cannot recognize anything. Check the console on Chrome I get SpeechRecognitionError
currentTarget: SpeechRecognition
defaultPrevented: false
error: "network"
type: "error"
I have working network. And it just happen to my chrome, my coworker chrome is working fine.
I suspect this bug is because of chrome itself, is there any work around for it?
|
Q: Web Speech API has "Network Error" I'm using Web Speech API to recognize user voice. Recently I meet the Error that I cannot recognize anything. Check the console on Chrome I get SpeechRecognitionError
currentTarget: SpeechRecognition
defaultPrevented: false
error: "network"
type: "error"
I have working network. And it just happen to my chrome, my coworker chrome is working fine.
I suspect this bug is because of chrome itself, is there any work around for it?
|
stackoverflow
|
{
"language": "en",
"length": 75,
"provenance": "stackexchange_0000F.jsonl.gz:837333",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456314"
}
|
9c543b2cb73b00b020d5d1e4b21a234f3f75b440
|
Stackoverflow Stackexchange
Q: apache adds extra parameters to url I installed apache2 on my debian 8 server, then I created a file, named 12.html in the apache web root.
<html>
<a href="sdf.html?sdf=sdf">sdf</a>
</html>
now when I click on sdf link, it adds an extra parameter to the url,
http://MY_SERVER_ADDRESS/sdf.html?sdf=sdf&1534-D83A_1933715A=51066fe70b253674b08e33752e6dd6b2a3779812
as you can see, unknown added key is:
1534-D83A_1933715A
and it's value is:
51066fe70b253674b08e33752e6dd6b2a3779812
I searched the net and found out that many sites have this unknown parameter!!
what is it? I really want to remove it.
I tried reinstalling php and apache but the problem still exists.
A: After many many researches, I foudn that the Cyberoam firewall adds this parameter to our urls.
this completely out of our server and depends on firewall configurations.
I changed firewall configurations and problem solved.
|
Q: apache adds extra parameters to url I installed apache2 on my debian 8 server, then I created a file, named 12.html in the apache web root.
<html>
<a href="sdf.html?sdf=sdf">sdf</a>
</html>
now when I click on sdf link, it adds an extra parameter to the url,
http://MY_SERVER_ADDRESS/sdf.html?sdf=sdf&1534-D83A_1933715A=51066fe70b253674b08e33752e6dd6b2a3779812
as you can see, unknown added key is:
1534-D83A_1933715A
and it's value is:
51066fe70b253674b08e33752e6dd6b2a3779812
I searched the net and found out that many sites have this unknown parameter!!
what is it? I really want to remove it.
I tried reinstalling php and apache but the problem still exists.
A: After many many researches, I foudn that the Cyberoam firewall adds this parameter to our urls.
this completely out of our server and depends on firewall configurations.
I changed firewall configurations and problem solved.
|
stackoverflow
|
{
"language": "en",
"length": 130,
"provenance": "stackexchange_0000F.jsonl.gz:837365",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456408"
}
|
b3794db6e03e1e4143a6151ef15e0351fd05b586
|
Stackoverflow Stackexchange
Q: PHP mail function not working in godaddy account The code is shown below
<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";
if(mail($to,$subject,$txt,$headers))
{
echo "success";
}
else{
echo "failure";
}
?>
This code works perfectly in my server but it moved to GoDaddy server it shows the success message but i didn't get the mail.
|
Q: PHP mail function not working in godaddy account The code is shown below
<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";
if(mail($to,$subject,$txt,$headers))
{
echo "success";
}
else{
echo "failure";
}
?>
This code works perfectly in my server but it moved to GoDaddy server it shows the success message but i didn't get the mail.
|
stackoverflow
|
{
"language": "en",
"length": 69,
"provenance": "stackexchange_0000F.jsonl.gz:837394",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456503"
}
|
9cd8db1d990eb8c31202416cb9ae3287f9178170
|
Stackoverflow Stackexchange
Q: rails query not in statement formatting correct I do this:
check1 = inquiries.select("question_id").where(:membership_id => self.id)
This returny a active Record array with entries like this:
#<ActiveRecord::AssociationRelation [#<Inquiry id: nil, question_id: 21113>,
Now I want to select in a secon query all questions which are not in the inqueries
Tried this:
lesson.questions.where("NOT IN ?",check1)
But that does not work, probably because the first query returns an active record array with 2 values for each object?
how could look like a solution?
A: Make use of pluck
check1 = inquiries.where(membership_id: self.id).pluck(:question_id)
#=> [1, 2, 3] # List of ids
lesson.questions.where("id NOT IN (?)", check1)
# OR
lesson.questions.where.not(id: check1)
NOTE: If you have an association between lesson and inquiries you can make use of joins and get the result in one query itself.
|
Q: rails query not in statement formatting correct I do this:
check1 = inquiries.select("question_id").where(:membership_id => self.id)
This returny a active Record array with entries like this:
#<ActiveRecord::AssociationRelation [#<Inquiry id: nil, question_id: 21113>,
Now I want to select in a secon query all questions which are not in the inqueries
Tried this:
lesson.questions.where("NOT IN ?",check1)
But that does not work, probably because the first query returns an active record array with 2 values for each object?
how could look like a solution?
A: Make use of pluck
check1 = inquiries.where(membership_id: self.id).pluck(:question_id)
#=> [1, 2, 3] # List of ids
lesson.questions.where("id NOT IN (?)", check1)
# OR
lesson.questions.where.not(id: check1)
NOTE: If you have an association between lesson and inquiries you can make use of joins and get the result in one query itself.
A: Can you try the following?
check1 = inquiries.where(membership_id: self.id).select(:question_id)
lesson.questions.where.not(id: check1)
|
stackoverflow
|
{
"language": "en",
"length": 143,
"provenance": "stackexchange_0000F.jsonl.gz:837426",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456574"
}
|
8c058d3b5c25038f322f117d5bf305177697aa86
|
Stackoverflow Stackexchange
Q: HTTPS with Snap in production I have the following configuration for my Snap
Local.withPool 2 $ \pool -> do
Local.parallel_ pool [ httpServe (setPort (read port) config) Main.skite
--, httpServe (setPort 8003 config) Ws.brz
]
--httpServe (setPort 8003 config) Ws.brz
where
config =
setErrorLog ConfigNoLog $
setAccessLog ConfigNoLog $
setSSLPort 443 $
setSSLCert "/etc/letsencrypt/../cert.pem" $
setSSLKey "/etc/letsencrypt/../privkey.pem" $
defaultConfig
After i am building and uploading, all the certs are in the place, yet the https:// won't work. Do you have any clues?
Thanks
A: I did it:
First of all i added this two lines to the config
setSSLBind "0.0.0.0" $
setSSLChainCert False $
After this, is very important to build with ghc -threaded and this will get it up and running
|
Q: HTTPS with Snap in production I have the following configuration for my Snap
Local.withPool 2 $ \pool -> do
Local.parallel_ pool [ httpServe (setPort (read port) config) Main.skite
--, httpServe (setPort 8003 config) Ws.brz
]
--httpServe (setPort 8003 config) Ws.brz
where
config =
setErrorLog ConfigNoLog $
setAccessLog ConfigNoLog $
setSSLPort 443 $
setSSLCert "/etc/letsencrypt/../cert.pem" $
setSSLKey "/etc/letsencrypt/../privkey.pem" $
defaultConfig
After i am building and uploading, all the certs are in the place, yet the https:// won't work. Do you have any clues?
Thanks
A: I did it:
First of all i added this two lines to the config
setSSLBind "0.0.0.0" $
setSSLChainCert False $
After this, is very important to build with ghc -threaded and this will get it up and running
|
stackoverflow
|
{
"language": "en",
"length": 123,
"provenance": "stackexchange_0000F.jsonl.gz:837431",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456586"
}
|
f79efe6e6dba93601c18343773b092d887c134ec
|
Stackoverflow Stackexchange
Q: MLPClassifer status when fitting the model When I am Training Using Neural Network I want to see the Progress For that reason in MLPClassifier() function I wrote verbose = True and after that I use fit() function.Now it shows:
RUNNING THE L-BFGS-B CODE
* * *
Machine precision = 2.220D-16
N = 344079 M = 10
This problem is unconstrained.
At X0 0 variables are exactly at the bounds
At iterate 0 f= 2.70346D+00 |proj g|= 1.94826D-01
At iterate 1 f= 2.41155D+00 |proj g|= 1.19097D-01
At iterate 2 f= 2.11866D+00 |proj g|= 1.55296D-01
At iterate 3 f= 1.95068D+00 |proj g|= 1.00021D-01
At iterate 4 f= 1.84819D+00 |proj g|= 1.57815D-01
I didn't understand the meaning..
Thanks in advance
|
Q: MLPClassifer status when fitting the model When I am Training Using Neural Network I want to see the Progress For that reason in MLPClassifier() function I wrote verbose = True and after that I use fit() function.Now it shows:
RUNNING THE L-BFGS-B CODE
* * *
Machine precision = 2.220D-16
N = 344079 M = 10
This problem is unconstrained.
At X0 0 variables are exactly at the bounds
At iterate 0 f= 2.70346D+00 |proj g|= 1.94826D-01
At iterate 1 f= 2.41155D+00 |proj g|= 1.19097D-01
At iterate 2 f= 2.11866D+00 |proj g|= 1.55296D-01
At iterate 3 f= 1.95068D+00 |proj g|= 1.00021D-01
At iterate 4 f= 1.84819D+00 |proj g|= 1.57815D-01
I didn't understand the meaning..
Thanks in advance
|
stackoverflow
|
{
"language": "en",
"length": 118,
"provenance": "stackexchange_0000F.jsonl.gz:837434",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456596"
}
|
f4d5bb755afe6062bbc80babe6fb9772bc409504
|
Stackoverflow Stackexchange
Q: How to implement XProc in BaseX I am working on a project where I must follow multiple steps at the time of data ingestion into the BaseX Database. I want to define these steps in XProc for the ease. Specially we need DOCX to DocBook and DocBook to DOC converstion.
My BaseX version is 8.6.44. I tried https://github.com/fgeorges/calabash-basex-steps but it is not supported. I tried to import some jar into BaseX but not working.
Please help me to start XProc on BaseX.
|
Q: How to implement XProc in BaseX I am working on a project where I must follow multiple steps at the time of data ingestion into the BaseX Database. I want to define these steps in XProc for the ease. Specially we need DOCX to DocBook and DocBook to DOC converstion.
My BaseX version is 8.6.44. I tried https://github.com/fgeorges/calabash-basex-steps but it is not supported. I tried to import some jar into BaseX but not working.
Please help me to start XProc on BaseX.
|
stackoverflow
|
{
"language": "en",
"length": 83,
"provenance": "stackexchange_0000F.jsonl.gz:837445",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456632"
}
|
42950fd00017d06d053229947d17b37baa4c63f6
|
Stackoverflow Stackexchange
Q: How to get notified about 3rd party library updates with Maven/Gradle? I would like to use the latest versions of 3rd party libraries I am using in my project without having to manually check for them or blindly downloading the latest version for the build. During some build phase I would like to receive a notification that a newer version of a dependency exist. Is there a way to do that with Maven/Gradle? Or may be there are better ways to get notified about newer dependency versions?
A: For maven, there's the maven-versions-plugin
For gradle, there's the gradle-versions-plugin
|
Q: How to get notified about 3rd party library updates with Maven/Gradle? I would like to use the latest versions of 3rd party libraries I am using in my project without having to manually check for them or blindly downloading the latest version for the build. During some build phase I would like to receive a notification that a newer version of a dependency exist. Is there a way to do that with Maven/Gradle? Or may be there are better ways to get notified about newer dependency versions?
A: For maven, there's the maven-versions-plugin
For gradle, there's the gradle-versions-plugin
A: I don't think you want this check to be made with each and every build, as I'd expect it will slow it down pretty much (and also add extra strain on repositories; imagine what would mean if each and every build, ever, would hit the mvn repository, every time).
The closest I came to solving this problem was with versions Maven plugin; it appears it has a feature which allows you to see the newest updates (check this link).
This is how it looks like:
[INFO] ------------------------------------------------------------------------
[INFO] Building Build Helper Maven Plugin
[INFO] task-segment: [versions:display-dependency-updates]
[INFO] ------------------------------------------------------------------------
[INFO] [versions:display-dependency-updates]
[INFO]
[INFO] The following dependency updates are available:
[INFO] org.apache.maven:maven-artifact ........................ 2.0 -> 2.0.9
[INFO] org.apache.maven:maven-plugin-api ...................... 2.0 -> 2.0.9
[INFO] org.apache.maven:maven-project ....................... 2.0.2 -> 2.0.9
[INFO] org.codehaus.plexus:plexus-utils ....................... 1.1 -> 1.5.6
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17 seconds
[INFO] Finished at: Fri Aug 15 10:46:03 IST 2008
[INFO] Final Memory: 10M/167M
[INFO] ------------------------------------------------------------------------
|
stackoverflow
|
{
"language": "en",
"length": 260,
"provenance": "stackexchange_0000F.jsonl.gz:837458",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456661"
}
|
38ec7cd47e2dd775b0a623f83bfb064a97bae344
|
Stackoverflow Stackexchange
Q: How to extract a string using Regex for POS Tagging With reference to the question, I am facing some difficulties in that solution for the following example.
"I/PRP did/VBD n't/RB experienced/VBN much/JJ service/NN differentiation/NN" The/DT desktop/NN and/CC CAD/NN support/NN is/VBZ working/VBG as/IN expected/VBN CAD-support/NNP Desktop/NNP management/NN related/VBD to/TO LSB/NNP Desktop/NNP management/NN team/NN is/VBZ very/RB committed/VBN ./."
The result is not coming as expected because of having apostrophe in "n't" and hyphen "CAD-Support". I am posting this as a new query as requested. Can anyone help me to resolve this. Thanks!!
A: If you want to use the previous solution, all you need to change is the regex to
[^\s/]+
in code:
str_extract_all(str1, "[^\\s/]+")
See the regex demo.
It will match 1 or more chars other than whitespace and /.
To avoid matching ./., you'll need to use something like
\w+(?:['-]\w+)*
in code:
str_extract_all(str1, "\\w+(?:['-]\\w+)*")
that will match 1+ word chars followed with 0+ sequences of ' or - followed with 1+ word chars. See this regex demo.
|
Q: How to extract a string using Regex for POS Tagging With reference to the question, I am facing some difficulties in that solution for the following example.
"I/PRP did/VBD n't/RB experienced/VBN much/JJ service/NN differentiation/NN" The/DT desktop/NN and/CC CAD/NN support/NN is/VBZ working/VBG as/IN expected/VBN CAD-support/NNP Desktop/NNP management/NN related/VBD to/TO LSB/NNP Desktop/NNP management/NN team/NN is/VBZ very/RB committed/VBN ./."
The result is not coming as expected because of having apostrophe in "n't" and hyphen "CAD-Support". I am posting this as a new query as requested. Can anyone help me to resolve this. Thanks!!
A: If you want to use the previous solution, all you need to change is the regex to
[^\s/]+
in code:
str_extract_all(str1, "[^\\s/]+")
See the regex demo.
It will match 1 or more chars other than whitespace and /.
To avoid matching ./., you'll need to use something like
\w+(?:['-]\w+)*
in code:
str_extract_all(str1, "\\w+(?:['-]\\w+)*")
that will match 1+ word chars followed with 0+ sequences of ' or - followed with 1+ word chars. See this regex demo.
|
stackoverflow
|
{
"language": "en",
"length": 168,
"provenance": "stackexchange_0000F.jsonl.gz:837464",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456676"
}
|
09250651e81b57b3020a2135958f6317f080724a
|
Stackoverflow Stackexchange
Q: Extend ReactNative's platform specific extensions? Is it possible to hook into React-Native's platform specific extensions to use custom ones?
In the same way you can diverge .ios.js and .android.js, is there a way to define custom extensions .xyz.js. (An equivalent to webpack's resolve.extensions)
A: You can override the original bundler configuration in rn-cli.config.js in the project root like this:
const { getDefaultConfig } = require('metro-config')
module.exports = (async () => {
const {
resolver: {
sourceExt
}
} = await getDefaultConfig()
return {
resolver: {
sourceExts: ['xyz.js', ...sourceExts]
}
}
})()
The bundler documentation suggests to use the platforms property instead of sourceExt, but unfortunately, I'm having no luck with that one yet (most probably because the actual target platform still will be ios or `android, so RN will use that one instead of ours).
sourceExts extends not the platform list itself, but the extension list, which is something like ['js', 'json', 'ts', 'tsx'] by default. If we expand it like ['xyz.js', 'js', 'json', 'ts', 'tsx'], RN will pick *.xyz.js, if exists, first.
|
Q: Extend ReactNative's platform specific extensions? Is it possible to hook into React-Native's platform specific extensions to use custom ones?
In the same way you can diverge .ios.js and .android.js, is there a way to define custom extensions .xyz.js. (An equivalent to webpack's resolve.extensions)
A: You can override the original bundler configuration in rn-cli.config.js in the project root like this:
const { getDefaultConfig } = require('metro-config')
module.exports = (async () => {
const {
resolver: {
sourceExt
}
} = await getDefaultConfig()
return {
resolver: {
sourceExts: ['xyz.js', ...sourceExts]
}
}
})()
The bundler documentation suggests to use the platforms property instead of sourceExt, but unfortunately, I'm having no luck with that one yet (most probably because the actual target platform still will be ios or `android, so RN will use that one instead of ours).
sourceExts extends not the platform list itself, but the extension list, which is something like ['js', 'json', 'ts', 'tsx'] by default. If we expand it like ['xyz.js', 'js', 'json', 'ts', 'tsx'], RN will pick *.xyz.js, if exists, first.
|
stackoverflow
|
{
"language": "en",
"length": 174,
"provenance": "stackexchange_0000F.jsonl.gz:837493",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456792"
}
|
be1608138bfe0960497c0ad690bae03771e11d1f
|
Stackoverflow Stackexchange
Q: Spacebar "doesn't work" in `button` element when i use the HTML5 `contenteditable`. How can i get it to working? Spacebar does not work in button element when i use the HTML5 contenteditable. But its working perfect in div element. How can i get it to working? can someone help me?
Please check it here: https://jsfiddle.net/Issact/f6jc5th4/
HTML:
<div contenteditable="true">
This is editable and the spacebar does work in "Div" for the white-space
</div>
<button contenteditable="true">
This is editable and the spacebar does not work in "button" for the white-space
</button>
CSS:
div {
background-color:black;
padding:20px;
color:#fff;
}
button {
background-color:green;
padding:20px;
color:#fff;
}
A: This may help you:
const button = document.querySelector('button[contenteditable]')
button.addEventListener('keydown', function (event) {
if (event.code !== 'Space') {
return
}
event.preventDefault()
document.execCommand("insertText", false, ' ')
})
Look example here: on JSFiddle
|
Q: Spacebar "doesn't work" in `button` element when i use the HTML5 `contenteditable`. How can i get it to working? Spacebar does not work in button element when i use the HTML5 contenteditable. But its working perfect in div element. How can i get it to working? can someone help me?
Please check it here: https://jsfiddle.net/Issact/f6jc5th4/
HTML:
<div contenteditable="true">
This is editable and the spacebar does work in "Div" for the white-space
</div>
<button contenteditable="true">
This is editable and the spacebar does not work in "button" for the white-space
</button>
CSS:
div {
background-color:black;
padding:20px;
color:#fff;
}
button {
background-color:green;
padding:20px;
color:#fff;
}
A: This may help you:
const button = document.querySelector('button[contenteditable]')
button.addEventListener('keydown', function (event) {
if (event.code !== 'Space') {
return
}
event.preventDefault()
document.execCommand("insertText", false, ' ')
})
Look example here: on JSFiddle
A: wrap the text inside the button tag with a span make that span contenteditable
html
<div contenteditable="true">
This is editable and the spacebar does work in "Div" for the white-space
</div>
<button >
<span contenteditable="true">
This is editable and the spacebar does not work in "button" for the white-space
</span>
</button>
css
div {
background-color:black;
padding:20px;
color:#fff;
}
button {
background-color:green;
padding:20px;
color:#fff;
}
hope this works
A: Use this
<button
contenteditable="true"
onclick="if (!event.x && !event.y && !event.clientX && !event.clientY) {event.preventDefault(); insertHtmlAtCursor(' ');} else { }"> This is editable and the spacebar does not work in "button" for the white-space </button>
<script type="text/javascript">
function insertHtmlAtCursor(html) {
var range, node;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
window.getSelection().collapseToEnd();
window.getSelection().modify('move', 'forward', 'character');
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
document.selection.collapseToEnd();
document.selection.modify('move', 'forward', 'character');
}
}
</script>
Added live demo here https://jsfiddle.net/jalayoza/f6jc5th4/3/
Hope this helps
A: You'll want to make an event listener that prevents the default event when the spacebar is clicked and then use execCommands to put the enter in programatically.
MDN Link: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
A: @Jalay's answer almost worked but not quite. This is what worked for me:
Comment out window.getSelection().collapseToEnd(); part of Jalay's function:
function insertHtmlAtCursor(html) {
var range, node;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
//window.getSelection().collapseToEnd();
window.getSelection().modify('move', 'forward', 'character');
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
document.selection.collapseToEnd();
document.selection.modify('move', 'forward', 'character');
}
}
Then listen for the spacebar keyup event, and insert a space as needed:
$(document).on('keyup', 'button', function(e){
if(e.keyCode == 32){
insertHtmlAtCursor(' ');
}
});
This also has the benefit of working for dynamically added content.
|
stackoverflow
|
{
"language": "en",
"length": 404,
"provenance": "stackexchange_0000F.jsonl.gz:837516",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456873"
}
|
b700a6801dacb5dffda161e2e494f26fe485204e
|
Stackoverflow Stackexchange
Q: Why using a LocationManager singleton in Android Activity is bad? In this talk (15:49) it's said sth which I do not understand. It's something like "when you use a LocationManager singleton in Activity it will cause memory leak".
Can you explain how that LocationManager singleton causes a leak?
A: The LocationManager will hold a reference to the Activity.
LocationManager instance will live until your app is destroyed holding that activity reference.
meanwhile the user could navigate out of that activity.
now your LocationManager is holding a reference to a activity that has finished it's cycle but could not be destroyed because it is referenced from the LocationManager -> activity has been leaked.
|
Q: Why using a LocationManager singleton in Android Activity is bad? In this talk (15:49) it's said sth which I do not understand. It's something like "when you use a LocationManager singleton in Activity it will cause memory leak".
Can you explain how that LocationManager singleton causes a leak?
A: The LocationManager will hold a reference to the Activity.
LocationManager instance will live until your app is destroyed holding that activity reference.
meanwhile the user could navigate out of that activity.
now your LocationManager is holding a reference to a activity that has finished it's cycle but could not be destroyed because it is referenced from the LocationManager -> activity has been leaked.
|
stackoverflow
|
{
"language": "en",
"length": 113,
"provenance": "stackexchange_0000F.jsonl.gz:837541",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44456949"
}
|
59cfd5b290b8d345784f343a92515021c4b3abc1
|
Stackoverflow Stackexchange
Q: UNUserNotificationCenter notifications after device reboot I have been searching online to see if the notifications that you have scheduled get deleted after the device reboots. I have found mixed opinions, so I've begun testing it. This is what I noticed:
*
*I have scheduled notifications in 10 minutes, restarted my phone: nothing comes up
*But, yesterday I scheduled a lot of notifications, and some of them were for the current day. Even though since yesterday I've rebooted my phone a lot of times, these notifications do come up.
Below there is a snippet of code which I used to do the scheduling:
let notificationContent = UNMutableNotificationContent()
notificationContent.body = "This is a notification"
notificationContent.categoryIdentifier = NotificationContentProvider.snoozeCategoryIdentifier
let unitFlags = [.hour, .minute, .second, .day, .month, .year] as [Calendar.Component]
let components = Calendar.current.dateComponents(Set(unitFlags), from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: "\(Int.random())", content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if let theError = error {
print(theError.localizedDescription)
}
})
|
Q: UNUserNotificationCenter notifications after device reboot I have been searching online to see if the notifications that you have scheduled get deleted after the device reboots. I have found mixed opinions, so I've begun testing it. This is what I noticed:
*
*I have scheduled notifications in 10 minutes, restarted my phone: nothing comes up
*But, yesterday I scheduled a lot of notifications, and some of them were for the current day. Even though since yesterday I've rebooted my phone a lot of times, these notifications do come up.
Below there is a snippet of code which I used to do the scheduling:
let notificationContent = UNMutableNotificationContent()
notificationContent.body = "This is a notification"
notificationContent.categoryIdentifier = NotificationContentProvider.snoozeCategoryIdentifier
let unitFlags = [.hour, .minute, .second, .day, .month, .year] as [Calendar.Component]
let components = Calendar.current.dateComponents(Set(unitFlags), from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: "\(Int.random())", content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if let theError = error {
print(theError.localizedDescription)
}
})
|
stackoverflow
|
{
"language": "en",
"length": 163,
"provenance": "stackexchange_0000F.jsonl.gz:837576",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457030"
}
|
89ddc531caaffa308ca9f1489352a5a3e4f7f5b6
|
Stackoverflow Stackexchange
Q: What's the earliest Android API level I can use Kotlin with? I think the question is pretty clear but what's the earliest API level I can target on Kotlin?
A: Actually, any API level.
That's because Kotlin is compiled into bytecode for JVM 6 platform, which is supported in all Android API levels. So, unless you use any of the newer Android API in your Kotlin code, it does not require any specific API level.
|
Q: What's the earliest Android API level I can use Kotlin with? I think the question is pretty clear but what's the earliest API level I can target on Kotlin?
A: Actually, any API level.
That's because Kotlin is compiled into bytecode for JVM 6 platform, which is supported in all Android API levels. So, unless you use any of the newer Android API in your Kotlin code, it does not require any specific API level.
|
stackoverflow
|
{
"language": "en",
"length": 76,
"provenance": "stackexchange_0000F.jsonl.gz:837586",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457061"
}
|
32312b0586e69060e63aefbb76c07ceda68dddf1
|
Stackoverflow Stackexchange
Q: Why i cannot find the Wordpress ACF custom field value not in database? The problem
I have a custom field of type "text" for my posts added with ACF (Advanced Custom Fields) plugin. I fill the field with a URL e.g "www.test.com" but I cannot find that value anywhere in the database.
I tried
1. I search for the value in all the tables using phpMyAdmin
2. I downloaded the .sql file, search it but still, I cannot find the value "www.test.com" anywhere.
What I expected
I was expecting the value to exist in the table "wp_postmeta". So I am not sure where or how that value is stored.
Any ideas how i can find and update the value via the database ? Thanks!
A: I finally figured out what was wrong. phpMyAdmin didn't show the last table rows of "wp_postmeta".
So i reloaded the who phpMyAdmin web page and i finally was able to see the latest rows of "wp_postmeta". I found the values that i updated the fields with.
So for everybody that cannot see the values on the database, make sure you see the last version of the database.
|
Q: Why i cannot find the Wordpress ACF custom field value not in database? The problem
I have a custom field of type "text" for my posts added with ACF (Advanced Custom Fields) plugin. I fill the field with a URL e.g "www.test.com" but I cannot find that value anywhere in the database.
I tried
1. I search for the value in all the tables using phpMyAdmin
2. I downloaded the .sql file, search it but still, I cannot find the value "www.test.com" anywhere.
What I expected
I was expecting the value to exist in the table "wp_postmeta". So I am not sure where or how that value is stored.
Any ideas how i can find and update the value via the database ? Thanks!
A: I finally figured out what was wrong. phpMyAdmin didn't show the last table rows of "wp_postmeta".
So i reloaded the who phpMyAdmin web page and i finally was able to see the latest rows of "wp_postmeta". I found the values that i updated the fields with.
So for everybody that cannot see the values on the database, make sure you see the last version of the database.
|
stackoverflow
|
{
"language": "en",
"length": 193,
"provenance": "stackexchange_0000F.jsonl.gz:837589",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457065"
}
|
bb937d95047a7a6c8bf5f419f2ac32fe079ff464
|
Stackoverflow Stackexchange
Q: Passing application to AndroidViewModel I would like to use AndroidViewModel for my view model in order to get access to the Context. It requires Application to be passed as a parameter. My ViewModel class looks like this:
class FooAndroidViewModel(application: Application?) : AndroidViewModel(aplication) {
...
}
It is getting instantiated like this:
val fooModel = ViewModelProviders.of(this).get(FooAndroidViewModel::class.java)
The problem is that this gives an error, that FooAndroidViewModel cannot be instantiated - probably because of the missing application parameter.
Question: how to pass application to ViewModelProviders.of(this).get(FooAndroidViewModel::class.java)?
A: Just replace application: Application? to application: Application. Following code should work:
class FooAndroidViewModel(application: Application) : AndroidViewModel(application) {
// class def
}
|
Q: Passing application to AndroidViewModel I would like to use AndroidViewModel for my view model in order to get access to the Context. It requires Application to be passed as a parameter. My ViewModel class looks like this:
class FooAndroidViewModel(application: Application?) : AndroidViewModel(aplication) {
...
}
It is getting instantiated like this:
val fooModel = ViewModelProviders.of(this).get(FooAndroidViewModel::class.java)
The problem is that this gives an error, that FooAndroidViewModel cannot be instantiated - probably because of the missing application parameter.
Question: how to pass application to ViewModelProviders.of(this).get(FooAndroidViewModel::class.java)?
A: Just replace application: Application? to application: Application. Following code should work:
class FooAndroidViewModel(application: Application) : AndroidViewModel(application) {
// class def
}
A: Even if we have it this way,
class FooAndroidViewModel(application: Application) : AndroidViewModel(aplication)
But we don't go with by viewModels() option and instead try to use this as,
val mViewModel = ViewModelProvider(this).get(FooAndroidViewModel::class.java)
Then it gives an exception,
java.lang.RuntimeException: Cannot create an instance of class x.y.z.FooAndroidViewModel
Caused by: java.lang.InstantiationException: java.lang.Class<x.y.z.FooAndroidViewModel> has no zero argument constructor
I solved it by creating instance of AndroidViewModel this way,
val mViewModel = ViewModelProvider.AndroidViewModelFactory(application).create(FooAndroidViewModel::class.java)
|
stackoverflow
|
{
"language": "en",
"length": 174,
"provenance": "stackexchange_0000F.jsonl.gz:837591",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457072"
}
|
74df985f1c5da4e11ec3f817554773fa4f7475fa
|
Stackoverflow Stackexchange
Q: Powermock keeps throwing errors for ScriptEngineManager Due to the fact that I wanted to use Categories from JUnit on my tests I had to rewrite some mocked tests with PowerMock (powermock on top of EasyMock to mock statics). From RunWith(PowermockRunner.class) to the below;
@Category(ServerTests.class)
@PrepareForTest(EnvironmentConfig.class)
@PowerMockIgnore( {"javax.management.*", "org.w3c.dom.*", "org.apache.log4j.*", "org.xml.sax.*", "javax.xml.*"})
public class JmsHelperTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
}
Unfortunately I already suppressed a few error with the PowerMockIgnore, but the last I cannot suppress and I hope you can help.
The error:
ScriptEngineManager providers.next():
javax.script.ScriptEngineFactory: Provider
jdk.nashorn.api.scripting.NashornScriptEngineFactory not a subtype
ScriptEngineManager providers.next():
javax.script.ScriptEngineFactory: Provider
jdk.nashorn.api.scripting.NashornScriptEngineFactory not a subtype
2017-06-09 13:37:24,660 main ERROR No ScriptEngine found for language
javascript. Available languages are: 2017-06-09 13:37:24,776 main
WARN No script named {} could be found
for reference the loaded packages;
import mypackage.EnvironmentConfig;
import mypackage.category.ServerTests;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
import static org.easymock.EasyMock.expect;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
A: I was focussing on the jdk.nashorn.*, however when I add javax.script.* to the @PowerMockIgnore it solved the errors.
|
Q: Powermock keeps throwing errors for ScriptEngineManager Due to the fact that I wanted to use Categories from JUnit on my tests I had to rewrite some mocked tests with PowerMock (powermock on top of EasyMock to mock statics). From RunWith(PowermockRunner.class) to the below;
@Category(ServerTests.class)
@PrepareForTest(EnvironmentConfig.class)
@PowerMockIgnore( {"javax.management.*", "org.w3c.dom.*", "org.apache.log4j.*", "org.xml.sax.*", "javax.xml.*"})
public class JmsHelperTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
}
Unfortunately I already suppressed a few error with the PowerMockIgnore, but the last I cannot suppress and I hope you can help.
The error:
ScriptEngineManager providers.next():
javax.script.ScriptEngineFactory: Provider
jdk.nashorn.api.scripting.NashornScriptEngineFactory not a subtype
ScriptEngineManager providers.next():
javax.script.ScriptEngineFactory: Provider
jdk.nashorn.api.scripting.NashornScriptEngineFactory not a subtype
2017-06-09 13:37:24,660 main ERROR No ScriptEngine found for language
javascript. Available languages are: 2017-06-09 13:37:24,776 main
WARN No script named {} could be found
for reference the loaded packages;
import mypackage.EnvironmentConfig;
import mypackage.category.ServerTests;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
import static org.easymock.EasyMock.expect;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
A: I was focussing on the jdk.nashorn.*, however when I add javax.script.* to the @PowerMockIgnore it solved the errors.
|
stackoverflow
|
{
"language": "en",
"length": 185,
"provenance": "stackexchange_0000F.jsonl.gz:837595",
"question_score": "16",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457080"
}
|
46741228e3f82923a89e4d5eb85b2e8400aed369
|
Stackoverflow Stackexchange
Q: kubetnetes port forward udp My service exposes UDP port 6831, and other ports. Here is the service description:
kubectl describe service jaeger-all-in-one 1:51
Name: jaeger-all-in-one
Namespace: myproject
Labels: jaeger-infra=all-in-one
Annotations: <none>
Selector: name=jaeger-all-in-one
Type: ClusterIP
IP: 172.30.213.142
Port: query-http 80/TCP
Endpoints: 172.17.0.3:16686
Port: agent-zipkin-thrift 5775/UDP
Endpoints: 172.17.0.3:5775
Port: agent-compact 6831/UDP
Endpoints: 172.17.0.3:6831
Port: agent-binary 6832/UDP
Endpoints: 172.17.0.3:6832
Session Affinity: None
Events: <none>
Forward port:
kubectl port-forward jaeger-all-in-one-1-cc8wd 12388:6831
However it forwards only TCP ports, I would like to send data to the UDP port.
|
Q: kubetnetes port forward udp My service exposes UDP port 6831, and other ports. Here is the service description:
kubectl describe service jaeger-all-in-one 1:51
Name: jaeger-all-in-one
Namespace: myproject
Labels: jaeger-infra=all-in-one
Annotations: <none>
Selector: name=jaeger-all-in-one
Type: ClusterIP
IP: 172.30.213.142
Port: query-http 80/TCP
Endpoints: 172.17.0.3:16686
Port: agent-zipkin-thrift 5775/UDP
Endpoints: 172.17.0.3:5775
Port: agent-compact 6831/UDP
Endpoints: 172.17.0.3:6831
Port: agent-binary 6832/UDP
Endpoints: 172.17.0.3:6832
Session Affinity: None
Events: <none>
Forward port:
kubectl port-forward jaeger-all-in-one-1-cc8wd 12388:6831
However it forwards only TCP ports, I would like to send data to the UDP port.
|
stackoverflow
|
{
"language": "en",
"length": 86,
"provenance": "stackexchange_0000F.jsonl.gz:837605",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457098"
}
|
b23b3ac7a8998eda3dd761897f1a2d7ac01d5039
|
Stackoverflow Stackexchange
Q: How do I limit size of generated sample with `clojure.spec/+`? clojure.spec/coll-of takes :gen-max option to limit the generated sample size.
Is there an analog for clojure.spec/+?
A: s/* and s/+ don't take an option like :gen-max but those repetitive regex specs do take clojure.spec.alpha/*recursion-limit* into account. I think that's fairly coarse-grained control and has no practical effect on simple specs like this, which seemingly always generate a longest sequence of ~200 elements for any positive *recursion-limit*:
(binding [clojure.spec.alpha/*recursion-limit* 1]
(->> (gen/sample (s/gen (s/* int?)) 200)
(map count)
(apply max)))
One way to limit the length of the generated sequences is to provide a custom generator:
(s/def ::ints
(s/with-gen
(s/+ int?)
#(gen/vector gen/int 1 10)))
(gen/sample (s/gen ::ints) 200)
This should always generate a vector of 1-10 integers.
|
Q: How do I limit size of generated sample with `clojure.spec/+`? clojure.spec/coll-of takes :gen-max option to limit the generated sample size.
Is there an analog for clojure.spec/+?
A: s/* and s/+ don't take an option like :gen-max but those repetitive regex specs do take clojure.spec.alpha/*recursion-limit* into account. I think that's fairly coarse-grained control and has no practical effect on simple specs like this, which seemingly always generate a longest sequence of ~200 elements for any positive *recursion-limit*:
(binding [clojure.spec.alpha/*recursion-limit* 1]
(->> (gen/sample (s/gen (s/* int?)) 200)
(map count)
(apply max)))
One way to limit the length of the generated sequences is to provide a custom generator:
(s/def ::ints
(s/with-gen
(s/+ int?)
#(gen/vector gen/int 1 10)))
(gen/sample (s/gen ::ints) 200)
This should always generate a vector of 1-10 integers.
|
stackoverflow
|
{
"language": "en",
"length": 128,
"provenance": "stackexchange_0000F.jsonl.gz:837620",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457155"
}
|
acb8e53620c706524b34e4821a29e0222e5ba15d
|
Stackoverflow Stackexchange
Q: How to reduce the spaces between columns in datatable object from DT R package? I would like to reduce the spaces between columns in datable object (DT package from R language). Please see below example:
datatable(iris)
|
Q: How to reduce the spaces between columns in datatable object from DT R package? I would like to reduce the spaces between columns in datable object (DT package from R language). Please see below example:
datatable(iris)
|
stackoverflow
|
{
"language": "en",
"length": 37,
"provenance": "stackexchange_0000F.jsonl.gz:837638",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457207"
}
|
4afb8e0dbb0a4357c4ac903ca03985310fccd8df
|
Stackoverflow Stackexchange
Q: Formatting @BindView code Android Studio by default format Butterknife code in this way:
@BindView(R.id.text_view)
TextView mTextView
Is there a way to tell Android Studio to format code in one line, like this:
@BindView(R.id.text_view) TextView mTextView
If this is possible I would like this rule to apply only to @BindView annotation.
A: in Android Studio 2.3.3
File -> Settings -> Editor ->Code Style -> Java -> Wrapping and Braces -> Field annotations -> set to "Do not Wrap"
but this will prevent AS to put the new line on all field annotations.
i don't know if it is possible to have this option only for @BindView, however, if you set the option like this, AS will not put all annotations inline. for instance if you have
@Nullable
String foo;
@BindView View bar;
and format the code, AS will leave both annotations as they are.
|
Q: Formatting @BindView code Android Studio by default format Butterknife code in this way:
@BindView(R.id.text_view)
TextView mTextView
Is there a way to tell Android Studio to format code in one line, like this:
@BindView(R.id.text_view) TextView mTextView
If this is possible I would like this rule to apply only to @BindView annotation.
A: in Android Studio 2.3.3
File -> Settings -> Editor ->Code Style -> Java -> Wrapping and Braces -> Field annotations -> set to "Do not Wrap"
but this will prevent AS to put the new line on all field annotations.
i don't know if it is possible to have this option only for @BindView, however, if you set the option like this, AS will not put all annotations inline. for instance if you have
@Nullable
String foo;
@BindView View bar;
and format the code, AS will leave both annotations as they are.
|
stackoverflow
|
{
"language": "en",
"length": 144,
"provenance": "stackexchange_0000F.jsonl.gz:837644",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457216"
}
|
3e048926ede623960027e1684bc8837e81e5a301
|
Stackoverflow Stackexchange
Q: How to have transparent background for button? I am develop na UWP app, and I would like to have a transparent button. I try this (Is a simple example of my button):
<Button Name="Button"
Opacity="0">
<Image Source="/Assets/image.png"/>
</Button>
I want a button with an image, in which only the button is transparent. I've tried it that way, and by putting: Opacity="0" it puts everything transparent, and I want it to just be transparent.
A: Method 1
Set Opacity="0" for Button.Background. You can do it by using below code.
<Button>
<Button.Background>
<SolidColorBrush Opacity="0"/>
</Button.Background>
</Button>
Method 2
Set #00000000 as the background color of the Button. Since UWP support ARGB(Alpha RGB) color you can directly set opacity for any color in UWP app.
<Button Background="#00000000"/>
|
Q: How to have transparent background for button? I am develop na UWP app, and I would like to have a transparent button. I try this (Is a simple example of my button):
<Button Name="Button"
Opacity="0">
<Image Source="/Assets/image.png"/>
</Button>
I want a button with an image, in which only the button is transparent. I've tried it that way, and by putting: Opacity="0" it puts everything transparent, and I want it to just be transparent.
A: Method 1
Set Opacity="0" for Button.Background. You can do it by using below code.
<Button>
<Button.Background>
<SolidColorBrush Opacity="0"/>
</Button.Background>
</Button>
Method 2
Set #00000000 as the background color of the Button. Since UWP support ARGB(Alpha RGB) color you can directly set opacity for any color in UWP app.
<Button Background="#00000000"/>
|
stackoverflow
|
{
"language": "en",
"length": 125,
"provenance": "stackexchange_0000F.jsonl.gz:837684",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457325"
}
|
26842e1acf4db2ea039f9d6e8cf2ba64194c8ae7
|
Stackoverflow Stackexchange
Q: How do I use npm forever-monitor to log to stdout I have a simple nodejs docker service. I'm watching stdout in development and logging to AWS cloudwatch in production.
I've just added forever-monitor, but that breaks my logging. So I've started catching stdout on the child process,
const forever = require('forever-monitor');
const child = new (forever.Monitor)('server.js', {
max: 3,
silent: true,
args: []
});
child.on('stdout', function(data) {
console.log(data);
});
but that just gives me byte code out -
[nodemon] starting `node forever.js`
<Buffer 63 6f 6e 6e 65 63 74 65 64 20 74 6f 20 6c 69 76 65 20 64 62 0a>
How do I get my console.log statements back into std-out?
A: It looks like data is a stream (see node docs).
I've updated my code to -
child.on('stdout', function(data) {
console.log(data.toString());
});
And now it's working as expected. (I found this question useful).
|
Q: How do I use npm forever-monitor to log to stdout I have a simple nodejs docker service. I'm watching stdout in development and logging to AWS cloudwatch in production.
I've just added forever-monitor, but that breaks my logging. So I've started catching stdout on the child process,
const forever = require('forever-monitor');
const child = new (forever.Monitor)('server.js', {
max: 3,
silent: true,
args: []
});
child.on('stdout', function(data) {
console.log(data);
});
but that just gives me byte code out -
[nodemon] starting `node forever.js`
<Buffer 63 6f 6e 6e 65 63 74 65 64 20 74 6f 20 6c 69 76 65 20 64 62 0a>
How do I get my console.log statements back into std-out?
A: It looks like data is a stream (see node docs).
I've updated my code to -
child.on('stdout', function(data) {
console.log(data.toString());
});
And now it's working as expected. (I found this question useful).
|
stackoverflow
|
{
"language": "en",
"length": 148,
"provenance": "stackexchange_0000F.jsonl.gz:837703",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457375"
}
|
f6e410aabdc0fb91a4c6290930abba45538e80ac
|
Stackoverflow Stackexchange
Q: ImportError: No module named ... on docker toolbar on windows Im currently having an issue trying to configure a project on my windows device.
I have docker-toolbar, which is supposed to run a dockerfile with python server, but on $ docker-compose up im getting a massive load of ImportError: No module named '<projects modules names>'
As the rest of teams run it successfully on Linux I suppose there is something to do with Windows, paths maybe or idk (inb4 'why not use linux').
Of course there is an option to use VM, but I would like to use it only in finality.
A: As stupid as it is, I still post my solution because maybe it helps some poor soul like me.
In my docker-compose.yml I had a wrong mapping in the volumes:
web:
...
volumes:
- .:app/wrong-subfolder
That's why my local code was mapped to a wrong directory and that caused django to not find the settings module.
|
Q: ImportError: No module named ... on docker toolbar on windows Im currently having an issue trying to configure a project on my windows device.
I have docker-toolbar, which is supposed to run a dockerfile with python server, but on $ docker-compose up im getting a massive load of ImportError: No module named '<projects modules names>'
As the rest of teams run it successfully on Linux I suppose there is something to do with Windows, paths maybe or idk (inb4 'why not use linux').
Of course there is an option to use VM, but I would like to use it only in finality.
A: As stupid as it is, I still post my solution because maybe it helps some poor soul like me.
In my docker-compose.yml I had a wrong mapping in the volumes:
web:
...
volumes:
- .:app/wrong-subfolder
That's why my local code was mapped to a wrong directory and that caused django to not find the settings module.
|
stackoverflow
|
{
"language": "en",
"length": 160,
"provenance": "stackexchange_0000F.jsonl.gz:837704",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457378"
}
|
87ac49f2680f78ccee46c6cde544677b73d8da6a
|
Stackoverflow Stackexchange
Q: UIStackView: add arranged views with the same width I have UIStackView and want add to this view some arranged views... sometimes one, sometimes two, three... etc. UIStackView has full width. I want arranged views to have the same width with alignment left, so that they do not fill full width of UIStackView.
This is what I have:
This is what I want:
Is it possible to do it somehow or do I need to change width of UIStackVIew depending on how many arranged I added?
My code:
// creating views
stackView = {
let v = UIStackView()
v.axis = .horizontal
v.alignment = .center
v.distribution = .fillEqually
v.spacing = 5
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
if let img = chosenImage {
let imageView: UIImageView = {
let l = UIImageView()
l.translatesAutoresizingMaskIntoConstraints = false
l.image = img
return l
}()
self.stackView?.addArrangedSubview(imageView)
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1, constant: 1))
imageView.setNeedsUpdateConstraints()
} else {
print("Something went wrong")
}
A: on storyboard, Select stackview, Attributes inspector -> Stackview -> Distribution, select Fill Equally.
|
Q: UIStackView: add arranged views with the same width I have UIStackView and want add to this view some arranged views... sometimes one, sometimes two, three... etc. UIStackView has full width. I want arranged views to have the same width with alignment left, so that they do not fill full width of UIStackView.
This is what I have:
This is what I want:
Is it possible to do it somehow or do I need to change width of UIStackVIew depending on how many arranged I added?
My code:
// creating views
stackView = {
let v = UIStackView()
v.axis = .horizontal
v.alignment = .center
v.distribution = .fillEqually
v.spacing = 5
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
if let img = chosenImage {
let imageView: UIImageView = {
let l = UIImageView()
l.translatesAutoresizingMaskIntoConstraints = false
l.image = img
return l
}()
self.stackView?.addArrangedSubview(imageView)
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1, constant: 1))
imageView.setNeedsUpdateConstraints()
} else {
print("Something went wrong")
}
A: on storyboard, Select stackview, Attributes inspector -> Stackview -> Distribution, select Fill Equally.
A: You can add an empty clear view to your StackView at the end and set the hugging and resistance priority for this View. It should resize to available space so hugging priority of "fill view" has to be higher and resistance for "fill view" should be low, on your real items set resistance to higher values
|
stackoverflow
|
{
"language": "en",
"length": 234,
"provenance": "stackexchange_0000F.jsonl.gz:837705",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457381"
}
|
99a4eb3126ca7d0c0f4c0b1f26256c16084f70fb
|
Stackoverflow Stackexchange
Q: Break URL into parts and locate the ID (longest part) I have a URL:
$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
I want to get the ID out of this URL. The ID is always the longest part of the URL 1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk, so my approach is to target the longest part.
How can I break this URL into parts and grab the longest part? I want to ignore the query variable part ?usp=sharing#helloworld when breaking it into parts.
What I've tried so far
I tried a preg_match_all() approach with a regex that doesn't seem to break the URL properly:
$regex = '/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/';
$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
$result = preg_match_all($regex, $url, $matches);
print($matches);
A: You can use the function explode to split a string in a array.
And the function parse_url()to get the path of your URL.
$path = parse_url($url, PHP_URL_PATH);
$array = explode("/", $path);
edit
If you want to include query-variables you can add this three lines.
parse_str($query,$queries);
$query = parse_url($url, PHP_URL_QUERY);
$array = array_merge($array, $queries);
Now you can look wich part is the longest.
$id = "";
foreach($array as $part){
if(strlen($id) < strlen($part)) {
$id = $part;
}
}
|
Q: Break URL into parts and locate the ID (longest part) I have a URL:
$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
I want to get the ID out of this URL. The ID is always the longest part of the URL 1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk, so my approach is to target the longest part.
How can I break this URL into parts and grab the longest part? I want to ignore the query variable part ?usp=sharing#helloworld when breaking it into parts.
What I've tried so far
I tried a preg_match_all() approach with a regex that doesn't seem to break the URL properly:
$regex = '/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/';
$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
$result = preg_match_all($regex, $url, $matches);
print($matches);
A: You can use the function explode to split a string in a array.
And the function parse_url()to get the path of your URL.
$path = parse_url($url, PHP_URL_PATH);
$array = explode("/", $path);
edit
If you want to include query-variables you can add this three lines.
parse_str($query,$queries);
$query = parse_url($url, PHP_URL_QUERY);
$array = array_merge($array, $queries);
Now you can look wich part is the longest.
$id = "";
foreach($array as $part){
if(strlen($id) < strlen($part)) {
$id = $part;
}
}
A: $url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
$partURL=explode('/', $url);
$lengths = array_map('strlen', $partURL);
$maxLength = max($lengths);
$index = array_search($maxLength, $lengths);
echo $partURL[$index];
Returns: 1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk
A: You can use this regex: ^.*\/d\/(.*)\/.*$
For example:
$regex = '/^.*\/d\/(.*)\/.*$/';
$url = 'https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld';
$result = preg_match_all($regex, $url, $matches);
print_r($matches);
in result you'll have:
Array
(
[0] => Array
(
[0] => https://docs.google.com/spreadsheets/d/1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk/edit?usp=sharing#helloworld
)
[1] => Array
(
[0] => 1ljJpZDiayzMLhIJ-JDSIJjdjdY_xg3RrUDljFVRB0Qk
)
)
A: you can use substr(string,start,length)
A: You can filter parse_url result with PHP_URL_QUERY, for example
$query = parse_url(<url string>, PHP_URL_QUERY);
parse_str($parts, $queryArray);
$queryArray[<KEY>]
|
stackoverflow
|
{
"language": "en",
"length": 274,
"provenance": "stackexchange_0000F.jsonl.gz:837725",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457443"
}
|
2bb254ecc2aabf0d113576ffb0b61f93617a093e
|
Stackoverflow Stackexchange
Q: How to run sbt multiple command in interactive mode I want to run several sbt-commands within sbt interactive mode, i.e. without leaving the sbt "shell"?
(Note:
Some questions answer how to pass argument to sbt-commands using sbt in the standard shell. Not what I wnat here)
Example: I am in sbt interactive shell, and I want to run "test:compile", then "test"
I know test will call required compilation, but in this example I want to run the compilation of all sub-projects, before any test is started.
A: To run commands sequentially within the sbt shell, use ; to chain commands:
> ;test:compile ;test
Note however that running the test task will compile your sources if necessary without you having to explicitly running the compile task.
|
Q: How to run sbt multiple command in interactive mode I want to run several sbt-commands within sbt interactive mode, i.e. without leaving the sbt "shell"?
(Note:
Some questions answer how to pass argument to sbt-commands using sbt in the standard shell. Not what I wnat here)
Example: I am in sbt interactive shell, and I want to run "test:compile", then "test"
I know test will call required compilation, but in this example I want to run the compilation of all sub-projects, before any test is started.
A: To run commands sequentially within the sbt shell, use ; to chain commands:
> ;test:compile ;test
Note however that running the test task will compile your sources if necessary without you having to explicitly running the compile task.
|
stackoverflow
|
{
"language": "en",
"length": 126,
"provenance": "stackexchange_0000F.jsonl.gz:837727",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457452"
}
|
99221849d2bb6d0821432dc0d53e5faf037454d8
|
Stackoverflow Stackexchange
Q: Python3 regex on bytes variable I'm trying to perform a regex substitution on a bytes variable but I receive the error
sequence item 0: expected a bytes-like object, str found
Here is a small code example to reproduce the problem with python3:
import re
try:
test = b'\x1babc\x07123'
test = re.sub(b"\x1b.*\x07", '', test)
print(test)
except Exception as e:
print(e)
A: Your replacement value must be a bytes object too:
re.sub(b"\x1b.*\x07", b'', test)
# ^^^
You can't replace matching bytes with a str object, even if that is an empty string object.
Demo:
>>> import re
>>> test = b'\x1babc\x07123'
>>> re.sub(b"\x1b.*\x07", b'', test)
b'123'
|
Q: Python3 regex on bytes variable I'm trying to perform a regex substitution on a bytes variable but I receive the error
sequence item 0: expected a bytes-like object, str found
Here is a small code example to reproduce the problem with python3:
import re
try:
test = b'\x1babc\x07123'
test = re.sub(b"\x1b.*\x07", '', test)
print(test)
except Exception as e:
print(e)
A: Your replacement value must be a bytes object too:
re.sub(b"\x1b.*\x07", b'', test)
# ^^^
You can't replace matching bytes with a str object, even if that is an empty string object.
Demo:
>>> import re
>>> test = b'\x1babc\x07123'
>>> re.sub(b"\x1b.*\x07", b'', test)
b'123'
A: When acting on bytes object, all arguments must be of type byte, including the replacement string. That is:
test = re.sub(b"\x1b.*\x07", b'', test)
|
stackoverflow
|
{
"language": "en",
"length": 129,
"provenance": "stackexchange_0000F.jsonl.gz:837728",
"question_score": "16",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457455"
}
|
9c458815deb4f74977eefb9935b5d2dfd2a2e8bf
|
Stackoverflow Stackexchange
Q: Web push notification click action tracking I am developing a website to send push notifications to my subscribers' using Firebase Cloud Messaging (Chrome & Firefox browsers) without using any third-party API. Push notification sending is working fine, but I don't know that "How to track notification click action". I can track click action by using JavaScript (ajax call) but I am not sure this will be right choice to proceed.
For example, consider that I am sending push notification to 1,00,000 subscribers in that if 50,000 subscribers clicked on that notification in few seconds, then it will be burden to the server. Is it possible?
Or Is there any other way to track push notifications click report from FCM. If so how to accomplish this?
Please help me out!
A: You can add the date to your URL like this:
yoursite.com/article/lorem-ipsum?utm_source=notification&utm_campaign=1554750619
Then on your GA you can generate reports based on your campaigns.
|
Q: Web push notification click action tracking I am developing a website to send push notifications to my subscribers' using Firebase Cloud Messaging (Chrome & Firefox browsers) without using any third-party API. Push notification sending is working fine, but I don't know that "How to track notification click action". I can track click action by using JavaScript (ajax call) but I am not sure this will be right choice to proceed.
For example, consider that I am sending push notification to 1,00,000 subscribers in that if 50,000 subscribers clicked on that notification in few seconds, then it will be burden to the server. Is it possible?
Or Is there any other way to track push notifications click report from FCM. If so how to accomplish this?
Please help me out!
A: You can add the date to your URL like this:
yoursite.com/article/lorem-ipsum?utm_source=notification&utm_campaign=1554750619
Then on your GA you can generate reports based on your campaigns.
|
stackoverflow
|
{
"language": "en",
"length": 154,
"provenance": "stackexchange_0000F.jsonl.gz:837729",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457465"
}
|
a25e1bd7d39b899185bae0c395fe22da99a64c9a
|
Stackoverflow Stackexchange
Q: checkout the first commit in the history containing a given String I think I have seen on twitter a way to specify a commit by providing a String that is contained in its message. So with a history like this
*
*alpha <-- current head
*beta
*gamma
*gamut
*omega
git checkout <magic stuff>'gam' would checkout the commit with commit message gamma.
What was the syntax for this?
Note 1: I'm not actually sure that was for checkout, might have been for a different command, but I'm hoping for one that is universally applicable.
Note 2: It might not have been specifying a single commit but the range starting at that commit and ending at the current HEAD.
A: Use the following form:
git checkout :/<term>
In your case it's:
git checkout :/gam
See https://stackoverflow.com/a/23303550/2067527 for more details on the various tree-ish and commit-ish forms.
|
Q: checkout the first commit in the history containing a given String I think I have seen on twitter a way to specify a commit by providing a String that is contained in its message. So with a history like this
*
*alpha <-- current head
*beta
*gamma
*gamut
*omega
git checkout <magic stuff>'gam' would checkout the commit with commit message gamma.
What was the syntax for this?
Note 1: I'm not actually sure that was for checkout, might have been for a different command, but I'm hoping for one that is universally applicable.
Note 2: It might not have been specifying a single commit but the range starting at that commit and ending at the current HEAD.
A: Use the following form:
git checkout :/<term>
In your case it's:
git checkout :/gam
See https://stackoverflow.com/a/23303550/2067527 for more details on the various tree-ish and commit-ish forms.
|
stackoverflow
|
{
"language": "en",
"length": 145,
"provenance": "stackexchange_0000F.jsonl.gz:837743",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457518"
}
|
461bba3be9c2cbd4d7f8b7c4d321d7cc3949786b
|
Stackoverflow Stackexchange
Q: How to remove a key value pair from mongodb when updating findOne result? user.findOne(params,(err,user){
if(user){
user.password=password;
delete user['otp'];
user.save(callback);
}
})
my user model has following fields
*
*user_id:string
*otp:number
*password:string
I want to remove otp field on update of password
ie. db should have userid and password after update
A: To delete the otp key from your document, setting the path to undefined and saving it should do it:
user.findOne(params, (err, user){
if (user) {
user.password = password;
user.otp = undefined;
user.save(callback);
}
});
|
Q: How to remove a key value pair from mongodb when updating findOne result? user.findOne(params,(err,user){
if(user){
user.password=password;
delete user['otp'];
user.save(callback);
}
})
my user model has following fields
*
*user_id:string
*otp:number
*password:string
I want to remove otp field on update of password
ie. db should have userid and password after update
A: To delete the otp key from your document, setting the path to undefined and saving it should do it:
user.findOne(params, (err, user){
if (user) {
user.password = password;
user.otp = undefined;
user.save(callback);
}
});
|
stackoverflow
|
{
"language": "en",
"length": 86,
"provenance": "stackexchange_0000F.jsonl.gz:837747",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457533"
}
|
0d987c5b8e81f96cf6f4275c5c5532db1d5a2c8c
|
Stackoverflow Stackexchange
Q: double borders when columns stack in bootstrap I am getting a double border on the cross, when these two columns stack on top of the other two columns. I am using bootstrap.
.border-col {
border:1px dotted grey;
}
<div class="row">
<div class="col-xs-6 border-col"></div>
<div class="col-xs-6 border-col"></div>
<div class="col-xs-6 border-col"></div>
<div class="col-xs-6 border-col"></div>
</div>
How do I avoid the double border? I have tried using the child selector, but cannot seem to get it exactly right.
Thanks for your help.
A: the examples before are not considering the vertical, here is one example that might be better. its depended on css3.
.border-col {
border: 1px dotted gray;
border-bottom: none
}
.border-col:nth-child(odd) {
border-right: none;
}
.border-col:nth-last-child(2) {
border-bottom: 1px dotted gray;
}
.border-col:last-child {
border: 1px dotted gray;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="col-xs-6 border-col">text</div>
<div class="col-xs-6 border-col">text</div>
<div class="col-xs-6 border-col">text</div>
<div class="col-xs-6 border-col">text</div>
<div class="col-xs-6 border-col">text</div>
</div>
</div>
|
Q: double borders when columns stack in bootstrap I am getting a double border on the cross, when these two columns stack on top of the other two columns. I am using bootstrap.
.border-col {
border:1px dotted grey;
}
<div class="row">
<div class="col-xs-6 border-col"></div>
<div class="col-xs-6 border-col"></div>
<div class="col-xs-6 border-col"></div>
<div class="col-xs-6 border-col"></div>
</div>
How do I avoid the double border? I have tried using the child selector, but cannot seem to get it exactly right.
Thanks for your help.
A: the examples before are not considering the vertical, here is one example that might be better. its depended on css3.
.border-col {
border: 1px dotted gray;
border-bottom: none
}
.border-col:nth-child(odd) {
border-right: none;
}
.border-col:nth-last-child(2) {
border-bottom: 1px dotted gray;
}
.border-col:last-child {
border: 1px dotted gray;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="col-xs-6 border-col">text</div>
<div class="col-xs-6 border-col">text</div>
<div class="col-xs-6 border-col">text</div>
<div class="col-xs-6 border-col">text</div>
<div class="col-xs-6 border-col">text</div>
</div>
</div>
A: .border-col {
border:1px dotted grey;
border-bottom:0;
}
.border-col:last-child {
border:1px dotted grey;
}
PEN Here
A: Use only one border for all the div's expect first div or last div that will help you to avoid the double border
.border-col {
border:1px dotted grey;
border-bottom: 0;
}
.border-col:last-child {
border: 1px dotted grey;
}
|
stackoverflow
|
{
"language": "en",
"length": 208,
"provenance": "stackexchange_0000F.jsonl.gz:837760",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457572"
}
|
850895a0faef9adb1545be3869cb9dea31337c79
|
Stackoverflow Stackexchange
Q: Can I use Maven without setting the Environment variable? I want to use Maven for my project.
In my office computer , I don't have the Admin privilege . Hence I am not able to set the "System Variable".
I have access only to "User Variable" where I can set only the Java_Home.
Can I use Maven without adding the M2_Home and editing the Path variable ?
A: It depends if you are using it inside an ide or building project from terminal.
*
*If you are using an IDE, there is probably an embedded maven ( there is one inside Eclipse and Intellij IDEA)
*If you are building using CLI you can invoke maven using the full path
for instance :
/home/<your_folder>/tools/apache-maven-3.5.0/bin/mvn clean install from your project path
|
Q: Can I use Maven without setting the Environment variable? I want to use Maven for my project.
In my office computer , I don't have the Admin privilege . Hence I am not able to set the "System Variable".
I have access only to "User Variable" where I can set only the Java_Home.
Can I use Maven without adding the M2_Home and editing the Path variable ?
A: It depends if you are using it inside an ide or building project from terminal.
*
*If you are using an IDE, there is probably an embedded maven ( there is one inside Eclipse and Intellij IDEA)
*If you are building using CLI you can invoke maven using the full path
for instance :
/home/<your_folder>/tools/apache-maven-3.5.0/bin/mvn clean install from your project path
A: You could set the M2_HOME user variable even you are not an administrator, and the variable path is unnecessary, you could easily do the same task referencing the maven fullpath bin directory.
A: Sure you can, you just need to build your project from maven home actualy
Here is an example from stackoverflow
A: If you don't have admin rights, simply set the path till Maven's bin in lets say MAVEN_HOME in user variables.
Then go to the Path variable in user variables and add MAVEN_HOME to it.
You are all set then, just go to command prompt and type mvn -version and you should be good with maven setup in your system.
A: We can add .bat file and link it to cmd by default so whenever you open the terminal that code will execute and set your variable
You can refer more in detail here.
Update:
For Windows 10 user can add detail for your account and doesn't require admin access. Search for below text in windows search bar
Edit Environment variables for your Account
|
stackoverflow
|
{
"language": "en",
"length": 308,
"provenance": "stackexchange_0000F.jsonl.gz:837774",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457619"
}
|
07d93ba2224f9c45103576856d6895e4b62f287a
|
Stackoverflow Stackexchange
Q: How to check user input against pattern? In my Ruby on Rails application I need to check user input against patterns consisting of letters, numbers and a few special characters (like dashes and underscores) and I don't know how to do it.
For example, if the pattern is LL-NNNN and the user submits a string AB-0001, that would be valid.
If the pattern is NN-LL and the user submits 77-ABC, that would be invalid.
I was thinking about converting each pattern into a regular expression, but since each user can define their own pattern (which means there will be many of them) I am concerned that this might lead to unexpected results.
Can anybody tell me what's the best way to solve this?
A: In a loop, check if each character from the input string satisfies the corresponding pattern-character.
def match?(pattern, input)
return false if pattern.length != input.length
pattern.each_char.with_index.all? do |char, i|
case char
when 'L' then input[i] =~ /[A-Z]/
when 'N' then input[i] =~ /[0-9]/
when '-' then input[i] == '-'
else raise 'invalid pattern'
end
end
end
match?('LL-NNNN', 'AB-1234') #=> true
match?('NN-LL', '77-ABC') #=> false
match?('NN-LL', '77-99') #=> false
match?('NN-LL', '77-AB') #=> true
|
Q: How to check user input against pattern? In my Ruby on Rails application I need to check user input against patterns consisting of letters, numbers and a few special characters (like dashes and underscores) and I don't know how to do it.
For example, if the pattern is LL-NNNN and the user submits a string AB-0001, that would be valid.
If the pattern is NN-LL and the user submits 77-ABC, that would be invalid.
I was thinking about converting each pattern into a regular expression, but since each user can define their own pattern (which means there will be many of them) I am concerned that this might lead to unexpected results.
Can anybody tell me what's the best way to solve this?
A: In a loop, check if each character from the input string satisfies the corresponding pattern-character.
def match?(pattern, input)
return false if pattern.length != input.length
pattern.each_char.with_index.all? do |char, i|
case char
when 'L' then input[i] =~ /[A-Z]/
when 'N' then input[i] =~ /[0-9]/
when '-' then input[i] == '-'
else raise 'invalid pattern'
end
end
end
match?('LL-NNNN', 'AB-1234') #=> true
match?('NN-LL', '77-ABC') #=> false
match?('NN-LL', '77-99') #=> false
match?('NN-LL', '77-AB') #=> true
A: If the pattern is always going to be a combination of L => Letter, N => number, and - you could convert it into a regex with Regex.new(value)
The whole thing would look like this for either case
def match(pattern, value)
/\A#{pattern.gsub(/[LN]/, 'L' => '[a-zA-Z]', 'N' => '\d')}\z/.match(value)
end
and this for only upper case
def match(pattern, value)
/\A#{pattern.gsub(/[LN]/, 'L' => '[A-Z]', 'N' => '\d')}\z/.match(value)
end
You could even do the conversion to regex format early, and store the regex in the DB instead of the pattern to optimize processing time.
def regex_from_pattern(pattern)
"\\A#{pattern.gsub(/[LN]/, 'L' => '[a-zA-Z]', 'N' => '\d')}\\z"
end
def match(regex_string, value)
Regexp.new(regex_string).match(value)
end
A: Because we like one-liners so much in Ruby, here's a quick hack.
Replace the input characters with their corresponding pattern-character:
'AB-1234'.gsub(/[A-Z]/, 'N') #=> "NN-1234"
.gsub(/[0-9]/, 'L') #=> "NN-LLLL"
And compare the result to the pattern:
'AB-1234'.gsub(/[A-Z]/, 'N').gsub(/[0-9]/, 'L') == 'NN-LLLL'
#=> true
A: You can create regexp builder and Regexp.escape will help you.
Let's assume you've set user defined pattern alphabet:
ALPHABET = 'LN-_:=.\\'
Then you can check if user's pattern is right:
PATTERN_REGEXP = Regexp.new('\A[%s]+\z' % Regexp.escape(ALPHABET))
def is_pattern_ok?(pattern)
PATTERN_REGEXP =~ pattern
end
Next step is to created user defined input regexp string from his pattern:
def regexp_str_from(pattern)
('\A%s\z' % Regexp.escape(pattern))
.gsub('N', '\d')
.gsub('L', '[a-zA-Z]'))
end
And save it somewhere in user settings in DB.
So, you can validate user input with user defined pattern:
Regexp.new(regexp_str) =~ user_input
Edited: Note: Regexp.escape is mandatory to avoid "unexpected results".
A: You can use this in our model
validates_format_of :your_field_name, with: /(your regex)/i, on: :create
|
stackoverflow
|
{
"language": "en",
"length": 457,
"provenance": "stackexchange_0000F.jsonl.gz:837791",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457693"
}
|
b9404ee945f9c33f91542a7df8d626444c670fb4
|
Stackoverflow Stackexchange
Q: 3D Image Rotation Simple ITK Python I'm trying to rotate a 3D-Image with Simple ITK.
Here is my Code:
imagetoresize is the original image. The size of the image is (512,512,149)
targetimage = imagetoresize
origin = imagetoresize.GetOrigin()
targetimage = imagetoresize
imagetoresize.SetOrigin((0,0,0))
transform = sitk.VersorTransform((0,0,1), np.pi)
transform.SetCenter((256,256,74))
outimage=sitk.Resample(imagetoresize,targetimage.GetSize(),transform,sitk.sitkLinear,[0,0,0], imagetoresize.GetSpacing(), imagetoresize.GetDirection())
outimage.SetOrigin(origin)
The code rotates the image but the center is shifted.Orginal Image
Image after rotate
Can someone explain to me why the center is shifted?
Any help will be much appreciated.
A: You are setting the center of rotation in pixels and not in physical space.
SimpleITK ( and ITK ) perform transformation and resampling in physical space and not index space. It should be unnecessary to set the origin of you image to 0. I believe the you should use imagetoresize.TransformContinuousIndexToPhysicalPoint(center_index) to obtain the center in physical space.
|
Q: 3D Image Rotation Simple ITK Python I'm trying to rotate a 3D-Image with Simple ITK.
Here is my Code:
imagetoresize is the original image. The size of the image is (512,512,149)
targetimage = imagetoresize
origin = imagetoresize.GetOrigin()
targetimage = imagetoresize
imagetoresize.SetOrigin((0,0,0))
transform = sitk.VersorTransform((0,0,1), np.pi)
transform.SetCenter((256,256,74))
outimage=sitk.Resample(imagetoresize,targetimage.GetSize(),transform,sitk.sitkLinear,[0,0,0], imagetoresize.GetSpacing(), imagetoresize.GetDirection())
outimage.SetOrigin(origin)
The code rotates the image but the center is shifted.Orginal Image
Image after rotate
Can someone explain to me why the center is shifted?
Any help will be much appreciated.
A: You are setting the center of rotation in pixels and not in physical space.
SimpleITK ( and ITK ) perform transformation and resampling in physical space and not index space. It should be unnecessary to set the origin of you image to 0. I believe the you should use imagetoresize.TransformContinuousIndexToPhysicalPoint(center_index) to obtain the center in physical space.
|
stackoverflow
|
{
"language": "en",
"length": 139,
"provenance": "stackexchange_0000F.jsonl.gz:837799",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457722"
}
|
48f4069678ee722fe2b702805d9f403743169a01
|
Stackoverflow Stackexchange
Q: "Auto-property accessor is never used" warning from ReSharper Our Application is an MVC Application . I tried to run code analysis using ReSharper. I am getting "Auto-property accessor is never used" as warnings in many of my view model properties.
For example, ReSharper shows the warning on this:
public bool IsLegalEntry { get; set; }
Can I make a private setter, or can anybody suggest an alternative?
A: You could make the setter private
public bool IsLegalEntry { get; private set; }
However, this could cause a runtime error if the setter is used implicitly. Alternatively you could decorate the setter with the JetBrains.Annotations.UsedImplicitlyAttribute.
public bool IsLegalEntry { get; [UsedImplicitly] set; }
|
Q: "Auto-property accessor is never used" warning from ReSharper Our Application is an MVC Application . I tried to run code analysis using ReSharper. I am getting "Auto-property accessor is never used" as warnings in many of my view model properties.
For example, ReSharper shows the warning on this:
public bool IsLegalEntry { get; set; }
Can I make a private setter, or can anybody suggest an alternative?
A: You could make the setter private
public bool IsLegalEntry { get; private set; }
However, this could cause a runtime error if the setter is used implicitly. Alternatively you could decorate the setter with the JetBrains.Annotations.UsedImplicitlyAttribute.
public bool IsLegalEntry { get; [UsedImplicitly] set; }
A: Alternative to "warning fixing/suppressing" paradigm, you can add testing project to your solution. Then write a test for you business logic hitting the accessor(s) in question among other things.
Not sure this is the action you were looking for, however
*
*it provides the effect you were after
*saves for redundant annotation attributes
*adds testing bonus
|
stackoverflow
|
{
"language": "en",
"length": 170,
"provenance": "stackexchange_0000F.jsonl.gz:837825",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457784"
}
|
ea66148fe4e3b65e7be4ea104c147f093e347c91
|
Stackoverflow Stackexchange
Q: How to use ng-include with Angular 2/4 I tried to include a html component in an other but I don't know how to resolve it by using ngInclude in angular 2/4...
my html component
<form class="form-horizontal">
<div ng-include="'folder_consult.html'"></div>
<div class="panel panel-info">
<div class="panel-heading">
...
</div>
</div>
</form>
I tried this code, but it does not work ..
Issue for using ngInclude ?
|
Q: How to use ng-include with Angular 2/4 I tried to include a html component in an other but I don't know how to resolve it by using ngInclude in angular 2/4...
my html component
<form class="form-horizontal">
<div ng-include="'folder_consult.html'"></div>
<div class="panel panel-info">
<div class="panel-heading">
...
</div>
</div>
</form>
I tried this code, but it does not work ..
Issue for using ngInclude ?
|
stackoverflow
|
{
"language": "en",
"length": 63,
"provenance": "stackexchange_0000F.jsonl.gz:837852",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457855"
}
|
39593b91071ae23aa04c6b09757c96faa4662c57
|
Stackoverflow Stackexchange
Q: Saving user meta as single values or an array I'm working on a plugin which is going to save about 10 custom user meta for certain users bound to the plugin. Among these metas we find: Address, zip, occupation, etc...
These metas will only be used by the plugin, and mostly (if not always) all of them will be fetched from the DB together to be shown in a table view in the admin.
So, I'm thinking about the best way to save these values.
I could do this:
add_user_meta( $user_id, 'address', 'kings street 45');
add_user_meta( $user_id, 'zip', '12345');
add_user_meta( $user_id, 'occupation', 'nurse');
... some more meta
Or would it be better to do this:
add_user_meta( $user_id, 'plugin_name_user_meta', array(
'address' => 'kings street 45'
'zip' => '12345'
'occupation' => 'nurse')
... some more meta
);
A: In WordPress I prefer to work with arrays because in helps keeping my data organized, so I would go the second way. Nevertheless, if you go the first way, prefix all the metas with a unique ID related to your plugin.
|
Q: Saving user meta as single values or an array I'm working on a plugin which is going to save about 10 custom user meta for certain users bound to the plugin. Among these metas we find: Address, zip, occupation, etc...
These metas will only be used by the plugin, and mostly (if not always) all of them will be fetched from the DB together to be shown in a table view in the admin.
So, I'm thinking about the best way to save these values.
I could do this:
add_user_meta( $user_id, 'address', 'kings street 45');
add_user_meta( $user_id, 'zip', '12345');
add_user_meta( $user_id, 'occupation', 'nurse');
... some more meta
Or would it be better to do this:
add_user_meta( $user_id, 'plugin_name_user_meta', array(
'address' => 'kings street 45'
'zip' => '12345'
'occupation' => 'nurse')
... some more meta
);
A: In WordPress I prefer to work with arrays because in helps keeping my data organized, so I would go the second way. Nevertheless, if you go the first way, prefix all the metas with a unique ID related to your plugin.
A: I disagree with the first answer and I would use your first suggestion.
Why? Because if you use add_user_meta for each field you have a seperate field in the database for each value. That means:
1) You can do meta and Wildcard Queries e.g. "Select all user with a ZIP starting with 11". This is impossible if you save an array especially as the array will be saved in serialized format.
Keep this possibility open! Some day you may want to do complicated queries on this data even if it is not the case currently.
Have a look at the WP Meta Query class and even better the WP User Query class:
https://codex.wordpress.org/Class_Reference/WP_Meta_Query
https://codex.wordpress.org/Class_Reference/WP_User_Query#Custom_Field_Parameters
2) You do not have a disadvantage in extensibility: As these fields are already saved in a meta table and not within fixed columns you can add and remove values dynamically.
However @Juan is right with the hint on prefixes: You definitly should prefix your meta_values in order to avoid collisions.
|
stackoverflow
|
{
"language": "en",
"length": 344,
"provenance": "stackexchange_0000F.jsonl.gz:837858",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44457868"
}
|
c1f07e4d372ec3550ce66330aa27334777765709
|
Stackoverflow Stackexchange
Q: How can kSCNetworkReachabilityFlagsIsWWAN be true and kSCNetworkReachabilityFlagsReachable be false In iOS reachability, synchronously checking the SCNetworkReachabilityFlags and getting a combination of flags which are:
*
*kSCNetworkReachabilityFlagsReachable: 0
*kSCNetworkReachabilityFlagsIsWWAN: 1
According to Apple's documentation (but also the reachability implementations in other libraries such as AFNetworking), kSCNetworkReachabilityFlagsIsWWAN indicates it is available by a cellular network, but when this is true, the overall kSCNetworkReachabilityFlagsReachable should be true also.
This seems to happen only when you switch from Wifi to Mobile. (When you start on Mobile, it generates, correctly both flags as true).
Any ideas how this situation might be generated (new in 10.3.2?), or is my understanding of the flag meanings wrong?
A: I had a similar issue, and the issue was that the user had disabled Mobile Data for the app in question
|
Q: How can kSCNetworkReachabilityFlagsIsWWAN be true and kSCNetworkReachabilityFlagsReachable be false In iOS reachability, synchronously checking the SCNetworkReachabilityFlags and getting a combination of flags which are:
*
*kSCNetworkReachabilityFlagsReachable: 0
*kSCNetworkReachabilityFlagsIsWWAN: 1
According to Apple's documentation (but also the reachability implementations in other libraries such as AFNetworking), kSCNetworkReachabilityFlagsIsWWAN indicates it is available by a cellular network, but when this is true, the overall kSCNetworkReachabilityFlagsReachable should be true also.
This seems to happen only when you switch from Wifi to Mobile. (When you start on Mobile, it generates, correctly both flags as true).
Any ideas how this situation might be generated (new in 10.3.2?), or is my understanding of the flag meanings wrong?
A: I had a similar issue, and the issue was that the user had disabled Mobile Data for the app in question
|
stackoverflow
|
{
"language": "en",
"length": 132,
"provenance": "stackexchange_0000F.jsonl.gz:837915",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458020"
}
|
e4229b1ab8c0bf26af7a49649cd66e78dd0b39f1
|
Stackoverflow Stackexchange
Q: How to reply to a notification using NotificationListener Service in android I am working on an android app where I need to get incoming message from whatsapp or any other chatting app and then reply to that message using my app.
I am able to extract message and other data from notification using NotificationListener Service, but I don't know how to reply to that notification from my app.
I got all the information using the following method of NotificationListener Class.
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
Intent intent = new Intent(this, ChatHeadService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
String key = sbn.getKey(); // notification key
PendingIntent intent1 = sbn.getNotification().contentIntent; // pending intent
String pack = sbn.getPackageName(); // package name of app
Bundle noti = sbn.getNotification().extras; // extra bundle of notification
String name = noti.getString("android.title"); // name of the sender
Bitmap img = sbn.getNotification().largeIcon; // the icon of the sender user
CharSequence[] textlines = noti.getCharSequenceArray("android.textLines");
if (textlines != null)
Log.i("textlines", textlines.toString());
Now I need to reply to the above notification!
|
Q: How to reply to a notification using NotificationListener Service in android I am working on an android app where I need to get incoming message from whatsapp or any other chatting app and then reply to that message using my app.
I am able to extract message and other data from notification using NotificationListener Service, but I don't know how to reply to that notification from my app.
I got all the information using the following method of NotificationListener Class.
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
Intent intent = new Intent(this, ChatHeadService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
String key = sbn.getKey(); // notification key
PendingIntent intent1 = sbn.getNotification().contentIntent; // pending intent
String pack = sbn.getPackageName(); // package name of app
Bundle noti = sbn.getNotification().extras; // extra bundle of notification
String name = noti.getString("android.title"); // name of the sender
Bitmap img = sbn.getNotification().largeIcon; // the icon of the sender user
CharSequence[] textlines = noti.getCharSequenceArray("android.textLines");
if (textlines != null)
Log.i("textlines", textlines.toString());
Now I need to reply to the above notification!
|
stackoverflow
|
{
"language": "en",
"length": 169,
"provenance": "stackexchange_0000F.jsonl.gz:837931",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458068"
}
|
9d3cd10bb9426dbcd4955bd7c4fb75007d2f3262
|
Stackoverflow Stackexchange
Q: Alternative to possessive quantifier in python I am trying to match all occurences of the String Article followed by a number (single or more digits) which are not followed by an opening parentheses. In Sublime Text, I am using the following regex:
Article\s[0-9]++(?!\()
to search the following String:
Article 29
Article 30(1)
which does not match Article 30(1) (as I expect it to) but Article 29 and Article 1.
When attempting to do the same in Python (3) using
import re
article_list = re.findall(r'Article\s[0-9]++(?!\()', "Article 30(1)")
I get an the following Error as I am using a (nested) possessive quantifier which is not supported by Python regex. Is there any way to match what I want it (not) to match in Python?
A: You can also emulate an atomic group (?>...) around what you want to match, using the (?=(...))\1 workaround:
(?=(Article\s[0-9]+))\1(?!\()
(a lookahead behaves naturally like an a atomic group, all you need is a capture and a backreference)
|
Q: Alternative to possessive quantifier in python I am trying to match all occurences of the String Article followed by a number (single or more digits) which are not followed by an opening parentheses. In Sublime Text, I am using the following regex:
Article\s[0-9]++(?!\()
to search the following String:
Article 29
Article 30(1)
which does not match Article 30(1) (as I expect it to) but Article 29 and Article 1.
When attempting to do the same in Python (3) using
import re
article_list = re.findall(r'Article\s[0-9]++(?!\()', "Article 30(1)")
I get an the following Error as I am using a (nested) possessive quantifier which is not supported by Python regex. Is there any way to match what I want it (not) to match in Python?
A: You can also emulate an atomic group (?>...) around what you want to match, using the (?=(...))\1 workaround:
(?=(Article\s[0-9]+))\1(?!\()
(a lookahead behaves naturally like an a atomic group, all you need is a capture and a backreference)
A: Python re does not support possessive quantifiers. You may consider using Python PyPi regex module instead, that supports this type of quantifiers. Or use the following work-arounds.
You need to either add a digit to the lookahead:
Article\s[0-9]+(?![(0-9])
^^^
See this regex demo.
Alternatively, use a word boundary:
Article\s[0-9]+\b(?!\()
^
See this regex demo.
A: Just an additional information to the work-arounds:
From Python 3.11 on, the re module supports atomic grouping and possessive quantifiers, see https://docs.python.org/3.11/whatsnew/3.11.html#re and https://github.com/python/cpython/issues/34627.
|
stackoverflow
|
{
"language": "en",
"length": 241,
"provenance": "stackexchange_0000F.jsonl.gz:837948",
"question_score": "12",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458122"
}
|
7c96af9ae29ffdac2d09511c6d73e53380ea970d
|
Stackoverflow Stackexchange
Q: How to read OTP from gmail in protractor? Conf.js
How to read OTP from gmail. I tried but am not able to and also am not getting any error.
A: You can use a few mail listener approaches for a cleaner solution, inbucket and mail-listener2 are two popular solutions for email reading purposes in e2e testing.
I would personally recommend inbucket for its simple implementation. You can run it as a docker container with a simple command mentioned here, and then consume the exposed APIs using this Javascript Client.
You can also use mail-listener2, it also offers the same functionality but requires a few configuration in the .conf file.
|
Q: How to read OTP from gmail in protractor? Conf.js
How to read OTP from gmail. I tried but am not able to and also am not getting any error.
A: You can use a few mail listener approaches for a cleaner solution, inbucket and mail-listener2 are two popular solutions for email reading purposes in e2e testing.
I would personally recommend inbucket for its simple implementation. You can run it as a docker container with a simple command mentioned here, and then consume the exposed APIs using this Javascript Client.
You can also use mail-listener2, it also offers the same functionality but requires a few configuration in the .conf file.
A: Here is the code I came up with. I made the assumption that the OTP is inside the first email in your inbox. It is also helpful to turn off the setting in gmail that allows similar messages to group together as this can cause issues.
(Please pardon the use of browser.driver.sleep(), this can be replaced)
var tokenKey;
function getKey(a) {
// Open email from *******@gmail.com
// Its a non-angular site, so need to turn off synchronization
browser.ignoreSynchronization = true;
browser.driver.sleep(3000);
// Opens a new tab in which you retrieve OTP
browser.driver.executeScript(function() {
(function(a){
document.body.appendChild(a);
a.setAttribute('href', 'https://gmail.com');
a.dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
return e;
}(document.createEvent('MouseEvents'))))}(document.createElement('a')));
});
browser.driver.sleep(3000);
// Switch to new tab
browser.getAllWindowHandles().then(function (handles) {
browser.switchTo().window(handles[1]);
if(a){
var username = browser.driver.findElement(by.xpath('//*[@id="identifierId"]'));
username.sendKeys('*********@gmail.com');
browser.driver.findElement(by.id('identifierNext')).click();
}
var EC = protractor.ExpectedConditions;
var firstEmail = element(by.xpath('//*[@id=":3d"]'));
var passwordInput = element(by.xpath('//*[@id="password"]/div[1]/div/div[1]/input'));
if(a){
browser.wait(EC.visibilityOf(passwordInput), 5000);
browser.driver.sleep(1000);
passwordInput.sendKeys('*********');
browser.driver.findElement(by.id('passwordNext')).click();
}
browser.wait(EC.visibilityOf(firstEmail), 5000);
firstEmail.click().then(function () {
browser.driver.sleep(2000);
element.all(by.cssContainingText('div', 'Text Leading up to password:')).count().then(function (results) {
element.all(by.cssContainingText('div', 'Text Leading up to password::')).get(results-1).getText().then(function (token) {
//console.log(token);
tokenKey = token.substring(token.indexOf('-')+1, token.length);
//console.log(tokenKey);
});
});
});
browser.driver.close();
browser.switchTo().window(handles[0]);
});
}
|
stackoverflow
|
{
"language": "en",
"length": 300,
"provenance": "stackexchange_0000F.jsonl.gz:837987",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458259"
}
|
4a35ef030db3812d70a84c154ef37e4c25f29e1a
|
Stackoverflow Stackexchange
Q: How to escape "${}" in cloudformations "Fn::Sub" I want this resource to work with the !Sub (or Fn::Sub) intrinsic function
Resource: !Sub 'arn:aws:iam::${AWS::AccountId}:user/${aws:username}'
The aws:username is a pollicy variable that mustn't be replaced.
One solution would be to use Fn::Join instead and write a bit more boilerplate code.
Better: Can you escape the ${aws:username} so that !Sub will work here? Unfortunately, the documentation does not mention anything about escaping.
A: You actually can escape $ characters with ${!}.
So your resource would look like this:
Resource: !Sub 'arn:aws:iam::${AWS::AccountId}:user/${!aws:username}'
It is mentioned in the docs under the string parameter section.
To write a dollar sign and curly braces (${}) literally, add an
exclamation point (!) after the open curly brace, such as ${!Literal}.
AWS CloudFormation resolves this text as ${Literal}.
|
Q: How to escape "${}" in cloudformations "Fn::Sub" I want this resource to work with the !Sub (or Fn::Sub) intrinsic function
Resource: !Sub 'arn:aws:iam::${AWS::AccountId}:user/${aws:username}'
The aws:username is a pollicy variable that mustn't be replaced.
One solution would be to use Fn::Join instead and write a bit more boilerplate code.
Better: Can you escape the ${aws:username} so that !Sub will work here? Unfortunately, the documentation does not mention anything about escaping.
A: You actually can escape $ characters with ${!}.
So your resource would look like this:
Resource: !Sub 'arn:aws:iam::${AWS::AccountId}:user/${!aws:username}'
It is mentioned in the docs under the string parameter section.
To write a dollar sign and curly braces (${}) literally, add an
exclamation point (!) after the open curly brace, such as ${!Literal}.
AWS CloudFormation resolves this text as ${Literal}.
|
stackoverflow
|
{
"language": "en",
"length": 130,
"provenance": "stackexchange_0000F.jsonl.gz:838008",
"question_score": "49",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458304"
}
|
75d5b6d14fa85f6fda30413c6cde38429b1140a7
|
Stackoverflow Stackexchange
Q: Gitlab-CI runner: ignore self-signed certificate gitlab-ci-multi-runner register
gave me
couldn't execute POST against https://xxxx/ci/api/v1/runners/register.json:
Post https://xxxx/ci/api/v1/runners/register.json:
x509: cannot validate certificate for xxxx because it doesn't contain any IP SANs
Is there a way to disable certification validation?
I'm using Gitlab 8.13.1 and gitlab-ci-multi-runner 1.11.2.
A: Ok I followed step by step this post http://moonlightbox.logdown.com/posts/2016/09/12/gitlab-ci-runner-register-x509-error and then it worked like a charm.
To prevent dead link I copy the steps below:
First edit ssl configuration on the GitLab server (not the runner)
vim /etc/pki/tls/openssl.cnf
[ v3_ca ]
subjectAltName=IP:192.168.1.1 <---- Add this line. 192.168.1.1 is your GitLab server IP.
Re-generate self-signed certificate
cd /etc/gitlab/ssl
sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/gitlab/ssl/192.168.1.1.key -out /etc/gitlab/ssl/192.168.1.1.crt
sudo openssl dhparam -out /etc/gitlab/ssl/dhparam.pem 2048
sudo gitlab-ctl restart
Copy the new CA to the GitLab CI runner
scp /etc/gitlab/ssl/192.168.1.1.crt [email protected]:/etc/gitlab-runner/certs
Thanks @Moon Light @Wassim Dhif
|
Q: Gitlab-CI runner: ignore self-signed certificate gitlab-ci-multi-runner register
gave me
couldn't execute POST against https://xxxx/ci/api/v1/runners/register.json:
Post https://xxxx/ci/api/v1/runners/register.json:
x509: cannot validate certificate for xxxx because it doesn't contain any IP SANs
Is there a way to disable certification validation?
I'm using Gitlab 8.13.1 and gitlab-ci-multi-runner 1.11.2.
A: Ok I followed step by step this post http://moonlightbox.logdown.com/posts/2016/09/12/gitlab-ci-runner-register-x509-error and then it worked like a charm.
To prevent dead link I copy the steps below:
First edit ssl configuration on the GitLab server (not the runner)
vim /etc/pki/tls/openssl.cnf
[ v3_ca ]
subjectAltName=IP:192.168.1.1 <---- Add this line. 192.168.1.1 is your GitLab server IP.
Re-generate self-signed certificate
cd /etc/gitlab/ssl
sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/gitlab/ssl/192.168.1.1.key -out /etc/gitlab/ssl/192.168.1.1.crt
sudo openssl dhparam -out /etc/gitlab/ssl/dhparam.pem 2048
sudo gitlab-ctl restart
Copy the new CA to the GitLab CI runner
scp /etc/gitlab/ssl/192.168.1.1.crt [email protected]:/etc/gitlab-runner/certs
Thanks @Moon Light @Wassim Dhif
A: Based on Wassim's answer, and gitlab documentation about tls-self-signed and custom CA-signed certificates, here's to save some time if you're not the admin of the gitlab server but just of the server with the runners (and if the runner is run as root):
SERVER=gitlab.example.com
PORT=443
CERTIFICATE=/etc/gitlab-runner/certs/${SERVER}.crt
# Create the certificates hierarchy expected by gitlab
sudo mkdir -p $(dirname "$CERTIFICATE")
# Get the certificate in PEM format and store it
openssl s_client -connect ${SERVER}:${PORT} -showcerts </dev/null 2>/dev/null | sed -e '/-----BEGIN/,/-----END/!d' | sudo tee "$CERTIFICATE" >/dev/null
# Register your runner
gitlab-runner register --tls-ca-file="$CERTIFICATE" [your other options]
Update 1: CERTIFICATE must be an absolute path to the certificate file.
Update 2: it might still fail with custom CA-signed because of gitlab-runner bug #2675
A: The following steps worked in my environment. (Ubuntu)
Download certificate
I did not have access to the gitlab server. Therefore,
*
*Open https://some-host-gitlab.com in browser (I use chrome).
*View site information, usually a green lock in URL bar.
*Download/Export certificate by navigating to certificate information(chrome, firefox has this option)
In gitlab-runner host
*
*Rename the downloaded certificate with .crt
$ mv some-host-gitlab.com some-host-gitlab.com.crt
*Register the runner now with this file
$ sudo gitlab-runner register --tls-ca-file /path/to/some-host-gitlab.com.crt
I was able to register runner to a project.
A: Currently there is no possibility to run the multi runner with an insecure ssl option.
There is currently an open issue at GitLab about that.
Still you should be able to get your certificate, make it a PEM file and give it to the runner command using --tls-ca-file
To craft the PEM file use openssl.
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
A: In my setup the following the following worked as well. It's just important that IP/Name used for creating certificate matches IP/Name used for registering the runner.
gitlab-runner register --tls-ca-file /my/path/gitlab/gitlab.myserver.com.pem
Furthermore, it could be necessary to add a line for hostname lookup to the runners config.toml file also (section [runners.docker]):
extra_hosts = ["git.domain.com:192.168.99.100"]
see also https://gitlab.com/gitlab-org/gitlab-runner/issues/2209
In addition, there could be some network-trouble if for gitlab/gitlab-runner network-mode host is used, it has to be added to the config.toml as well, as it starts additional containers, which otherwise could have a problem to connect to the gitlab-host ((section [runners.docker]):
network_mode="host"
Finally, there might be an issue with the self-signed SSL-Cert (https://gitlab.com/gitlab-org/gitlab-runner/issues/2659).
A dirty workaround is to add
environment = ["GIT_SSL_NO_VERIFY=true"]
to the [[runners]] section.
A: In my case I got it working by adding the path to the .pem file as following:
sudo gitlab-runner register --tls-ca-file /my/path/gitlab/gitlab.myserver.com.pem
Often, gitlab-runners are hosted in a docker container. In that case, one needs to make sure that the tls-ca-file is available in the container.
|
stackoverflow
|
{
"language": "en",
"length": 585,
"provenance": "stackexchange_0000F.jsonl.gz:838040",
"question_score": "40",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458410"
}
|
3ed0effff023ce4d0bc93fbd16daadf5c7ab550e
|
Stackoverflow Stackexchange
Q: How to remove default Metrics data provided by Spring Actuator I am trying to get Production metrics for my application. I am using Actuator on top of Spring Boot. Actuator exposes an endpoint for that "/metrics". I have Autowired CounterService class to get my own metrics data. I will be displaying the metrics data in one of our Application Management UI. The problem here is that I don't want all the default metrics data, as the Response JSON given back by the /metrics endpoint is kind off heavy for me to parse and most of the default metrics data are useless for me and give it to the UI. I have gone through the Spring Docs, I didn't get any help.
Appreciate your help on this!
A: Oh So I found a way to deal with the scenario. Actually Spring This GitHub Link pretty much solves my problem. Actuator Supports Reqex support to query for the data you need. So my url looks like this now : http://{{hostname}}/metrics/counter.*.count instead of this http://{{hostname}}/metrics/. Hope this helps.
|
Q: How to remove default Metrics data provided by Spring Actuator I am trying to get Production metrics for my application. I am using Actuator on top of Spring Boot. Actuator exposes an endpoint for that "/metrics". I have Autowired CounterService class to get my own metrics data. I will be displaying the metrics data in one of our Application Management UI. The problem here is that I don't want all the default metrics data, as the Response JSON given back by the /metrics endpoint is kind off heavy for me to parse and most of the default metrics data are useless for me and give it to the UI. I have gone through the Spring Docs, I didn't get any help.
Appreciate your help on this!
A: Oh So I found a way to deal with the scenario. Actually Spring This GitHub Link pretty much solves my problem. Actuator Supports Reqex support to query for the data you need. So my url looks like this now : http://{{hostname}}/metrics/counter.*.count instead of this http://{{hostname}}/metrics/. Hope this helps.
A: Have you tried wrapping the response class from metrics, with a Custom class?
|
stackoverflow
|
{
"language": "en",
"length": 190,
"provenance": "stackexchange_0000F.jsonl.gz:838091",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458560"
}
|
0f1e6bc76461a76517480aa3862b83b1c2715083
|
Stackoverflow Stackexchange
Q: Indexing elements in matrix and corresponding column numbers I have a matrix full of integers and I need to create an index where for each of these integers I get the numbers of columns containing it (using R).
For instance, suppose I have this table:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 31738 3136023010 777150982 2318301701 44 3707934113
[2,] 1687741813 44 31738 1284682632 462137835 445275140
[3,] 44 123 123 31738 1215490197 123
In my case I have 31738 being present in columns:
1,2 and 4
elements: [1,1], [2,3] and [3,4]
and 44 being present in columns 1,2 and 5 (elements [3,1], [2,2] and [1,5]
So for all elements in my table, I need to have an index like
31738 = 1 3 4
3136023010 = 2
777150982 = 3
44 = 1 2 3
....
123 = 2 3 6
etc
edit: i corrected my mistake pointed out in comment bellow.
A: We can do
setNames(lapply(unique(m1), function(i)
as.vector(which(m1==i, arr.ind = TRUE)[,2])), unique(m1))
Or another option is
split(col(m1), m1)
data
m1 <- structure(c(31738, 1687741813, 44, 3136023010, 44, 123, 777150982,
31738, 123, 2318301701, 1284682632, 31738, 44, 462137835, 1215490197,
3707934113, 445275140, 123), .Dim = c(3L, 6L))
|
Q: Indexing elements in matrix and corresponding column numbers I have a matrix full of integers and I need to create an index where for each of these integers I get the numbers of columns containing it (using R).
For instance, suppose I have this table:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 31738 3136023010 777150982 2318301701 44 3707934113
[2,] 1687741813 44 31738 1284682632 462137835 445275140
[3,] 44 123 123 31738 1215490197 123
In my case I have 31738 being present in columns:
1,2 and 4
elements: [1,1], [2,3] and [3,4]
and 44 being present in columns 1,2 and 5 (elements [3,1], [2,2] and [1,5]
So for all elements in my table, I need to have an index like
31738 = 1 3 4
3136023010 = 2
777150982 = 3
44 = 1 2 3
....
123 = 2 3 6
etc
edit: i corrected my mistake pointed out in comment bellow.
A: We can do
setNames(lapply(unique(m1), function(i)
as.vector(which(m1==i, arr.ind = TRUE)[,2])), unique(m1))
Or another option is
split(col(m1), m1)
data
m1 <- structure(c(31738, 1687741813, 44, 3136023010, 44, 123, 777150982,
31738, 123, 2318301701, 1284682632, 31738, 44, 462137835, 1215490197,
3707934113, 445275140, 123), .Dim = c(3L, 6L))
|
stackoverflow
|
{
"language": "en",
"length": 194,
"provenance": "stackexchange_0000F.jsonl.gz:838098",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458587"
}
|
974341fd88c234ae0ee2c428cbe97b203b0539b9
|
Stackoverflow Stackexchange
Q: ASP.NET MVC Request ServerVariables I am using ASP.NET MVC, and need to obtain and log Request Information.
I'm looking at Microsoft.AspNetCore.Http.HttpRequest and do not see ServerVariables. Has this been removed?
Is there a way I can get to the same data as I could via System.Web.HttpRequest.ServerVariables?
Thanks!
Philip
A: Microsoft.AspNetCore.Http.HttpRequest is as the namespace says part of asp.net core. The ServerVariables is a collection of variables provided by IIS. As asp.net core does not depend on IIS this property doesn't exist anymore.
If do not use asp.net core this is the HttpRequest class to use.
|
Q: ASP.NET MVC Request ServerVariables I am using ASP.NET MVC, and need to obtain and log Request Information.
I'm looking at Microsoft.AspNetCore.Http.HttpRequest and do not see ServerVariables. Has this been removed?
Is there a way I can get to the same data as I could via System.Web.HttpRequest.ServerVariables?
Thanks!
Philip
A: Microsoft.AspNetCore.Http.HttpRequest is as the namespace says part of asp.net core. The ServerVariables is a collection of variables provided by IIS. As asp.net core does not depend on IIS this property doesn't exist anymore.
If do not use asp.net core this is the HttpRequest class to use.
|
stackoverflow
|
{
"language": "en",
"length": 96,
"provenance": "stackexchange_0000F.jsonl.gz:838134",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458707"
}
|
1a0d3395d4199bf802719cca3d5eab32d2f8fa78
|
Stackoverflow Stackexchange
Q: Can A Static Website Consist of JavaScript? Can a website with JavaScript consider as a static website? Or static website can only consist of pure HTML without JavaScript?
A: Yes! "static pages" means pages that are plain html instead of php or other dynamic page-producing technologies. These are the kind of files that look the same being loaded from the desktop as they do a remote server. Each page is always the same each time it's loaded.
It doesn't have to do with JS, which can appear on static and dynamic pages.
|
Q: Can A Static Website Consist of JavaScript? Can a website with JavaScript consider as a static website? Or static website can only consist of pure HTML without JavaScript?
A: Yes! "static pages" means pages that are plain html instead of php or other dynamic page-producing technologies. These are the kind of files that look the same being loaded from the desktop as they do a remote server. Each page is always the same each time it's loaded.
It doesn't have to do with JS, which can appear on static and dynamic pages.
A: A static site can use javascript. If you use bootstrap for the front-end it will come with js libraries that enhance the UX and look'n'fell for instance.
A dynamic site is a site with a server side language (php, python etc.)
You could therefore have a dynamic site without javascript ;)
A: tl;dr if the javascript code manipulates the DOM like a SPA does, it is a client-side dynamic webpage.
As far as the required server infrastructure is concerned, a website with JavaScript can still be considered static because it can be hosted by static hosting services (no server code involved).
But with the extensive use of JavaScript for Client-Side Rendering in Single Page Applications (SPAs) we have to introduce a second dimension of that classification: The way the Document Object Model (DOM) is generated in the browser.
With traditional static webpages the DOM is generated by the browser by parsing an HTML file. Pure static websites which just consist of HTML and maybe some simple JavaScript are therefore static in terms of hosting and DOM generation. In SPAs the DOM is generated by JavaScript creating and manipulating DOM Nodes through the DOM API. Typical SPAs are therefore static in terms of hosting, but dynamic in terms of DOM generation.
Blogpost: The Static Site Awakens and Strikes back
|
stackoverflow
|
{
"language": "en",
"length": 312,
"provenance": "stackexchange_0000F.jsonl.gz:838138",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458712"
}
|
5cd7e98440ca7ef7202b64de53382b126936e280
|
Stackoverflow Stackexchange
Q: How to base64 encode inputs in React? I am trying to post two inputs with axios and I want to base64 encode them before I send them.
A: Is better you use Buffer.from('Your String').toString('base64'), because new Buffer is deprecated
|
Q: How to base64 encode inputs in React? I am trying to post two inputs with axios and I want to base64 encode them before I send them.
A: Is better you use Buffer.from('Your String').toString('base64'), because new Buffer is deprecated
A: Deprecated since v6
const encodedString = new Buffer('your string here').toString('base64');
Use Instead
const encodedString = Buffer.from('your string here').toString('base64');
A: Consider using base-64 as well which is compatible with btoa and atob, worked for me in react and react native:
npm install base-64 --save
import {decode as base64_decode, encode as base64_encode} from 'base-64';
let encoded = base64_encode('YOUR_DECODED_STRING');
let decoded = base64_decode('YOUR_ENCODED_STRING');
In case you are using typescript, use @types/base-64 for typing
npm i --save-dev @types/base-64
|
stackoverflow
|
{
"language": "en",
"length": 115,
"provenance": "stackexchange_0000F.jsonl.gz:838188",
"question_score": "18",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458874"
}
|
dd647d514c51c19a2322718f0adfe1fe50828eab
|
Stackoverflow Stackexchange
Q: Tensorflow keeps all files. How to prevent that? Since updating to tensoflow version 1.0 which introduced the new Saver V2, tf does not delete old files any more with the 'max_to_keep' argument. This is a problem on my system since my models are pretty big but my free space is limited.
Using the dummy program below I end up with following files for every number from 1 to 10 while I only expect the last 3 (8,9,10) to actually be there.
*
*testfile-1.data-00000-of-00001
*testfile-1.index
*testfile-1.meta
program:
import tensorflow as tf
a = tf.Variable(name='a', initial_value=0)
addops = a+1
saver = tf.train.Saver(max_to_keep=3)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
sess.run(tf.global_variables_initializer())
for i in range(10):
sess.run(addops)
save_path = saver.save(sess, 'testfile', global_step=i+1)
sess.close()
Is this just me or this a known bug?
What are possible problems which could lead to this misbehavior?
Is there any log or smth similar I could get more information from?
A: I can reproduce this. It seems to be a bug.
However the problem is gone once I save into a different location (different from the executed .py file path)
save_path = saver.save(sess, 'data/testfile', global_step=i+1)
|
Q: Tensorflow keeps all files. How to prevent that? Since updating to tensoflow version 1.0 which introduced the new Saver V2, tf does not delete old files any more with the 'max_to_keep' argument. This is a problem on my system since my models are pretty big but my free space is limited.
Using the dummy program below I end up with following files for every number from 1 to 10 while I only expect the last 3 (8,9,10) to actually be there.
*
*testfile-1.data-00000-of-00001
*testfile-1.index
*testfile-1.meta
program:
import tensorflow as tf
a = tf.Variable(name='a', initial_value=0)
addops = a+1
saver = tf.train.Saver(max_to_keep=3)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
sess.run(tf.global_variables_initializer())
for i in range(10):
sess.run(addops)
save_path = saver.save(sess, 'testfile', global_step=i+1)
sess.close()
Is this just me or this a known bug?
What are possible problems which could lead to this misbehavior?
Is there any log or smth similar I could get more information from?
A: I can reproduce this. It seems to be a bug.
However the problem is gone once I save into a different location (different from the executed .py file path)
save_path = saver.save(sess, 'data/testfile', global_step=i+1)
|
stackoverflow
|
{
"language": "en",
"length": 189,
"provenance": "stackexchange_0000F.jsonl.gz:838214",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458947"
}
|
4f4e1ecf8f87cb89146e63ed648fcfd6f9a626c2
|
Stackoverflow Stackexchange
Q: Change in pickle file for same object I'm pickling an object, then do things to it, then pickle it again, and check it the object is still the same. Maybe not the best way to ensure equality, but a very strict and simple one.
However, I get unexpected difference in the pickle file on some machines running python2.7.
I used pickletools to analyze the resulting files.
The difference is additional PUT codes, though these registers are never accessed. When are PUT statements generated, and why are they generated differently when calling pickle twice on the same object?
|
Q: Change in pickle file for same object I'm pickling an object, then do things to it, then pickle it again, and check it the object is still the same. Maybe not the best way to ensure equality, but a very strict and simple one.
However, I get unexpected difference in the pickle file on some machines running python2.7.
I used pickletools to analyze the resulting files.
The difference is additional PUT codes, though these registers are never accessed. When are PUT statements generated, and why are they generated differently when calling pickle twice on the same object?
|
stackoverflow
|
{
"language": "en",
"length": 98,
"provenance": "stackexchange_0000F.jsonl.gz:838216",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44458953"
}
|
c8b955759a88fa0beb6a43675525d84bef2d5e96
|
Stackoverflow Stackexchange
Q: Play json Read and Default parameters for case class? I have a problem with default parameters and using Play Json Read.
Here is my code:
case class Test(action: String, storeResult: Option[Boolean] = Some(true), returndata: Option[Boolean] = Some(true))
val json =
"""
{"action": "Test"}"""
implicit val testReads: Reads[Test] =
(
(JsPath \\ "action").read[String](minLength[String](1)) and
(JsPath \\ "store_result").readNullable[Boolean] and
(JsPath \\ "returndata").readNullable[Boolean]
) (Test.apply _)
val js = Json.parse(json)
js.validate[Test] match {
case JsSuccess(a, _) => println(a)
case JsError(errors) =>
println("Here")
println(errors)
}
What I was hoping to get at the end is
Test("Test", Some(true), Some(true))
but I got:
Test("Test",None,None)
Why is this so? If I didn't provide parameter in the json why it didn't got default value? How to achieve what I want?
A: in Play 2.6 you can write simply:
Json.using[Json.WithDefaultValues].reads[Test]
|
Q: Play json Read and Default parameters for case class? I have a problem with default parameters and using Play Json Read.
Here is my code:
case class Test(action: String, storeResult: Option[Boolean] = Some(true), returndata: Option[Boolean] = Some(true))
val json =
"""
{"action": "Test"}"""
implicit val testReads: Reads[Test] =
(
(JsPath \\ "action").read[String](minLength[String](1)) and
(JsPath \\ "store_result").readNullable[Boolean] and
(JsPath \\ "returndata").readNullable[Boolean]
) (Test.apply _)
val js = Json.parse(json)
js.validate[Test] match {
case JsSuccess(a, _) => println(a)
case JsError(errors) =>
println("Here")
println(errors)
}
What I was hoping to get at the end is
Test("Test", Some(true), Some(true))
but I got:
Test("Test",None,None)
Why is this so? If I didn't provide parameter in the json why it didn't got default value? How to achieve what I want?
A: in Play 2.6 you can write simply:
Json.using[Json.WithDefaultValues].reads[Test]
A: It looks as if support for default parameters is in version 2.6.
A workaround for prior versions is to do something like the following:
object TestBuilder {
def apply(action: String, storeResult: Option[Boolean], returndata: Option[Boolean]) =
Test(
action,
Option(storeResult.getOrElse(true)),
Option(returndata.getOrElse(true))
)
}
implicit val testReads: Reads[Test] =
(
(JsPath \\ "action").read[String](minLength[String](1)) and
(JsPath \\ "store_result").readNullable[Boolean] and
(JsPath \\ "returndata").readNullable[Boolean]
)(TestBuilder.apply _)
A: Do you really need Options in your case class if you supply default values? Without Options the following code should work
case class Test(action: String, storeResult: Boolean = true, returndata: Boolean = true)
implicit val testReads: Reads[Test] =
(
(JsPath \\ "action").read[String](minLength[String](1)) and
((JsPath \\ "store_result").read[Boolean] or Reads.pure(true)) and
((JsPath \\ "returndata").read[Boolean] or Reads.pure(true))
) (Test.apply _)
If you need Options then this code might work (not tested!)
case class Test(action: String, storeResult: Option[Boolean] = Some(true), returndata: Option[Boolean] = Some(true))
implicit val testReads: Reads[Test] =
(
(JsPath \\ "action").read[String](minLength[String](1)) and
((JsPath \\ "store_result").read[Boolean] or Reads.pure(true)).map(x=>Some(x)) and
((JsPath \\ "returndata").read[Boolean] or Reads.pure(true)).map(x=>Some(x))
) (Test.apply _)
|
stackoverflow
|
{
"language": "en",
"length": 298,
"provenance": "stackexchange_0000F.jsonl.gz:838246",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44459027"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.