content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
Map background colour/transparency within R leaflet
I'm using a geojson file to produce a map with leaflet on R. I would like to change the background colour to the white, or make the background transparent if it is possible (this is actually really desired one). I have seen this and this. I am able to change the border colour and filled colour but cannot change the colour of the outside of map > background colour.
wLeaf <- leaflet(states) %>%
addProviderTiles("MapBox", options = providerTileOptions(
id = "mapbox.light",
accessToken = Sys.getenv('MAPBOX_ACCESS_TOKEN')))%>%
addPolygons(
weight = 2,
opacity = 1,
color = "#222",
fillColor = "gray",
)
How can I handle the colour or transparency issue of background for the map?
Thanks
A:
in case it helps, first create the background call
backg <- htmltools::tags$style(".leaflet-container { background: tomato; }" )
Then you can add this object as CSS format to your map
sts <- tigris::states(cb = TRUE) # you map
leaflet::leaflet(data = sts) %>%
addPolygons(fillColor = "grey90", stroke = FALSE) %>%
htmlwidgets::prependContent(backg) #this applies the CSS format
All together:
library(dplyr)
backg <- htmltools::tags$style(".leaflet-container { background: tomato; }" )
sts <- tigris::states(cb = TRUE)
leaflet::leaflet(data = sts) %>%
addPolygons(fillColor = "grey90", stroke = FALSE) %>%
htmlwidgets::prependContent(backg)
Cheers!
|
Map background colour/transparency within R leaflet
|
I'm using a geojson file to produce a map with leaflet on R. I would like to change the background colour to the white, or make the background transparent if it is possible (this is actually really desired one). I have seen this and this. I am able to change the border colour and filled colour but cannot change the colour of the outside of map > background colour.
wLeaf <- leaflet(states) %>%
addProviderTiles("MapBox", options = providerTileOptions(
id = "mapbox.light",
accessToken = Sys.getenv('MAPBOX_ACCESS_TOKEN')))%>%
addPolygons(
weight = 2,
opacity = 1,
color = "#222",
fillColor = "gray",
)
How can I handle the colour or transparency issue of background for the map?
Thanks
|
[
"in case it helps, first create the background call\nbackg <- htmltools::tags$style(\".leaflet-container { background: tomato; }\" )\n\nThen you can add this object as CSS format to your map\nsts <- tigris::states(cb = TRUE) # you map\nleaflet::leaflet(data = sts) %>% \naddPolygons(fillColor = \"grey90\", stroke = FALSE) %>%\nhtmlwidgets::prependContent(backg) #this applies the CSS format\n\nAll together:\nlibrary(dplyr)\nbackg <- htmltools::tags$style(\".leaflet-container { background: tomato; }\" ) \nsts <- tigris::states(cb = TRUE)\nleaflet::leaflet(data = sts) %>% \naddPolygons(fillColor = \"grey90\", stroke = FALSE) %>%\nhtmlwidgets::prependContent(backg)\n\n\nCheers!\n"
] |
[
0
] |
[] |
[] |
[
"geojson",
"leaflet",
"r",
"r_leaflet"
] |
stackoverflow_0072376088_geojson_leaflet_r_r_leaflet.txt
|
Q:
overwrite dataframe rows with merge
I am trying to overwrite specific rows and columns from one dataframe with a second dataframe rows and columns. I can't give the actual data but I will use a proxy here.
Here is an example and what I have tried:
df1
UID B C D
0 X14 cat red One
1 X26 cat blue Two
2 X99 cat pink One
3 X54 cat pink One
df2
UID B C EX2
0 X14 dog blue coat
1 X88 rat green jacket
2 X99 bat red glasses
3 X29 bat red shoes
What I want to do here is overwrite column B and C in df1 with the values in df2 based upon UID. Therefore in this example X88 and X29 from df2 would not appear in df2. Also column D would not be affected and EX2 not
The outcome would looks as such:
df1
UID B C D
0 X14 dog blue One
1 X26 cat blue Two
2 X99 bat red One
3 X54 cat pink One
I looked at this solution : Pandas merge two dataframe and overwrite rows
However this appears to only update null values whereas I want an overwrite.
My attempt looked this like:
df = df1.merge(df2.filter(['B', 'C']), on=['B', 'C'], how='left')
For my data this actually doesn't seem to overwrite anything. Please could someone explain why this would not work?
Thanks
A:
You can approach this by using reindex_like and combine_first.
Try this :
out = (
df2.set_index("UID")
.reindex_like(df1.set_index("UID"))
.combine_first(df1.set_index("UID"))
.reset_index()
)
# Output :
print(out)
UID B C D
0 X14 dog blue One
1 X26 cat blue Two
2 X99 bat red One
3 X54 cat pink One
A:
One approach could be as follows:
First, use df.set_index to make column UID your index (inplace).
Next, use df.update with parameter overwrite set to True (also use set_index here for the "other" df: df2). This will overwrite all the columns that the two dfs have in common (i.e. B and C) based on index matches (i.e. now UID).
Finally, restore the standard index using df.reset_index.
df1.set_index('UID', inplace=True)
df1.update(df2.set_index('UID'), overwrite=True)
df1.reset_index(inplace=True)
print(df1)
UID B C D
0 X14 dog blue One
1 X26 cat blue Two
2 X99 bat red One
3 X54 cat pink One
A:
Using Update function
df1.set_index('UID', inplace=True)
df2.set_index('UID', inplace=True)
df1.update(df2)
df1.reset_index(inplace=True)
print(df1)
Output
UID B C D
0 X14 dog blue One
1 X26 cat blue Two
2 X99 bat red One
3 X54 cat pink One
|
overwrite dataframe rows with merge
|
I am trying to overwrite specific rows and columns from one dataframe with a second dataframe rows and columns. I can't give the actual data but I will use a proxy here.
Here is an example and what I have tried:
df1
UID B C D
0 X14 cat red One
1 X26 cat blue Two
2 X99 cat pink One
3 X54 cat pink One
df2
UID B C EX2
0 X14 dog blue coat
1 X88 rat green jacket
2 X99 bat red glasses
3 X29 bat red shoes
What I want to do here is overwrite column B and C in df1 with the values in df2 based upon UID. Therefore in this example X88 and X29 from df2 would not appear in df2. Also column D would not be affected and EX2 not
The outcome would looks as such:
df1
UID B C D
0 X14 dog blue One
1 X26 cat blue Two
2 X99 bat red One
3 X54 cat pink One
I looked at this solution : Pandas merge two dataframe and overwrite rows
However this appears to only update null values whereas I want an overwrite.
My attempt looked this like:
df = df1.merge(df2.filter(['B', 'C']), on=['B', 'C'], how='left')
For my data this actually doesn't seem to overwrite anything. Please could someone explain why this would not work?
Thanks
|
[
"You can approach this by using reindex_like and combine_first.\nTry this :\nout = (\n df2.set_index(\"UID\")\n .reindex_like(df1.set_index(\"UID\"))\n .combine_first(df1.set_index(\"UID\"))\n .reset_index()\n )\n\n# Output :\nprint(out)\n\n UID B C D\n0 X14 dog blue One\n1 X26 cat blue Two\n2 X99 bat red One\n3 X54 cat pink One\n\n",
"One approach could be as follows:\n\nFirst, use df.set_index to make column UID your index (inplace).\nNext, use df.update with parameter overwrite set to True (also use set_index here for the \"other\" df: df2). This will overwrite all the columns that the two dfs have in common (i.e. B and C) based on index matches (i.e. now UID).\nFinally, restore the standard index using df.reset_index.\n\ndf1.set_index('UID', inplace=True)\ndf1.update(df2.set_index('UID'), overwrite=True)\ndf1.reset_index(inplace=True)\nprint(df1)\n\n UID B C D\n0 X14 dog blue One\n1 X26 cat blue Two\n2 X99 bat red One\n3 X54 cat pink One\n\n",
"Using Update function\ndf1.set_index('UID', inplace=True)\ndf2.set_index('UID', inplace=True)\n\ndf1.update(df2)\ndf1.reset_index(inplace=True)\nprint(df1)\n\nOutput\n UID B C D\n0 X14 dog blue One\n1 X26 cat blue Two\n2 X99 bat red One\n3 X54 cat pink One\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074666769_dataframe_pandas_python.txt
|
Q:
Counter Observe when I scroll
Problem
I created a counter using HTML, CSS and JS (such as satisfied customer numbers, branch numbers, etc.)
The counter is also animated but since it's down the page, I'd like to animate it only when it gets to that point on the page. How do I do with the js?
const counters = document.querySelectorAll('.value');
const speed = 400;
counters.forEach( counter => {
const animate = () => {
const value = +counter.getAttribute('akhi');
const data = +counter.innerText;
const time = value / speed;
if(data < value) {
counter.innerText = Math.ceil(data + time);
setTimeout(animate, 1);
}else{
counter.innerText = value;
}
}
animate();
});
.counter-box {
display: block;
background: #f6f6f6;
padding: 40px 20px 37px;
text-align: center
}
.counter-box p {
margin: 5px 0 0;
padding: 0;
color: #909090;
font-size: 18px;
font-weight: 500
}
.counter {
display: block;
font-size: 32px;
font-weight: 700;
color: #666;
line-height: 28px
}
.counter-box.colored {
background: #eab736;
}
.counter-box.colored p,
.counter-box.colored .counter {
color: #fff;
}
<div class="container">
<div class="row contatore">
<div class="col-md-4">
<div class="counter-box colored">
<span class="counter value" akhi="560">0</span>
<p>Countries visited</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" akhi="3275">0</span>
<p>Registered travellers</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" id="conta" akhi="289">0</span>
<p>Partners</p>
</div>
</div>
</div>
</div>
What I have tried
i had tried with
const target = document.querySelector('.counter');
observer.observe(target);
but it doesn't seem to work. Many thanks to whoever can help me.
A:
I would recommend, as others have suggested, to use the Intersection Observer API to animate your elements once they appear in the viewport.
The idea is simple, we'll create an observer that will observe the counters to animate and we're going to configure it so that it calls the animate function once a counter is fully visible in the viewport.
You may learn more about the options that an IntersectionObserver can accept in order to customize its behavior. Meanwhile, here's a live demo that illustrates how to make the counters animate once they appear in the screen (the code below has some helpful comments):
const counters = document.querySelectorAll('.value'),
speed = 400,
/**
* create an IntersectionObserver with the specified callback that will be executed for each intersection change for every counter we have.
* You may customize the options (2nd argument) per you requirement
*/
observer = new IntersectionObserver(
entries => entries.forEach(entry => entry.isIntersecting && animate(entry.target)),
{
threshold: 1 // tells the browser that we only need to execute the callback only when an element (counter) is fully visible in the viewport
}
),
// the animate function now accepts a counter (HTML element)
animate = counter => {
const value = +counter.dataset.akhi,
data = +counter.innerText,
time = value / speed;
if (data < value) {
counter.innerText = Math.ceil(data + time);
setTimeout(() => animate(counter), 1);
} else {
counter.innerText = value;
}
};
// attach the counters to the observer
counters.forEach(c => observer.observe(c));
.counter-box {
display: block;
background: #f6f6f6;
padding: 40px 20px 37px;
text-align: center
}
.counter-box p {
margin: 5px 0 0;
padding: 0;
color: #909090;
font-size: 18px;
font-weight: 500
}
.counter {
display: block;
font-size: 32px;
font-weight: 700;
color: #666;
line-height: 28px
}
.counter-box.colored {
background: #eab736;
}
.counter-box.colored p,
.counter-box.colored .counter {
color: #fff;
}
<div class="container">
<div class="row contatore">
<div class="col-md-4">
<div class="counter-box colored">
<!-- it is recommended to use "data-*" attributes to cache data that we might use later. The "data-akhi" contains the number to animate -->
<span class="counter value" data-akhi="560">0</span>
<p>Countries visited</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" data-akhi="3275">0</span>
<p>Registered travellers</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" id="conta" data-akhi="289">0</span>
<p>Partners</p>
</div>
</div>
</div>
</div>
A:
As others suggested, you should use Intersection Observer.
This is how I'd do:
Scrolldown the snippet in order to see the counter animating up once is on the screen.
const counters = document.querySelectorAll('.value');
const speed = 400;
const observer = new IntersectionObserver( items => {
if(items[0].isIntersecting) {
const target = items[0].target;
const animate = () => {
const value = + target.getAttribute('akhi');
const data = + target.innerText;
const time = value / speed;
if(data < value) {
target.innerText = Math.ceil(data + time);
setTimeout(animate, 1);
}else{
target.innerText = value;
}
}
animate();
observer.unobserve(target);
}
})
counters.forEach( counter => observer.observe(counter));
.counter-box {
display: block;
background: #f6f6f6;
padding: 40px 20px 37px;
text-align: center
}
.counter-box p {
margin: 5px 0 0;
padding: 0;
color: #909090;
font-size: 18px;
font-weight: 500
}
.counter {
display: block;
font-size: 32px;
font-weight: 700;
color: #666;
line-height: 28px
}
.counter-box.colored {
background: #eab736;
}
.counter-box.colored p,
.counter-box.colored .counter {
color: #fff;
}
<div style="height: 600px;">
</div>
<div class="container">
<div class="row contatore">
<div class="col-md-4">
<div class="counter-box colored">
<span class="counter value" akhi="560">0</span>
<p>Countries visited</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" akhi="3275">0</span>
<p>Registered travellers</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" id="conta" akhi="289">0</span>
<p>Partners</p>
</div>
</div>
</div>
</div>
|
Counter Observe when I scroll
|
Problem
I created a counter using HTML, CSS and JS (such as satisfied customer numbers, branch numbers, etc.)
The counter is also animated but since it's down the page, I'd like to animate it only when it gets to that point on the page. How do I do with the js?
const counters = document.querySelectorAll('.value');
const speed = 400;
counters.forEach( counter => {
const animate = () => {
const value = +counter.getAttribute('akhi');
const data = +counter.innerText;
const time = value / speed;
if(data < value) {
counter.innerText = Math.ceil(data + time);
setTimeout(animate, 1);
}else{
counter.innerText = value;
}
}
animate();
});
.counter-box {
display: block;
background: #f6f6f6;
padding: 40px 20px 37px;
text-align: center
}
.counter-box p {
margin: 5px 0 0;
padding: 0;
color: #909090;
font-size: 18px;
font-weight: 500
}
.counter {
display: block;
font-size: 32px;
font-weight: 700;
color: #666;
line-height: 28px
}
.counter-box.colored {
background: #eab736;
}
.counter-box.colored p,
.counter-box.colored .counter {
color: #fff;
}
<div class="container">
<div class="row contatore">
<div class="col-md-4">
<div class="counter-box colored">
<span class="counter value" akhi="560">0</span>
<p>Countries visited</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" akhi="3275">0</span>
<p>Registered travellers</p>
</div>
</div>
<div class="col-md-4">
<div class="counter-box">
<span class="counter value" id="conta" akhi="289">0</span>
<p>Partners</p>
</div>
</div>
</div>
</div>
What I have tried
i had tried with
const target = document.querySelector('.counter');
observer.observe(target);
but it doesn't seem to work. Many thanks to whoever can help me.
|
[
"I would recommend, as others have suggested, to use the Intersection Observer API to animate your elements once they appear in the viewport.\nThe idea is simple, we'll create an observer that will observe the counters to animate and we're going to configure it so that it calls the animate function once a counter is fully visible in the viewport.\nYou may learn more about the options that an IntersectionObserver can accept in order to customize its behavior. Meanwhile, here's a live demo that illustrates how to make the counters animate once they appear in the screen (the code below has some helpful comments):\n\n\nconst counters = document.querySelectorAll('.value'),\n speed = 400,\n /**\n * create an IntersectionObserver with the specified callback that will be executed for each intersection change for every counter we have. \n * You may customize the options (2nd argument) per you requirement\n */\n observer = new IntersectionObserver(\n entries => entries.forEach(entry => entry.isIntersecting && animate(entry.target)), \n {\n threshold: 1 // tells the browser that we only need to execute the callback only when an element (counter) is fully visible in the viewport\n }\n ),\n // the animate function now accepts a counter (HTML element)\n animate = counter => {\n const value = +counter.dataset.akhi,\n data = +counter.innerText,\n time = value / speed;\n if (data < value) {\n counter.innerText = Math.ceil(data + time);\n setTimeout(() => animate(counter), 1);\n } else {\n counter.innerText = value;\n }\n };\n\n// attach the counters to the observer\ncounters.forEach(c => observer.observe(c));\n.counter-box {\n display: block;\n background: #f6f6f6;\n padding: 40px 20px 37px;\n text-align: center\n}\n\n.counter-box p {\n margin: 5px 0 0;\n padding: 0;\n color: #909090;\n font-size: 18px;\n font-weight: 500\n}\n\n.counter {\n display: block;\n font-size: 32px;\n font-weight: 700;\n color: #666;\n line-height: 28px\n}\n\n.counter-box.colored {\n background: #eab736;\n}\n\n.counter-box.colored p,\n.counter-box.colored .counter {\n color: #fff;\n}\n<div class=\"container\">\n <div class=\"row contatore\">\n <div class=\"col-md-4\">\n <div class=\"counter-box colored\">\n <!-- it is recommended to use \"data-*\" attributes to cache data that we might use later. The \"data-akhi\" contains the number to animate -->\n <span class=\"counter value\" data-akhi=\"560\">0</span>\n <p>Countries visited</p>\n </div>\n </div>\n <div class=\"col-md-4\">\n <div class=\"counter-box\">\n <span class=\"counter value\" data-akhi=\"3275\">0</span>\n <p>Registered travellers</p>\n </div>\n </div>\n <div class=\"col-md-4\">\n <div class=\"counter-box\">\n <span class=\"counter value\" id=\"conta\" data-akhi=\"289\">0</span>\n <p>Partners</p>\n </div>\n </div>\n </div>\n</div>\n\n\n\n",
"As others suggested, you should use Intersection Observer.\nThis is how I'd do:\nScrolldown the snippet in order to see the counter animating up once is on the screen.\n\n\nconst counters = document.querySelectorAll('.value');\nconst speed = 400;\n\nconst observer = new IntersectionObserver( items => {\n \n if(items[0].isIntersecting) { \n const target = items[0].target;\n const animate = () => {\n const value = + target.getAttribute('akhi');\n const data = + target.innerText;\n \n const time = value / speed;\n if(data < value) {\n target.innerText = Math.ceil(data + time);\n setTimeout(animate, 1);\n }else{\n target.innerText = value;\n } \n } \n animate(); \n observer.unobserve(target);\n }\n})\n\ncounters.forEach( counter => observer.observe(counter));\n.counter-box {\n\n display: block;\n background: #f6f6f6;\n padding: 40px 20px 37px;\n text-align: center\n\n}\n.counter-box p {\n\n margin: 5px 0 0;\n padding: 0;\n color: #909090;\n font-size: 18px;\n font-weight: 500\n\n}\n\n.counter { \n\n display: block;\n font-size: 32px;\n font-weight: 700;\n color: #666;\n line-height: 28px\n\n}\n.counter-box.colored {\n\n background: #eab736;\n\n}\n.counter-box.colored p,\n.counter-box.colored .counter {\n\n color: #fff;\n\n}\n<div style=\"height: 600px;\">\n\n</div>\n\n\n<div class=\"container\">\n <div class=\"row contatore\">\n <div class=\"col-md-4\">\n <div class=\"counter-box colored\">\n <span class=\"counter value\" akhi=\"560\">0</span>\n <p>Countries visited</p>\n </div>\n </div>\n\n <div class=\"col-md-4\">\n <div class=\"counter-box\">\n <span class=\"counter value\" akhi=\"3275\">0</span>\n <p>Registered travellers</p>\n </div>\n </div>\n\n <div class=\"col-md-4\">\n <div class=\"counter-box\">\n <span class=\"counter value\" id=\"conta\" akhi=\"289\">0</span>\n <p>Partners</p>\n </div>\n </div>\n </div> \n </div>\n\n\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"javascript"
] |
stackoverflow_0074666244_javascript.txt
|
Q:
How to build release Flutter project using Android Studio
I cannot build my project using Android Studio. I create project using console, then edit at VSCode. Now I open it at Android Studio and I cannot build release. Why this command Build bundles (green arrow) is not available?
A:
Try to hover on Flutter name in that list or click on arrow button then build apk then create your .apk file
Or run below command
flutter build apk --release
See below image:
See your apk here-> directory:\your_project_name\build\app\outputs\flutter-apk
A:
Open The Android Studio and also open your project.
First you click the build->Flutter->build APK.
Second you get the massage path.
Third you get the build folder then you click the
build->app->outputs->flutter-apk->app-release.apk.
You can see the image for the 3 steps to Build Apk:
A:
Flutter project consist of subprojects:
/MyProject
/iOS - (iOS subproject)
/android - (android subproject)
When I open project "MyProject" I see:
But when I open android submodule/subproject "MyProject/android" I see another options under "Build":
So solution is:
If You want build Android package for Google Play store, You must open in IDE Android submodule, for example solder /MyProject/android
Case with Xcode, iOS and AppStore package looks similar - it is important to open iOS submodule, not whole MyProject.
|
How to build release Flutter project using Android Studio
|
I cannot build my project using Android Studio. I create project using console, then edit at VSCode. Now I open it at Android Studio and I cannot build release. Why this command Build bundles (green arrow) is not available?
|
[
"Try to hover on Flutter name in that list or click on arrow button then build apk then create your .apk file\nOr run below command\nflutter build apk --release\n\nSee below image:\n\nSee your apk here-> directory:\\your_project_name\\build\\app\\outputs\\flutter-apk\n",
"Open The Android Studio and also open your project.\nFirst you click the build->Flutter->build APK.\nSecond you get the massage path.\nThird you get the build folder then you click the\nbuild->app->outputs->flutter-apk->app-release.apk.\nYou can see the image for the 3 steps to Build Apk:\n\n",
"Flutter project consist of subprojects:\n\n/MyProject\n\n/iOS - (iOS subproject)\n/android - (android subproject)\n\n\n\nWhen I open project \"MyProject\" I see:\n\nBut when I open android submodule/subproject \"MyProject/android\" I see another options under \"Build\":\n\nSo solution is:\nIf You want build Android package for Google Play store, You must open in IDE Android submodule, for example solder /MyProject/android\nCase with Xcode, iOS and AppStore package looks similar - it is important to open iOS submodule, not whole MyProject.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"android_studio",
"flutter",
"google_play",
"release"
] |
stackoverflow_0071298590_android_studio_flutter_google_play_release.txt
|
Q:
Directing microphone input to speakers and writing a custom DSP function with CSCore library
CSCore (https://github.com/filoe/cscore) seems to be a very good audio library for C# but it lacks documentation and good examples.
I've been playing with Bass.Net for a long time and the architecture of CSCore is not like the Bass library so it is really hard to find out the right way to do some common tasks.
I'm trying to capture microphone input from WasapiCapture device and output the recorded data to WasapiOut device but I could not succeed it.
The following is the code I could find after googling but it does not work.
MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();
MMDeviceCollection devices = deviceEnum.EnumAudioEndpoints(DataFlow.Capture, DeviceState.Active);
using (var capture = new WasapiCapture())
{
capture.Device = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
capture.Initialize();
using (var source = new SoundInSource(capture))
{
using (var soundOut = new WasapiOut())
{
capture.Start();
soundOut.Device = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
soundOut.Initialize(source);
soundOut.Play();
}
}
}
What I am trying to do is write an application like this one:
http://www.pitchtech.ch/PitchBox/
I have my own DSP functions which I want to apply to recorded data.
Does anybody have examples of directing WasapiCapture to WasapiOut and writing a custom DSP?
A:
I found the solution with the help of the CSCore library creator Florian Rosmann (filoe).
Here is a sample DSP class which amplifies the provided audio data.
class DSPGain: ISampleSource
{
ISampleSource _source;
public DSPGain(ISampleSource source)
{
if (source == null)
throw new ArgumentNullException("source");
_source = source;
}
public int Read(float[] buffer, int offset, int count)
{
float gainAmplification = (float)(Math.Pow(10.0, GainDB / 20.0));
int samples = _source.Read(buffer, offset, count);
for (int i = offset; i < offset + samples; i++)
{
buffer[i] = Math.Max(Math.Min(buffer[i] * gainAmplification, 1), -1);
}
return samples;
}
public float GainDB { get; set; }
public bool CanSeek
{
get { return _source.CanSeek; }
}
public WaveFormat WaveFormat
{
get { return _source.WaveFormat; }
}
public long Position
{
get
{
return _source.Position;
}
set
{
_source.Position = value;
}
}
public long Length
{
get { return _source.Length; }
}
public void Dispose()
{
}
}
And you can use this class as in the sample below:
WasapiCapture waveIn;
WasapiOut soundOut;
DSPGain gain;
private void StartFullDuplex()
{
try
{
MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();
MMDeviceCollection devices = deviceEnum.EnumAudioEndpoints(DataFlow.Capture, DeviceState.Active);
waveIn = new WasapiCapture(false, AudioClientShareMode.Exclusive, 5);
waveIn.Device = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
waveIn.Initialize();
waveIn.Start();
var source = new SoundInSource(waveIn) { FillWithZeros = true };
soundOut = new WasapiOut(false, AudioClientShareMode.Exclusive, 5);
soundOut.Device = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
gain = new DSPGain(source.ToSampleSource());
gain.GainDB = 5;
soundOut.Initialize(gain.ToWaveSource(16));
soundOut.Play();
}
catch (Exception ex)
{
Debug.WriteLine("Exception in StartFullDuplex: " + ex.Message);
}
}
private void StopFullDuplex()
{
if (soundOut != null) soundOut.Dispose();
if (waveIn != null) waveIn.Dispose();
}
This answer was posted as an edit to the question Directing microphone input to speakers and writing a custom DSP function with CSCore library by the OP Ahmet Uzun under CC BY-SA 3.0.
|
Directing microphone input to speakers and writing a custom DSP function with CSCore library
|
CSCore (https://github.com/filoe/cscore) seems to be a very good audio library for C# but it lacks documentation and good examples.
I've been playing with Bass.Net for a long time and the architecture of CSCore is not like the Bass library so it is really hard to find out the right way to do some common tasks.
I'm trying to capture microphone input from WasapiCapture device and output the recorded data to WasapiOut device but I could not succeed it.
The following is the code I could find after googling but it does not work.
MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();
MMDeviceCollection devices = deviceEnum.EnumAudioEndpoints(DataFlow.Capture, DeviceState.Active);
using (var capture = new WasapiCapture())
{
capture.Device = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
capture.Initialize();
using (var source = new SoundInSource(capture))
{
using (var soundOut = new WasapiOut())
{
capture.Start();
soundOut.Device = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
soundOut.Initialize(source);
soundOut.Play();
}
}
}
What I am trying to do is write an application like this one:
http://www.pitchtech.ch/PitchBox/
I have my own DSP functions which I want to apply to recorded data.
Does anybody have examples of directing WasapiCapture to WasapiOut and writing a custom DSP?
|
[
"I found the solution with the help of the CSCore library creator Florian Rosmann (filoe).\nHere is a sample DSP class which amplifies the provided audio data.\nclass DSPGain: ISampleSource\n{\n ISampleSource _source;\n public DSPGain(ISampleSource source)\n {\n if (source == null)\n throw new ArgumentNullException(\"source\");\n _source = source;\n }\n public int Read(float[] buffer, int offset, int count)\n {\n float gainAmplification = (float)(Math.Pow(10.0, GainDB / 20.0));\n int samples = _source.Read(buffer, offset, count);\n for (int i = offset; i < offset + samples; i++)\n {\n buffer[i] = Math.Max(Math.Min(buffer[i] * gainAmplification, 1), -1);\n }\n return samples;\n }\n\n public float GainDB { get; set; }\n\n public bool CanSeek\n {\n get { return _source.CanSeek; }\n }\n\n public WaveFormat WaveFormat\n {\n get { return _source.WaveFormat; }\n }\n\n public long Position\n {\n get\n {\n return _source.Position;\n }\n set\n {\n _source.Position = value;\n }\n }\n\n public long Length\n {\n get { return _source.Length; }\n }\n\n public void Dispose()\n {\n }\n}\n\nAnd you can use this class as in the sample below:\nWasapiCapture waveIn;\nWasapiOut soundOut;\nDSPGain gain;\nprivate void StartFullDuplex()\n{\n try\n {\n MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();\n MMDeviceCollection devices = deviceEnum.EnumAudioEndpoints(DataFlow.Capture, DeviceState.Active);\n\n waveIn = new WasapiCapture(false, AudioClientShareMode.Exclusive, 5);\n waveIn.Device = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);\n waveIn.Initialize();\n waveIn.Start();\n\n\n var source = new SoundInSource(waveIn) { FillWithZeros = true };\n soundOut = new WasapiOut(false, AudioClientShareMode.Exclusive, 5);\n soundOut.Device = deviceEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);\n\n gain = new DSPGain(source.ToSampleSource());\n gain.GainDB = 5;\n\n soundOut.Initialize(gain.ToWaveSource(16));\n soundOut.Play();\n }\n catch (Exception ex)\n {\n Debug.WriteLine(\"Exception in StartFullDuplex: \" + ex.Message);\n }\n\n}\n\nprivate void StopFullDuplex()\n{\n if (soundOut != null) soundOut.Dispose();\n if (waveIn != null) waveIn.Dispose();\n}\n\n\nThis answer was posted as an edit to the question Directing microphone input to speakers and writing a custom DSP function with CSCore library by the OP Ahmet Uzun under CC BY-SA 3.0.\n"
] |
[
0
] |
[] |
[] |
[
"audio",
"c#",
"cscore",
"wasapi"
] |
stackoverflow_0034634726_audio_c#_cscore_wasapi.txt
|
Q:
How to add a Zero-or-more-condition (?) to multiple characters via regex without creating a capturing group?
The function rearrange_name should be given a name in the format:
Last Name (Normal or Double-barrelled name) followed by a "," " " and the First Name (either just one first name or together with middle initial name or full middle name)
Then the name should be rearranged to print it out as first name + last name.
This is the start of the code.
import re
def rearrange_name(name):
result = re.search (r"^(\w*), (\w*)$", name)
if result == None:
return name
return "{} {}".format(result[2], result[1])
name=rearrange_name("Kennedy, John F.")
print(name)
I know this specific problem has already been posted before
(Fix the regular expression used in the rearrange_name function so that it can match middle names, middle initials, as well as double surnames),
but i have a problem with the solution that was given that time as it allows for nonsense names like "-, John F." or " , John F." to be processed as well. I would have added a comment, but i don't have any reputation at all. This is my first post ever on stack overflow.
I'd like to change the code for it to be correct 100%.
The original solution given:
import re
def rearrange_name(name):
result = re.search(r"^([\w -]+), ([\w. ]+)$", name)
if result == None:
return name
return "{} {}".format(result[2], result[1])
name=rearrange_name("Kennedy, John F.")
print(name)
name=rearrange_name("Kennedy, John Fitzgerald")
print(name)
name=rearrange_name("Kennedy-McJohnson, John Fitzgerald")
print(name)
My solution approach, which you can see in the screenshot of regex101.com detects all the possible names given correctly, but the groups aren't detected the way they should.
enter image description here
I am struggling with it, as at least in my opinion you have to use "or" sequences ()? as groups which then aren't detected by the print function.
To give some examples:
These should all work and everything else shouldnt (obviously varying letters should be allowed:
"Kennedy, John"
just normal Last name + First name
Output: John Kennedy
"Kennedy, John F." - Last name + First name + Middle name initials
Output: John F. Kennedy
"Kennedy, John Fitzgerald" Last name + First name + Middle name
John Fitzgerald Kennedy
"Kennedy-McJohnson, John Fitzgerald" Last name double barreled + First name + Middle name
Output: John Fitzgerald Kennedy-McJohnson
"Kennedy-McJohnson, John F." Last name double barreled + First name + Middle name initials
John F. Kennedy-McJohnson
Swap every letter for another letter.
Characters that should be allowed: Letters (except for the spaces in between the names, the "." for the initial, the "-" for the double barreled name.
Not expected output as it should be considered invalid input:
input: |||?!**Kennedy, John F#####.
output:
|||?!**Kennedy, John F#####.
So if it is a valid name, the order is changed and put to the screen.
If it is not a valid name, the name is printed out the way it is presented first.
A:
Try the pattern:
([A-Z][a-zA-Z]+(?:-[A-Z][a-zA-Z]+)?), ([A-Z][a-zA-Z]+\s*(?:[A-Z][a-zA-Z]+|[A-Z]\.)?)
Regex demo.
import re
pat = re.compile(
r"([A-Z][a-zA-Z]+(?:-[A-Z][a-zA-Z]+)?), ([A-Z][a-zA-Z]+\s*(?:[A-Z][a-zA-Z]+|[A-Z]\.)?)"
)
def rearrange_name(name):
m = pat.match(name)
if m:
return "{} {}".format(m.group(2), m.group(1))
return name
name = rearrange_name("Kennedy, John F.")
print(name)
name = rearrange_name("Kennedy, John Fitzgerald")
print(name)
name = rearrange_name("Kennedy-McJohnson, John Fitzgerald")
print(name)
Prints:
John F. Kennedy
John Fitzgerald Kennedy
John Fitzgerald Kennedy-McJohnson
|
How to add a Zero-or-more-condition (?) to multiple characters via regex without creating a capturing group?
|
The function rearrange_name should be given a name in the format:
Last Name (Normal or Double-barrelled name) followed by a "," " " and the First Name (either just one first name or together with middle initial name or full middle name)
Then the name should be rearranged to print it out as first name + last name.
This is the start of the code.
import re
def rearrange_name(name):
result = re.search (r"^(\w*), (\w*)$", name)
if result == None:
return name
return "{} {}".format(result[2], result[1])
name=rearrange_name("Kennedy, John F.")
print(name)
I know this specific problem has already been posted before
(Fix the regular expression used in the rearrange_name function so that it can match middle names, middle initials, as well as double surnames),
but i have a problem with the solution that was given that time as it allows for nonsense names like "-, John F." or " , John F." to be processed as well. I would have added a comment, but i don't have any reputation at all. This is my first post ever on stack overflow.
I'd like to change the code for it to be correct 100%.
The original solution given:
import re
def rearrange_name(name):
result = re.search(r"^([\w -]+), ([\w. ]+)$", name)
if result == None:
return name
return "{} {}".format(result[2], result[1])
name=rearrange_name("Kennedy, John F.")
print(name)
name=rearrange_name("Kennedy, John Fitzgerald")
print(name)
name=rearrange_name("Kennedy-McJohnson, John Fitzgerald")
print(name)
My solution approach, which you can see in the screenshot of regex101.com detects all the possible names given correctly, but the groups aren't detected the way they should.
enter image description here
I am struggling with it, as at least in my opinion you have to use "or" sequences ()? as groups which then aren't detected by the print function.
To give some examples:
These should all work and everything else shouldnt (obviously varying letters should be allowed:
"Kennedy, John"
just normal Last name + First name
Output: John Kennedy
"Kennedy, John F." - Last name + First name + Middle name initials
Output: John F. Kennedy
"Kennedy, John Fitzgerald" Last name + First name + Middle name
John Fitzgerald Kennedy
"Kennedy-McJohnson, John Fitzgerald" Last name double barreled + First name + Middle name
Output: John Fitzgerald Kennedy-McJohnson
"Kennedy-McJohnson, John F." Last name double barreled + First name + Middle name initials
John F. Kennedy-McJohnson
Swap every letter for another letter.
Characters that should be allowed: Letters (except for the spaces in between the names, the "." for the initial, the "-" for the double barreled name.
Not expected output as it should be considered invalid input:
input: |||?!**Kennedy, John F#####.
output:
|||?!**Kennedy, John F#####.
So if it is a valid name, the order is changed and put to the screen.
If it is not a valid name, the name is printed out the way it is presented first.
|
[
"Try the pattern:\n([A-Z][a-zA-Z]+(?:-[A-Z][a-zA-Z]+)?), ([A-Z][a-zA-Z]+\\s*(?:[A-Z][a-zA-Z]+|[A-Z]\\.)?)\n\nRegex demo.\nimport re\n\n\npat = re.compile(\n r\"([A-Z][a-zA-Z]+(?:-[A-Z][a-zA-Z]+)?), ([A-Z][a-zA-Z]+\\s*(?:[A-Z][a-zA-Z]+|[A-Z]\\.)?)\"\n)\n\n\ndef rearrange_name(name):\n m = pat.match(name)\n if m:\n return \"{} {}\".format(m.group(2), m.group(1))\n\n return name\n\n\nname = rearrange_name(\"Kennedy, John F.\")\nprint(name)\n\nname = rearrange_name(\"Kennedy, John Fitzgerald\")\nprint(name)\n\nname = rearrange_name(\"Kennedy-McJohnson, John Fitzgerald\")\nprint(name)\n\nPrints:\nJohn F. Kennedy\nJohn Fitzgerald Kennedy\nJohn Fitzgerald Kennedy-McJohnson\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0074666500_python_regex.txt
|
Q:
reversed regex mashine implementation
I'm trying to match a string starting from the last character to fail as soon as possible. This way I can fail a match with a custom string cstr (see specification below) with least amount of operations (4th property).
From a theoritical perspective the regex can be represented as a finite state mashine and the arrows can be flipped, creating the reversed regex.
I'm looking for an implementation of this. A library/program which I can give the string and the pattern. cstr is implemented in python, so if possible a python module. (For the curious i-th character is not calculated until needed.) For anything other I need to do much more work because of cstr's calculation is hard to port to another language.
The implementation doesn't have to cover all latex syntax. I'm looking for the basics. No lookaheads or fancy stuff. See specification below.
I may be lacking common knowledge. Please do comment obvious things, too.
Specification
The custom string cstr has the following properties:
String can be calculated in finite time.
String has finite length
The last character is known
Every previous character requires a costly calculation
Until the string is calculated fully, length is unknown
When the string is calcualted fully, I want to match it with a simple regex which may contain these from the syntax. No look aheads or fancy stuff.
alphanumeric characters
uinicode characters
., *, +, ?, \w, \W, [], |, escape char \, range specifitation with { , }
PS: This is not a homework question. I'm trying to formulate my question as clear as possible.
A:
OP here. Here are some thougts:
Since I'm looking for an unoptimized regex mashine, I have to build it myself, which takes time.
Alternatively we can define an upperbound for cstr length and create all strings that matches given regex with length < upperbound. Then we put all solutions to a tire data structure and match it. This depends on the use case and maybe a cache can be involved.
What I'm going for is python module greenery
from greenery import parse
pattern = parse.Pattern(...)
pattern.reversed()
...
this sometimes provieds a good matching experience. Sometimes not but it is ok for me.
|
reversed regex mashine implementation
|
I'm trying to match a string starting from the last character to fail as soon as possible. This way I can fail a match with a custom string cstr (see specification below) with least amount of operations (4th property).
From a theoritical perspective the regex can be represented as a finite state mashine and the arrows can be flipped, creating the reversed regex.
I'm looking for an implementation of this. A library/program which I can give the string and the pattern. cstr is implemented in python, so if possible a python module. (For the curious i-th character is not calculated until needed.) For anything other I need to do much more work because of cstr's calculation is hard to port to another language.
The implementation doesn't have to cover all latex syntax. I'm looking for the basics. No lookaheads or fancy stuff. See specification below.
I may be lacking common knowledge. Please do comment obvious things, too.
Specification
The custom string cstr has the following properties:
String can be calculated in finite time.
String has finite length
The last character is known
Every previous character requires a costly calculation
Until the string is calculated fully, length is unknown
When the string is calcualted fully, I want to match it with a simple regex which may contain these from the syntax. No look aheads or fancy stuff.
alphanumeric characters
uinicode characters
., *, +, ?, \w, \W, [], |, escape char \, range specifitation with { , }
PS: This is not a homework question. I'm trying to formulate my question as clear as possible.
|
[
"OP here. Here are some thougts:\n\nSince I'm looking for an unoptimized regex mashine, I have to build it myself, which takes time.\n\nAlternatively we can define an upperbound for cstr length and create all strings that matches given regex with length < upperbound. Then we put all solutions to a tire data structure and match it. This depends on the use case and maybe a cache can be involved.\n\nWhat I'm going for is python module greenery\n\n\nfrom greenery import parse\npattern = parse.Pattern(...)\npattern.reversed()\n...\n\nthis sometimes provieds a good matching experience. Sometimes not but it is ok for me.\n"
] |
[
0
] |
[] |
[] |
[
"implementation",
"javascript",
"python",
"regex"
] |
stackoverflow_0074665144_implementation_javascript_python_regex.txt
|
Q:
How to read data from Excel which is open and getting updated every seconds using C# ASP.NET?
I am using Office.Interop.Excel to read data from Excel using C# ASP.Net & Dotnet 6.
I can read the Data and everything seems to be working fine.
But I have a challenge here.
The excel which I am reading data from would be updated every second.
But I am seeing an error while trying to open it and update random data.
The error says that the file is locked for editing.
Please have a look at the code below:
public double GetGoldPrice()
{
string filename = @"D:\Test.xlsx";
int row = 1;
int column = 1;
Application excelApplication = new Application();
Workbook excelWorkBook = excelApplication.Workbooks.Open(filename);
string workbookName = excelWorkBook.Name;
int worksheetcount = excelWorkBook.Worksheets.Count;
if (worksheetcount > 0)
{
Worksheet worksheet = (Worksheet)excelWorkBook.Worksheets[1];
string firstworksheetname = worksheet.Name;
var data = ((Microsoft.Office.Interop.Excel.Range) worksheet.Cells[row, column]).Value;
excelApplication.Quit();
return data;
}
else
{
Console.WriteLine("No worksheets available");
excelApplication.Quit();
return 0;
}
}
My end goal is to get live data from Excel whenever I fire the function.
The Excel would be open and can be editing any time.
Please help!
A:
You said your file is xlsx so you would be better not using Interop but Open XML SDK 2.5. Then you can open the file in read only mode:
using (SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(fileName, false))
{
// Code removed here.
}
Check here to get familiar with Open XML SDK
|
How to read data from Excel which is open and getting updated every seconds using C# ASP.NET?
|
I am using Office.Interop.Excel to read data from Excel using C# ASP.Net & Dotnet 6.
I can read the Data and everything seems to be working fine.
But I have a challenge here.
The excel which I am reading data from would be updated every second.
But I am seeing an error while trying to open it and update random data.
The error says that the file is locked for editing.
Please have a look at the code below:
public double GetGoldPrice()
{
string filename = @"D:\Test.xlsx";
int row = 1;
int column = 1;
Application excelApplication = new Application();
Workbook excelWorkBook = excelApplication.Workbooks.Open(filename);
string workbookName = excelWorkBook.Name;
int worksheetcount = excelWorkBook.Worksheets.Count;
if (worksheetcount > 0)
{
Worksheet worksheet = (Worksheet)excelWorkBook.Worksheets[1];
string firstworksheetname = worksheet.Name;
var data = ((Microsoft.Office.Interop.Excel.Range) worksheet.Cells[row, column]).Value;
excelApplication.Quit();
return data;
}
else
{
Console.WriteLine("No worksheets available");
excelApplication.Quit();
return 0;
}
}
My end goal is to get live data from Excel whenever I fire the function.
The Excel would be open and can be editing any time.
Please help!
|
[
"You said your file is xlsx so you would be better not using Interop but Open XML SDK 2.5. Then you can open the file in read only mode:\n using (SpreadsheetDocument spreadsheetDocument = \n SpreadsheetDocument.Open(fileName, false))\n {\n // Code removed here.\n }\n\nCheck here to get familiar with Open XML SDK\n"
] |
[
0
] |
[] |
[] |
[
"asp.net_core",
"c#",
"interop"
] |
stackoverflow_0074666749_asp.net_core_c#_interop.txt
|
Q:
DataConversionWarning: A column-vector y was passed when a 1d array was expected
I keep having an error running this part of my code:
scores = cross_val_score(XGB_Clf, X_resampled, y_resampled, cv=kf)
The error is :
DataConversionWarning: A column-vector y was passed when a 1d array
was expected. Please change the shape of y to (n_samples, ), for
example using ravel(). y = column_or_1d(y, warn=True)
I know there are lots of answers to this question, and that I need to use ravel(), but using it does not change anything!
Also, the array "y" I'm passing to the function is not a column-vector ...
See:
y_resampled
Out[82]: array([0, 0, 0, ..., 1, 1, 1], dtype=int64)
When I run
y_resampled.ravel()
I get
Out[81]: array([0, 0, 0, ..., 1, 1, 1], dtype=int64)
which is exactly the same as my initial variable...
Also, when I run y_resampled.values.ravel() I get an error telling me that this is well a numpy array...
Traceback (most recent call last):
File "<ipython-input-80-9d28d21eeab5>", line 1, in <module>
y_resampled.values.ravel()
AttributeError: 'numpy.ndarray' object has no attribute 'values'
Does any one of you have a solution to this?
Thanks a lot!
A:
in you write y_resampled as dataframe, you can use values function.
import pandas as pd
y_resampled = pd.DataFrame(y_resampled)
A:
Check out this answer man!
Simply:
model = forest.fit(train_fold, train_y.values.ravel())
|
DataConversionWarning: A column-vector y was passed when a 1d array was expected
|
I keep having an error running this part of my code:
scores = cross_val_score(XGB_Clf, X_resampled, y_resampled, cv=kf)
The error is :
DataConversionWarning: A column-vector y was passed when a 1d array
was expected. Please change the shape of y to (n_samples, ), for
example using ravel(). y = column_or_1d(y, warn=True)
I know there are lots of answers to this question, and that I need to use ravel(), but using it does not change anything!
Also, the array "y" I'm passing to the function is not a column-vector ...
See:
y_resampled
Out[82]: array([0, 0, 0, ..., 1, 1, 1], dtype=int64)
When I run
y_resampled.ravel()
I get
Out[81]: array([0, 0, 0, ..., 1, 1, 1], dtype=int64)
which is exactly the same as my initial variable...
Also, when I run y_resampled.values.ravel() I get an error telling me that this is well a numpy array...
Traceback (most recent call last):
File "<ipython-input-80-9d28d21eeab5>", line 1, in <module>
y_resampled.values.ravel()
AttributeError: 'numpy.ndarray' object has no attribute 'values'
Does any one of you have a solution to this?
Thanks a lot!
|
[
"in you write y_resampled as dataframe, you can use values function.\nimport pandas as pd\ny_resampled = pd.DataFrame(y_resampled)\n\n",
"Check out this answer man!\nSimply:\nmodel = forest.fit(train_fold, train_y.values.ravel())\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"arrays",
"numpy",
"python_3.x"
] |
stackoverflow_0042719863_arrays_numpy_python_3.x.txt
|
Q:
Flask-Caching use UWSGI cache with NGINX
The UWSGI is connected to the flask app per UNIX-Socket:
NGINX (LISTEN TO PORT 80) <-> UWSGI (LISTER PER UNIX-SOCKER) <-> FLASK-APP
I have initalized a uwsgi cache to handle global data.
I want to handle the cache with python package flask-caching.
I am trying to init the Cache-instance with the correct cache address. There seems to be something wrong.
I think, that the parameters for app.run() are not relevant for uwsgi.
If I am setting a cache entry, it return always None:
app.route("/")
def test():
cache.set("test", "OK", timeout=0)
a = cache.get("test")
return a
main.py
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
# Check Configuring Flask-Caching section for more details
cache = Cache(app, config={'CACHE_TYPE': 'uwsgi', 'CACHE_UWSGI_NAME':'mycache@localhost'})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
uwsgi.ini
[uwsgi]
module = main
callable = app
cache2 = name=mycache,items=100
nginx.conf
server {
listen 80;
location / {
try_files $uri @app;
}
location @app {
include uwsgi_params;
uwsgi_pass unix:///tmp/uwsgi.sock;
}
location /static {
alias /app/testapp/static;
}
}
I am working with the docker build from https://github.com/tiangolo/uwsgi-nginx-flask-docker. The app is working, expect the cache.
A:
Be aware of using of spawning multiple processes for NGINX. Every process handles its own cache. Without an additional layer, it is not possible to access to a cache from different nginx process.
This answer was posted as an edit to the question Flask-Caching use UWSGI cache with NGINX by the OP ewro under CC BY-SA 4.0.
|
Flask-Caching use UWSGI cache with NGINX
|
The UWSGI is connected to the flask app per UNIX-Socket:
NGINX (LISTEN TO PORT 80) <-> UWSGI (LISTER PER UNIX-SOCKER) <-> FLASK-APP
I have initalized a uwsgi cache to handle global data.
I want to handle the cache with python package flask-caching.
I am trying to init the Cache-instance with the correct cache address. There seems to be something wrong.
I think, that the parameters for app.run() are not relevant for uwsgi.
If I am setting a cache entry, it return always None:
app.route("/")
def test():
cache.set("test", "OK", timeout=0)
a = cache.get("test")
return a
main.py
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
# Check Configuring Flask-Caching section for more details
cache = Cache(app, config={'CACHE_TYPE': 'uwsgi', 'CACHE_UWSGI_NAME':'mycache@localhost'})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
uwsgi.ini
[uwsgi]
module = main
callable = app
cache2 = name=mycache,items=100
nginx.conf
server {
listen 80;
location / {
try_files $uri @app;
}
location @app {
include uwsgi_params;
uwsgi_pass unix:///tmp/uwsgi.sock;
}
location /static {
alias /app/testapp/static;
}
}
I am working with the docker build from https://github.com/tiangolo/uwsgi-nginx-flask-docker. The app is working, expect the cache.
|
[
"Be aware of using of spawning multiple processes for NGINX. Every process handles its own cache. Without an additional layer, it is not possible to access to a cache from different nginx process.\n\nThis answer was posted as an edit to the question Flask-Caching use UWSGI cache with NGINX by the OP ewro under CC BY-SA 4.0.\n"
] |
[
0
] |
[] |
[] |
[
"flask_cache",
"flask_caching",
"nginx",
"python",
"uwsgi"
] |
stackoverflow_0052096704_flask_cache_flask_caching_nginx_python_uwsgi.txt
|
Q:
ionic capacitror app with firebase throes 403
I have a capacitor app with a firebase database and authentication. When the user signs in it get a token. After that, I'm placing an order and it throws me a 403 forbidden error.
This error is thrown only when I'm pointing to the server. The local server works just fine.
Any help is more than welcome since I've been stuck on it for some time.
here is a screenshot of the errors.
Any help and tips to solve this issue are more than welcome.
A:
One issue about having 403 error with google firebase is the google sanctions. I'm not sure if that is your case, but try using a VPN, it might solve your problem.
|
ionic capacitror app with firebase throes 403
|
I have a capacitor app with a firebase database and authentication. When the user signs in it get a token. After that, I'm placing an order and it throws me a 403 forbidden error.
This error is thrown only when I'm pointing to the server. The local server works just fine.
Any help is more than welcome since I've been stuck on it for some time.
here is a screenshot of the errors.
Any help and tips to solve this issue are more than welcome.
|
[
"One issue about having 403 error with google firebase is the google sanctions. I'm not sure if that is your case, but try using a VPN, it might solve your problem.\n"
] |
[
0
] |
[] |
[] |
[
"angular",
"capacitor",
"firebase",
"firebase_authentication",
"ionic_framework"
] |
stackoverflow_0074640527_angular_capacitor_firebase_firebase_authentication_ionic_framework.txt
|
Q:
Coud'nt fetch data from MYSQL data base using php
I am using this code to fetch data but mysqli_num_rows($result) === 0 is always true and shows that data not found.
kindly help to fetch data!
$sql = "SELECT * from mydata where email='$email'";
$result = mysqli_query($conn,$sql);
echo $result;
if (mysqli_num_rows($result) === 0) {
echo "email was not found";
} else {
echo "email was found";
// }
A:
Here are some possible reasons why you might be unable to fetch data from your MySQL database using PHP:
Invalid or incorrect SQL query - Check the SQL query you are using
to fetch the data to make sure it is correct and valid.
Incorrect database connection parameters - If you are using the
correct SQL query but still not able to fetch the data, it could be
because of incorrect database connection parameters. Check the
hostname, username, password, and database name you are using to
connect to the database.
Incorrect data type - Make sure you are using the correct data type
for the email column in your SQL query. For example, if the email
column is of type VARCHAR, then you should use single quotes around
the email value in your query.
Table or column name typo - Check if you have typed the table or
column name correctly in your SQL query.
Data not present in the database - If the data is not present in the
database, then mysqli_num_rows() will return 0, which is why you are
seeing "email was not found" message.
Here is an example of how you can troubleshoot and fix the issue:
Check the SQL query and make sure it is correct - You can check the
syntax of the SQL query using a tool like MySQL Workbench or using
the command line interface. If there are any syntax errors, then you
need to fix them before running the query again.
Check the database connection parameters - Make sure you are using
the correct hostname, username, password, and database name to
connect to the database. If any of these parameters are incorrect,
then you need to update them.
Check the data type of the email column - If the email column is of
type VARCHAR, then you need to use single quotes around the email
value in your query.
Check the table and column name - If you have typed the table or
column name incorrectly in your SQL query, then you need to fix it.
Check if the data is present in the database - If the data is not
present in the database, then mysqli_num_rows() will return 0. In
this case, you need to insert the data into the database before you
can fetch it using your SQL query.
By following the above steps, you should be able to fetch data from your MySQL database using PHP.
|
Coud'nt fetch data from MYSQL data base using php
|
I am using this code to fetch data but mysqli_num_rows($result) === 0 is always true and shows that data not found.
kindly help to fetch data!
$sql = "SELECT * from mydata where email='$email'";
$result = mysqli_query($conn,$sql);
echo $result;
if (mysqli_num_rows($result) === 0) {
echo "email was not found";
} else {
echo "email was found";
// }
|
[
"Here are some possible reasons why you might be unable to fetch data from your MySQL database using PHP:\n\nInvalid or incorrect SQL query - Check the SQL query you are using\nto fetch the data to make sure it is correct and valid.\nIncorrect database connection parameters - If you are using the\ncorrect SQL query but still not able to fetch the data, it could be\nbecause of incorrect database connection parameters. Check the\nhostname, username, password, and database name you are using to\nconnect to the database.\nIncorrect data type - Make sure you are using the correct data type\nfor the email column in your SQL query. For example, if the email\ncolumn is of type VARCHAR, then you should use single quotes around\nthe email value in your query.\nTable or column name typo - Check if you have typed the table or\ncolumn name correctly in your SQL query.\nData not present in the database - If the data is not present in the\ndatabase, then mysqli_num_rows() will return 0, which is why you are\nseeing \"email was not found\" message.\n\nHere is an example of how you can troubleshoot and fix the issue:\n\nCheck the SQL query and make sure it is correct - You can check the\nsyntax of the SQL query using a tool like MySQL Workbench or using\nthe command line interface. If there are any syntax errors, then you\nneed to fix them before running the query again.\nCheck the database connection parameters - Make sure you are using\nthe correct hostname, username, password, and database name to\nconnect to the database. If any of these parameters are incorrect,\nthen you need to update them.\nCheck the data type of the email column - If the email column is of\ntype VARCHAR, then you need to use single quotes around the email\nvalue in your query.\nCheck the table and column name - If you have typed the table or\ncolumn name incorrectly in your SQL query, then you need to fix it.\nCheck if the data is present in the database - If the data is not\npresent in the database, then mysqli_num_rows() will return 0. In\nthis case, you need to insert the data into the database before you\ncan fetch it using your SQL query.\n\nBy following the above steps, you should be able to fetch data from your MySQL database using PHP.\n"
] |
[
0
] |
[] |
[] |
[
"mysql",
"php",
"sql"
] |
stackoverflow_0074666917_mysql_php_sql.txt
|
Q:
python beautifulsoup: how to find all before certain stop tag?
I need to find all tags of a certain kind (class "nice") but excluding those after a certain other tag (class "stop").
<div class="nice"></div>
<div class="nice"></div>
<div class="stop">here should be the end of found items</div>
<div class="nice"></div>
<div class="nice"></div>
How do I accomplish this using bs4?
I found this as a similar question but it appears a bit fuzzy.
A:
You can use for example .find_previous to filter out unwanted tags:
from bs4 import BeautifulSoup
html_doc = """\
<div class="nice">want 1</div>
<div class="nice">want 2</div>
<div class="stop">here should be the end of found items</div>
<div class="nice">do not want 1</div>
<div class="nice">do not want 2</div>"""
soup = BeautifulSoup(html_doc, "html.parser")
for div in soup.find_all("div", class_="nice"):
if div.find_previous("div", class_="stop"):
break
print(div)
Prints:
<div class="nice">want 1</div>
<div class="nice">want 2</div>
|
python beautifulsoup: how to find all before certain stop tag?
|
I need to find all tags of a certain kind (class "nice") but excluding those after a certain other tag (class "stop").
<div class="nice"></div>
<div class="nice"></div>
<div class="stop">here should be the end of found items</div>
<div class="nice"></div>
<div class="nice"></div>
How do I accomplish this using bs4?
I found this as a similar question but it appears a bit fuzzy.
|
[
"You can use for example .find_previous to filter out unwanted tags:\nfrom bs4 import BeautifulSoup\n\n\nhtml_doc = \"\"\"\\\n<div class=\"nice\">want 1</div>\n<div class=\"nice\">want 2</div>\n<div class=\"stop\">here should be the end of found items</div>\n<div class=\"nice\">do not want 1</div>\n<div class=\"nice\">do not want 2</div>\"\"\"\n\nsoup = BeautifulSoup(html_doc, \"html.parser\")\n\nfor div in soup.find_all(\"div\", class_=\"nice\"):\n if div.find_previous(\"div\", class_=\"stop\"):\n break\n print(div)\n\nPrints:\n<div class=\"nice\">want 1</div>\n<div class=\"nice\">want 2</div>\n\n"
] |
[
1
] |
[] |
[] |
[
"beautifulsoup",
"html",
"python"
] |
stackoverflow_0074666897_beautifulsoup_html_python.txt
|
Q:
Reverse Odd-length Words in the given String in Java
I expect the User to provide a sentence.
And as an output, they will reverse a string with only the odd-length words reversed (i.e. even-length words should remain intact).
static String secretAgentII(String s) {
StringBuffer sb = new StringBuffer();
String[] newStr = s.split(" ");
String result = "";
for (int i = 0; i < newStr.length; i++) {
if (newStr[i].length() % 2 != 0) {
sb.append(newStr[i]).reverse();
result += sb + " ";
}
result += newStr[i] + " ";
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(secretAgentII(s));
}
Input:
One two three Four
Expected Output:
enO owT eerhT Four
The actual Output:
enO One owtOne two eerhtenOtwo three Four
How can I fix that?
A:
In your method secretAgentII the StringBuffer should have no other values so that it would not be concatenated to other strings.
I placed sb.replace(0, newStr[i].length(), newStr[i]).reverse(); inside the for loop so that it would replace the existing string in every use.
I also placed an else before the line result += newStr[i] + " "; for the original string doesn't need to be concatenated when it is reversed.
static String secretAgentII(String s) {
StringBuffer sb = new StringBuffer();
String[] newStr = s.split(" ");
String result = "";
for (int i = 0; i < newStr.length; i++) {
if (newStr[i].length() % 2 != 0) {
sb.replace(0, newStr[i].length(), newStr[i]).reverse();
result += sb + " ";
} else
result += newStr[i] + " ";
}
return result;
}
Input: One Two Three Four
Output: enO owT eerhT Four
note: you are using too many spaces, try researching Java conventions on writing code.
A:
I went ahead and wrote a method for what I think you are asking for.
public static String secretAgentII(String input){
StringBuilder returnValue = new StringBuilder();
input = input.replaceAll(" +", " ");
String[] tempArray = input.split(" ");
for (int i = 0; i < tempArray.length; i++) {
String currentString = tempArray[i];
if (currentString.length() % 2 == 1) {
char[] tempArrayOfStringChars = currentString.toCharArray();
for (int j = tempArrayOfStringChars.length - 1; j >= 0; j--) {
returnValue.append(tempArrayOfStringChars[j]);
}
} else {
returnValue.append(currentString);
}
if (i != tempArray.length - 1) { //This prevents a leading space at the end of your string
returnValue.append(' ');
}
}
return returnValue.toString();
}
From what I could tell, you only want the words of odd length to be reversed.
My sample input and output was as follows.
Input: One two three four five six seven eight nine ten
Output: enO owt eerht four five xis neves thgie nine net
A:
Your problem is that you add to result the whole sb, instead of just the current reverse word. Meaning you need to "reset" (create a new) StringBurrer for each iteration.
You're also missing the else where you want to preserve the correct word's order
for (int i = 0; i < newStr.length; i++) {
if (newStr[i].length() % 2 == 1) {
StringBuffer sb = new StringBuffer();
sb.append(newStr[i]);
result += sb.reverse() + " ";
}
else {
result += newStr[i] + " ";
}
}
A:
StringBuilder + StringJoiner
Never use plain string concatenation the loop because in Java Strings are immutable. That means every s1 + s2 produces new intermediate string, which don't need (since only the end result would be used). Concatenation in the loop effects performance and increase memory allocation.
Therefore, it's highly advisable to use StringBuilder, or other built-in mechanisms like static method String.join(), StringJoiner or Collector joining() when you need to combine multiple strings together.
To avoid bother about adding a white space after each word ourself, we can make use of the StringJoiner. Through its parameterized constructor we can provide the required delimiter " ".
That's how it might be implemented:
public static String reverseOdd1(String str) {
StringJoiner result = new StringJoiner(" ");
String[] words = str.split(" ");
for (String word : words) {
if (word.length() % 2 != 0) result.add(new StringBuilder(word).reverse());
else result.add(word);
}
return result.toString();
}
Note that it's not advisable to use StringBuffer in single-threaded environment because its methods are synchronized to make it tread-safe (and synchronization doesn't come for free), and instead use it sibling StringBuilder which has the same methods.
Here's a couple of more advanced solutions.
Stream IPA - Collectors.joining()
You can generate a Stream of words, revers odd-length words using map() operation, and generate the resulting string using Collector joining().
public static String reverseOdd2(String str) {
return Arrays.stream(str.split(" "))
.map(s -> s.length() % 2 == 0 ? s : new StringBuilder(s).reverse().toString())
.collect(Collectors.joining(" "));
}
Regex - Matcher.replaceAll()
Another option is to use regular expressions.
To capture a separate word we can use the following pattern:
public static final Pattern WORD = Pattern.compile("\\b(\\w+)\\b");
Where \\b is a so-called boundary matcher denoting a word boundary (for more information, refer to the documentation).
We can create a Matcher instance using this patter and the given string and make use of the Java 9 method Matcher.replaceAll() to generate the resulting string.
public static String reverseOdd3(String str) {
return WORD.matcher(str).replaceAll(matchResult -> {
String group = matchResult.group(1);
return group.length() % 2 == 0 ? group : new StringBuilder(group).reverse().toString();
});
}
Usage Example
main
public static void main(String[] args) {
System.out.println(reverseOdd1("One Two Three Four"));
System.out.println(reverseOdd2("One Two Three Four"));
System.out.println(reverseOdd3("One Two Three Four"));
}
Output:
enO owT eerhT Four
enO owT eerhT Four
enO owT eerhT Four
|
Reverse Odd-length Words in the given String in Java
|
I expect the User to provide a sentence.
And as an output, they will reverse a string with only the odd-length words reversed (i.e. even-length words should remain intact).
static String secretAgentII(String s) {
StringBuffer sb = new StringBuffer();
String[] newStr = s.split(" ");
String result = "";
for (int i = 0; i < newStr.length; i++) {
if (newStr[i].length() % 2 != 0) {
sb.append(newStr[i]).reverse();
result += sb + " ";
}
result += newStr[i] + " ";
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(secretAgentII(s));
}
Input:
One two three Four
Expected Output:
enO owT eerhT Four
The actual Output:
enO One owtOne two eerhtenOtwo three Four
How can I fix that?
|
[
"In your method secretAgentII the StringBuffer should have no other values so that it would not be concatenated to other strings.\nI placed sb.replace(0, newStr[i].length(), newStr[i]).reverse(); inside the for loop so that it would replace the existing string in every use.\nI also placed an else before the line result += newStr[i] + \" \"; for the original string doesn't need to be concatenated when it is reversed.\nstatic String secretAgentII(String s) {\n StringBuffer sb = new StringBuffer();\n String[] newStr = s.split(\" \");\n String result = \"\";\n\n for (int i = 0; i < newStr.length; i++) {\n if (newStr[i].length() % 2 != 0) {\n sb.replace(0, newStr[i].length(), newStr[i]).reverse();\n result += sb + \" \";\n } else\n result += newStr[i] + \" \";\n }\n return result;\n}\n\nInput: One Two Three Four\nOutput: enO owT eerhT Four\nnote: you are using too many spaces, try researching Java conventions on writing code.\n",
"I went ahead and wrote a method for what I think you are asking for.\n public static String secretAgentII(String input){\n StringBuilder returnValue = new StringBuilder();\n input = input.replaceAll(\" +\", \" \");\n String[] tempArray = input.split(\" \");\n for (int i = 0; i < tempArray.length; i++) {\n String currentString = tempArray[i];\n if (currentString.length() % 2 == 1) {\n char[] tempArrayOfStringChars = currentString.toCharArray();\n for (int j = tempArrayOfStringChars.length - 1; j >= 0; j--) {\n returnValue.append(tempArrayOfStringChars[j]);\n }\n } else {\n returnValue.append(currentString);\n }\n if (i != tempArray.length - 1) { //This prevents a leading space at the end of your string\n returnValue.append(' ');\n }\n }\n return returnValue.toString();\n }\n\nFrom what I could tell, you only want the words of odd length to be reversed.\nMy sample input and output was as follows.\nInput: One two three four five six seven eight nine ten\nOutput: enO owt eerht four five xis neves thgie nine net \n\n",
"Your problem is that you add to result the whole sb, instead of just the current reverse word. Meaning you need to \"reset\" (create a new) StringBurrer for each iteration.\nYou're also missing the else where you want to preserve the correct word's order\nfor (int i = 0; i < newStr.length; i++) {\n if (newStr[i].length() % 2 == 1) {\n StringBuffer sb = new StringBuffer();\n sb.append(newStr[i]);\n result += sb.reverse() + \" \";\n }\n else {\n result += newStr[i] + \" \";\n }\n}\n\n",
"StringBuilder + StringJoiner\nNever use plain string concatenation the loop because in Java Strings are immutable. That means every s1 + s2 produces new intermediate string, which don't need (since only the end result would be used). Concatenation in the loop effects performance and increase memory allocation.\nTherefore, it's highly advisable to use StringBuilder, or other built-in mechanisms like static method String.join(), StringJoiner or Collector joining() when you need to combine multiple strings together.\nTo avoid bother about adding a white space after each word ourself, we can make use of the StringJoiner. Through its parameterized constructor we can provide the required delimiter \" \".\nThat's how it might be implemented:\npublic static String reverseOdd1(String str) {\n StringJoiner result = new StringJoiner(\" \");\n String[] words = str.split(\" \");\n \n for (String word : words) {\n if (word.length() % 2 != 0) result.add(new StringBuilder(word).reverse());\n else result.add(word);\n }\n return result.toString();\n}\n\nNote that it's not advisable to use StringBuffer in single-threaded environment because its methods are synchronized to make it tread-safe (and synchronization doesn't come for free), and instead use it sibling StringBuilder which has the same methods.\nHere's a couple of more advanced solutions.\nStream IPA - Collectors.joining()\nYou can generate a Stream of words, revers odd-length words using map() operation, and generate the resulting string using Collector joining().\npublic static String reverseOdd2(String str) {\n \n return Arrays.stream(str.split(\" \"))\n .map(s -> s.length() % 2 == 0 ? s : new StringBuilder(s).reverse().toString())\n .collect(Collectors.joining(\" \"));\n}\n\nRegex - Matcher.replaceAll()\nAnother option is to use regular expressions.\nTo capture a separate word we can use the following pattern:\npublic static final Pattern WORD = Pattern.compile(\"\\\\b(\\\\w+)\\\\b\");\n\nWhere \\\\b is a so-called boundary matcher denoting a word boundary (for more information, refer to the documentation).\nWe can create a Matcher instance using this patter and the given string and make use of the Java 9 method Matcher.replaceAll() to generate the resulting string.\npublic static String reverseOdd3(String str) {\n \n return WORD.matcher(str).replaceAll(matchResult -> {\n String group = matchResult.group(1);\n return group.length() % 2 == 0 ? group : new StringBuilder(group).reverse().toString();\n });\n}\n\nUsage Example\nmain\npublic static void main(String[] args) {\n System.out.println(reverseOdd1(\"One Two Three Four\"));\n System.out.println(reverseOdd2(\"One Two Three Four\"));\n System.out.println(reverseOdd3(\"One Two Three Four\"));\n}\n\nOutput:\nenO owT eerhT Four\nenO owT eerhT Four\nenO owT eerhT Four\n\n"
] |
[
0,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"java",
"string"
] |
stackoverflow_0074665149_algorithm_java_string.txt
|
Q:
How to remove shipping from the PayPal subscribe button and default other values?
I'm creating a subscription button using the JavaScript SDK from PayPal. Here's the basic code snippet I'm following:
paypal.Buttons({
createSubscription: function(data, actions) {
return actions.subscription.create({
'plan_id': 'P-2UF78835G6983425GLSM44MA'
});
},
onApprove: function(data, actions) {
alert('You have successfully created subscription ' + data.subscriptionID);
}
}).render('#paypal-button-container');
When a user selects Credit Card (non PayPal account option),the next PayPal popup Window has a long form, collecting Credit Card, Billing Address, Shipping Address, Phone Number, and Email. For my needs, I don't need a shipping address and I'd like to be able to default things like Billing Address, Phone, and Email.
The PayPal SDK documentation is large but somehow lacking critical details around this library. My questions are:
How can I exclude shipping address collection from this form?
How can I default the other info I have already collected from the user (phone, email, etc)?
Thank you.
A:
All available parameters are the same as the create subscription API operation.
Set application_context.shipping_preference to NO_SHIPPING
Phone, email, and other information can be set in the subscriber object.
|
How to remove shipping from the PayPal subscribe button and default other values?
|
I'm creating a subscription button using the JavaScript SDK from PayPal. Here's the basic code snippet I'm following:
paypal.Buttons({
createSubscription: function(data, actions) {
return actions.subscription.create({
'plan_id': 'P-2UF78835G6983425GLSM44MA'
});
},
onApprove: function(data, actions) {
alert('You have successfully created subscription ' + data.subscriptionID);
}
}).render('#paypal-button-container');
When a user selects Credit Card (non PayPal account option),the next PayPal popup Window has a long form, collecting Credit Card, Billing Address, Shipping Address, Phone Number, and Email. For my needs, I don't need a shipping address and I'd like to be able to default things like Billing Address, Phone, and Email.
The PayPal SDK documentation is large but somehow lacking critical details around this library. My questions are:
How can I exclude shipping address collection from this form?
How can I default the other info I have already collected from the user (phone, email, etc)?
Thank you.
|
[
"All available parameters are the same as the create subscription API operation.\n\nSet application_context.shipping_preference to NO_SHIPPING\n\nPhone, email, and other information can be set in the subscriber object.\n\n\n"
] |
[
0
] |
[] |
[] |
[
"paypal"
] |
stackoverflow_0074666899_paypal.txt
|
Q:
.Net Core JwtBearer middleware using Amazon Cognito
I am using Cognito(using the amazon-javascript-sdk) in a .net Core angular application and im trying to verify the access_token that i get from amazon in my .net core back-end so that I can protect my Web Api.
Using the Amazon cognito JWKS I am able to validate the access_token and therefore allow/deny access to my api. The thing is that I now have the JWK keys hardcoded in my startup.cs.
What I understand from JWKS is that these keys can rotate(did not find if amazon does this) so i would like to somehow tell my middleware to get the keys from an endpoint. I read something about discovery documents and other stuff but cant find anything on how to configure the middleware to do this automatic.
For OpenId you can use the MetadataAddress to point to https://cognito-idp.{awsregion}.amazonaws.com/{userPool}/.well-known/openid-configuration and that will get all the configuration necessary.
I feel something similar should exists for the IssuerSigningKey(JWK) if you use JwtBearer middleware. Instead of setting a hardcoded key i expect to point to the JWK url where the middleware will locate the keys and does it magic. The JWKS also contains multiple keys so therefore I expect the middleware to figure out itself which key to use.
Relevant code:
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
jwt.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = MagicFunction("hardcodedRSAModules","hardcodedRSA")
ValidIssuer = "https://cognito-idp.us-east-2.amazonaws.com/{userpool}",
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateAudience = false,
ClockSkew = TimeSpan.FromMinutes(0)
};
});
A:
Using the amazon openid-configuration, available here:
https://cognito-idp.{region}.amazonaws.com/{UserPoolId}/.well-known/openid-configuration
you can use the Configurationmanager to get the SecurityKey's. In the TokenValidationParameters you can set the IssuerSigningKeys to the keys you get from the configurationmanager.
This article was also very helpful to finding the solution https://developer.okta.com/blog/2018/03/23/token-authentication-aspnetcore-complete-guide
This answer was posted as an edit to the question .Net Core JwtBearer middleware using Amazon Cognito by the OP blaataap under CC BY-SA 4.0.
|
.Net Core JwtBearer middleware using Amazon Cognito
|
I am using Cognito(using the amazon-javascript-sdk) in a .net Core angular application and im trying to verify the access_token that i get from amazon in my .net core back-end so that I can protect my Web Api.
Using the Amazon cognito JWKS I am able to validate the access_token and therefore allow/deny access to my api. The thing is that I now have the JWK keys hardcoded in my startup.cs.
What I understand from JWKS is that these keys can rotate(did not find if amazon does this) so i would like to somehow tell my middleware to get the keys from an endpoint. I read something about discovery documents and other stuff but cant find anything on how to configure the middleware to do this automatic.
For OpenId you can use the MetadataAddress to point to https://cognito-idp.{awsregion}.amazonaws.com/{userPool}/.well-known/openid-configuration and that will get all the configuration necessary.
I feel something similar should exists for the IssuerSigningKey(JWK) if you use JwtBearer middleware. Instead of setting a hardcoded key i expect to point to the JWK url where the middleware will locate the keys and does it magic. The JWKS also contains multiple keys so therefore I expect the middleware to figure out itself which key to use.
Relevant code:
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
jwt.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = MagicFunction("hardcodedRSAModules","hardcodedRSA")
ValidIssuer = "https://cognito-idp.us-east-2.amazonaws.com/{userpool}",
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateAudience = false,
ClockSkew = TimeSpan.FromMinutes(0)
};
});
|
[
"Using the amazon openid-configuration, available here:\nhttps://cognito-idp.{region}.amazonaws.com/{UserPoolId}/.well-known/openid-configuration\n\nyou can use the Configurationmanager to get the SecurityKey's. In the TokenValidationParameters you can set the IssuerSigningKeys to the keys you get from the configurationmanager.\nThis article was also very helpful to finding the solution https://developer.okta.com/blog/2018/03/23/token-authentication-aspnetcore-complete-guide\n\nThis answer was posted as an edit to the question .Net Core JwtBearer middleware using Amazon Cognito by the OP blaataap under CC BY-SA 4.0.\n"
] |
[
0
] |
[] |
[] |
[
".net",
".net_core",
"amazon_cognito",
"jwk",
"jwt"
] |
stackoverflow_0052945663_.net_.net_core_amazon_cognito_jwk_jwt.txt
|
Q:
I'm having trouble adding a scrollbar to my project that I developed with tkinter
`
import tkinter
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from tkinter import *
import pandas as pd
from tkinter import ttk
from datetime import datetime
#tkinter
master = Tk()
master.title("Anket")
master.state('zoomed')
#new mainframe
frame = tkinter.Frame(master)
frame.pack()
#label inputs
Label(frame, text="Katılımcı Ad Soyad").grid(row=1, column=0)
entry2 = Entry(frame)
entry2.grid(row=1, column=1)
Label(frame, text="Katılımcı Yaş").grid(row=2, column=0)
entry3 = Entry(frame)
entry3.grid(row=2, column=1)
Label(frame, text="Eğitim").grid(row=3, column=0)
entry4 = Entry(frame)
entry4.grid(row=3, column=1)
tkinter.Label(frame, text="Önceden VR tecrübeniz var mıydı?").grid(row=4, column=0)
entry5 = tkinter.StringVar()
tkinter.Radiobutton(frame, text="Var", variable=entry5, value="Var").grid(row=4, column=1)
tkinter.Radiobutton(frame, text="Yok", variable=entry5, value="Yok").grid(row=4, column=2)
#label func
def griding_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="1", variable=entry, value=1).grid(row=row, column=1)
tkinter.Radiobutton(frame, text="2", variable=entry, value=2).grid(row=row, column=2)
tkinter.Radiobutton(frame, text="3", variable=entry, value=3).grid(row=row, column=3)
tkinter.Radiobutton(frame, text="4", variable=entry, value=4).grid(row=row, column=4)
tkinter.Radiobutton(frame, text="5", variable=entry, value=5).grid(row=row, column=5)
def griding_ipq_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="1", variable=entry, value=1).grid(row=row, column=1)
tkinter.Radiobutton(frame, text="2", variable=entry, value=2).grid(row=row, column=2)
tkinter.Radiobutton(frame, text="3", variable=entry, value=3).grid(row=row, column=3)
tkinter.Radiobutton(frame, text="4", variable=entry, value=4).grid(row=row, column=4)
tkinter.Radiobutton(frame, text="5", variable=entry, value=5).grid(row=row, column=5)
tkinter.Radiobutton(frame, text="6", variable=entry, value=6).grid(row=row, column=6)
def griding_ss_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="Hiçbiri", variable=entry, value="Hiçbiri").grid(row=row, column=1)
tkinter.Radiobutton(frame, text="Hafif", variable=entry, value="Hafif").grid(row=row, column=2)
tkinter.Radiobutton(frame, text="Orta", variable=entry, value="Orta").grid(row=row, column=3)
tkinter.Radiobutton(frame, text="Şiddetli", variable=entry, value="Şiddetli").grid(row=row, column=4)
def griding_tam_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="1", variable=entry, value=1).grid(row=row, column=1)
tkinter.Radiobutton(frame, text="2", variable=entry, value=2).grid(row=row, column=2)
tkinter.Radiobutton(frame, text="3", variable=entry, value=3).grid(row=row, column=3)
tkinter.Radiobutton(frame, text="4", variable=entry, value=4).grid(row=row, column=4)
tkinter.Radiobutton(frame, text="5", variable=entry, value=5).grid(row=row, column=5)
tkinter.Radiobutton(frame, text="6", variable=entry, value=6).grid(row=row, column=6)
tkinter.Radiobutton(frame, text="7", variable=entry, value=7).grid(row=row, column=7)
def griding_vas_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="1", variable=entry, value=1).grid(row=row, column=1)
tkinter.Radiobutton(frame, text="2", variable=entry, value=2).grid(row=row, column=2)
tkinter.Radiobutton(frame, text="3", variable=entry, value=3).grid(row=row, column=3)
tkinter.Radiobutton(frame, text="4", variable=entry, value=4).grid(row=row, column=4)
tkinter.Radiobutton(frame, text="5", variable=entry, value=5).grid(row=row, column=5)
tkinter.Radiobutton(frame, text="6", variable=entry, value=6).grid(row=row, column=6)
tkinter.Radiobutton(frame, text="7", variable=entry, value=7).grid(row=row, column=7)
tkinter.Radiobutton(frame, text="8", variable=entry, value=8).grid(row=row, column=8)
tkinter.Radiobutton(frame, text="9", variable=entry, value=9).grid(row=row, column=9)
tkinter.Radiobutton(frame, text="10", variable=entry, value=10).grid(row=row, column=10)
entry6 = tkinter.IntVar()
griding_questions("1. Bu sistemi sık sık kullanmak isterim.", 5, entry6)
entry7 = tkinter.IntVar()
griding_questions("2. Bu sistemi gereksiz yere karmaşık buldum.", 6, entry7)
entry8 = tkinter.IntVar()
griding_questions("3. Sistemin kullanımının kolay olduğunu düşündüm.", 7, entry8)
entry9 = tkinter.IntVar()
griding_questions("4. Bu sistemi kullanabilmek için teknik bir kişinin desteğine ihtiyacım olacağını düşünüyorum.", 8,
entry9)
entry10 = tkinter.IntVar()
griding_questions("5. Bu sistemdeki çeşitli fonksiyonların iyi bir şekilde entegre olduğunu gördüm.", 9, entry10)
entry11 = tkinter.IntVar()
griding_questions("6. Bu sistemde çok fazla tutarsızlık olduğunu düşündüm.", 10, entry11)
entry12 = tkinter.IntVar()
griding_questions("7. Çoğu insanın bu sistemi çok çabuk kullanmayı öğreneceğini hayal ediyorum.", 11, entry12)
entry13 = tkinter.IntVar()
griding_questions("8. Bu sistemi kullanmayı çok hantal (garip) buldum.", 12, entry13)
entry14 = tkinter.IntVar()
griding_questions("9. Bu sistemi kullanırken kendimi çok güvende hissettim.", 13, entry14)
entry15 = tkinter.IntVar()
griding_questions("10. Bu sisteme geçmeden önce çok şey öğrenmem gerekiyordu.", 14, entry15)
entry16 = tkinter.IntVar()
griding_ipq_questions("IPQ1. Bilgisayar tarafından oluşturulan dünyada bir \"orada olma\" duygusuna sahiptim.", 15,
entry16)
entry17 = tkinter.IntVar()
griding_ipq_questions("IPQ2. Bir şekilde sanal dünyanın etrafımı sardığını hissettim.", 16, entry17)
entry18 = tkinter.IntVar()
griding_ipq_questions("IPQ3. Sadece resimleri algılıyormuş gibi hissettim.", 17, entry18)
entry19 = tkinter.IntVar()
griding_ipq_questions("IPQ4. Sanal uzayda kendimi mevcut hissetmiyordum.", 18, entry19)
entry20 = tkinter.IntVar()
griding_ipq_questions("IPQ5. Dışarıdan bir şey çalıştırmak yerine sanal alanda hareket etme duygusu vardı.", 19,
entry20)
entry21 = tkinter.IntVar()
griding_ipq_questions("IPQ6. Sanal uzayda kendimi mevcut (oradaymış gibi) hissettim.", 20, entry21)
entry22 = tkinter.IntVar()
griding_ipq_questions(
"IPQ7. Sanal dünyada gezinirken etrafınızdaki gerçek dünyanın ne kadar farkındaydınız? (yani sesler, oda sıcaklığı, diğer insanlar vb.)?",
21, entry22)
entry23 = tkinter.IntVar()
griding_ipq_questions("IPQ8. Gerçek çevremin farkında değildim.", 22, entry23)
entry24 = tkinter.IntVar()
griding_ipq_questions("IPQ9. Yine de gerçek çevreye dikkat ettim.", 23, entry24)
entry25 = tkinter.IntVar()
griding_ipq_questions("IPQ10. Tamamen sanal dünyanın büyüsüne kapıldım.", 24, entry25)
entry26 = tkinter.IntVar()
griding_ipq_questions("IPQ11. Sanal dünya size ne kadar gerçek göründü?", 25, entry26)
entry27 = tkinter.IntVar()
griding_ipq_questions("IPQ12. Sanal ortamdaki deneyiminiz, gerçek dünya deneyiminizle ne kadar tutarlı görünüyordu?",
26, entry27)
entry28 = tkinter.IntVar()
griding_ipq_questions("IPQ13. Sanal dünya size ne kadar gerçek göründü?", 27, entry28)
entry29 = tkinter.IntVar()
griding_ipq_questions("IPQ14. Sanal dünya gerçek dünyadan daha gerçekçi görünüyordu.", 28, entry29)
entry30 = tkinter.StringVar()
griding_ss_questions("SSQ1. Genel rahatsızlık", 29, entry30)
entry31 = tkinter.StringVar()
griding_ss_questions("SSQ2. Tükenmişlik, yorgunluk", 30, entry31)
entry32 = tkinter.StringVar()
griding_ss_questions("SSQ3. Baş ağrısı", 31, entry32)
entry33 = tkinter.StringVar()
griding_ss_questions("SSQ4. Göz yorgunluğu", 32, entry33)
entry34 = tkinter.StringVar()
griding_ss_questions("SSQ5. Odaklanma zorluğu", 33, entry34)
entry35 = tkinter.StringVar()
griding_ss_questions("SSQ6. Artan tükürük", 34, entry35)
entry36 = tkinter.StringVar()
griding_ss_questions("SSQ7. Terleme", 35, entry36)
entry37 = tkinter.StringVar()
griding_ss_questions("SSQ8. Mide bulantısı", 36, entry37)
entry38 = tkinter.StringVar()
griding_ss_questions("SSQ9. Konsantrasyon bozukluğu", 37, entry38)
entry39 = tkinter.StringVar()
griding_ss_questions("SSQ10. Baş dolgunluğu", 38, entry39)
entry40 = tkinter.StringVar()
griding_ss_questions("SSQ11. Bulanık görme", 39, entry40)
entry41 = tkinter.StringVar()
griding_ss_questions("SSQ12. Baş dönmesi (gözler açık)", 40, entry41)
entry42 = tkinter.StringVar()
griding_ss_questions("SSQ13. Baş dönmesi (gözler kapalı)", 41, entry42)
entry43 = tkinter.StringVar()
griding_ss_questions("SSQ14. Vertigo, kontrol kaybı", 42, entry43)
entry44 = tkinter.StringVar()
griding_ss_questions("SSQ15. Mide farkındalığı", 43, entry44)
entry45 = tkinter.StringVar()
griding_ss_questions("SSQ16. Geğirme", 44, entry45)
entry46 = tkinter.IntVar()
griding_tam_questions("TAM1. VR_Locomotion kullanmak, görevleri daha hızlı tamamlamamı sağladı.", 45, entry46)
entry47 = tkinter.IntVar()
griding_tam_questions("TAM2. VR_Locomotion kullanmak iş performansımı iyileştirdi.", 46, entry47)
entry48 = tkinter.IntVar()
griding_tam_questions("TAM3. VR_Locomotion kullanmak üretkenliğimi artırdı.", 47, entry48)
entry49 = tkinter.IntVar()
griding_tam_questions("TAM4. VR_Locomotion kullanmak etkinliğimi artırdı.", 48, entry49)
entry50 = tkinter.IntVar()
griding_tam_questions("TAM5. VR_Locomotion kullanmak, onunla yapmam gereken şeyleri yapmayı kolaylaştırdı.", 49,
entry50)
entry51 = tkinter.IntVar()
griding_tam_questions("TAM6. VR_Locomotion'u faydalı buldum.", 50, entry51)
entry52 = tkinter.IntVar()
griding_tam_questions("TAM7. VR_Locomotion'u kullanmayı öğrenmek kolaydı.", 51, entry52)
entry53 = tkinter.IntVar()
griding_tam_questions("TAM8. VR_Locomotion'un yapmasını istediğim şeyi yapmasını kolay buldum.", 52, entry53)
entry54 = tkinter.IntVar()
griding_tam_questions("TAM9. VR_Locomotion ile etkileşimim açık ve anlaşılırdı.", 53, entry54)
entry55 = tkinter.IntVar()
griding_tam_questions("TAM 10. VR_Locomotion ile esnek bir etkileşim kurdum.", 54, entry55)
entry56 = tkinter.IntVar()
griding_tam_questions("TAM11. VR_Locomotion kullanmakta ustalaşmak benim için kolaydı.", 55, entry56)
entry57 = tkinter.IntVar()
griding_tam_questions("TAM12. VR_Locomotion'un kullanımını kolay buldum.", 56, entry57)
entry58 = tkinter.IntVar()
griding_tam_questions("UMUX1. VR_Locomotion'ın yetenekleri gereksinimlerimi karşılıyor.", 57, entry58)
entry59 = tkinter.IntVar()
griding_tam_questions("UMUX2. VR_Locomotion'u kullanmak sinir bozucu bir deneyimdir.", 58, entry59)
entry60 = tkinter.IntVar()
griding_tam_questions("UMUX3. VR_Locomotion'un kullanımı kolaydır.", 59, entry60)
entry61 = tkinter.IntVar()
griding_tam_questions("UMUX4. VR_Locomotion ile bir şeyleri düzeltmek için çok fazla zaman harcamak zorundayım.", 60,
entry61)
entry62 = tkinter.IntVar()
griding_vas_questions("VAS1: (Kendi kendine hareket) Tüm vücudumun ileriye doğru hareket ettiğini hissettim.", 61,
entry62)
entry63 = tkinter.IntVar()
griding_vas_questions("VAS2: (Yürüme hissi) İleriye doğru yürüyormuş gibi hissettim.", 62, entry63)
entry64 = tkinter.IntVar()
griding_vas_questions("VAS3: (Bacak hareketi) Ayaklarım yere çarpıyormuş gibi hissettim.", 63, entry64)
entry65 = tkinter.IntVar()
griding_vas_questions(
"VAS4 : Olay yerinde varmışım gibi hissettim (kişinin gerçek konumunun dışında bir yerde varmış gibi "
"hissetmesi) .",
64, entry65)
Label(frame, text="E-posta Adresi").grid(row=65, column=0)
entry66 = Entry(frame)
entry66.grid(row=65, column=1)
#quit and submit
Button(frame, text='Quit', command=frame.quit).grid(row=5, column=15, pady=4)
Button(frame, text='Submit', command=submit_fields).grid(row=8, column=15, pady=4)
#mainloop
mainloop()
`
I cannot add with pack to places where grid is used, and with grid to places where pack is used. I searched the internet for a solution and couldn't find much. Adding canvas is problematic. It requires me to add an extra text, treeframe etc inside the frame. sometimes I can add it with some methods, but this time it doesn't scroll. I'm stuck.
A:
I did not test it. Use tkinter.tix.ScrolledWindow.
from tkinter.tix import *
:
:
:
#add this between line 16 to 21.
#new mainframe
frame = tkinter.Frame(master)
frame.pack()
swin = ScrolledWindow(frame, width=500, height=500)
swin.pack()
#label inputs
|
I'm having trouble adding a scrollbar to my project that I developed with tkinter
|
`
import tkinter
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from tkinter import *
import pandas as pd
from tkinter import ttk
from datetime import datetime
#tkinter
master = Tk()
master.title("Anket")
master.state('zoomed')
#new mainframe
frame = tkinter.Frame(master)
frame.pack()
#label inputs
Label(frame, text="Katılımcı Ad Soyad").grid(row=1, column=0)
entry2 = Entry(frame)
entry2.grid(row=1, column=1)
Label(frame, text="Katılımcı Yaş").grid(row=2, column=0)
entry3 = Entry(frame)
entry3.grid(row=2, column=1)
Label(frame, text="Eğitim").grid(row=3, column=0)
entry4 = Entry(frame)
entry4.grid(row=3, column=1)
tkinter.Label(frame, text="Önceden VR tecrübeniz var mıydı?").grid(row=4, column=0)
entry5 = tkinter.StringVar()
tkinter.Radiobutton(frame, text="Var", variable=entry5, value="Var").grid(row=4, column=1)
tkinter.Radiobutton(frame, text="Yok", variable=entry5, value="Yok").grid(row=4, column=2)
#label func
def griding_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="1", variable=entry, value=1).grid(row=row, column=1)
tkinter.Radiobutton(frame, text="2", variable=entry, value=2).grid(row=row, column=2)
tkinter.Radiobutton(frame, text="3", variable=entry, value=3).grid(row=row, column=3)
tkinter.Radiobutton(frame, text="4", variable=entry, value=4).grid(row=row, column=4)
tkinter.Radiobutton(frame, text="5", variable=entry, value=5).grid(row=row, column=5)
def griding_ipq_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="1", variable=entry, value=1).grid(row=row, column=1)
tkinter.Radiobutton(frame, text="2", variable=entry, value=2).grid(row=row, column=2)
tkinter.Radiobutton(frame, text="3", variable=entry, value=3).grid(row=row, column=3)
tkinter.Radiobutton(frame, text="4", variable=entry, value=4).grid(row=row, column=4)
tkinter.Radiobutton(frame, text="5", variable=entry, value=5).grid(row=row, column=5)
tkinter.Radiobutton(frame, text="6", variable=entry, value=6).grid(row=row, column=6)
def griding_ss_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="Hiçbiri", variable=entry, value="Hiçbiri").grid(row=row, column=1)
tkinter.Radiobutton(frame, text="Hafif", variable=entry, value="Hafif").grid(row=row, column=2)
tkinter.Radiobutton(frame, text="Orta", variable=entry, value="Orta").grid(row=row, column=3)
tkinter.Radiobutton(frame, text="Şiddetli", variable=entry, value="Şiddetli").grid(row=row, column=4)
def griding_tam_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="1", variable=entry, value=1).grid(row=row, column=1)
tkinter.Radiobutton(frame, text="2", variable=entry, value=2).grid(row=row, column=2)
tkinter.Radiobutton(frame, text="3", variable=entry, value=3).grid(row=row, column=3)
tkinter.Radiobutton(frame, text="4", variable=entry, value=4).grid(row=row, column=4)
tkinter.Radiobutton(frame, text="5", variable=entry, value=5).grid(row=row, column=5)
tkinter.Radiobutton(frame, text="6", variable=entry, value=6).grid(row=row, column=6)
tkinter.Radiobutton(frame, text="7", variable=entry, value=7).grid(row=row, column=7)
def griding_vas_questions(text, row, entry):
tkinter.Label(frame, text=text).grid(row=row, column=0)
tkinter.Radiobutton(frame, text="1", variable=entry, value=1).grid(row=row, column=1)
tkinter.Radiobutton(frame, text="2", variable=entry, value=2).grid(row=row, column=2)
tkinter.Radiobutton(frame, text="3", variable=entry, value=3).grid(row=row, column=3)
tkinter.Radiobutton(frame, text="4", variable=entry, value=4).grid(row=row, column=4)
tkinter.Radiobutton(frame, text="5", variable=entry, value=5).grid(row=row, column=5)
tkinter.Radiobutton(frame, text="6", variable=entry, value=6).grid(row=row, column=6)
tkinter.Radiobutton(frame, text="7", variable=entry, value=7).grid(row=row, column=7)
tkinter.Radiobutton(frame, text="8", variable=entry, value=8).grid(row=row, column=8)
tkinter.Radiobutton(frame, text="9", variable=entry, value=9).grid(row=row, column=9)
tkinter.Radiobutton(frame, text="10", variable=entry, value=10).grid(row=row, column=10)
entry6 = tkinter.IntVar()
griding_questions("1. Bu sistemi sık sık kullanmak isterim.", 5, entry6)
entry7 = tkinter.IntVar()
griding_questions("2. Bu sistemi gereksiz yere karmaşık buldum.", 6, entry7)
entry8 = tkinter.IntVar()
griding_questions("3. Sistemin kullanımının kolay olduğunu düşündüm.", 7, entry8)
entry9 = tkinter.IntVar()
griding_questions("4. Bu sistemi kullanabilmek için teknik bir kişinin desteğine ihtiyacım olacağını düşünüyorum.", 8,
entry9)
entry10 = tkinter.IntVar()
griding_questions("5. Bu sistemdeki çeşitli fonksiyonların iyi bir şekilde entegre olduğunu gördüm.", 9, entry10)
entry11 = tkinter.IntVar()
griding_questions("6. Bu sistemde çok fazla tutarsızlık olduğunu düşündüm.", 10, entry11)
entry12 = tkinter.IntVar()
griding_questions("7. Çoğu insanın bu sistemi çok çabuk kullanmayı öğreneceğini hayal ediyorum.", 11, entry12)
entry13 = tkinter.IntVar()
griding_questions("8. Bu sistemi kullanmayı çok hantal (garip) buldum.", 12, entry13)
entry14 = tkinter.IntVar()
griding_questions("9. Bu sistemi kullanırken kendimi çok güvende hissettim.", 13, entry14)
entry15 = tkinter.IntVar()
griding_questions("10. Bu sisteme geçmeden önce çok şey öğrenmem gerekiyordu.", 14, entry15)
entry16 = tkinter.IntVar()
griding_ipq_questions("IPQ1. Bilgisayar tarafından oluşturulan dünyada bir \"orada olma\" duygusuna sahiptim.", 15,
entry16)
entry17 = tkinter.IntVar()
griding_ipq_questions("IPQ2. Bir şekilde sanal dünyanın etrafımı sardığını hissettim.", 16, entry17)
entry18 = tkinter.IntVar()
griding_ipq_questions("IPQ3. Sadece resimleri algılıyormuş gibi hissettim.", 17, entry18)
entry19 = tkinter.IntVar()
griding_ipq_questions("IPQ4. Sanal uzayda kendimi mevcut hissetmiyordum.", 18, entry19)
entry20 = tkinter.IntVar()
griding_ipq_questions("IPQ5. Dışarıdan bir şey çalıştırmak yerine sanal alanda hareket etme duygusu vardı.", 19,
entry20)
entry21 = tkinter.IntVar()
griding_ipq_questions("IPQ6. Sanal uzayda kendimi mevcut (oradaymış gibi) hissettim.", 20, entry21)
entry22 = tkinter.IntVar()
griding_ipq_questions(
"IPQ7. Sanal dünyada gezinirken etrafınızdaki gerçek dünyanın ne kadar farkındaydınız? (yani sesler, oda sıcaklığı, diğer insanlar vb.)?",
21, entry22)
entry23 = tkinter.IntVar()
griding_ipq_questions("IPQ8. Gerçek çevremin farkında değildim.", 22, entry23)
entry24 = tkinter.IntVar()
griding_ipq_questions("IPQ9. Yine de gerçek çevreye dikkat ettim.", 23, entry24)
entry25 = tkinter.IntVar()
griding_ipq_questions("IPQ10. Tamamen sanal dünyanın büyüsüne kapıldım.", 24, entry25)
entry26 = tkinter.IntVar()
griding_ipq_questions("IPQ11. Sanal dünya size ne kadar gerçek göründü?", 25, entry26)
entry27 = tkinter.IntVar()
griding_ipq_questions("IPQ12. Sanal ortamdaki deneyiminiz, gerçek dünya deneyiminizle ne kadar tutarlı görünüyordu?",
26, entry27)
entry28 = tkinter.IntVar()
griding_ipq_questions("IPQ13. Sanal dünya size ne kadar gerçek göründü?", 27, entry28)
entry29 = tkinter.IntVar()
griding_ipq_questions("IPQ14. Sanal dünya gerçek dünyadan daha gerçekçi görünüyordu.", 28, entry29)
entry30 = tkinter.StringVar()
griding_ss_questions("SSQ1. Genel rahatsızlık", 29, entry30)
entry31 = tkinter.StringVar()
griding_ss_questions("SSQ2. Tükenmişlik, yorgunluk", 30, entry31)
entry32 = tkinter.StringVar()
griding_ss_questions("SSQ3. Baş ağrısı", 31, entry32)
entry33 = tkinter.StringVar()
griding_ss_questions("SSQ4. Göz yorgunluğu", 32, entry33)
entry34 = tkinter.StringVar()
griding_ss_questions("SSQ5. Odaklanma zorluğu", 33, entry34)
entry35 = tkinter.StringVar()
griding_ss_questions("SSQ6. Artan tükürük", 34, entry35)
entry36 = tkinter.StringVar()
griding_ss_questions("SSQ7. Terleme", 35, entry36)
entry37 = tkinter.StringVar()
griding_ss_questions("SSQ8. Mide bulantısı", 36, entry37)
entry38 = tkinter.StringVar()
griding_ss_questions("SSQ9. Konsantrasyon bozukluğu", 37, entry38)
entry39 = tkinter.StringVar()
griding_ss_questions("SSQ10. Baş dolgunluğu", 38, entry39)
entry40 = tkinter.StringVar()
griding_ss_questions("SSQ11. Bulanık görme", 39, entry40)
entry41 = tkinter.StringVar()
griding_ss_questions("SSQ12. Baş dönmesi (gözler açık)", 40, entry41)
entry42 = tkinter.StringVar()
griding_ss_questions("SSQ13. Baş dönmesi (gözler kapalı)", 41, entry42)
entry43 = tkinter.StringVar()
griding_ss_questions("SSQ14. Vertigo, kontrol kaybı", 42, entry43)
entry44 = tkinter.StringVar()
griding_ss_questions("SSQ15. Mide farkındalığı", 43, entry44)
entry45 = tkinter.StringVar()
griding_ss_questions("SSQ16. Geğirme", 44, entry45)
entry46 = tkinter.IntVar()
griding_tam_questions("TAM1. VR_Locomotion kullanmak, görevleri daha hızlı tamamlamamı sağladı.", 45, entry46)
entry47 = tkinter.IntVar()
griding_tam_questions("TAM2. VR_Locomotion kullanmak iş performansımı iyileştirdi.", 46, entry47)
entry48 = tkinter.IntVar()
griding_tam_questions("TAM3. VR_Locomotion kullanmak üretkenliğimi artırdı.", 47, entry48)
entry49 = tkinter.IntVar()
griding_tam_questions("TAM4. VR_Locomotion kullanmak etkinliğimi artırdı.", 48, entry49)
entry50 = tkinter.IntVar()
griding_tam_questions("TAM5. VR_Locomotion kullanmak, onunla yapmam gereken şeyleri yapmayı kolaylaştırdı.", 49,
entry50)
entry51 = tkinter.IntVar()
griding_tam_questions("TAM6. VR_Locomotion'u faydalı buldum.", 50, entry51)
entry52 = tkinter.IntVar()
griding_tam_questions("TAM7. VR_Locomotion'u kullanmayı öğrenmek kolaydı.", 51, entry52)
entry53 = tkinter.IntVar()
griding_tam_questions("TAM8. VR_Locomotion'un yapmasını istediğim şeyi yapmasını kolay buldum.", 52, entry53)
entry54 = tkinter.IntVar()
griding_tam_questions("TAM9. VR_Locomotion ile etkileşimim açık ve anlaşılırdı.", 53, entry54)
entry55 = tkinter.IntVar()
griding_tam_questions("TAM 10. VR_Locomotion ile esnek bir etkileşim kurdum.", 54, entry55)
entry56 = tkinter.IntVar()
griding_tam_questions("TAM11. VR_Locomotion kullanmakta ustalaşmak benim için kolaydı.", 55, entry56)
entry57 = tkinter.IntVar()
griding_tam_questions("TAM12. VR_Locomotion'un kullanımını kolay buldum.", 56, entry57)
entry58 = tkinter.IntVar()
griding_tam_questions("UMUX1. VR_Locomotion'ın yetenekleri gereksinimlerimi karşılıyor.", 57, entry58)
entry59 = tkinter.IntVar()
griding_tam_questions("UMUX2. VR_Locomotion'u kullanmak sinir bozucu bir deneyimdir.", 58, entry59)
entry60 = tkinter.IntVar()
griding_tam_questions("UMUX3. VR_Locomotion'un kullanımı kolaydır.", 59, entry60)
entry61 = tkinter.IntVar()
griding_tam_questions("UMUX4. VR_Locomotion ile bir şeyleri düzeltmek için çok fazla zaman harcamak zorundayım.", 60,
entry61)
entry62 = tkinter.IntVar()
griding_vas_questions("VAS1: (Kendi kendine hareket) Tüm vücudumun ileriye doğru hareket ettiğini hissettim.", 61,
entry62)
entry63 = tkinter.IntVar()
griding_vas_questions("VAS2: (Yürüme hissi) İleriye doğru yürüyormuş gibi hissettim.", 62, entry63)
entry64 = tkinter.IntVar()
griding_vas_questions("VAS3: (Bacak hareketi) Ayaklarım yere çarpıyormuş gibi hissettim.", 63, entry64)
entry65 = tkinter.IntVar()
griding_vas_questions(
"VAS4 : Olay yerinde varmışım gibi hissettim (kişinin gerçek konumunun dışında bir yerde varmış gibi "
"hissetmesi) .",
64, entry65)
Label(frame, text="E-posta Adresi").grid(row=65, column=0)
entry66 = Entry(frame)
entry66.grid(row=65, column=1)
#quit and submit
Button(frame, text='Quit', command=frame.quit).grid(row=5, column=15, pady=4)
Button(frame, text='Submit', command=submit_fields).grid(row=8, column=15, pady=4)
#mainloop
mainloop()
`
I cannot add with pack to places where grid is used, and with grid to places where pack is used. I searched the internet for a solution and couldn't find much. Adding canvas is problematic. It requires me to add an extra text, treeframe etc inside the frame. sometimes I can add it with some methods, but this time it doesn't scroll. I'm stuck.
|
[
"I did not test it. Use tkinter.tix.ScrolledWindow.\nfrom tkinter.tix import *\n:\n:\n:\n#add this between line 16 to 21.\n#new mainframe\nframe = tkinter.Frame(master)\nframe.pack()\n\nswin = ScrolledWindow(frame, width=500, height=500)\nswin.pack()\n\n#label inputs\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"scrollbar",
"tkinter",
"tkinter_canvas"
] |
stackoverflow_0074665863_python_scrollbar_tkinter_tkinter_canvas.txt
|
Q:
Hibernate doesn't creating table based on entity
After starting the program (launching TomCat) there are no tables created in the schema, but the table "player" has to be created automatically.
I checked hibernate config, but can't find where is the problem.
I've tried changing hbm2ddl.auto to hibernate.hbm2ddl.auto (also create, create-drop etc.) but it didn't help.
If there are any ideas, please let me know. Thanks.
Entity class:
package com.game.entity;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(schema = "rpg", name = "player")
public class Player {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name", length = 12, nullable = false)
private String name;
@Column(name = "title", length = 30, nullable = false)
private String title;
@Column(name = "race", nullable = false)
@Enumerated(EnumType.ORDINAL)
private Race race;
@Column(name = "profession", nullable = false)
@Enumerated(EnumType.ORDINAL)
private Profession profession;
@Column(name = "birthday", nullable = false)
private Date birthday;
@Column(name = "banned", nullable = false)
private Boolean banned;
@Column(name = "level", nullable = false)
private Integer level;
public Player() {
}
public Player(Long id, String name, String title, Race race, Profession profession, Date birthday, Boolean banned, Integer level) {
this.id = id;
this.name = name;
this.title = title;
this.race = race;
this.profession = profession;
this.birthday = birthday;
this.banned = banned;
this.level = level;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Race getRace() {
return race;
}
public void setRace(Race race) {
this.race = race;
}
public Profession getProfession() {
return profession;
}
public void setProfession(Profession profession) {
this.profession = profession;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Boolean getBanned() {
return banned;
}
public void setBanned(Boolean banned) {
this.banned = banned;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
Repository class:
package com.game.repository;
import com.game.entity.Player;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.springframework.stereotype.Repository;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Optional;
@Repository(value = "db")
public class PlayerRepositoryDB implements IPlayerRepository {
private final SessionFactory sessionFactory;
public PlayerRepositoryDB() {
Configuration configuration = new Configuration().configure().addAnnotatedClass(Player.class);
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
@Override
public List<Player> getAll(int pageNumber, int pageSize) {
try(Session session = sessionFactory.openSession()){
NativeQuery<Player> nativeQuery = session.createNativeQuery("SELECT * FROM rpg.player", Player.class);
nativeQuery.setFirstResult(pageNumber * pageSize);
nativeQuery.setMaxResults(pageSize);
return nativeQuery.list();
}
}
Hibernate configuration:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/rpg</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Full project code with pom.xml is available by link:
https://github.com/gamlethot/project-hibernate-1
A:
1-Hibernate does not recognize your repository. You should not mark repo classes as @Repository because they are not interfaces and in your example they are working like a service. So they can be @Service.
2-Do not implement IPlayerRepository. Mark it as @Repository and just autowire it to your service classes (or use constructor injection and just use like a variable)
Like:
@Service
public class PlayerRepositoryDB {
private IPlayerRepository playerRepository;
public PlayerRepositoryDB (IPlayerRepository playerRepository){ //CONSTRUCTOR
this.playerRepository = playerRepository;...
3- DB repository classes are implementing IPlayerRepository but it must be marked as @Repository and It should extend either CrudRepository or JpaRepository (which extends CrudRepository already).
Like:
@Repository
public interface IPlayerRepository extends JpaRepository<Player, Long> {
//Here are the methods;
}
Here, the Long is the type of primary key of Player class.
A:
Hibernate XML:
<property name="hibernate.connection.CharSet">utf8mb4</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>
<property name="hibernate.connection.useUnicode">true</property>
Connection url:
db.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4
As a side note I would like to make one clarification that UTF-8 is the character encoding while utf8mb4 is a character set that MySQL supports. MySQL's utf8mb4 is a superset to MySQL's utf8.
Spring/Hibernate filter:
<form accept-charset="UTF-8">
A:
Problem solved.
It was because of javax.persistence.; import instead of
jakarta.persistence. in entity class.
|
Hibernate doesn't creating table based on entity
|
After starting the program (launching TomCat) there are no tables created in the schema, but the table "player" has to be created automatically.
I checked hibernate config, but can't find where is the problem.
I've tried changing hbm2ddl.auto to hibernate.hbm2ddl.auto (also create, create-drop etc.) but it didn't help.
If there are any ideas, please let me know. Thanks.
Entity class:
package com.game.entity;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(schema = "rpg", name = "player")
public class Player {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name", length = 12, nullable = false)
private String name;
@Column(name = "title", length = 30, nullable = false)
private String title;
@Column(name = "race", nullable = false)
@Enumerated(EnumType.ORDINAL)
private Race race;
@Column(name = "profession", nullable = false)
@Enumerated(EnumType.ORDINAL)
private Profession profession;
@Column(name = "birthday", nullable = false)
private Date birthday;
@Column(name = "banned", nullable = false)
private Boolean banned;
@Column(name = "level", nullable = false)
private Integer level;
public Player() {
}
public Player(Long id, String name, String title, Race race, Profession profession, Date birthday, Boolean banned, Integer level) {
this.id = id;
this.name = name;
this.title = title;
this.race = race;
this.profession = profession;
this.birthday = birthday;
this.banned = banned;
this.level = level;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Race getRace() {
return race;
}
public void setRace(Race race) {
this.race = race;
}
public Profession getProfession() {
return profession;
}
public void setProfession(Profession profession) {
this.profession = profession;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Boolean getBanned() {
return banned;
}
public void setBanned(Boolean banned) {
this.banned = banned;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
Repository class:
package com.game.repository;
import com.game.entity.Player;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.springframework.stereotype.Repository;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Optional;
@Repository(value = "db")
public class PlayerRepositoryDB implements IPlayerRepository {
private final SessionFactory sessionFactory;
public PlayerRepositoryDB() {
Configuration configuration = new Configuration().configure().addAnnotatedClass(Player.class);
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
@Override
public List<Player> getAll(int pageNumber, int pageSize) {
try(Session session = sessionFactory.openSession()){
NativeQuery<Player> nativeQuery = session.createNativeQuery("SELECT * FROM rpg.player", Player.class);
nativeQuery.setFirstResult(pageNumber * pageSize);
nativeQuery.setMaxResults(pageSize);
return nativeQuery.list();
}
}
Hibernate configuration:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/rpg</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Full project code with pom.xml is available by link:
https://github.com/gamlethot/project-hibernate-1
|
[
"1-Hibernate does not recognize your repository. You should not mark repo classes as @Repository because they are not interfaces and in your example they are working like a service. So they can be @Service.\n2-Do not implement IPlayerRepository. Mark it as @Repository and just autowire it to your service classes (or use constructor injection and just use like a variable)\nLike:\n@Service\npublic class PlayerRepositoryDB {\n\nprivate IPlayerRepository playerRepository;\n\npublic PlayerRepositoryDB (IPlayerRepository playerRepository){ //CONSTRUCTOR\nthis.playerRepository = playerRepository;...\n\n3- DB repository classes are implementing IPlayerRepository but it must be marked as @Repository and It should extend either CrudRepository or JpaRepository (which extends CrudRepository already).\nLike:\n @Repository\n public interface IPlayerRepository extends JpaRepository<Player, Long> {\n//Here are the methods;\n}\n\nHere, the Long is the type of primary key of Player class.\n",
"Hibernate XML:\n <property name=\"hibernate.connection.CharSet\">utf8mb4</property>\n <property name=\"hibernate.connection.characterEncoding\">UTF-8</property>\n <property name=\"hibernate.connection.useUnicode\">true</property>\n\nConnection url:\ndb.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4\n\nAs a side note I would like to make one clarification that UTF-8 is the character encoding while utf8mb4 is a character set that MySQL supports. MySQL's utf8mb4 is a superset to MySQL's utf8.\nSpring/Hibernate filter:\n<form accept-charset=\"UTF-8\">\n\n",
"Problem solved.\nIt was because of javax.persistence.; import instead of\njakarta.persistence. in entity class.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"entity",
"hibernate",
"java",
"mysql",
"spring"
] |
stackoverflow_0074535293_entity_hibernate_java_mysql_spring.txt
|
Q:
tkinter.place() not working and window still blank
I have a problem with tkinter.place, why it is not working?
class KafeDaun(tk.Frame):
def __init__(self, master = None):
super().__init__(master)
self.master.title("Kafe Daun-Daun Pacilkom v2.0 ")
self.master.geometry("500x300")
self.master.configure(bg="grey")
self.create_widgets()
self.pack()
def create_widgets(self):
self.btn_buat_pesanan = tk.Button(self, text = "Buat Pesanan", width = 20)
self.btn_buat_pesanan.place(x = 250, y = 100)
self.btn_meja = tk.Button(self, text = "Selesai Gunakan Meja", width = 20)
I still get this blank Frame even though already use tkinter.place on btn_buat_pesanan
I expect it to have a button on the exact location, like when using tkinter.pack() or tkinter.grid(). Do you have any suggestion
... ... ... ... ..
A:
Try this.
You have to pack the frame like this self.pack(fill="both", expand=True). Because the place did not change the parent size, that's why it didn't visible
import tkinter as tk
class KafeDaun(tk.Frame):
def __init__(self, master = None):
super().__init__(master)
self.master.title("Kafe Daun-Daun Pacilkom v2.0 ")
self.master.geometry("500x300")
self.master.configure(bg="grey")
self.create_widgets()
self.pack(fill="both", expand=True)
def create_widgets(self):
self.btn_buat_pesanan = tk.Button(self, text = "Buat Pesanan", width = 20)
self.btn_buat_pesanan.place(x = 250, y = 100)
self.btn_meja = tk.Button(self, text = "Selesai Gunakan Meja", width = 20)
app =tk.Tk()
s = KafeDaun(app)
app.mainloop()
Or you can set the width and height of the frame. super().__init__(master, width=<width>, height=<height>)
|
tkinter.place() not working and window still blank
|
I have a problem with tkinter.place, why it is not working?
class KafeDaun(tk.Frame):
def __init__(self, master = None):
super().__init__(master)
self.master.title("Kafe Daun-Daun Pacilkom v2.0 ")
self.master.geometry("500x300")
self.master.configure(bg="grey")
self.create_widgets()
self.pack()
def create_widgets(self):
self.btn_buat_pesanan = tk.Button(self, text = "Buat Pesanan", width = 20)
self.btn_buat_pesanan.place(x = 250, y = 100)
self.btn_meja = tk.Button(self, text = "Selesai Gunakan Meja", width = 20)
I still get this blank Frame even though already use tkinter.place on btn_buat_pesanan
I expect it to have a button on the exact location, like when using tkinter.pack() or tkinter.grid(). Do you have any suggestion
... ... ... ... ..
|
[
"Try this.\nYou have to pack the frame like this self.pack(fill=\"both\", expand=True). Because the place did not change the parent size, that's why it didn't visible\nimport tkinter as tk\nclass KafeDaun(tk.Frame):\n def __init__(self, master = None):\n super().__init__(master)\n self.master.title(\"Kafe Daun-Daun Pacilkom v2.0 \")\n self.master.geometry(\"500x300\")\n self.master.configure(bg=\"grey\")\n self.create_widgets()\n self.pack(fill=\"both\", expand=True)\n\n def create_widgets(self):\n self.btn_buat_pesanan = tk.Button(self, text = \"Buat Pesanan\", width = 20)\n self.btn_buat_pesanan.place(x = 250, y = 100)\n\n self.btn_meja = tk.Button(self, text = \"Selesai Gunakan Meja\", width = 20)\napp =tk.Tk()\n\n\ns = KafeDaun(app)\napp.mainloop()\n\nOr you can set the width and height of the frame. super().__init__(master, width=<width>, height=<height>)\n"
] |
[
1
] |
[] |
[] |
[
"methods",
"python",
"tkinter",
"tkinter_button",
"tkinter_canvas"
] |
stackoverflow_0074666863_methods_python_tkinter_tkinter_button_tkinter_canvas.txt
|
Q:
How to get two data from Hashmap in room database?
I took the data from a money exchange API and saved it to the room. I want to extract 2 values from the data I saved, for example, the user wants to convert 120 dollars to euros. I will take the conversion rate of the dollar and the conversion rate of the euro from my room database and convert it with a mathematical operation accordingly. However, I did not know how to get these two values from my data that I keep as Hashmap.
I wrote a code like this,
dao
@Dao
interface ExchangeDao {
@Query("SELECT * FROM ExchangeValues WHERE conversion_rates=:currency")
suspend fun getConversionRateByCurrency(currency : String) : Double
}
entity
@Entity(tableName = "ExchangeValues")
data class ExchangeEntity(
@ColumnInfo(name = "base_code") val base_code: String,
@ColumnInfo(name = "conversion_rates") val conversion_rates: HashMap<String,Double>,
@ColumnInfo(name = "result") val result: String,
@PrimaryKey(autoGenerate = true) val uid:Int?=null
)
repositoryImpl
class ExchangeRepositoryImpl @Inject constructor(
private val dao:ExchangeDao,
private val api: ExchangeApi
) : ExchangeRepository{
override suspend fun getConversionRateByCurrency(currency: String): Double {
return dao.getConversionRateByCurrency(currency)
}
}
repository
interface ExchangeRepository {
suspend fun getConversionRateByCurrency(currency : String) : Double
}
use case
class GetConversionRateByCurrencyUseCase @Inject constructor(
private val repository: ExchangeRepository
) {
suspend fun getConversionRateByCurrency(currency:String) : Double {
return repository.getConversionRateByCurrency(currency)
}
}
but it gave an error like this
error: Not sure how to convert a Cursor to this method's return type (java.lang.Double).
public abstract java.lang.Object getConversionRateByCurrency(@org.jetbrains.annotations.NotNull()
error: The columns returned by the query does not have the fields [value] in java.lang.Double even though they are annotated as non-null or primitive. Columns returned by the query: [base_code,conversion_rates,result,uid]
public abstract java.lang.Object getConversionRateByCurrency(@org.jetbrains.annotations.NotNull()
A:
To get multiple values from a HashMap in a Room database, you can do the following:
Define an Entity class that has a primary key and a column for the HashMap. For example:
@Entity(primaryKeys = {"id"})
public class MyEntity {
private int id;
@ColumnInfo(name = "data_map")
private HashMap<String, String> dataMap;
public MyEntity(int id, HashMap<String, String> dataMap) {
this.id = id;
this.dataMap = dataMap;
}
public int getId() {
return id;
}
public HashMap<String, String> getDataMap() {
return dataMap;
}
}
Define a Dao (data access object) that has a method to get the Entity by its primary key and return the values from the HashMap. For example:
@Dao
public interface MyDao {
@Query("SELECT * FROM my_entity WHERE id = :id")
MyEntity getEntityById(int id);
// Method to get two values from the HashMap in MyEntity
@Transaction
default String[] getData(int id, String key1, String key2) {
MyEntity entity = getEntityById(id);
if (entity == null) {
return null;
}
HashMap<String, String> dataMap = entity.getDataMap();
String value1 = dataMap.get(key1);
String value2 = dataMap.get(key2);
return new String[] {value1, value2};
}
}
In your code, call the Dao method and provide the primary key and the keys for the values you want to get from the HashMap. For example:
// Get an instance of the database
MyDatabase database = MyDatabase.getInstance(context);
// Get the Dao
MyDao dao = database.myDao();
// Call the Dao method and pass the primary key and the keys for the values you want to get
int id = 1;
String[] data = dao.getData(id, "key1", "key2");
This will return an array of strings with the values for the specified keys in the HashMap. You can then use these values as needed in your code.
|
How to get two data from Hashmap in room database?
|
I took the data from a money exchange API and saved it to the room. I want to extract 2 values from the data I saved, for example, the user wants to convert 120 dollars to euros. I will take the conversion rate of the dollar and the conversion rate of the euro from my room database and convert it with a mathematical operation accordingly. However, I did not know how to get these two values from my data that I keep as Hashmap.
I wrote a code like this,
dao
@Dao
interface ExchangeDao {
@Query("SELECT * FROM ExchangeValues WHERE conversion_rates=:currency")
suspend fun getConversionRateByCurrency(currency : String) : Double
}
entity
@Entity(tableName = "ExchangeValues")
data class ExchangeEntity(
@ColumnInfo(name = "base_code") val base_code: String,
@ColumnInfo(name = "conversion_rates") val conversion_rates: HashMap<String,Double>,
@ColumnInfo(name = "result") val result: String,
@PrimaryKey(autoGenerate = true) val uid:Int?=null
)
repositoryImpl
class ExchangeRepositoryImpl @Inject constructor(
private val dao:ExchangeDao,
private val api: ExchangeApi
) : ExchangeRepository{
override suspend fun getConversionRateByCurrency(currency: String): Double {
return dao.getConversionRateByCurrency(currency)
}
}
repository
interface ExchangeRepository {
suspend fun getConversionRateByCurrency(currency : String) : Double
}
use case
class GetConversionRateByCurrencyUseCase @Inject constructor(
private val repository: ExchangeRepository
) {
suspend fun getConversionRateByCurrency(currency:String) : Double {
return repository.getConversionRateByCurrency(currency)
}
}
but it gave an error like this
error: Not sure how to convert a Cursor to this method's return type (java.lang.Double).
public abstract java.lang.Object getConversionRateByCurrency(@org.jetbrains.annotations.NotNull()
error: The columns returned by the query does not have the fields [value] in java.lang.Double even though they are annotated as non-null or primitive. Columns returned by the query: [base_code,conversion_rates,result,uid]
public abstract java.lang.Object getConversionRateByCurrency(@org.jetbrains.annotations.NotNull()
|
[
"To get multiple values from a HashMap in a Room database, you can do the following:\nDefine an Entity class that has a primary key and a column for the HashMap. For example:\n@Entity(primaryKeys = {\"id\"})\npublic class MyEntity {\n private int id;\n @ColumnInfo(name = \"data_map\")\n private HashMap<String, String> dataMap;\n\n public MyEntity(int id, HashMap<String, String> dataMap) {\n this.id = id;\n this.dataMap = dataMap;\n }\n\n public int getId() {\n return id;\n }\n\n public HashMap<String, String> getDataMap() {\n return dataMap;\n }\n}\n\nDefine a Dao (data access object) that has a method to get the Entity by its primary key and return the values from the HashMap. For example:\n@Dao\npublic interface MyDao {\n @Query(\"SELECT * FROM my_entity WHERE id = :id\")\n MyEntity getEntityById(int id);\n\n // Method to get two values from the HashMap in MyEntity\n @Transaction\n default String[] getData(int id, String key1, String key2) {\n MyEntity entity = getEntityById(id);\n if (entity == null) {\n return null;\n }\n\n HashMap<String, String> dataMap = entity.getDataMap();\n String value1 = dataMap.get(key1);\n String value2 = dataMap.get(key2);\n return new String[] {value1, value2};\n }\n}\n\nIn your code, call the Dao method and provide the primary key and the keys for the values you want to get from the HashMap. For example:\n// Get an instance of the database\nMyDatabase database = MyDatabase.getInstance(context);\n\n// Get the Dao\nMyDao dao = database.myDao();\n\n// Call the Dao method and pass the primary key and the keys for the values you want to get\nint id = 1;\nString[] data = dao.getData(id, \"key1\", \"key2\");\n\nThis will return an array of strings with the values for the specified keys in the HashMap. You can then use these values as needed in your code.\n"
] |
[
0
] |
[] |
[] |
[
"android_room",
"hashmap",
"kotlin"
] |
stackoverflow_0074666627_android_room_hashmap_kotlin.txt
|
Q:
VBA Username and Password Regex (MS Access)
Supposing I have the following code in a button: (with the implementation of userNameMatches and passwordMatches missing)
Private Sub Command1_Click()
If userNameMatches And passwordMatches Then
MsgBox "Welcome!"
DoCmd.Close
DoCmd.OpenReport "HomePage", acViewReport
Else
MsgBox "Please enter valid credentials."
End If
End Sub
The username text input field is named username. The password text input field is named password.
The regex pattern I want for the username is: "^[A-Za-z][A-Za-z0-9_]{3,16}$"
The regex pattern I want for the password is: "^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"
My Question:
How do I implement userNameMatches and passwordMatches to return True if their respective text fields match the patterns, and False if they do not?
Thanks a lot in advance!
A:
To implement userNameMatches and passwordMatches, you can use the Like operator in VBA to check if the strings in the username and password text fields match the regex patterns.
The Like operator allows you to compare a string to a pattern and returns True if the string matches the pattern, and False otherwise. The syntax for using the Like operator is as follows:
string Like pattern
Here, string is the string you want to compare to the pattern, and pattern is the regex pattern you want to use. The Like operator supports the same regex syntax as the Match function in VBA.
To implement userNameMatches and passwordMatches, you can use the Like operator in the following way:
Private Function userNameMatches() As Boolean
userNameMatches = username.Value Like "^[A-Za-z][A-Za-z0-9_]{3,16}$"
End Function
Private Function passwordMatches() As Boolean
passwordMatches = password.Value Like "^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"
End Function
In the above code, userNameMatches returns True if the value in the username text field matches the regex pattern "^[A-Za-z][A-Za-z0-9_]{3,16}$", and False otherwise. Similarly, passwordMatches returns True if the value in the password text field matches the regex pattern "^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$", and False otherwise.
You can then use these functions in your Command1_Click event handler as follows:
Private Sub Command1_Click()
If userNameMatches() And passwordMatches() Then
MsgBox "Welcome!"
DoCmd.Close
DoCmd.OpenReport "HomePage", acViewReport
Else
MsgBox "Please enter valid credentials."
End If
End Sub
In this code, if both userNameMatches() and passwordMatches() return True, the user is welcomed and the HomePage report is opened. Otherwise, a message is displayed prompting the user to enter valid credentials.
|
VBA Username and Password Regex (MS Access)
|
Supposing I have the following code in a button: (with the implementation of userNameMatches and passwordMatches missing)
Private Sub Command1_Click()
If userNameMatches And passwordMatches Then
MsgBox "Welcome!"
DoCmd.Close
DoCmd.OpenReport "HomePage", acViewReport
Else
MsgBox "Please enter valid credentials."
End If
End Sub
The username text input field is named username. The password text input field is named password.
The regex pattern I want for the username is: "^[A-Za-z][A-Za-z0-9_]{3,16}$"
The regex pattern I want for the password is: "^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"
My Question:
How do I implement userNameMatches and passwordMatches to return True if their respective text fields match the patterns, and False if they do not?
Thanks a lot in advance!
|
[
"To implement userNameMatches and passwordMatches, you can use the Like operator in VBA to check if the strings in the username and password text fields match the regex patterns.\nThe Like operator allows you to compare a string to a pattern and returns True if the string matches the pattern, and False otherwise. The syntax for using the Like operator is as follows:\nstring Like pattern\n\nHere, string is the string you want to compare to the pattern, and pattern is the regex pattern you want to use. The Like operator supports the same regex syntax as the Match function in VBA.\nTo implement userNameMatches and passwordMatches, you can use the Like operator in the following way:\nPrivate Function userNameMatches() As Boolean\n userNameMatches = username.Value Like \"^[A-Za-z][A-Za-z0-9_]{3,16}$\"\nEnd Function\n\nPrivate Function passwordMatches() As Boolean\n passwordMatches = password.Value Like \"^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$\"\nEnd Function\n\nIn the above code, userNameMatches returns True if the value in the username text field matches the regex pattern \"^[A-Za-z][A-Za-z0-9_]{3,16}$\", and False otherwise. Similarly, passwordMatches returns True if the value in the password text field matches the regex pattern \"^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$\", and False otherwise.\nYou can then use these functions in your Command1_Click event handler as follows:\nPrivate Sub Command1_Click()\n If userNameMatches() And passwordMatches() Then\n MsgBox \"Welcome!\"\n DoCmd.Close\n DoCmd.OpenReport \"HomePage\", acViewReport\n Else\n MsgBox \"Please enter valid credentials.\"\n End If\nEnd Sub\n\nIn this code, if both userNameMatches() and passwordMatches() return True, the user is welcomed and the HomePage report is opened. Otherwise, a message is displayed prompting the user to enter valid credentials.\n"
] |
[
1
] |
[] |
[] |
[
"ms_access",
"regex",
"vba"
] |
stackoverflow_0074656244_ms_access_regex_vba.txt
|
Q:
'{}' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Record'
I find a few questions already like this. But I don't know how to fixed more alike typscript style. I don't want to use 'as'.
These are my some questions example:
First Error: Type '{}' is not assignable to type 'T'.
function copy<T extends Record<string, any>>(target: T): T {
const res: T = {} // Error 1: Type '{}' is not assignable to type 'T'.
Object.keys(target).forEach(key => {
if (typeof target[key] === 'object') res[key] = copy(target[key])
else if (typeof target[key] === 'string') res[key] = target[key];
});
return res
}
Second Error: Type 'Record<string, any>' is not assignable to type 'T'
function copy<T extends Record<string, any>>(target: T): T {
const res: Record<string, any> = {};
Object.keys(target).forEach(key => {
if (typeof target[key] === 'object') res[key] = copy(target[key])
else if (typeof target[key] === 'string') res[key] = target[key];
});
return res // Type 'Record<string, any>' is not assignable to type 'T'.
}
And I use 'as' to fixed, see: ts playground
function copy<T extends Record<string, any>>(target: T): T {
const res: Record<string, any> = {};
Object.keys(target).forEach(key => {
if (typeof target[key] === 'object') res[key] = copy(target[key])
else if (typeof target[key] === 'string') res[key] = target[key];
});
return res as T;
}
Do somebody have other ways to solve this? Or how can I pass T type to function and want to return T Type, T need extends object or Record.
A:
These are both essentially the same problem. You know that T looks like a Record, but you don't know anything else about it, so initializing it with {} is not safe, and since TypeScript can't guarantee it, it doesn't let you do it.
It's like having a class Cat and trying to initialize it with an instance of a class Animal ... you know that it is an Animal, but that's not enough to properly initialize a Cat.
Specifically, for your first error you are trying to initialize a Cat with an instance of Animal, and for your second error, you have created an Animal and you're trying to return it as a Cat.
Here's an example with your copy that would fail if it was permitted.
let counter = 0;
class MyClass implements Record<string, any> {
public instanceNumber: number;
constructor() {
console.log("Reporting to central command, new MyClass")
this.instanceNumber = counter++;
}
printInstanceNumber() {
console.log(`I am ${this.instanceNumber}`);
}
}
function copy<T extends Record<string, any>>(target: T): T {
const res: Record<string, any> = {};
Object.keys(target).forEach(key => {
if (typeof target[key] === 'object') res[key] = copy(target[key])
else if (typeof target[key] === 'string') res[key] = target[key];
else if (typeof target[key] === 'number') res[key] = target[key];
});
return res as T;
}
const originalInstance = new MyClass();
const myCopy = copy(originalInstance);
// Has the wrong instance number...
console.log("original instanceNumber:", originalInstance.instanceNumber); // 0
console.log("copied instanceNumber:", myCopy.instanceNumber); // 0
// And crashes, no printInstanceNumber
originalInstance.printInstanceNumber(); // works
myCopy.printInstanceNumber(); // crashes, myCopy.printInstanceNumber is not a function
|
'{}' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Record'
|
I find a few questions already like this. But I don't know how to fixed more alike typscript style. I don't want to use 'as'.
These are my some questions example:
First Error: Type '{}' is not assignable to type 'T'.
function copy<T extends Record<string, any>>(target: T): T {
const res: T = {} // Error 1: Type '{}' is not assignable to type 'T'.
Object.keys(target).forEach(key => {
if (typeof target[key] === 'object') res[key] = copy(target[key])
else if (typeof target[key] === 'string') res[key] = target[key];
});
return res
}
Second Error: Type 'Record<string, any>' is not assignable to type 'T'
function copy<T extends Record<string, any>>(target: T): T {
const res: Record<string, any> = {};
Object.keys(target).forEach(key => {
if (typeof target[key] === 'object') res[key] = copy(target[key])
else if (typeof target[key] === 'string') res[key] = target[key];
});
return res // Type 'Record<string, any>' is not assignable to type 'T'.
}
And I use 'as' to fixed, see: ts playground
function copy<T extends Record<string, any>>(target: T): T {
const res: Record<string, any> = {};
Object.keys(target).forEach(key => {
if (typeof target[key] === 'object') res[key] = copy(target[key])
else if (typeof target[key] === 'string') res[key] = target[key];
});
return res as T;
}
Do somebody have other ways to solve this? Or how can I pass T type to function and want to return T Type, T need extends object or Record.
|
[
"These are both essentially the same problem. You know that T looks like a Record, but you don't know anything else about it, so initializing it with {} is not safe, and since TypeScript can't guarantee it, it doesn't let you do it.\nIt's like having a class Cat and trying to initialize it with an instance of a class Animal ... you know that it is an Animal, but that's not enough to properly initialize a Cat.\nSpecifically, for your first error you are trying to initialize a Cat with an instance of Animal, and for your second error, you have created an Animal and you're trying to return it as a Cat.\nHere's an example with your copy that would fail if it was permitted.\nlet counter = 0;\nclass MyClass implements Record<string, any> {\n public instanceNumber: number;\n constructor() {\n console.log(\"Reporting to central command, new MyClass\")\n this.instanceNumber = counter++;\n }\n\n printInstanceNumber() {\n console.log(`I am ${this.instanceNumber}`);\n }\n}\n\nfunction copy<T extends Record<string, any>>(target: T): T {\n const res: Record<string, any> = {};\n Object.keys(target).forEach(key => {\n if (typeof target[key] === 'object') res[key] = copy(target[key])\n else if (typeof target[key] === 'string') res[key] = target[key];\n else if (typeof target[key] === 'number') res[key] = target[key];\n });\n return res as T;\n}\n\nconst originalInstance = new MyClass();\n\nconst myCopy = copy(originalInstance);\n\n// Has the wrong instance number...\nconsole.log(\"original instanceNumber:\", originalInstance.instanceNumber); // 0\nconsole.log(\"copied instanceNumber:\", myCopy.instanceNumber); // 0\n\n// And crashes, no printInstanceNumber\noriginalInstance.printInstanceNumber(); // works\nmyCopy.printInstanceNumber(); // crashes, myCopy.printInstanceNumber is not a function \n\n"
] |
[
0
] |
[] |
[] |
[
"subtype",
"typescript"
] |
stackoverflow_0074664701_subtype_typescript.txt
|
Q:
Set 'Content-Type' header using RestSharp
I'm building a client for an RSS reading service. I'm using the RestSharp library to interact with their API.
The API states:
When creating or updating a record you must set application/json;charset=utf-8 as the Content-Type header.
This is what my code looks like:
RestRequest request = new RestRequest("/v2/starred_entries.json", Method.POST);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.RequestFormat = DataFormat.Json;
request.AddParameter("starred_entries", id);
//Pass the request to the RestSharp client
Messagebox.Show(rest.ExecuteAsPost(request, "POST").Content);
However; the service is returning an error
Error 415: Please use the 'Content-Type: application/json; charset=utf-8' header
Why isn't RestSharp passing the header?
A:
The solution provided on my blog is not tested beyond version 1.02 of RestSharp. If you submit a comment on my answer with your specific issue with my solution, I can update it.
var client = new RestClient("http://www.example.com/where/else?key=value");
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", strJSONContent, ParameterType.RequestBody);
var response = client.Execute(request);
A:
In version 105.2.3.0 I can solve the problem this way:
var client = new RestClient("https://www.example.com");
var request = new RestRequest("api/v1/records", Method.POST);
request.AddJsonBody(new { id = 1, name = "record 1" });
var response = client.Execute(request);
Old question but still top of my search - adding for completeness.
A:
Although this is a bit old: I ran into the same problem.. seems some attributes such as "content-type" or "date" cannot be added as parameter but are added internally. To alter the value of "content-type" I had to change the serialzer setting (altough I didn`t use it because I added a json in the body that was serialized before!)
RestClient client = new RestClient(requURI);
RestRequest request = new RestRequest(reqPath, method);
request.JsonSerializer.ContentType = "application/json; charset=utf-8";
as soon as I did this the header showed up as intended:
System.Net Information: 0 : [5620] ConnectStream#61150033 - Header
{
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp 104.1.0.0
Content-Type: application/json; charset=utf-8
...
}
A:
You most probably run into this problem: https://github.com/restsharp/restsharp/issues/221 There is a working solution to your problem @ http://itanex.blogspot.co.at/2012/02/restsharp-and-advanced-post-requests.html
A:
Worked for me:
request.AddParameter("Content-Type", "text/xml; charset=utf-8", ParameterType.HttpHeader);
|
Set 'Content-Type' header using RestSharp
|
I'm building a client for an RSS reading service. I'm using the RestSharp library to interact with their API.
The API states:
When creating or updating a record you must set application/json;charset=utf-8 as the Content-Type header.
This is what my code looks like:
RestRequest request = new RestRequest("/v2/starred_entries.json", Method.POST);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.RequestFormat = DataFormat.Json;
request.AddParameter("starred_entries", id);
//Pass the request to the RestSharp client
Messagebox.Show(rest.ExecuteAsPost(request, "POST").Content);
However; the service is returning an error
Error 415: Please use the 'Content-Type: application/json; charset=utf-8' header
Why isn't RestSharp passing the header?
|
[
"The solution provided on my blog is not tested beyond version 1.02 of RestSharp. If you submit a comment on my answer with your specific issue with my solution, I can update it. \nvar client = new RestClient(\"http://www.example.com/where/else?key=value\");\nvar request = new RestRequest();\n\nrequest.Method = Method.POST;\nrequest.AddHeader(\"Accept\", \"application/json\");\nrequest.Parameters.Clear();\nrequest.AddParameter(\"application/json\", strJSONContent, ParameterType.RequestBody);\n\nvar response = client.Execute(request);\n\n",
"In version 105.2.3.0 I can solve the problem this way:\nvar client = new RestClient(\"https://www.example.com\");\nvar request = new RestRequest(\"api/v1/records\", Method.POST);\nrequest.AddJsonBody(new { id = 1, name = \"record 1\" });\nvar response = client.Execute(request);\n\nOld question but still top of my search - adding for completeness.\n",
"Although this is a bit old: I ran into the same problem.. seems some attributes such as \"content-type\" or \"date\" cannot be added as parameter but are added internally. To alter the value of \"content-type\" I had to change the serialzer setting (altough I didn`t use it because I added a json in the body that was serialized before!)\nRestClient client = new RestClient(requURI);\nRestRequest request = new RestRequest(reqPath, method);\nrequest.JsonSerializer.ContentType = \"application/json; charset=utf-8\";\n\nas soon as I did this the header showed up as intended:\n System.Net Information: 0 : [5620] ConnectStream#61150033 - Header \n {\n Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml\n User-Agent: RestSharp 104.1.0.0\n Content-Type: application/json; charset=utf-8\n ...\n }\n\n",
"You most probably run into this problem: https://github.com/restsharp/restsharp/issues/221 There is a working solution to your problem @ http://itanex.blogspot.co.at/2012/02/restsharp-and-advanced-post-requests.html\n",
"Worked for me:\nrequest.AddParameter(\"Content-Type\", \"text/xml; charset=utf-8\", ParameterType.HttpHeader);\n\n"
] |
[
69,
40,
11,
3,
0
] |
[
"Here is the solution \nhttp://restsharp.blogspot.ca/\nCreate a json object with same name properties and set the values (Make sure they are similar to those of name value pair for post request.)\nAfter that use default httpclient. \n"
] |
[
-4
] |
[
"c#",
"http_headers",
"restsharp"
] |
stackoverflow_0017815065_c#_http_headers_restsharp.txt
|
Q:
Adding plugin to Webpack with Rails
I'm using the Webpacker gem with Rails 5.2, and would like to access the environment in the Front End by setting a NODE_ENV global variable.
This is my config/webpack/environment.js file :
const { environment } = require('@rails/webpacker')
// Bootstrap 3 has a dependency over jQuery:
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
)
module.exports = environment
I saw that I needed to add the following plugin to webpack to be able access the environment in the front-end :
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
But I don't know how to add it... I tried many options, including the line below and it always, either doesn't work, or break jQuery (i.e. Uncaught ReferenceError: jQuery is not defined) :
environment.plugins.prepend('Provide',
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
)
A:
It turns out you just need to prepend/append a new plugin and give it a different name that those of your other plugins. Now my config/webpack/environment.js looks like that:
const { environment } = require('@rails/webpacker')
// Bootstrap 3 has a dependency over jQuery:
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
)
environment.plugins.prepend('env',
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
)
module.exports = environment
I can now access NODE_ENV from every js/jsx file !!
This answer was posted as an edit to the question Adding plugin to Webpack with Rails by the OP oruhtra under CC BY-SA 4.0.
|
Adding plugin to Webpack with Rails
|
I'm using the Webpacker gem with Rails 5.2, and would like to access the environment in the Front End by setting a NODE_ENV global variable.
This is my config/webpack/environment.js file :
const { environment } = require('@rails/webpacker')
// Bootstrap 3 has a dependency over jQuery:
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
)
module.exports = environment
I saw that I needed to add the following plugin to webpack to be able access the environment in the front-end :
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
But I don't know how to add it... I tried many options, including the line below and it always, either doesn't work, or break jQuery (i.e. Uncaught ReferenceError: jQuery is not defined) :
environment.plugins.prepend('Provide',
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
)
|
[
"It turns out you just need to prepend/append a new plugin and give it a different name that those of your other plugins. Now my config/webpack/environment.js looks like that:\n\n\nconst { environment } = require('@rails/webpacker')\n\n// Bootstrap 3 has a dependency over jQuery:\nconst webpack = require('webpack')\n\nenvironment.plugins.prepend('Provide',\n new webpack.ProvidePlugin({\n $: 'jquery',\n jQuery: 'jquery'\n })\n)\n\nenvironment.plugins.prepend('env',\n new webpack.DefinePlugin({\n 'NODE_ENV': JSON.stringify(process.env.NODE_ENV)\n })\n)\n\n\nmodule.exports = environment\n\n\n\nI can now access NODE_ENV from every js/jsx file !!\n\nThis answer was posted as an edit to the question Adding plugin to Webpack with Rails by the OP oruhtra under CC BY-SA 4.0.\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"ruby_on_rails",
"webpack"
] |
stackoverflow_0051447443_javascript_ruby_on_rails_webpack.txt
|
Q:
Flutter get value from provider
I am using provider as state management. To use value between multiple files i create a provider like this
class globalProvider with ChangeNotifier, DiagnosticableTreeMixin {
String uuID = "";
String get _uuID => uuID;
void changeuuID(id) {
uuID = id;
notifyListeners();
}
}
I am updating value like this
final uuidUpdate = Provider.of<globalProvider>(context, listen: false);
uuidUpdate.changeuuID(user.uid);
Now on other page I need to print uuID value. I try to do like this
print(Provider.of<globalProvider>(context).uuID);
But its showing error Tried to listen to a value exposed with provider, from outside of the widget tree.
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => globalProvider()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginPage(),
),
),
);
}
A:
you need to add your state up in your widgets tree like:
ChangeNotifierProvider(
create: (context) => globalProvider (),
builder: (context, _) {
return theRestOfTheTreeWidgets();}
)
A:
in your main.dart add ChangeNotifierProvider.value(value: GlobalProvider) in MultiProvider widget,
Make sure that your class starts with capital letter and let me know if arrow still exists.
A:
You need to print it out with listen: false like this,
print(Provider.of<globalProvider>(context, listen: false).uuID);
|
Flutter get value from provider
|
I am using provider as state management. To use value between multiple files i create a provider like this
class globalProvider with ChangeNotifier, DiagnosticableTreeMixin {
String uuID = "";
String get _uuID => uuID;
void changeuuID(id) {
uuID = id;
notifyListeners();
}
}
I am updating value like this
final uuidUpdate = Provider.of<globalProvider>(context, listen: false);
uuidUpdate.changeuuID(user.uid);
Now on other page I need to print uuID value. I try to do like this
print(Provider.of<globalProvider>(context).uuID);
But its showing error Tried to listen to a value exposed with provider, from outside of the widget tree.
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => globalProvider()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginPage(),
),
),
);
}
|
[
"you need to add your state up in your widgets tree like:\nChangeNotifierProvider(\n create: (context) => globalProvider (),\n builder: (context, _) {\n return theRestOfTheTreeWidgets();}\n )\n\n",
"in your main.dart add ChangeNotifierProvider.value(value: GlobalProvider) in MultiProvider widget,\nMake sure that your class starts with capital letter and let me know if arrow still exists.\n",
"You need to print it out with listen: false like this,\nprint(Provider.of<globalProvider>(context, listen: false).uuID);\n\n"
] |
[
0,
0,
0
] |
[
"You can use this package\n\nget_it: ^7.2.0\n\nclass GlobalProvider with ChangeNotifier, DiagnosticableTreeMixin {\n String _uuID = \"\";\n\n String get uuID => _uuID;\n\n void changeuuID(id) {\n _uuID = id;\n notifyListeners();\n }\n\n}\n\nin your main.dart .please must use Upper cast\nand paste the below code in main.dart\nvoid main() async {\n WidgetsFlutterBinding.ensureInitialized();\n await Firebase.initializeApp();\n await di.init();\n runApp(\n MultiProvider(\n providers: [\n ChangeNotifierProvider(create: (context) => di.sl<GlobalProvider >()),\n ],\n child: MaterialApp(\n debugShowCheckedModeBanner: false,\n home: LoginPage(),\n ),\n ),\n );\n}\n\nmake a new dart file and paste this code\nfinal sl = GetIt.instance;\n\nFuture<void> init() async {\n sl.registerFactory(() => GlobalProvider ());\n}\n\nand I use this init() function in main file already ..just import library\n"
] |
[
-1
] |
[
"dart",
"flutter"
] |
stackoverflow_0071572319_dart_flutter.txt
|
Q:
.net core how to add Content-range to header
I'm having no luck find out how to add Content-Range to the header of my odata requests. My api requires a format as such for paging:
Content-Range: posts 0-24/319
The closest thing I can find is HTTP Byte Range Support. From here:
https://blogs.msdn.microsoft.com/webdev/2012/11/23/asp-net-web-api-and-http-byte-range-support/ . The OP says a post will be written about [Queryable] which is supposed to add support for paging, but I have yet to see any info on this.
[EnableQuery]
[ODataRoute]
public IActionResult Get(ODataQueryOptions<HC_PortalActivity>
options)
{
return Ok(Db.HC_PortalActivity_Collection);
}
A:
You can add the Content-Range header to your HttpRequest.Content object:
request.Content.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(0, 24, 319);
request.Content.Headers.ContentRange.Unit = "posts";
Remember to set the Unit otherwise it will default to `bytes'
EDIT
The Content property is only available on the HttpRequestMessage class, not the HttpRequest class. So you will need to create one to be able to access the ContentRange property.
var request = new HttpRequestMessage();
... // as above
Assuming you are using a HttpClient to send your request you can pass the request in the SendAsync method
var httpClient = new HttpClient();
... // other setup
httpClient.SendAsync(request);
A:
Here is what I ended up doing:
public static void IncludeContentRange<T>(ODataQueryOptions<T> options, HttpRequest context)
{
var range = options.Request.Query["range"][0].Replace("[", "").Replace("]", "").Split(',');
var q = from x in Db.HC_PortalActivity_Collection
select x;
var headerValue = string.Format("{0} {1}-{2}/{3}", options.Context.NavigationSource.Name.ToLower(), range[0], range[1], q.Count());
context.HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Range");
context.HttpContext.Response.Headers.Add("Content-Range", headerValue);
}
A:
If you are into an ASP.NET Core controller and want to return the 'Content-Range' header for clients, you can use Response property from ControllerBase.
base.Response.Headers.ContentRange = "posts 0-24/319";
|
.net core how to add Content-range to header
|
I'm having no luck find out how to add Content-Range to the header of my odata requests. My api requires a format as such for paging:
Content-Range: posts 0-24/319
The closest thing I can find is HTTP Byte Range Support. From here:
https://blogs.msdn.microsoft.com/webdev/2012/11/23/asp-net-web-api-and-http-byte-range-support/ . The OP says a post will be written about [Queryable] which is supposed to add support for paging, but I have yet to see any info on this.
[EnableQuery]
[ODataRoute]
public IActionResult Get(ODataQueryOptions<HC_PortalActivity>
options)
{
return Ok(Db.HC_PortalActivity_Collection);
}
|
[
"You can add the Content-Range header to your HttpRequest.Content object:\nrequest.Content.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(0, 24, 319);\n\nrequest.Content.Headers.ContentRange.Unit = \"posts\";\n\nRemember to set the Unit otherwise it will default to `bytes'\nEDIT\nThe Content property is only available on the HttpRequestMessage class, not the HttpRequest class. So you will need to create one to be able to access the ContentRange property.\nvar request = new HttpRequestMessage();\n... // as above\n\nAssuming you are using a HttpClient to send your request you can pass the request in the SendAsync method\nvar httpClient = new HttpClient();\n... // other setup\n\nhttpClient.SendAsync(request);\n\n",
"Here is what I ended up doing:\n public static void IncludeContentRange<T>(ODataQueryOptions<T> options, HttpRequest context)\n {\n var range = options.Request.Query[\"range\"][0].Replace(\"[\", \"\").Replace(\"]\", \"\").Split(',');\n var q = from x in Db.HC_PortalActivity_Collection\n select x;\n\n var headerValue = string.Format(\"{0} {1}-{2}/{3}\", options.Context.NavigationSource.Name.ToLower(), range[0], range[1], q.Count());\n context.HttpContext.Response.Headers.Add(\"Access-Control-Expose-Headers\", \"Content-Range\");\n context.HttpContext.Response.Headers.Add(\"Content-Range\", headerValue);\n }\n\n",
"If you are into an ASP.NET Core controller and want to return the 'Content-Range' header for clients, you can use Response property from ControllerBase.\nbase.Response.Headers.ContentRange = \"posts 0-24/319\";\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
".net_core",
"odata"
] |
stackoverflow_0053289657_.net_core_odata.txt
|
Q:
User remains logged in if session is deleted
I have created a fresh Laravel project with a simple user authentication based on their docs.
It works fine, the user is remembered on return.
$auth = Auth::loginUsingId($user->id, true);
But when I delete the session from the database, the user remains logged in.
Instead of being logged off, a new entry is simply created with a new session ID.
Is this intended or a bug? How can I prevent a user from still being logged in despite a deleted session?
PHP 8.1.10
Laravel 9.42.2
A:
It is intended behavior for the user to remain logged in if their session is deleted. Laravel will create a new session with a new session ID in this scenario.
To prevent a user from remaining logged in despite a deleted session, you can use the Auth::logout() method to explicitly log the user out. This will clear the user's session and prevent them from remaining logged in.
Alternatively, you can set the expire_on_close option to true when calling Auth::loginUsingId(). This will cause the user's session to expire when they close their browser, effectively logging them out.
$auth = Auth::loginUsingId($user->id, true, ['expire_on_close' => true]);
|
User remains logged in if session is deleted
|
I have created a fresh Laravel project with a simple user authentication based on their docs.
It works fine, the user is remembered on return.
$auth = Auth::loginUsingId($user->id, true);
But when I delete the session from the database, the user remains logged in.
Instead of being logged off, a new entry is simply created with a new session ID.
Is this intended or a bug? How can I prevent a user from still being logged in despite a deleted session?
PHP 8.1.10
Laravel 9.42.2
|
[
"It is intended behavior for the user to remain logged in if their session is deleted. Laravel will create a new session with a new session ID in this scenario.\nTo prevent a user from remaining logged in despite a deleted session, you can use the Auth::logout() method to explicitly log the user out. This will clear the user's session and prevent them from remaining logged in.\nAlternatively, you can set the expire_on_close option to true when calling Auth::loginUsingId(). This will cause the user's session to expire when they close their browser, effectively logging them out.\n$auth = Auth::loginUsingId($user->id, true, ['expire_on_close' => true]);\n\n"
] |
[
0
] |
[] |
[] |
[
"authentication",
"laravel",
"laravel_9",
"php",
"session"
] |
stackoverflow_0074666906_authentication_laravel_laravel_9_php_session.txt
|
Q:
TIdHTTP slow downloads
I use TIdHTTP to download updates of my application. The install file is about 80 mb.
It works, but I noticed that somehow, the download speed is way slower than the same link downloaded directly from Google Chrome.
Why does this happen? Is there any setup I should do on TIdHTTP to speed up the download?
Nothing fancy on my code, I just use the Get() method like this:
idh := TIdHTTP.Create(nil);
ssl := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
ssl.SSLOptions.Method := sslvSSLv23;
ssl.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];
f := TFileStream.Create(localFileName, fmCreate);
idh.Get(remoteFile, f);
A:
With TIdHTTP you may implement parallel downloading by launching two or more HTTP GET Requests in different threads, which each download a specific part of the resource. This however only will increase download speed if the system has enough CPU resources to execute the threads on different "cores".
See https://stackoverflow.com/a/9678441/80901 for some related information
|
TIdHTTP slow downloads
|
I use TIdHTTP to download updates of my application. The install file is about 80 mb.
It works, but I noticed that somehow, the download speed is way slower than the same link downloaded directly from Google Chrome.
Why does this happen? Is there any setup I should do on TIdHTTP to speed up the download?
Nothing fancy on my code, I just use the Get() method like this:
idh := TIdHTTP.Create(nil);
ssl := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
ssl.SSLOptions.Method := sslvSSLv23;
ssl.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];
f := TFileStream.Create(localFileName, fmCreate);
idh.Get(remoteFile, f);
|
[
"With TIdHTTP you may implement parallel downloading by launching two or more HTTP GET Requests in different threads, which each download a specific part of the resource. This however only will increase download speed if the system has enough CPU resources to execute the threads on different \"cores\".\nSee https://stackoverflow.com/a/9678441/80901 for some related information\n"
] |
[
1
] |
[] |
[] |
[
"delphi",
"http",
"indy",
"indy10"
] |
stackoverflow_0074666664_delphi_http_indy_indy10.txt
|
Q:
Calling a class function in blade view laravel
I have a CartController with the following function:
public function getTotalCartPrice()
{
$totalCartPrice = 1;
return $totalCartPrice;
}
Cart.blade.php
<h3 class="cartTotal">Cart total: {{ Cart::getTotalCartPrice }} </h3>
Routes
Route::resource('/cart', CartController::class);
Using this does not seem to display the total cart price and I get an error saying class "Cart" not found. I have attempted to change my route to this:
Route::get('/cartPrice', [CartController::class, 'getTotalCartPrice'])->name('getTotalCartPrice');
and then inside my blade view:
<h3 class="cartTotal">Cart total: {{ route('getTotalCartPrice') }} </h3>
But I just get an output on the website:
Cart total: http://localhost/cartPrice
A:
To fix this error and display the total cart price, you can do the following:
In your CartController, add the Cart class to the use statement:
use Cart;
public function getTotalCartPrice()
{
$totalCartPrice = 1;
return $totalCartPrice;
}
In your blade view, you need to call the function using () after the function name:
<h3 class="cartTotal">Cart total: {{ Cart::getTotalCartPrice() }} </h3>
In your routes file, you can use the resource method to create routes for the CartController class and its methods:
Route::resource('/cart', CartController::class);
In your blade view, you can use the route helper function to generate the URL for the getTotalCartPrice route and call the function using () after the function name:
<h3 class="cartTotal">Cart total: {{ route('cart.getTotalCartPrice')() }} </h3>
After making these changes, the total cart price should be displayed on the website.
A:
I'm trying to help you.
To fix this error, you should add static keyword to function getTotalCartPrice in CartController. So it will be :
public static function getTotalCartPrice()
{
$totalCartPrice = 1;
return $totalCartPrice;
}
After that, in your view (blade) you should add Cart class in the top of the code. In this case I assume that your Cart controller class name is Cart, so the example is :
@php
use App\Http\Controllers\Cart;
@endphp
// the rest of blade code
After that, you have to add () when you call the function from your blade
<h3 class="cartTotal">Cart total: {{ Cart::getTotalCartPrice() }} </h3>
After that, the total cart must be shown.
|
Calling a class function in blade view laravel
|
I have a CartController with the following function:
public function getTotalCartPrice()
{
$totalCartPrice = 1;
return $totalCartPrice;
}
Cart.blade.php
<h3 class="cartTotal">Cart total: {{ Cart::getTotalCartPrice }} </h3>
Routes
Route::resource('/cart', CartController::class);
Using this does not seem to display the total cart price and I get an error saying class "Cart" not found. I have attempted to change my route to this:
Route::get('/cartPrice', [CartController::class, 'getTotalCartPrice'])->name('getTotalCartPrice');
and then inside my blade view:
<h3 class="cartTotal">Cart total: {{ route('getTotalCartPrice') }} </h3>
But I just get an output on the website:
Cart total: http://localhost/cartPrice
|
[
"To fix this error and display the total cart price, you can do the following:\nIn your CartController, add the Cart class to the use statement:\nuse Cart;\n\npublic function getTotalCartPrice()\n{\n $totalCartPrice = 1;\n \n return $totalCartPrice;\n}\n\nIn your blade view, you need to call the function using () after the function name:\n<h3 class=\"cartTotal\">Cart total: {{ Cart::getTotalCartPrice() }} </h3>\n\nIn your routes file, you can use the resource method to create routes for the CartController class and its methods:\nRoute::resource('/cart', CartController::class);\n\nIn your blade view, you can use the route helper function to generate the URL for the getTotalCartPrice route and call the function using () after the function name:\n<h3 class=\"cartTotal\">Cart total: {{ route('cart.getTotalCartPrice')() }} </h3>\n\nAfter making these changes, the total cart price should be displayed on the website.\n",
"I'm trying to help you.\nTo fix this error, you should add static keyword to function getTotalCartPrice in CartController. So it will be :\npublic static function getTotalCartPrice()\n{\n $totalCartPrice = 1;\n \n return $totalCartPrice;\n}\n\nAfter that, in your view (blade) you should add Cart class in the top of the code. In this case I assume that your Cart controller class name is Cart, so the example is :\n@php\n use App\\Http\\Controllers\\Cart;\n@endphp\n// the rest of blade code\n\nAfter that, you have to add () when you call the function from your blade\n<h3 class=\"cartTotal\">Cart total: {{ Cart::getTotalCartPrice() }} </h3>\n\nAfter that, the total cart must be shown.\n"
] |
[
0,
0
] |
[] |
[] |
[
"laravel",
"php"
] |
stackoverflow_0074666870_laravel_php.txt
|
Q:
In RouteAction.php line 84: Invalid route action
When I create a controller in laravel 5.4 I get this error
In RouteAction.php line 84:
Invalid route action:
[App\Http\Controllers\Admin\DashboardController].
I do not create Admin/DashboardController. Still makes a errors
web.php
Route::group(['namespace' => 'Admin', 'middleware' => ['auth:web', 'CheckAdmin'], 'prefix' => 'admin'],function (){
$this->resource('authorities', 'AuthoritiesController');
$this->resource('complaints', 'ComplaintsController');
$this->resource('schools-list', 'SchoolsListController');
$this->resource('inspection-failed', 'InspectionFailedController');
$this->resource('inspection-register', 'InspectionRegisterController');
$this->resource('inspection-results', 'InspectionResultsController');
$this->resource('inspectors-list', 'InspectionListController');
$this->resource('investigators', 'InvestigatorsController');
$this->resource('notification-infringement', 'NotificationInfringementController');
$this->resource('system-experts', 'SystemExpertsController');
$this->resource('submit-information', 'SubmitInformationController');
$this->resource('primary-committee-meeting', 'PrimaryCommitteeMeetingController');
$this->resource('list-violations-school', 'ListViolationsSchoolController');
$this->resource('announcing', 'AnnouncingController');
$this->resource('display-vote', 'DisplayVoteController');
$this->resource('announcing-supervisory-vote', 'AnnouncingSupervisoryVoteController');
$this->resource('supervisory-board-vote', 'SupervisoryBoardVoteController');
$this->resource('defense', 'DefenseController');
$this->resource('votiing-supervisory-board', 'VotiingSupervisoryBoardController');
$this->get('dashboard', 'DashboardController');
});
A:
Because it is invalid. As you're using GET route, you must specify method name(unless you used ::resource):
$this->get('dashboard', 'DashboardController@methodName');
A:
If you are using laravel 8 you need to add your controller and method name inside the array, otherwise, it will throw an error.
Route::get('/projects', User\ProjectController::class, 'index')->name('user.projects');
TO
Route::get('/projects', [User\ProjectController::class, 'index'])->name('user.projects');
A:
I also face a similar problem:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'Frontend\FrontendController@index')->name('home');
Route::get('/post', 'Frontend\FrontendController@post')->name('post');
Route::get('/contact', 'Frontend\FrontendController@contact')->name('contact_us');
Route::group(['prefix' => 'admin'], function () {
Route::get('/create', 'Backend\BackendController@index');
//User Route
Route::get('/registration', '');
});
And I just remove the Route::get('/registration', ''); and it's work for me :)
A:
try removes route cache file by
php artisan route:clear
A:
Those who are new to Laravel or learning use
Route::resource('resource_name','controller_name')
to avoid this kind of error when you type:
php artisan route:list
In cmd or any other command line.
A:
i think its because of :: before the class name instead use @
Route::get('/about','App\Http\Controllers\DemoController::about'); (Not working gives an error)
Route::get('/about','App\Http\Controllers\DemoController@about'); (But this statement works)
A:
I hit the same issue but with a different cause. So I'm documenting here just in case someone else hits the same cause.
Specifically if you are using a Single Action Controller (ie: with __invoke), if you haven't added or omitted the correct use Laravel will hide the missing controller with "Invalid route action: [XController]."
This will fail
<?php
use Illuminate\Support\Facades\Route;
Route::post('/order', XController::class);
This will pass
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\XController;
Route::post('/order', XController::class);
I think its a bit unfortunate that Laravel masks the underlying issue, but I think it only applies to invokable controllers, even though its a silly mistake on my behalf.
A:
Lastly if you set the route like below:
Route::post('example', PostController::class);
You should have an __invoke method in your controller.
|
In RouteAction.php line 84: Invalid route action
|
When I create a controller in laravel 5.4 I get this error
In RouteAction.php line 84:
Invalid route action:
[App\Http\Controllers\Admin\DashboardController].
I do not create Admin/DashboardController. Still makes a errors
web.php
Route::group(['namespace' => 'Admin', 'middleware' => ['auth:web', 'CheckAdmin'], 'prefix' => 'admin'],function (){
$this->resource('authorities', 'AuthoritiesController');
$this->resource('complaints', 'ComplaintsController');
$this->resource('schools-list', 'SchoolsListController');
$this->resource('inspection-failed', 'InspectionFailedController');
$this->resource('inspection-register', 'InspectionRegisterController');
$this->resource('inspection-results', 'InspectionResultsController');
$this->resource('inspectors-list', 'InspectionListController');
$this->resource('investigators', 'InvestigatorsController');
$this->resource('notification-infringement', 'NotificationInfringementController');
$this->resource('system-experts', 'SystemExpertsController');
$this->resource('submit-information', 'SubmitInformationController');
$this->resource('primary-committee-meeting', 'PrimaryCommitteeMeetingController');
$this->resource('list-violations-school', 'ListViolationsSchoolController');
$this->resource('announcing', 'AnnouncingController');
$this->resource('display-vote', 'DisplayVoteController');
$this->resource('announcing-supervisory-vote', 'AnnouncingSupervisoryVoteController');
$this->resource('supervisory-board-vote', 'SupervisoryBoardVoteController');
$this->resource('defense', 'DefenseController');
$this->resource('votiing-supervisory-board', 'VotiingSupervisoryBoardController');
$this->get('dashboard', 'DashboardController');
});
|
[
"Because it is invalid. As you're using GET route, you must specify method name(unless you used ::resource):\n$this->get('dashboard', 'DashboardController@methodName');\n\n",
"If you are using laravel 8 you need to add your controller and method name inside the array, otherwise, it will throw an error.\nRoute::get('/projects', User\\ProjectController::class, 'index')->name('user.projects');\n\nTO\n Route::get('/projects', [User\\ProjectController::class, 'index'])->name('user.projects');\n\n",
"I also face a similar problem: \n<?php\n\n/*\n|--------------------------------------------------------------------------\n| Web Routes\n|--------------------------------------------------------------------------\n|\n| Here is where you can register web routes for your application. These\n| routes are loaded by the RouteServiceProvider within a group which\n| contains the \"web\" middleware group. Now create something great!\n|\n*/\n\nRoute::get('/', 'Frontend\\FrontendController@index')->name('home');\nRoute::get('/post', 'Frontend\\FrontendController@post')->name('post');\nRoute::get('/contact', 'Frontend\\FrontendController@contact')->name('contact_us');\nRoute::group(['prefix' => 'admin'], function () {\n\n Route::get('/create', 'Backend\\BackendController@index');\n\n //User Route\n\n Route::get('/registration', '');\n});\n\nAnd I just remove the Route::get('/registration', ''); and it's work for me :) \n",
"try removes route cache file by\n\nphp artisan route:clear\n\n",
"Those who are new to Laravel or learning use \nRoute::resource('resource_name','controller_name')\n\nto avoid this kind of error when you type:\nphp artisan route:list\n\nIn cmd or any other command line.\n",
"i think its because of :: before the class name instead use @\nRoute::get('/about','App\\Http\\Controllers\\DemoController::about'); (Not working gives an error)\nRoute::get('/about','App\\Http\\Controllers\\DemoController@about'); (But this statement works)\n",
"I hit the same issue but with a different cause. So I'm documenting here just in case someone else hits the same cause.\nSpecifically if you are using a Single Action Controller (ie: with __invoke), if you haven't added or omitted the correct use Laravel will hide the missing controller with \"Invalid route action: [XController].\"\nThis will fail\n<?php\nuse Illuminate\\Support\\Facades\\Route;\n\nRoute::post('/order', XController::class);\n\nThis will pass\n<?php\nuse Illuminate\\Support\\Facades\\Route;\nuse App\\Http\\Controllers\\XController;\n\nRoute::post('/order', XController::class);\n\nI think its a bit unfortunate that Laravel masks the underlying issue, but I think it only applies to invokable controllers, even though its a silly mistake on my behalf.\n",
"Lastly if you set the route like below:\nRoute::post('example', PostController::class);\n\nYou should have an __invoke method in your controller.\n"
] |
[
29,
4,
3,
3,
2,
2,
1,
0
] |
[] |
[] |
[
"laravel"
] |
stackoverflow_0050095242_laravel.txt
|
Q:
git: rename local branch failed
I don't know why my attempt of renaming local branch failed. I basically cloned the project, then I also have a submodule within the project, and I downloaded the submodule code as well. However, when I use git branch within the submodule, I have:
* (no branch)
master
The code looks like I'm on another branch but the output shows that it doesn't have a name. Then I searched online to find how to rename local branch and I got this:
git branch -m <newname>
After I run this command git gave me this error:
error: refname refs/heads/HEAD not found
fatal: Branch rename failed
Anybody know why this happens? Thanks.
A:
I get into this issue too. The reason is that I didn't have any commit on this git repository.
When I run the command git branch -M main. I get the following error message.
error: refname refs/heads/master not found
fatal: Branch rename failed
After I add my first commit by the following command, all things work.
git add .
git commit -m 'Init'
A:
You are currently in detached head state. You must checkout a new branch to associate it with the current commit:
git checkout -b new_branch
A:
I thought it was a conflict of "git init" creating master branch and github's (new) "main".
After:
git add .
git commit -m "first commit"
I was able to git branch -M main
A:
You can change the name from master to main in few steps, locally before you even make a commit.
Navigate to the directory where your project sits.
In it, show hidden file since by default, .git would be hidden.
Inside .git, there is a file, HEAD, open it in a text editor.
You'd see, ref: refs/heads/master.
Simple enough, change, master to main.
We just renamed the master branch as main. Verify this merely by entering, git branch from the terminal.
A:
First set your email and username config using:
git config --global user.email “[email protected]”
git config --global user.name “Your Name”
Then add your files:
git add .
Then make your first commit :
git commit -m "Initial commit"
And now run the command :
git branch -M main
It worked for me this way.
A:
My guess is that you're not on a branch named "(no branch)", but rather not on a branch.
If you first checkout master:
git checkout master
and then create a new branch:
git checkout -b new_branch
that would make it look like you'd expect.
A:
I also got that error but I fixed it with:
git commit -m"your commit"
before :
git branch -M main
and it worked correctly
A:
you can run following command to switch from master to main.
git add .
git commit -m "Init"
git branch -m main
|
git: rename local branch failed
|
I don't know why my attempt of renaming local branch failed. I basically cloned the project, then I also have a submodule within the project, and I downloaded the submodule code as well. However, when I use git branch within the submodule, I have:
* (no branch)
master
The code looks like I'm on another branch but the output shows that it doesn't have a name. Then I searched online to find how to rename local branch and I got this:
git branch -m <newname>
After I run this command git gave me this error:
error: refname refs/heads/HEAD not found
fatal: Branch rename failed
Anybody know why this happens? Thanks.
|
[
"I get into this issue too. The reason is that I didn't have any commit on this git repository.\nWhen I run the command git branch -M main. I get the following error message.\nerror: refname refs/heads/master not found\nfatal: Branch rename failed\n\nAfter I add my first commit by the following command, all things work.\ngit add .\ngit commit -m 'Init'\n\n",
"You are currently in detached head state. You must checkout a new branch to associate it with the current commit:\ngit checkout -b new_branch\n\n",
"I thought it was a conflict of \"git init\" creating master branch and github's (new) \"main\".\nAfter:\ngit add .\ngit commit -m \"first commit\" \n\nI was able to git branch -M main\n\n",
"You can change the name from master to main in few steps, locally before you even make a commit.\n\nNavigate to the directory where your project sits.\nIn it, show hidden file since by default, .git would be hidden.\nInside .git, there is a file, HEAD, open it in a text editor.\nYou'd see, ref: refs/heads/master.\nSimple enough, change, master to main.\n\nWe just renamed the master branch as main. Verify this merely by entering, git branch from the terminal.\n",
"First set your email and username config using:\ngit config --global user.email “[email protected]”\ngit config --global user.name “Your Name”\n\nThen add your files:\ngit add .\n\nThen make your first commit :\ngit commit -m \"Initial commit\"\n\nAnd now run the command :\ngit branch -M main\n\nIt worked for me this way.\n",
"My guess is that you're not on a branch named \"(no branch)\", but rather not on a branch.\nIf you first checkout master:\ngit checkout master\n\nand then create a new branch:\ngit checkout -b new_branch\n\nthat would make it look like you'd expect.\n",
"I also got that error but I fixed it with:\ngit commit -m\"your commit\"\nbefore :\ngit branch -M main\nand it worked correctly\n",
"\nyou can run following command to switch from master to main.\ngit add .\ngit commit -m \"Init\"\ngit branch -m main\n\n\n\n"
] |
[
257,
121,
31,
12,
9,
7,
2,
0
] |
[
"Try this:\n\ngit config --global user.email “your-email”\n\ngit config --global user.name “your-username”\n\ngit commit -m \"TypeScript React using Tailwind\"\n\ngit branch -M main\n\ngit push -u origin main\n\n\nit must work! :)\n"
] |
[
-2
] |
[
"branch",
"git",
"rename"
] |
stackoverflow_0018382986_branch_git_rename.txt
|
Q:
Plolty combine timeline on one line into subplots
I try to put a px.timeline into subplot, but my timeline format change.
import pandas as pd
import plotly.express as px
import plotly.subplots as sp
df1 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
dict(unit='MVT',Task="Job B", Start='2009-02-28', Finish='2009-04-15'),
dict(unit='MVT',Task="Job A", Start='2009-04-15', Finish='2009-05-30')
])
df2 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009-01-15', Finish='2009-02-15'),
dict(unit='MVT',Task="Job B", Start='2009-02-15', Finish='2009-04-28'),
dict(unit='MVT',Task="Job A", Start='2009-04-28', Finish='2009-05-30')
])
fig1 = px.timeline(df1, x_start="Start", x_end="Finish", y="unit",color="Task")
fig2 = px.timeline(df2, x_start="Start", x_end="Finish", y="unit",color="Task")
fig_sub = sp.make_subplots(rows=2)
for i in range(0,len(fig['data'])):
fig_sub.append_trace(fig1['data'][i], row=1, col=1)
for i in range(0,len(fig['data'])):
fig_sub.append_trace(fig2['data'][i], row=2, col=1)
fig_sub.update_xaxes(type='date')
My fig 1 look like that
but one into subplit i got this
Any idea of how to fix it? thanks
A:
I found it, we need to add
fig_sub.update_layout(barmode="overlay")
by default in sub_plots it is put in barmode="group"
|
Plolty combine timeline on one line into subplots
|
I try to put a px.timeline into subplot, but my timeline format change.
import pandas as pd
import plotly.express as px
import plotly.subplots as sp
df1 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
dict(unit='MVT',Task="Job B", Start='2009-02-28', Finish='2009-04-15'),
dict(unit='MVT',Task="Job A", Start='2009-04-15', Finish='2009-05-30')
])
df2 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009-01-15', Finish='2009-02-15'),
dict(unit='MVT',Task="Job B", Start='2009-02-15', Finish='2009-04-28'),
dict(unit='MVT',Task="Job A", Start='2009-04-28', Finish='2009-05-30')
])
fig1 = px.timeline(df1, x_start="Start", x_end="Finish", y="unit",color="Task")
fig2 = px.timeline(df2, x_start="Start", x_end="Finish", y="unit",color="Task")
fig_sub = sp.make_subplots(rows=2)
for i in range(0,len(fig['data'])):
fig_sub.append_trace(fig1['data'][i], row=1, col=1)
for i in range(0,len(fig['data'])):
fig_sub.append_trace(fig2['data'][i], row=2, col=1)
fig_sub.update_xaxes(type='date')
My fig 1 look like that
but one into subplit i got this
Any idea of how to fix it? thanks
|
[
"I found it, we need to add\nfig_sub.update_layout(barmode=\"overlay\") \n\nby default in sub_plots it is put in barmode=\"group\"\n"
] |
[
1
] |
[] |
[] |
[
"plotly",
"python",
"subplot"
] |
stackoverflow_0074666793_plotly_python_subplot.txt
|
Q:
C# Image rotation and moving uses a lot of RAM
I'm developing an interface in C#. I move the indicators of my vehicle that I will control instantly. Some of these are rotation operations and some are move operations.
These gestures consume a lot of RAM. I'm looking for a way to optimize.
I am open to all your suggestions. Thank you from now.
`
public static Bitmap RotateImage(Image image, float angle)
{
return RotateImage(image, new PointF((float)image.Width / 2, (float)image.Height / 2), angle);
}
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
if (image == null)
throw new ArgumentNullException("image");
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
Graphics g = Graphics.FromImage(rotatedBmp);
g.TranslateTransform(offset.X, offset.Y);
g.RotateTransform(angle);
g.TranslateTransform(-offset.X, -offset.Y);
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
private void RotateImage(PictureBox pb, Image img, float angle)
{
if (img == null || pb.Image == null)
return;
Image oldImage = pb.Image;
pb.Image = RotateImage(img, angle);
if (oldImage != null)
{
oldImage.Dispose();
}
}
`
`
if (foot - first_value_roll == 1)
{
picture.Location = new Point(picture.Location.X, picture.Location.Y + 10);
first_value_roll = foot;
}
else if (foot - first_value_roll == -1)
{
picture.Location = new Point(picture.Location.X, picture.Location.Y - 10);
first_value_roll = foot;
}
`
C# Image rotation and moving uses a lot of RAM
A:
The code you provided has a memory leak. You did not disposed the graphics object. So in your code:
g.DrawImage(image, new PointF(0, 0));
g.Dispose();
return rotatedBmp;
I think this would resolve the problem.
|
C# Image rotation and moving uses a lot of RAM
|
I'm developing an interface in C#. I move the indicators of my vehicle that I will control instantly. Some of these are rotation operations and some are move operations.
These gestures consume a lot of RAM. I'm looking for a way to optimize.
I am open to all your suggestions. Thank you from now.
`
public static Bitmap RotateImage(Image image, float angle)
{
return RotateImage(image, new PointF((float)image.Width / 2, (float)image.Height / 2), angle);
}
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
if (image == null)
throw new ArgumentNullException("image");
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
Graphics g = Graphics.FromImage(rotatedBmp);
g.TranslateTransform(offset.X, offset.Y);
g.RotateTransform(angle);
g.TranslateTransform(-offset.X, -offset.Y);
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
private void RotateImage(PictureBox pb, Image img, float angle)
{
if (img == null || pb.Image == null)
return;
Image oldImage = pb.Image;
pb.Image = RotateImage(img, angle);
if (oldImage != null)
{
oldImage.Dispose();
}
}
`
`
if (foot - first_value_roll == 1)
{
picture.Location = new Point(picture.Location.X, picture.Location.Y + 10);
first_value_roll = foot;
}
else if (foot - first_value_roll == -1)
{
picture.Location = new Point(picture.Location.X, picture.Location.Y - 10);
first_value_roll = foot;
}
`
C# Image rotation and moving uses a lot of RAM
|
[
"The code you provided has a memory leak. You did not disposed the graphics object. So in your code:\n g.DrawImage(image, new PointF(0, 0));\n g.Dispose(); \n return rotatedBmp;\n\nI think this would resolve the problem.\n"
] |
[
0
] |
[] |
[] |
[
"c#",
"interface"
] |
stackoverflow_0074666371_c#_interface.txt
|
Q:
What's the real point of using @Transactional(read-only = true)?
@Transactional Spring Javadoc about read-only flag said:
A boolean flag that can be set to true if the transaction is
effectively read-only, allowing for corresponding optimizations at
runtime. This just serves as a hint for the actual transaction
subsystem; it will not necessarily cause failure of write access
attempts. A transaction manager which cannot interpret the read-only
hint will not throw an exception when asked for a read-only
transaction but rather silently ignore the hint.
So I got that some transaction optimizations are being undertaken in runtime, but I can't figure out what the specific point of a transaction is if no data changes (at least semantically) are planned? Isn't it better for performance reasons to just avoid the transaction altogether in such a scenario? Or are there any specific cases that such a transaction can close? I also think it's a problem that Spring doesn't throw up any action items in case of a prospective data change in such a transaction, because this could seriously confuse the developers, is there any way to throw such exceptions?
A:
There are several reasons why you might want to use a read-only transaction even if no data changes are planned:
To ensure consistency: If your application needs to read data from multiple tables, a read-only transaction can ensure that the data you read is consistent with respect to the state of the database when the transaction started. This is because a read-only transaction will not allow any concurrent write transactions to modify the data you are reading.
To improve performance: As the Javadoc mentions, a read-only transaction allows for certain runtime optimizations, such as skipping certain locking or logging operations that are not necessary for read-only transactions. This can result in improved performance and reduced contention in your database.
To avoid unintended changes: By using a read-only transaction, you can prevent accidentally modifying data in your database. This can be useful if you are working with sensitive data or if you want to avoid making changes to data that you are not authorized to modify.
But I must admit, not sure about exception throwing
|
What's the real point of using @Transactional(read-only = true)?
|
@Transactional Spring Javadoc about read-only flag said:
A boolean flag that can be set to true if the transaction is
effectively read-only, allowing for corresponding optimizations at
runtime. This just serves as a hint for the actual transaction
subsystem; it will not necessarily cause failure of write access
attempts. A transaction manager which cannot interpret the read-only
hint will not throw an exception when asked for a read-only
transaction but rather silently ignore the hint.
So I got that some transaction optimizations are being undertaken in runtime, but I can't figure out what the specific point of a transaction is if no data changes (at least semantically) are planned? Isn't it better for performance reasons to just avoid the transaction altogether in such a scenario? Or are there any specific cases that such a transaction can close? I also think it's a problem that Spring doesn't throw up any action items in case of a prospective data change in such a transaction, because this could seriously confuse the developers, is there any way to throw such exceptions?
|
[
"There are several reasons why you might want to use a read-only transaction even if no data changes are planned:\n\nTo ensure consistency: If your application needs to read data from multiple tables, a read-only transaction can ensure that the data you read is consistent with respect to the state of the database when the transaction started. This is because a read-only transaction will not allow any concurrent write transactions to modify the data you are reading.\nTo improve performance: As the Javadoc mentions, a read-only transaction allows for certain runtime optimizations, such as skipping certain locking or logging operations that are not necessary for read-only transactions. This can result in improved performance and reduced contention in your database.\nTo avoid unintended changes: By using a read-only transaction, you can prevent accidentally modifying data in your database. This can be useful if you are working with sensitive data or if you want to avoid making changes to data that you are not authorized to modify.\n\nBut I must admit, not sure about exception throwing\n"
] |
[
3
] |
[] |
[] |
[
"spring",
"spring_data",
"sql",
"transactions"
] |
stackoverflow_0074666963_spring_spring_data_sql_transactions.txt
|
Q:
X'val' notation in mysql appears to always evaluate to zero and complains about the value being incorrect
I am convinced I'm overlooking something painfully simple and obvious here ...
I have copied the example from the Hexadecimal Literals page of the MySQL 8.0 manual (here: https://dev.mysql.com/doc/refman/8.0/en/hexadecimal-literals.html)
Specifically, halfway down the page, the manual gives the following example:
mysql> SET @v1 = X'41';
mysql> SET @v2 = X'41'+0;
mysql> SET @v3 = CAST(X'41' AS UNSIGNED);
mysql> SELECT @v1, @v2, @v3;
+------+------+------+
| @v1 | @v2 | @v3 |
+------+------+------+
| A | 65 | 65 |
+------+------+------+
However, when I use the example, verbatim, I get the following output (I've switched on warnings so you can see what's happening):
MariaDB> \W
Show warnings enabled.
MariaDB> SET @v1 = X'41';
Query OK, 0 rows affected (0.00 sec)
MariaDB> SET @v2 = X'41'+0;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Warning (Code 1292): Truncated incorrect DOUBLE value: 'A'
MariaDB> SET @v3=CAST(X'41' AS UNSIGNED);
Query OK, 0 rows affected, 1 warning (0.00 sec)
Warning (Code 1292): Truncated incorrect INTEGER value: 'A'
MariaDB> SELECT @v1, @v2, @v3;
+------+------+------+
| @v1 | @v2 | @v3 |
+------+------+------+
| A | 0 | 0 |
+------+------+------+
1 row in set (0.00 sec)
And if it helps you see what might be incorrect with my setup:
MariaDB> SELECT @@character_set_database, @@collation_database;
+--------------------------+----------------------+
| @@character_set_database | @@collation_database |
+--------------------------+----------------------+
| utf8mb4 | utf8mb4_general_ci |
+--------------------------+----------------------+
1 row in set (0.00 sec)
Clearly it's not happy with me, I assume there's something I haven't done that I should have done, but I have no idea what.
I am using:
mysql Ver 15.1 Distrib 10.1.48-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
EDIT: (More info). I wondered if the problem was related to the MariaDB client, however the problem persists when I call MySQL from PHP. Example:
\core\report($this->query("SELECT X'41'+0")->toArray()); //report() and toArray() are my own functions.
produces the following output in my log file:
object(stdClass)#23 (1) {
["X'41'+0"]=>
string(1) "0" <--- Still 0
}
A:
MariaDB is not MySQL, so you have to check the manual of MariaDB. See the chapter of hexadecimal literals, specially the sub chapter Differences Between MariaDB and MySQL, where this behavior is defined:
Differences Between MariaDB and MySQL
SELECT x'0a'+0;
+---------+
| x'0a'+0 |
+---------+
| 0 |
+---------+
1 row in set, 1 warning (0.00 sec)
Warning (Code 1292): Truncated incorrect DOUBLE value: '\x0A'
SELECT X'0a'+0;
+---------+
| X'0a'+0 |
+---------+
| 0 |
+---------+
1 row in set, 1 warning (0.00 sec)
Warning (Code 1292): Truncated incorrect DOUBLE value: '\x0A'
SELECT 0x0a+0;
+--------+
| 0x0a+0 |
+--------+
| 10 |
+--------+
In MySQL (up until at least MySQL 8.0.26):
SELECT x'0a'+0;
+---------+
| x'0a'+0 |
+---------+
| 10 |
+---------+
SELECT X'0a'+0;
+---------+
| X'0a'+0 |
+---------+
| 10 |
+---------+
SELECT 0x0a+0;
+--------+
| 0x0a+0 |
+--------+
| 10 |
+--------+
|
X'val' notation in mysql appears to always evaluate to zero and complains about the value being incorrect
|
I am convinced I'm overlooking something painfully simple and obvious here ...
I have copied the example from the Hexadecimal Literals page of the MySQL 8.0 manual (here: https://dev.mysql.com/doc/refman/8.0/en/hexadecimal-literals.html)
Specifically, halfway down the page, the manual gives the following example:
mysql> SET @v1 = X'41';
mysql> SET @v2 = X'41'+0;
mysql> SET @v3 = CAST(X'41' AS UNSIGNED);
mysql> SELECT @v1, @v2, @v3;
+------+------+------+
| @v1 | @v2 | @v3 |
+------+------+------+
| A | 65 | 65 |
+------+------+------+
However, when I use the example, verbatim, I get the following output (I've switched on warnings so you can see what's happening):
MariaDB> \W
Show warnings enabled.
MariaDB> SET @v1 = X'41';
Query OK, 0 rows affected (0.00 sec)
MariaDB> SET @v2 = X'41'+0;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Warning (Code 1292): Truncated incorrect DOUBLE value: 'A'
MariaDB> SET @v3=CAST(X'41' AS UNSIGNED);
Query OK, 0 rows affected, 1 warning (0.00 sec)
Warning (Code 1292): Truncated incorrect INTEGER value: 'A'
MariaDB> SELECT @v1, @v2, @v3;
+------+------+------+
| @v1 | @v2 | @v3 |
+------+------+------+
| A | 0 | 0 |
+------+------+------+
1 row in set (0.00 sec)
And if it helps you see what might be incorrect with my setup:
MariaDB> SELECT @@character_set_database, @@collation_database;
+--------------------------+----------------------+
| @@character_set_database | @@collation_database |
+--------------------------+----------------------+
| utf8mb4 | utf8mb4_general_ci |
+--------------------------+----------------------+
1 row in set (0.00 sec)
Clearly it's not happy with me, I assume there's something I haven't done that I should have done, but I have no idea what.
I am using:
mysql Ver 15.1 Distrib 10.1.48-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
EDIT: (More info). I wondered if the problem was related to the MariaDB client, however the problem persists when I call MySQL from PHP. Example:
\core\report($this->query("SELECT X'41'+0")->toArray()); //report() and toArray() are my own functions.
produces the following output in my log file:
object(stdClass)#23 (1) {
["X'41'+0"]=>
string(1) "0" <--- Still 0
}
|
[
"MariaDB is not MySQL, so you have to check the manual of MariaDB. See the chapter of hexadecimal literals, specially the sub chapter Differences Between MariaDB and MySQL, where this behavior is defined:\n\nDifferences Between MariaDB and MySQL\nSELECT x'0a'+0;\n+---------+\n| x'0a'+0 |\n+---------+\n| 0 |\n+---------+\n1 row in set, 1 warning (0.00 sec)\n\nWarning (Code 1292): Truncated incorrect DOUBLE value: '\\x0A'\n\nSELECT X'0a'+0;\n+---------+\n| X'0a'+0 |\n+---------+\n| 0 |\n+---------+\n1 row in set, 1 warning (0.00 sec)\n\nWarning (Code 1292): Truncated incorrect DOUBLE value: '\\x0A'\n\nSELECT 0x0a+0;\n+--------+\n| 0x0a+0 |\n+--------+\n| 10 |\n+--------+\n\nIn MySQL (up until at least MySQL 8.0.26):\nSELECT x'0a'+0;\n+---------+\n| x'0a'+0 |\n+---------+\n| 10 |\n+---------+\n\nSELECT X'0a'+0;\n+---------+\n| X'0a'+0 |\n+---------+\n| 10 |\n+---------+\n\nSELECT 0x0a+0;\n+--------+\n| 0x0a+0 |\n+--------+\n| 10 |\n+--------+\n\n\n"
] |
[
1
] |
[] |
[] |
[
"mariadb"
] |
stackoverflow_0074665514_mariadb.txt
|
Q:
Empty ajax return with server side datatables
I am facing with a problem with server side script. The count of the rows are correct but the data is empty. There was an error also that the values cannot empty or NULL.
I have added defaultContent to the columns in the script with the message Not set and now the rows are correct but i have only the Not set notification.
I tried to add the UTF-8 Charset but still not working.
JS for the server-side:
var DatatablesDataSourceAjaxServer= {
init:function() {
$("#m_table_1").DataTable( {
responsive:true,
searchDelay:500,
processing:true,
serverSide:true,
ajax:"assets/data/scripts/data-user-table.php",
columns:[ {
data: "name",
//defaultContent: "<i>Not set</i>"
}
, {
data: "mail",
defaultContent: "<i>Not set</i>"
}
, {
data: "status",
defaultContent: "<i>Not set</i>"
}
, {
data: "role",
defaultContent: "<i>Not set</i>"
}
, {
data: "created",
defaultContent: "<i>Not set</i>"
}
, {
data: "login",
defaultContent: "<i>Not set</i>"
}
, {
data: "Actions"
}
], columnDefs:[ {
targets:-1,
title:"Actions", orderable:!1, render:function(a, e, t, n) {
return'\n <a href="" class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" title="View or edit account">\n <i class="la la-edit"></i>\n </a> <a href="#" class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" title="Cancel account">\n <i class="la la-trash"></i>\n </a>'
}
}
, {
targets:2, render:function(a, e, t, n) {
var s= {
1: {
title: "Pending", class: "m-badge--brand"
}
, 2: {
title: "Delivered", class: " m-badge--metal"
}
, 3: {
title: "Canceled", class: " m-badge--primary"
}
, 4: {
title: "Success", class: " m-badge--success"
}
, 5: {
title: "Info", class: " m-badge--info"
}
, 6: {
title: "Danger", class: " m-badge--danger"
}
, 7: {
title: "Warning", class: " m-badge--warning"
}
}
;
return void 0===s[a]?a:'<span class="m-badge '+s[a].class+' m-badge--wide">'+s[a].title+"</span>"
}
}
, {
targets:3, render:function(a, e, t, n) {
var s= {
1: {
title: "Online", state: "danger"
}
, 2: {
title: "Retail", state: "primary"
}
, 3: {
title: "Direct", state: "accent"
}
}
;
return void 0===s[a]?a:'<span class="m-badge m-badge--'+s[a].state+' m-badge--dot"></span> <span class="m--font-bold m--font-'+s[a].state+'">'+s[a].title+"</span>"
}
}
]
}
)
}
}
;
jQuery(document).ready(function() {
DatatablesDataSourceAjaxServer.init()
}
);
And the data-user-table.php:
<?php
// DB table to use
$table = 'users';
// Table's primary key
$primaryKey = 'uid';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
array( 'db' => 'name', 'dt' => 0 ),
array( 'db' => 'mail', 'dt' => 1 ),
array( 'db' => 'status', 'dt' => 2 ),
array( 'db' => 'role', 'dt' => 3 ),
array(
'db' => 'created',
'dt' => 4,
'formatter' => function( $d, $row ) {
return date( 'jS M y', strtotime($d));
}
),
array(
'db' => 'login',
'dt' => 5,
'formatter' => function( $d, $row ) {
return '$'.number_format($d);
}
)
);
// SQL server connection information
$sql_details = array(
'user' => '',
'pass' => '',
'db' => '',
'host' => '',
'charset' => 'utf8'
);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP
* server-side, there is no need to edit below this line.
*/
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
A:
If you have special characters in your database (e.g. 'ø'), search ssp.class.php for this line:
"mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
...and replace it with:
"mysql:host={$sql_details['host']};dbname={$sql_details['db']};charset=UTF8",
Credit for the solution to https://datatables.net/forums/discussion/47358/ssp-class-php-especial-characters-problem-solution
Note: In my case, my table functioned correctly in my local test environment without adding ;charset=UTF8". I don't know why.
|
Empty ajax return with server side datatables
|
I am facing with a problem with server side script. The count of the rows are correct but the data is empty. There was an error also that the values cannot empty or NULL.
I have added defaultContent to the columns in the script with the message Not set and now the rows are correct but i have only the Not set notification.
I tried to add the UTF-8 Charset but still not working.
JS for the server-side:
var DatatablesDataSourceAjaxServer= {
init:function() {
$("#m_table_1").DataTable( {
responsive:true,
searchDelay:500,
processing:true,
serverSide:true,
ajax:"assets/data/scripts/data-user-table.php",
columns:[ {
data: "name",
//defaultContent: "<i>Not set</i>"
}
, {
data: "mail",
defaultContent: "<i>Not set</i>"
}
, {
data: "status",
defaultContent: "<i>Not set</i>"
}
, {
data: "role",
defaultContent: "<i>Not set</i>"
}
, {
data: "created",
defaultContent: "<i>Not set</i>"
}
, {
data: "login",
defaultContent: "<i>Not set</i>"
}
, {
data: "Actions"
}
], columnDefs:[ {
targets:-1,
title:"Actions", orderable:!1, render:function(a, e, t, n) {
return'\n <a href="" class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" title="View or edit account">\n <i class="la la-edit"></i>\n </a> <a href="#" class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" title="Cancel account">\n <i class="la la-trash"></i>\n </a>'
}
}
, {
targets:2, render:function(a, e, t, n) {
var s= {
1: {
title: "Pending", class: "m-badge--brand"
}
, 2: {
title: "Delivered", class: " m-badge--metal"
}
, 3: {
title: "Canceled", class: " m-badge--primary"
}
, 4: {
title: "Success", class: " m-badge--success"
}
, 5: {
title: "Info", class: " m-badge--info"
}
, 6: {
title: "Danger", class: " m-badge--danger"
}
, 7: {
title: "Warning", class: " m-badge--warning"
}
}
;
return void 0===s[a]?a:'<span class="m-badge '+s[a].class+' m-badge--wide">'+s[a].title+"</span>"
}
}
, {
targets:3, render:function(a, e, t, n) {
var s= {
1: {
title: "Online", state: "danger"
}
, 2: {
title: "Retail", state: "primary"
}
, 3: {
title: "Direct", state: "accent"
}
}
;
return void 0===s[a]?a:'<span class="m-badge m-badge--'+s[a].state+' m-badge--dot"></span> <span class="m--font-bold m--font-'+s[a].state+'">'+s[a].title+"</span>"
}
}
]
}
)
}
}
;
jQuery(document).ready(function() {
DatatablesDataSourceAjaxServer.init()
}
);
And the data-user-table.php:
<?php
// DB table to use
$table = 'users';
// Table's primary key
$primaryKey = 'uid';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
array( 'db' => 'name', 'dt' => 0 ),
array( 'db' => 'mail', 'dt' => 1 ),
array( 'db' => 'status', 'dt' => 2 ),
array( 'db' => 'role', 'dt' => 3 ),
array(
'db' => 'created',
'dt' => 4,
'formatter' => function( $d, $row ) {
return date( 'jS M y', strtotime($d));
}
),
array(
'db' => 'login',
'dt' => 5,
'formatter' => function( $d, $row ) {
return '$'.number_format($d);
}
)
);
// SQL server connection information
$sql_details = array(
'user' => '',
'pass' => '',
'db' => '',
'host' => '',
'charset' => 'utf8'
);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP
* server-side, there is no need to edit below this line.
*/
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
|
[
"If you have special characters in your database (e.g. 'ø'), search ssp.class.php for this line:\n\"mysql:host={$sql_details['host']};dbname={$sql_details['db']}\",\n\n...and replace it with:\n\"mysql:host={$sql_details['host']};dbname={$sql_details['db']};charset=UTF8\",\n\nCredit for the solution to https://datatables.net/forums/discussion/47358/ssp-class-php-especial-characters-problem-solution\nNote: In my case, my table functioned correctly in my local test environment without adding ;charset=UTF8\". I don't know why.\n"
] |
[
0
] |
[] |
[] |
[
"ajax",
"datatables",
"javascript"
] |
stackoverflow_0051932617_ajax_datatables_javascript.txt
|
Q:
Trying to pass MediaMetadataRetriever to a class to make MainActivity less clutered, but methods return null
`I've made this MusicData class to replace a method in main activity passing the path for a music file in the storage and an initialized MediaMetaDataRetriever from MainActivity.
public class MusicData {
String path;
String artist;
String title;
String album;
public String getTitle(String path, MediaMetadataRetriever metadataRetriever){
metadataRetriever.setDataSource(path);
try{
title = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
return title;
}catch(Exception e){
title = path.substring(path.lastIndexOf("/")).replace("/","");
return title;
}
}
public Bitmap getBitmap(String path){
metadataRetriever.setDataSource(path);
try{
byte [] data = metadataRetriever.getEmbeddedPicture();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
metadataRetriever.release();
return bitmap;
}catch(Exception e){
return null;
}
}
}
I think I need to pass the context from MainActivity so the class could retrieve the data from storage, but I have yet to figure out how utilize that.
A:
I figured I would take a different approach, instead of sending the file path I send the File data itself and create a MediaMetadataRetriever inside of the class.
public String getTitle(File file){
path = file.getAbsolutePath();
MediaMetadataRetriever mr = new MediaMetadataRetriever();
mr.setDataSource(file.getAbsolutePath());
try{
title = mr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
mr.release();
return title;
}catch(Exception e){
mr.release();
title = path.substring(path.lastIndexOf("/")).replace("/","");
return title;
}
}
|
Trying to pass MediaMetadataRetriever to a class to make MainActivity less clutered, but methods return null
|
`I've made this MusicData class to replace a method in main activity passing the path for a music file in the storage and an initialized MediaMetaDataRetriever from MainActivity.
public class MusicData {
String path;
String artist;
String title;
String album;
public String getTitle(String path, MediaMetadataRetriever metadataRetriever){
metadataRetriever.setDataSource(path);
try{
title = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
return title;
}catch(Exception e){
title = path.substring(path.lastIndexOf("/")).replace("/","");
return title;
}
}
public Bitmap getBitmap(String path){
metadataRetriever.setDataSource(path);
try{
byte [] data = metadataRetriever.getEmbeddedPicture();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
metadataRetriever.release();
return bitmap;
}catch(Exception e){
return null;
}
}
}
I think I need to pass the context from MainActivity so the class could retrieve the data from storage, but I have yet to figure out how utilize that.
|
[
"I figured I would take a different approach, instead of sending the file path I send the File data itself and create a MediaMetadataRetriever inside of the class.\npublic String getTitle(File file){\n path = file.getAbsolutePath();\n MediaMetadataRetriever mr = new MediaMetadataRetriever();\n mr.setDataSource(file.getAbsolutePath());\n try{\n title = mr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);\n mr.release();\n return title;\n }catch(Exception e){\n mr.release();\n title = path.substring(path.lastIndexOf(\"/\")).replace(\"/\",\"\");\n return title;\n }\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"android",
"java"
] |
stackoverflow_0074666324_android_java.txt
|
Q:
How to create a session token programmatically in wordpress?
I need to create a new Session Token in wordpress programmatically, I'm a little newby in the world of wordpress.
I'm using the class WP_Session_Tokens to do this, here are the docs: https://developer.wordpress.org/reference/classes/wp_session_tokens/create/
I have this code but doesn't work and I don't know what is happening, could someone help me pls?
Example 1:
if ($sessionToken = WP_Session_Tokens::create($expirationDate))
{
return $sessionToken;
}
Example 2:
$sessionToken = new WP_Session_Tokens($user->ID);
$sessionToken = $sessionToken->create($expirationDate);
I'm getting error 500 and I can't turn on the debug mode to check what is the error, because I don't have access to the wp_config.php file.
A:
Exploring other issues I found the solution to my problem, this code works to create a session token:
$manager = WP_Session_Tokens::get_instance( $user_id );
$token = $manager->create( $expiration );
This answer was posted as an edit to the question How to create a session token programmatically in wordpress? by the OP Radames E. Hernandez under CC BY-SA 3.0.
|
How to create a session token programmatically in wordpress?
|
I need to create a new Session Token in wordpress programmatically, I'm a little newby in the world of wordpress.
I'm using the class WP_Session_Tokens to do this, here are the docs: https://developer.wordpress.org/reference/classes/wp_session_tokens/create/
I have this code but doesn't work and I don't know what is happening, could someone help me pls?
Example 1:
if ($sessionToken = WP_Session_Tokens::create($expirationDate))
{
return $sessionToken;
}
Example 2:
$sessionToken = new WP_Session_Tokens($user->ID);
$sessionToken = $sessionToken->create($expirationDate);
I'm getting error 500 and I can't turn on the debug mode to check what is the error, because I don't have access to the wp_config.php file.
|
[
"Exploring other issues I found the solution to my problem, this code works to create a session token:\n$manager = WP_Session_Tokens::get_instance( $user_id );\n$token = $manager->create( $expiration );\n\n\nThis answer was posted as an edit to the question How to create a session token programmatically in wordpress? by the OP Radames E. Hernandez under CC BY-SA 3.0.\n"
] |
[
0
] |
[] |
[] |
[
"php",
"runtime_error",
"wordpress"
] |
stackoverflow_0046009653_php_runtime_error_wordpress.txt
|
Q:
How to parse string with key value pair inside in redshift
I have a text column in Redshift and want to extract manager or manager employee id from:
"Manager"=>"Alex Dar"
, "Cost Center"=>"02-40-731"
, "Manager employee ID"=>"[email protected]"
, "Manager First Name"=>"Sohn",
I'm expecting to get manager, manager employee id and Manager First Name
A:
So, here is solution.
At first, change it to json and then parse the json.
json_extract_path_text(concat('{',concat(replace(custom_fields,'=>',':'),'}')),'Manager employee ID')
|
How to parse string with key value pair inside in redshift
|
I have a text column in Redshift and want to extract manager or manager employee id from:
"Manager"=>"Alex Dar"
, "Cost Center"=>"02-40-731"
, "Manager employee ID"=>"[email protected]"
, "Manager First Name"=>"Sohn",
I'm expecting to get manager, manager employee id and Manager First Name
|
[
"So, here is solution.\nAt first, change it to json and then parse the json.\njson_extract_path_text(concat('{',concat(replace(custom_fields,'=>',':'),'}')),'Manager employee ID')\n"
] |
[
0
] |
[] |
[] |
[
"amazon_redshift",
"extract",
"key_pair",
"parsing",
"sql"
] |
stackoverflow_0074666149_amazon_redshift_extract_key_pair_parsing_sql.txt
|
Q:
How to improve the knn model?
I built a knn model for classification. Unfortunately, my model has accuracy > 80%, and I would like to get a better result. Can I ask for some tips? Maybe I used too many predictors?
My data = https://www.openml.org/search?type=data&sort=runs&id=53&status=active
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score
from sklearn.model_selection import GridSearchCV
heart_disease = pd.read_csv('heart_disease.csv', sep=';', decimal=',')
y = heart_disease['heart_disease']
X = heart_disease.drop(["heart_disease"], axis=1)
correlation_matrix = heart_disease.corr()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=123)
scaler = MinMaxScaler(feature_range=(-1,1))
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
knn_3 = KNeighborsClassifier(3, n_jobs = -1)
knn_3.fit(X_train, y_train)
y_train_pred = knn_3.predict(X_train)
labels = ['0', '1']
print('Training set')
print(pd.DataFrame(confusion_matrix(y_train, y_train_pred), index = labels, columns = labels))
print(accuracy_score(y_train, y_train_pred))
print(f1_score(y_train, y_train_pred))
y_test_pred = knn_3.predict(X_test)
print('Test set')
print(pd.DataFrame(confusion_matrix(y_test, y_test_pred), index = labels, columns = labels))
print(accuracy_score(y_test, y_test_pred))
print(f1_score(y_test, y_test_pred))
hyperparameters = {'n_neighbors' : range(1, 15), 'weights': ['uniform','distance']}
knn_best = GridSearchCV(KNeighborsClassifier(), hyperparameters, n_jobs = -1, error_score = 'raise')
knn_best.fit(X_train,y_train)
knn_best.best_params_
y_train_pred_best = knn_best.predict(X_train)
y_test_pred_best = knn_best.predict(X_test)
print('Training set')
print(pd.DataFrame(confusion_matrix(y_train, y_train_pred_best), index = labels, columns = labels))
print(accuracy_score(y_train, y_train_pred_best))
print(f1_score(y_train, y_train_pred_best))
print('Test set')
print(pd.DataFrame(confusion_matrix(y_test, y_test_pred_best), index = labels, columns = labels))
print(accuracy_score(y_test, y_test_pred_best))
print(f1_score(y_test, y_test_pred_best))
A:
There are a few things you can try to improve the accuracy of your KNN model.
First, you can try tuning the hyperparameters of your model, such as the number of nearest neighbors to consider or the distance metric used to measure the similarity between points.
To tune the hyperparameters of your KNN model, you can use techniques like grid search or cross-validation to try different combinations of hyperparameters and find the combination that works best for your data.
You can also try preprocessing your data to make it more suitable for KNN. For example, you can try reducing the dimensionality of the data using techniques like principal component analysis (PCA). This can help to remove redundancies in your data and reduce the number of dimensions, which can make it easier for KNN to find the nearest neighbors.
Additionally, you can try using a different classification algorithm altogether, such as logistic regression or a decision tree. These algorithms may be better suited to your data and can potentially yield better results than KNN.
Another thing you can try is using an ensemble method, such as bagging or boosting, to combine multiple KNN models and potentially improve their accuracy. Ensemble methods can be effective at reducing overfitting and improving the generalizability of your model.
A:
Just a little part of answer, to find the best number for k_neighbors.
errlist = [] #an error list to append
for i in range(1,40): #from 0-40 numbers to use in k_neighbors
knn_i = KNeighborsClassifier(k_neighbors=i)
knn_i.fit(X_train,y_train)
errlist.append(np.mean(knn_i.predict(X_test)!=y_test)) # append the mean of failed-predict numbers
plot a line to see best k_neighbors:
plt.plot(range(1,40),errlist)
feel free to change the numbers for range.
|
How to improve the knn model?
|
I built a knn model for classification. Unfortunately, my model has accuracy > 80%, and I would like to get a better result. Can I ask for some tips? Maybe I used too many predictors?
My data = https://www.openml.org/search?type=data&sort=runs&id=53&status=active
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score
from sklearn.model_selection import GridSearchCV
heart_disease = pd.read_csv('heart_disease.csv', sep=';', decimal=',')
y = heart_disease['heart_disease']
X = heart_disease.drop(["heart_disease"], axis=1)
correlation_matrix = heart_disease.corr()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=123)
scaler = MinMaxScaler(feature_range=(-1,1))
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
knn_3 = KNeighborsClassifier(3, n_jobs = -1)
knn_3.fit(X_train, y_train)
y_train_pred = knn_3.predict(X_train)
labels = ['0', '1']
print('Training set')
print(pd.DataFrame(confusion_matrix(y_train, y_train_pred), index = labels, columns = labels))
print(accuracy_score(y_train, y_train_pred))
print(f1_score(y_train, y_train_pred))
y_test_pred = knn_3.predict(X_test)
print('Test set')
print(pd.DataFrame(confusion_matrix(y_test, y_test_pred), index = labels, columns = labels))
print(accuracy_score(y_test, y_test_pred))
print(f1_score(y_test, y_test_pred))
hyperparameters = {'n_neighbors' : range(1, 15), 'weights': ['uniform','distance']}
knn_best = GridSearchCV(KNeighborsClassifier(), hyperparameters, n_jobs = -1, error_score = 'raise')
knn_best.fit(X_train,y_train)
knn_best.best_params_
y_train_pred_best = knn_best.predict(X_train)
y_test_pred_best = knn_best.predict(X_test)
print('Training set')
print(pd.DataFrame(confusion_matrix(y_train, y_train_pred_best), index = labels, columns = labels))
print(accuracy_score(y_train, y_train_pred_best))
print(f1_score(y_train, y_train_pred_best))
print('Test set')
print(pd.DataFrame(confusion_matrix(y_test, y_test_pred_best), index = labels, columns = labels))
print(accuracy_score(y_test, y_test_pred_best))
print(f1_score(y_test, y_test_pred_best))
|
[
"There are a few things you can try to improve the accuracy of your KNN model.\nFirst, you can try tuning the hyperparameters of your model, such as the number of nearest neighbors to consider or the distance metric used to measure the similarity between points.\nTo tune the hyperparameters of your KNN model, you can use techniques like grid search or cross-validation to try different combinations of hyperparameters and find the combination that works best for your data.\nYou can also try preprocessing your data to make it more suitable for KNN. For example, you can try reducing the dimensionality of the data using techniques like principal component analysis (PCA). This can help to remove redundancies in your data and reduce the number of dimensions, which can make it easier for KNN to find the nearest neighbors.\nAdditionally, you can try using a different classification algorithm altogether, such as logistic regression or a decision tree. These algorithms may be better suited to your data and can potentially yield better results than KNN.\nAnother thing you can try is using an ensemble method, such as bagging or boosting, to combine multiple KNN models and potentially improve their accuracy. Ensemble methods can be effective at reducing overfitting and improving the generalizability of your model.\n",
"Just a little part of answer, to find the best number for k_neighbors.\nerrlist = [] #an error list to append\nfor i in range(1,40): #from 0-40 numbers to use in k_neighbors\n knn_i = KNeighborsClassifier(k_neighbors=i)\n knn_i.fit(X_train,y_train)\n errlist.append(np.mean(knn_i.predict(X_test)!=y_test)) # append the mean of failed-predict numbers\n\nplot a line to see best k_neighbors:\nplt.plot(range(1,40),errlist)\n\nfeel free to change the numbers for range.\n"
] |
[
2,
1
] |
[] |
[] |
[
"knn",
"machine_learning",
"python",
"scikit_learn"
] |
stackoverflow_0074666866_knn_machine_learning_python_scikit_learn.txt
|
Q:
nvcc fatal : Unsupported gpu architecture 'compute_86'
I have a Nvidia RTX 3090 ti 24GB with this drivers
CUDA Version: 11.4
Driver Version: 470.74
18.04.1-Ubuntu SMP
Cuda compilation tools, release 9.1, V9.1.85
I've looked for this card architecture and it is Ampere so the version of library are compute_86 or sm_86(if I am not wrong). But while compiling with nvcc it gives me back
nvcc fatal : Unsupported gpu architecture 'compute_86'
I've runned nvcc --help and I've found something strange, it returned me that for gpu-code and gpu-architecture
Allowed values for this option: 'compute_30','compute_32','compute_35',
'compute_37','compute_50','compute_52','compute_53','compute_60','compute_61',
'compute_62','compute_70','compute_72','sm_30','sm_32','sm_35','sm_37','sm_50',
'sm_52','sm_53','sm_60','sm_61','sm_62','sm_70','sm_72'.
So I'm missing any driver version or some library that has to be donwloaded or I can't compile with my GPU?
A:
In your posted system information, the last line
Cuda compilation tools, release 9.1, V9.1.85
indicates that your NVCC is currently V9.1 (use nvcc -V to know for sure). NVCC of this version is too old to support compute_86. A possible reason for which this happens is that you have installed the CUDA toolkit (including NVCC) and the GPU drivers separately, with different CUDA versions. You can solve it by updating it to V11.4 by following the instructions on this official page: developer.nvidia.com/cuda-11-4-2-download-archive. In my experience, managing NVIDIA drivers and CUDA toolkits with apt often messes up the system. So it is recommended to use the official installer instead. Remember to reset the CUDA-related environment variables to link to the new version if you have set them before.
To get another specific version of CUDA, you can just google "cuda toolkit (version number) download" and look for the official nvidia website results.
A:
this is how to easy install openpose
copy the following script and save it in new text file and save as bash file. example: rename text file as install.sh
also change the desired instal location in the second line
export SOFTWARE_INSTALL_DIR=/usr/local/soft
#!/bin/bash
export SOFTWARE_INSTALL_DIR=/usr/local/soft
# Prerequisites Installation
sudo apt update
sudo apt full-upgrade -y
sudo apt autoremove -y
sudo apt install gcc g++ make autoconf git libtool curl unzip python3-pip cmake-qt-gui caffe-cpu libopencv-dev python-dev libgoogle-glog-dev libboost-all-dev libhdf5-dev libatlas-base-dev -y
sudo apt clean
pip3 install -U pip numpy opencv-python
# Directory Configuration
sudo mkdir -p $SOFTWARE_INSTALL_DIR
cd $SOFTWARE_INSTALL_DIR
sudo chown -R $USERNAME:$USERNAME $SOFTWARE_INSTALL_DIR
# Protocol Buffers Installation
git clone https://github.com/protocolbuffers/protobuf.git
cd protobuf
git submodule update --init --recursive
./autogen.sh
./configure
make
make check
sudo make install
sudo ldconfig
# OpenPose Installation
cd $SOFTWARE_INSTALL_DIR
git clone https://github.com/CMU-Perceptual-Computing-Lab/openpose
cd openpose
git submodule update --init --recursive --remote
sudo mkdir build/
cd build/
sudo cmake-gui ..
make -j`nproc`
# Running Example
# cd $SOFTWARE_INSTALL_DIR/openpose
# ./build/examples/openpose/openpose.bin --video examples/media/video.avi
then run following command in terminal
sudo bash install.sh
|
nvcc fatal : Unsupported gpu architecture 'compute_86'
|
I have a Nvidia RTX 3090 ti 24GB with this drivers
CUDA Version: 11.4
Driver Version: 470.74
18.04.1-Ubuntu SMP
Cuda compilation tools, release 9.1, V9.1.85
I've looked for this card architecture and it is Ampere so the version of library are compute_86 or sm_86(if I am not wrong). But while compiling with nvcc it gives me back
nvcc fatal : Unsupported gpu architecture 'compute_86'
I've runned nvcc --help and I've found something strange, it returned me that for gpu-code and gpu-architecture
Allowed values for this option: 'compute_30','compute_32','compute_35',
'compute_37','compute_50','compute_52','compute_53','compute_60','compute_61',
'compute_62','compute_70','compute_72','sm_30','sm_32','sm_35','sm_37','sm_50',
'sm_52','sm_53','sm_60','sm_61','sm_62','sm_70','sm_72'.
So I'm missing any driver version or some library that has to be donwloaded or I can't compile with my GPU?
|
[
"In your posted system information, the last line\nCuda compilation tools, release 9.1, V9.1.85\n\nindicates that your NVCC is currently V9.1 (use nvcc -V to know for sure). NVCC of this version is too old to support compute_86. A possible reason for which this happens is that you have installed the CUDA toolkit (including NVCC) and the GPU drivers separately, with different CUDA versions. You can solve it by updating it to V11.4 by following the instructions on this official page: developer.nvidia.com/cuda-11-4-2-download-archive. In my experience, managing NVIDIA drivers and CUDA toolkits with apt often messes up the system. So it is recommended to use the official installer instead. Remember to reset the CUDA-related environment variables to link to the new version if you have set them before.\nTo get another specific version of CUDA, you can just google \"cuda toolkit (version number) download\" and look for the official nvidia website results.\n",
"this is how to easy install openpose\ncopy the following script and save it in new text file and save as bash file. example: rename text file as install.sh\nalso change the desired instal location in the second line\nexport SOFTWARE_INSTALL_DIR=/usr/local/soft\n#!/bin/bash\n\nexport SOFTWARE_INSTALL_DIR=/usr/local/soft\n\n# Prerequisites Installation\nsudo apt update\nsudo apt full-upgrade -y\nsudo apt autoremove -y\nsudo apt install gcc g++ make autoconf git libtool curl unzip python3-pip cmake-qt-gui caffe-cpu libopencv-dev python-dev libgoogle-glog-dev libboost-all-dev libhdf5-dev libatlas-base-dev -y\nsudo apt clean\npip3 install -U pip numpy opencv-python\n\n# Directory Configuration\nsudo mkdir -p $SOFTWARE_INSTALL_DIR\ncd $SOFTWARE_INSTALL_DIR\nsudo chown -R $USERNAME:$USERNAME $SOFTWARE_INSTALL_DIR\n\n# Protocol Buffers Installation\ngit clone https://github.com/protocolbuffers/protobuf.git\ncd protobuf\ngit submodule update --init --recursive\n./autogen.sh\n./configure\nmake\nmake check\nsudo make install\nsudo ldconfig\n\n# OpenPose Installation\ncd $SOFTWARE_INSTALL_DIR\ngit clone https://github.com/CMU-Perceptual-Computing-Lab/openpose\ncd openpose\ngit submodule update --init --recursive --remote\nsudo mkdir build/\ncd build/\nsudo cmake-gui ..\nmake -j`nproc`\n\n# Running Example\n# cd $SOFTWARE_INSTALL_DIR/openpose\n# ./build/examples/openpose/openpose.bin --video examples/media/video.avi\n\nthen run following command in terminal\nsudo bash install.sh\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"compiler_errors",
"nvcc",
"nvidia",
"pytorch",
"ubuntu"
] |
stackoverflow_0069865825_compiler_errors_nvcc_nvidia_pytorch_ubuntu.txt
|
Q:
strapi: Intercepting an assignment to a table relation field
I created a one-to one relationship between two tables in strapi.
As an example, suppose that Bob currently has a job, say messenger, if we assign Bob’s Job to secretary, Strapi simply reassigns the new Job, without warning that Bob was already in a job
If a person is not in a current job, it’s job would be ‘none’
I’d like to forbid the reassignment of the job, if Bob was already in a job (the user would have to assign the Bob's job to ‘none’ before assigning a new job)
In strapi, what would be the right way to forbid it (checking if the current job is not ‘none’, and, if it’s the case, stopping the assignment), using a service, a controller or a lifecycle hook?
Thanks in advance
Rafael
A:
One way to handle this in Strapi would be to use a lifecycle hook. Lifecycle hooks allow you to perform specific actions at certain stages of the CRUD operations (create, update, delete) on a model. In this case, you can use the beforeUpdate hook to check if the current job is not none before allowing the assignment of a new job:
// api/person/models/Person.js
module.exports = {
lifecycles: {
// This hook will be called before updating a person
async beforeUpdate(params, data) {
// Check if the current job is not 'none'
if (params.current.job !== 'none') {
// If the current job is not 'none', throw an error
throw new Error('Cannot reassign a job to a person who already has a job');
}
}
}
};
You can also use a service or a controller to handle this logic, but using a lifecycle hook allows you to centralize this logic and keep it separate from your business logic.
|
strapi: Intercepting an assignment to a table relation field
|
I created a one-to one relationship between two tables in strapi.
As an example, suppose that Bob currently has a job, say messenger, if we assign Bob’s Job to secretary, Strapi simply reassigns the new Job, without warning that Bob was already in a job
If a person is not in a current job, it’s job would be ‘none’
I’d like to forbid the reassignment of the job, if Bob was already in a job (the user would have to assign the Bob's job to ‘none’ before assigning a new job)
In strapi, what would be the right way to forbid it (checking if the current job is not ‘none’, and, if it’s the case, stopping the assignment), using a service, a controller or a lifecycle hook?
Thanks in advance
Rafael
|
[
"One way to handle this in Strapi would be to use a lifecycle hook. Lifecycle hooks allow you to perform specific actions at certain stages of the CRUD operations (create, update, delete) on a model. In this case, you can use the beforeUpdate hook to check if the current job is not none before allowing the assignment of a new job:\n// api/person/models/Person.js\n\nmodule.exports = {\n lifecycles: {\n // This hook will be called before updating a person\n async beforeUpdate(params, data) {\n // Check if the current job is not 'none'\n if (params.current.job !== 'none') {\n // If the current job is not 'none', throw an error\n throw new Error('Cannot reassign a job to a person who already has a job');\n }\n }\n }\n};\n\nYou can also use a service or a controller to handle this logic, but using a lifecycle hook allows you to centralize this logic and keep it separate from your business logic.\n"
] |
[
1
] |
[] |
[] |
[
"strapi",
"table_relationships"
] |
stackoverflow_0074667031_strapi_table_relationships.txt
|
Q:
Execute PHP function when clicking on a button
I know how to execute a PHP function when clicking on the "Save" button :
add_action('acf/save_post', 'my_function');
function my_function() {
$newvalue = get_field('some_field');
update_field('other_field',$newvalue, 1234)
}
I would like to execute this function only when clicking on a specific button, not when clicking on save (I don't mind if it saves the post at the same time).
Related question (for my personal knowledge) : All the answers i found on the subject were like "you need ajax for this". Does the "add_action('acf/save_post', 'my_function');" calls the function using AJAX, or not at all ?
A:
To execute a PHP function when clicking on a specific button, you can use jQuery to attach an event listener to the button and call the function when the button is clicked.
Here is an example:
// Add event listener to the button
jQuery('#my-button').on('click', function() {
// Call the PHP function
my_function();
});
function my_function() {
$newvalue = get_field('some_field');
update_field('other_field',$newvalue, 1234)
}
In this example, the PHP function is called when the button with the ID "my-button" is clicked.
To answer your related question, the "add_action('acf/save_post', 'my_function');" function does not use AJAX to call the function. It simply registers a hook that will call the function when the specified action is triggered. In this case, the function will be called when the post is saved. To call a PHP function using AJAX, you need to use the jQuery.ajax() method or a similar method.
|
Execute PHP function when clicking on a button
|
I know how to execute a PHP function when clicking on the "Save" button :
add_action('acf/save_post', 'my_function');
function my_function() {
$newvalue = get_field('some_field');
update_field('other_field',$newvalue, 1234)
}
I would like to execute this function only when clicking on a specific button, not when clicking on save (I don't mind if it saves the post at the same time).
Related question (for my personal knowledge) : All the answers i found on the subject were like "you need ajax for this". Does the "add_action('acf/save_post', 'my_function');" calls the function using AJAX, or not at all ?
|
[
"To execute a PHP function when clicking on a specific button, you can use jQuery to attach an event listener to the button and call the function when the button is clicked.\nHere is an example:\n// Add event listener to the button\njQuery('#my-button').on('click', function() {\n // Call the PHP function\n my_function();\n});\n\nfunction my_function() {\n $newvalue = get_field('some_field');\n update_field('other_field',$newvalue, 1234)\n}\n\nIn this example, the PHP function is called when the button with the ID \"my-button\" is clicked.\nTo answer your related question, the \"add_action('acf/save_post', 'my_function');\" function does not use AJAX to call the function. It simply registers a hook that will call the function when the specified action is triggered. In this case, the function will be called when the post is saved. To call a PHP function using AJAX, you need to use the jQuery.ajax() method or a similar method.\n"
] |
[
0
] |
[] |
[] |
[
"advanced_custom_fields",
"php",
"wordpress"
] |
stackoverflow_0074666850_advanced_custom_fields_php_wordpress.txt
|
Q:
Accessing a datalist element's id using AlpineJS
Is it possible to get the id value of a selected option in the example below using AlpineJS?
I'm trying to build a form that submits the id of a selected element instead of the value. In this example, when a user selects 'Firefox' from the list and submits the form, the value 1 should be submitted for the value of browserId instead of Firefox
<label for="browser">Choose your browser from the list:</label>
<input type="text" list="browsers" name="browser" id="browser">
<datalist id="browsers">
<option id=1 value="Firefox">
<option id=2 value="Edge">
<option id=3 value="Chrome">
</datalist>
<input id='browserId' type='hidden' value="Selected Browser's id should show up here"/>
I've tried using the x-model directive on #browser input element and x-bind directive on the #browserId element, but I only get the value and not the id.
A:
If <datalist> is expendable in favor of <select> you can do this:
<div x-data="{browser_id: 1}">
<label>Choose your browser from the list:</label>
<select id="browsers" name="browsers" x-on:change="browser_id = $el.value">
<option value="1">Firefox</option>
<option value="2">Edge</option>
<option value="3">Chrome</option>
</select>
<input id='browserId' type='hidden' :value="browser_id" />
|
Accessing a datalist element's id using AlpineJS
|
Is it possible to get the id value of a selected option in the example below using AlpineJS?
I'm trying to build a form that submits the id of a selected element instead of the value. In this example, when a user selects 'Firefox' from the list and submits the form, the value 1 should be submitted for the value of browserId instead of Firefox
<label for="browser">Choose your browser from the list:</label>
<input type="text" list="browsers" name="browser" id="browser">
<datalist id="browsers">
<option id=1 value="Firefox">
<option id=2 value="Edge">
<option id=3 value="Chrome">
</datalist>
<input id='browserId' type='hidden' value="Selected Browser's id should show up here"/>
I've tried using the x-model directive on #browser input element and x-bind directive on the #browserId element, but I only get the value and not the id.
|
[
"If <datalist> is expendable in favor of <select> you can do this:\n<div x-data=\"{browser_id: 1}\">\n\n<label>Choose your browser from the list:</label>\n\n <select id=\"browsers\" name=\"browsers\" x-on:change=\"browser_id = $el.value\">\n <option value=\"1\">Firefox</option>\n <option value=\"2\">Edge</option>\n <option value=\"3\">Chrome</option>\n </select>\n\n<input id='browserId' type='hidden' :value=\"browser_id\" />\n\n"
] |
[
0
] |
[] |
[] |
[
"alpine.js"
] |
stackoverflow_0074649655_alpine.js.txt
|
Q:
Migrating a Visual Studio C++ Project to Linux and CMake
I'm currently trying to move from Windows 10 to Linux (Pop!_OS), but I'm having trouble getting my C++ Project to compile and run correctly on the latter. My C++ project was created using Visual Studio, where I also specified the include folders, library folders, what should be linked, etc in the solution properties. I now want to switch to writing my code using Neovim and not Visual Studio (or Visual Studio Code) and have tried compiling it via G++. I quickly noticed that my include files weren't recognized, so I tried to use CMake and created a CMakeLists.txt. I tried using both
INCLUDE_DIRECTORIES()
and
TARGET_INCLUDE_DIRECTORIES()
but no matter what path I enter, my included files were not recognized. Even when I used a path to the specific include file that caused the first error, it still wasn't recognized.
My goal would be that I can specify an include folder and a library folder, so that I can just add files and folders in these and that the new files and folders automatically get recognized when compiling (i.e I would not have to edit the CMakeLists.txt in the future). Is that even possible with CMake and if yes, does anyone know where i can find further information about that or does anyone have a CMakeLists.txt file that does this? If no, would I have to specify each and every file and folder in the CMakeLists.txt file and do the same for every new include and library?
Project structure:
Overall folder
\- build
\- include
---> includeFolder1
---> includeFolder2
---> ...
\- libs
---> library1.lib
---> library2.lib
---> ...
\- src
--> main.cpp
--> other .cpp's and .h's
--> other folders with .cpp's and .h's
I've tried compiling with G++ and CMake, but both did not work, no matter what I specified as the include and library paths.
A:
I have found the problem that caused my errors. The problem wasn't with CMake, it was with Windows and Linux specific details. I always received errors like "<foo\foo.h> no such file or directory", which led me to think that CMake couldn't find the include directory or the files in it. The problem, however, is with the include path itself. On Windows, paths can be given with a backslash ('\') but on Linux, paths are denominated with a forward slash ('/'). So in my example, the path to the file was "../foo/foo.h" but my code had "#include <foo\foo.h>". So when migrating a project from Windows to Linux, be sure to watch out for backslashes in your #include statements!
Below is a template CMakeLists.txt, that should be a good starting point if you want to migrate your Visual Studio project to Linux. I've used glfw (+ glad) as an example library:
cmake_minimum_required(VERSION 3.20)
project(ExampleProject)
add_executable(${PROJECT_NAME} src/glad.c src/main.cpp)
target_include_directories(${PROJECT_NAME} PRIVATE include)
target_link_libraries(${PROJECT_NAME} GL dl glfw)
|
Migrating a Visual Studio C++ Project to Linux and CMake
|
I'm currently trying to move from Windows 10 to Linux (Pop!_OS), but I'm having trouble getting my C++ Project to compile and run correctly on the latter. My C++ project was created using Visual Studio, where I also specified the include folders, library folders, what should be linked, etc in the solution properties. I now want to switch to writing my code using Neovim and not Visual Studio (or Visual Studio Code) and have tried compiling it via G++. I quickly noticed that my include files weren't recognized, so I tried to use CMake and created a CMakeLists.txt. I tried using both
INCLUDE_DIRECTORIES()
and
TARGET_INCLUDE_DIRECTORIES()
but no matter what path I enter, my included files were not recognized. Even when I used a path to the specific include file that caused the first error, it still wasn't recognized.
My goal would be that I can specify an include folder and a library folder, so that I can just add files and folders in these and that the new files and folders automatically get recognized when compiling (i.e I would not have to edit the CMakeLists.txt in the future). Is that even possible with CMake and if yes, does anyone know where i can find further information about that or does anyone have a CMakeLists.txt file that does this? If no, would I have to specify each and every file and folder in the CMakeLists.txt file and do the same for every new include and library?
Project structure:
Overall folder
\- build
\- include
---> includeFolder1
---> includeFolder2
---> ...
\- libs
---> library1.lib
---> library2.lib
---> ...
\- src
--> main.cpp
--> other .cpp's and .h's
--> other folders with .cpp's and .h's
I've tried compiling with G++ and CMake, but both did not work, no matter what I specified as the include and library paths.
|
[
"I have found the problem that caused my errors. The problem wasn't with CMake, it was with Windows and Linux specific details. I always received errors like \"<foo\\foo.h> no such file or directory\", which led me to think that CMake couldn't find the include directory or the files in it. The problem, however, is with the include path itself. On Windows, paths can be given with a backslash ('\\') but on Linux, paths are denominated with a forward slash ('/'). So in my example, the path to the file was \"../foo/foo.h\" but my code had \"#include <foo\\foo.h>\". So when migrating a project from Windows to Linux, be sure to watch out for backslashes in your #include statements!\nBelow is a template CMakeLists.txt, that should be a good starting point if you want to migrate your Visual Studio project to Linux. I've used glfw (+ glad) as an example library:\ncmake_minimum_required(VERSION 3.20)\n\nproject(ExampleProject)\n\nadd_executable(${PROJECT_NAME} src/glad.c src/main.cpp)\n\ntarget_include_directories(${PROJECT_NAME} PRIVATE include)\n\ntarget_link_libraries(${PROJECT_NAME} GL dl glfw)\n\n"
] |
[
1
] |
[] |
[] |
[
"c++",
"cmake",
"linux"
] |
stackoverflow_0074640398_c++_cmake_linux.txt
|
Q:
Helmchart install status is success but no pods are deployed
Getting HTTP 404 not found when helm install is accessing (below mentioned paths) , these http calls are made during execution of command helm install connected-context ./connected-context2 -v=6 , command is executed on windows machine , using docker desktop and minikube.
"GET https://127.0.0.1:63746/api/v1/namespaces/default/configmaps/connected-context-app-conf"
"GET https://127.0.0.1:63746/apis/sparkoperator.k8s.io/v1beta2/namespaces/default/sparkapplications/connected-context-opsinsight-rule-engine"
Output status of command is DEPLOYED but no relevant pods are visible.
A:
Have you tried to look in all namespaces?
kubectl get pods --all-namespaces
Maybe you can provide more information (your helm templates). Otherwise, it will be hard to help you.
|
Helmchart install status is success but no pods are deployed
|
Getting HTTP 404 not found when helm install is accessing (below mentioned paths) , these http calls are made during execution of command helm install connected-context ./connected-context2 -v=6 , command is executed on windows machine , using docker desktop and minikube.
"GET https://127.0.0.1:63746/api/v1/namespaces/default/configmaps/connected-context-app-conf"
"GET https://127.0.0.1:63746/apis/sparkoperator.k8s.io/v1beta2/namespaces/default/sparkapplications/connected-context-opsinsight-rule-engine"
Output status of command is DEPLOYED but no relevant pods are visible.
|
[
"Have you tried to look in all namespaces?\nkubectl get pods --all-namespaces\n\nMaybe you can provide more information (your helm templates). Otherwise, it will be hard to help you.\n"
] |
[
0
] |
[] |
[] |
[
"apache_spark",
"kubernetes_helm"
] |
stackoverflow_0074651142_apache_spark_kubernetes_helm.txt
|
Q:
How can I print the number as elements of a list without the quotes and square brackets should be their?
The result should have square brackets enclosing the elements of list which are numbers , these numbers should not be enclosed into quotes.
i tried to do so with split function and for loop but was not able to get my desired result. i am expecting the answer.
A:
You can unpack all list elements into the print() function to print all values individually, separated by an empty space per default (that you can override using the sep argument). For example, the expression print(*my_list) prints the elements in my_list, empty space separated, without the enclosing square brackets and without the separating commas!
A:
You can use the join() method to print the list as a string, with the square brackets and commas between the elements, but without the quotation marks:
my_list = [1, 2, 3]
print('[{}]'.format(', '.join(str(x) for x in my_list)))
# Output: [1, 2, 3]
|
How can I print the number as elements of a list without the quotes and square brackets should be their?
|
The result should have square brackets enclosing the elements of list which are numbers , these numbers should not be enclosed into quotes.
i tried to do so with split function and for loop but was not able to get my desired result. i am expecting the answer.
|
[
"You can unpack all list elements into the print() function to print all values individually, separated by an empty space per default (that you can override using the sep argument). For example, the expression print(*my_list) prints the elements in my_list, empty space separated, without the enclosing square brackets and without the separating commas!\n",
"You can use the join() method to print the list as a string, with the square brackets and commas between the elements, but without the quotation marks:\nmy_list = [1, 2, 3]\nprint('[{}]'.format(', '.join(str(x) for x in my_list)))\n\n# Output: [1, 2, 3]\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"function",
"input",
"list",
"output",
"python"
] |
stackoverflow_0074666568_function_input_list_output_python.txt
|
Q:
aws glue job: best practice for new data as it comes in?
Im new to AWS and glue.
I have a glue job that uses a python script to convert a data source into a json formatted file. The new data is sent to us on a monthly basis and so my thought was to trigger the glue job to run every time the data was added to our s3 bucket.
I have the job setup to overwrite the file every time it run, but it would be nice to capture the differences between the monthly files so that I can have the historic info.
Here is the output of the code:
s3.put_object(Body=output_file, Bucket='mys3, Key='outputfile.json')
Could a crawler help with keeping track of the history? Like if could I crawl for new data only and then store it somewhere?
For my outputs I am viewing them in Athena, but maybe I should start compiling this data to a database on its own ?
Thanks in advance for any inputs!
A:
What I would suggest to you is to partition the data. Based on what you've said, you get the data on a monthly basis.
An S3 key represents the path to the file in an S3 bucket. In your example, outputfile.json is a top-level object in your S3 bucket. Based on your requirements, you could partition the data by year and month partitions, which you create. Your snippet of the code would then look like this (equality sign is important for partitioning):
s3.put_object(Body=output_file, Bucket='mys3, Key='year=2022/month=12/outputfile.json')
This way, you would see two prefixes in your bucket: year and month. Here's the code for this, so the year/month is not hardcoded:
from datetime import datetime
current_ts = datetime.now()
year = str(current_ts.year)
month = str(current_ts.month)
s3.put_object(Body=output_file, Bucket='mys3, Key=f'year={year}/month={month}/outputfile.json')
Could a crawler help with keeping track of the history? Like if could I crawl for new data only and then store it somewhere?
When a Glue crawler crawls that data, it will update the Data Catalog and track the partitions. You can then query that data through Athena, keeping the historical data. There is no need to move the data anywhere, you can keep it in your S3 bucket, but crawl it, so the new partitions are added to the Data Catalog.
For my outputs I am viewing them in Athena, but maybe I should start compiling this data to a database on its own ?
Based on your use case, Athena seems the best tool for the job. In the future, if the need arises you could always move the data to a standalone database, but this doesn't seem like a use case for it.
To add to all of this, you could always slap a timestamp value as a suffix to the file name and keep them all at the top level of your bucket, and in that way you would keep the previous version of the file. But using prefixes as partitions and using them in an Athena query, you limit the query scan data, and in that way lower your query costs.
|
aws glue job: best practice for new data as it comes in?
|
Im new to AWS and glue.
I have a glue job that uses a python script to convert a data source into a json formatted file. The new data is sent to us on a monthly basis and so my thought was to trigger the glue job to run every time the data was added to our s3 bucket.
I have the job setup to overwrite the file every time it run, but it would be nice to capture the differences between the monthly files so that I can have the historic info.
Here is the output of the code:
s3.put_object(Body=output_file, Bucket='mys3, Key='outputfile.json')
Could a crawler help with keeping track of the history? Like if could I crawl for new data only and then store it somewhere?
For my outputs I am viewing them in Athena, but maybe I should start compiling this data to a database on its own ?
Thanks in advance for any inputs!
|
[
"What I would suggest to you is to partition the data. Based on what you've said, you get the data on a monthly basis.\nAn S3 key represents the path to the file in an S3 bucket. In your example, outputfile.json is a top-level object in your S3 bucket. Based on your requirements, you could partition the data by year and month partitions, which you create. Your snippet of the code would then look like this (equality sign is important for partitioning):\ns3.put_object(Body=output_file, Bucket='mys3, Key='year=2022/month=12/outputfile.json')\n\nThis way, you would see two prefixes in your bucket: year and month. Here's the code for this, so the year/month is not hardcoded:\nfrom datetime import datetime\n\ncurrent_ts = datetime.now()\nyear = str(current_ts.year)\nmonth = str(current_ts.month)\n\ns3.put_object(Body=output_file, Bucket='mys3, Key=f'year={year}/month={month}/outputfile.json')\n\n\nCould a crawler help with keeping track of the history? Like if could I crawl for new data only and then store it somewhere?\n\nWhen a Glue crawler crawls that data, it will update the Data Catalog and track the partitions. You can then query that data through Athena, keeping the historical data. There is no need to move the data anywhere, you can keep it in your S3 bucket, but crawl it, so the new partitions are added to the Data Catalog.\n\nFor my outputs I am viewing them in Athena, but maybe I should start compiling this data to a database on its own ?\n\nBased on your use case, Athena seems the best tool for the job. In the future, if the need arises you could always move the data to a standalone database, but this doesn't seem like a use case for it.\nTo add to all of this, you could always slap a timestamp value as a suffix to the file name and keep them all at the top level of your bucket, and in that way you would keep the previous version of the file. But using prefixes as partitions and using them in an Athena query, you limit the query scan data, and in that way lower your query costs.\n"
] |
[
0
] |
[] |
[] |
[
"amazon_web_services",
"aws_glue",
"python"
] |
stackoverflow_0074650200_amazon_web_services_aws_glue_python.txt
|
Q:
Python program unable to access sound (and other files) from subdirectories
I have a few functions in my program to print from text files, and to play sound files using Path. One such function allows me to run the program from ANY directory, and it can still find and play its sound files. It works perfectly, except in only plays files located in the program directory:
def sound_player_loop(sound_file):
# a sound player function which plays sound_file asynchronously on a continuous loop
try:
p = Path(__file__).with_name(sound_file)
with p.open('rb') as sound:
if sound.readable():
winsound.PlaySound(str(p), winsound.SND_FILENAME | winsound.SND_LOOP | winsound.SND_ASYNC)
except FileNotFoundError:
print(f"{sound_file} not found in directory path.")
pause()
I simply want to be able to move my sound files to a sound\ subdirectory within the program directory and have the same functionality, but I am having trouble with Path.
app_dir\
|
|-----sound\
I have tried
sound_folder = Path("sound/")
file_to_play = sound_folder / sound_file
p = Path(__file__).with_name(file_to_play)
and a few other variations..
Which results in: TypeError: Path.replace() takes 2 positional arguments but 3 were given...
Current functionality is fine, except I just want to tidy up the program directory and move all sounds and eventually all externally printed text files to subdirectories. I am currently using Windows, but would like it to work on *nix as well.
A:
To resolve relative to the directory of __file__ you need something like
sound_folder = Path(__file__).with_name("sound")
...
p = sound_folder / sound_file
|
Python program unable to access sound (and other files) from subdirectories
|
I have a few functions in my program to print from text files, and to play sound files using Path. One such function allows me to run the program from ANY directory, and it can still find and play its sound files. It works perfectly, except in only plays files located in the program directory:
def sound_player_loop(sound_file):
# a sound player function which plays sound_file asynchronously on a continuous loop
try:
p = Path(__file__).with_name(sound_file)
with p.open('rb') as sound:
if sound.readable():
winsound.PlaySound(str(p), winsound.SND_FILENAME | winsound.SND_LOOP | winsound.SND_ASYNC)
except FileNotFoundError:
print(f"{sound_file} not found in directory path.")
pause()
I simply want to be able to move my sound files to a sound\ subdirectory within the program directory and have the same functionality, but I am having trouble with Path.
app_dir\
|
|-----sound\
I have tried
sound_folder = Path("sound/")
file_to_play = sound_folder / sound_file
p = Path(__file__).with_name(file_to_play)
and a few other variations..
Which results in: TypeError: Path.replace() takes 2 positional arguments but 3 were given...
Current functionality is fine, except I just want to tidy up the program directory and move all sounds and eventually all externally printed text files to subdirectories. I am currently using Windows, but would like it to work on *nix as well.
|
[
"To resolve relative to the directory of __file__ you need something like\nsound_folder = Path(__file__).with_name(\"sound\")\n...\np = sound_folder / sound_file\n\n"
] |
[
2
] |
[] |
[] |
[
"path",
"python"
] |
stackoverflow_0074666976_path_python.txt
|
Q:
Does MassTransit Transactional Outbox Work with Multi Bus scenarios
There is a situation that I have separate CommandBus and EventBus, I have a consumer that listens to the commands in the command bus and after the operation is handled it publishes related events to the Event Bus. I want to have the built-in support of the transactional outbox pattern on the EventBus.
Here is the link to a repo
The following is the configuration of the application:
public static void ConfigureServices(HostBuilderContext host, IServiceCollection services)
{
services.Configure<MessageBrokerConfiguration>(host.Configuration.GetSection("MessageBroker"));
var brokerConfiguration = new MessageBrokerConfiguration();
host.Configuration.Bind("MessageBroker", brokerConfiguration);
services.AddHostedService<DatabaseMigratorHostedService>();
services.AddMassTransit<ICommandBus>(mt =>
{
mt.UsingRabbitMq((context, configurator) =>
{
configurator.Host(brokerConfiguration.CommandBus);
configurator.ConfigureEndpoints(context);
});
mt.AddConsumersFromNamespaceContaining<CreateOrderConsumer>();
});
services.AddMassTransit(mt =>
{
mt.AddEntityFrameworkOutbox<OrderContext>(options =>
{
options.QueryDelay = TimeSpan.FromSeconds(1);
options.UsePostgres();
options.UseBusOutbox();
});
mt.UsingRabbitMq((context, configurator) =>
{
configurator.Host(brokerConfiguration.EventBus);
configurator.ConfigureEndpoints(context);
});
});
services.AddRepositories(host.Configuration);
services.AddScoped<IEventEmitter, MasstransitEventEmitter>();
}
and the following is my consumer that listens to a command in one bus and publishes an event to another:
public sealed class CreateOrderConsumer
: IConsumer<CreateOrder>
{
private readonly IEventEmitter _eventEmitter;
private readonly IUnitOfWork _unitOfWork;
private readonly IRepository<Order> _repository;
public CreateOrderConsumer(
IRepository<Order> repository,
IUnitOfWork unitOfWork,
IEventEmitter eventEmitter)
{
_unitOfWork = Guard.Against.Null(unitOfWork);
_repository = Guard.Against.Null(repository);
_eventEmitter = Guard.Against.Null(eventEmitter);
}
public async Task Consume(ConsumeContext<CreateOrder> context)
{
var order = new Order(context.Message.ProductId, context.Message.Quantity);
await _repository.StoreAsync(order);
await _eventEmitter.Emit(order.DomainEvents);
order.ClearDomainEvents();
await _unitOfWork.CommitAsync();
await context.RespondAsync<CreateOrderResult>(new { OrderId = order.Id });
}
and my IEventEmitter is getting a IBus:
public sealed class MasstransitEventEmitter : IEventEmitter
{
private readonly IPublishEndpoint _publishEndpoint;
public MasstransitEventEmitter(IBus publishEndpoint)
{
_publishEndpoint = Guard.Against.Null(publishEndpoint);
}
public async Task Emit(IEnumerable<IDomainEvent> domainEvents)
{
try
{
foreach (var domainEvent in domainEvents)
{
await _publishEndpoint.Publish(domainEvent, domainEvent.GetType(), CancellationToken.None);
}
}
catch (Exception)
{
// ignored
}
}
}
here is the DbContext that is used for the business logic and also transactional outbox configs:
public sealed class OrderContext : DbContext, IUnitOfWork
{
public OrderContext(DbContextOptions<OrderContext> options) : base(options)
{
}
internal DbSet<OrderEntity> Orders { get; private set; } = default!;
public async Task CommitAsync(CancellationToken cancellationToken = default)
=> await this.SaveChangesAsync(cancellationToken);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new OrderEntityConfiguration());
modelBuilder.AddInboxStateEntity();
modelBuilder.AddOutboxMessageEntity();
modelBuilder.AddOutboxStateEntity();
}
}
There is the API layer that sends commands to the command bus via IRequestClient<CreateOrder> and awaits to get a response back. The problem is that when the Event Bus (not command bus) is down, the transactional outbox is not working, and it continues until a time-out exception is happening.
[HttpPost]
public async Task<IActionResult> Post(
[FromBody] CreateOrderDto createOrderDto,
[FromServices] IRequestClient<CreateOrder> createOrderRequestClient)
{
var result = await createOrderRequestClient.GetResponse<CreateOrderResult>(
new CreateOrder{ ProductId = createOrderDto.ProductId,Quantity= createOrderDto.Quantity },
timeout: RequestTimeout.After(m:2));
return Ok(result);
}
And the logs for the API:
info: MassTransit[0]
Bus started: rabbitmq://localhost/
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:7129
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5134
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/shahab/dev/talks/Demo.TransactionalOutbox/Demo.TransactionalOutbox.Api
Logs for the Application Layer(Listens to the Commands and Publishes Events):
[13:33:45 INF] Configured endpoint CancelOrder, Consumer: Demo.TransactionalOutbox.Application.Consumers.CancelOrderConsumer
[13:33:45 INF] Configured endpoint CreateOrder, Consumer: Demo.TransactionalOutbox.Application.Consumers.CreateOrderConsumer
[13:33:45 INF] Configured endpoint GetOrder, Consumer: Demo.TransactionalOutbox.Application.Consumers.GetOrderConsumer
[13:33:49 DBG] Starting bus instances: ICommandBus, IBus
[13:33:49 DBG] Starting bus: rabbitmq://localhost/
[13:33:49 DBG] Starting bus: rabbitmq://localhost:6666/
[13:33:49 DBG] Connect: guest@localhost:5672/
[13:33:49 DBG] Connect: guest@localhost:6666/
[13:33:49 DBG] Connected: guest@localhost:5672/ (address: amqp://localhost:5672, local: 49955)
[13:33:49 DBG] Connected: guest@localhost:6666/ (address: amqp://localhost:6666, local: 49954)
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost/McShahab_DemoTransactio_bus_5emoyydyan1f7qhobdppkkw6gp?temporary=true
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost:6666/McShahab_DemoTransactio_bus_5emoyydyan1f7jiabdppkkw9bz?temporary=true
[13:33:50 INF] Bus started: rabbitmq://localhost:6666/
[13:33:50 DBG] Declare queue: name: CancelOrder, durable, consumer-count: 0 message-count: 0
[13:33:50 DBG] Declare queue: name: CreateOrder, durable, consumer-count: 0 message-count: 0
[13:33:50 DBG] Declare queue: name: GetOrder, durable, consumer-count: 0 message-count: 0
[13:33:50 DBG] Declare exchange: name: GetOrder, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: CreateOrder, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: CancelOrder, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: Demo.TransactionalOutbox.Domain.OrderAggregate.Queries:GetOrderStatus, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: Demo.TransactionalOutbox.Domain.OrderAggregate.Commands:CancelOrder, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: Demo.TransactionalOutbox.Domain.OrderAggregate.Commands:CreateOrder, type: fanout, durable
[13:33:50 DBG] Bind queue: source: GetOrder, destination: GetOrder
[13:33:50 DBG] Bind queue: source: CancelOrder, destination: CancelOrder
[13:33:50 DBG] Bind queue: source: CreateOrder, destination: CreateOrder
[13:33:50 DBG] Bind exchange: source: Demo.TransactionalOutbox.Domain.OrderAggregate.Commands:CreateOrder, destination: CreateOrder
[13:33:50 DBG] Bind exchange: source: Demo.TransactionalOutbox.Domain.OrderAggregate.Queries:GetOrderStatus, destination: GetOrder
[13:33:50 DBG] Bind exchange: source: Demo.TransactionalOutbox.Domain.OrderAggregate.Commands:CancelOrder, destination: CancelOrder
[13:33:50 DBG] Consumer Ok: rabbitmq://localhost/GetOrder - amq.ctag-jT06Ly0B8--gYF2XxxxyGQ
[13:33:50 DBG] Consumer Ok: rabbitmq://localhost/CreateOrder - amq.ctag-K2-6Gcdxk8z6UPxI0q-xQw
[13:33:50 DBG] Consumer Ok: rabbitmq://localhost/CancelOrder - amq.ctag-YRlkqWCWLKPX1JpCtEThJQ
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost/CreateOrder
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost/GetOrder
[13:33:50 INF] Bus started: rabbitmq://localhost/
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost/CancelOrder
and the Consumer of the Events:
[13:33:47 INF] Configured endpoint OrderCreated, Consumer: Demo.TransactionalOutbox.FancyConsumer.OrderCreatedConsumer
[13:33:48 DBG] Starting bus instances: IBus
[13:33:48 DBG] Starting bus: rabbitmq://localhost:6666/
[13:33:48 DBG] Connect: guest@localhost:6666/
[13:33:48 DBG] Connected: guest@localhost:6666/ (address: amqp://localhost:6666, local: 49947)
[13:33:48 DBG] Endpoint Ready: rabbitmq://localhost:6666/McShahab_DemoTransactio_bus_hrmoyydyan1fh45qbdppkkiyy5?temporary=true
[13:33:48 DBG] Declare queue: name: OrderCreated, durable, consumer-count: 0 message-count: 0
[13:33:48 DBG] Declare exchange: name: OrderCreated, type: fanout, durable
[13:33:48 DBG] Declare exchange: name: Demo.TransactionalOutbox.Domain.Events:OrderCreated, type: fanout, durable
[13:33:48 DBG] Bind queue: source: OrderCreated, destination: OrderCreated
[13:33:48 DBG] Bind exchange: source: Demo.TransactionalOutbox.Domain.Events:OrderCreated, destination: OrderCreated
[13:33:48 DBG] Consumer Ok: rabbitmq://localhost:6666/OrderCreated - amq.ctag-53c0dDTumv3l33VqwMiSpA
[13:33:48 DBG] Endpoint Ready: rabbitmq://localhost:6666/OrderCreated
[13:33:48 INF] Bus started: rabbitmq://localhost:6666/
In contrast to the sample application for the outbox pattern, I did not see any logs for the Outbox, neither when the rabbitmq is up&running nor when it is down.
A:
Short answer, Transactional Outbox only works with the primary (IBus) bus instance. Any additional bus instances when using MultiBus are unable to use the transactional outbox at this time.
Updated
In your event emitter, you can't use IBus as a publish endpoint because it isn't scoped. But you also can't just use IPublishEndpoint because it would probably be the ConsumeContext from the consumer on the command bus. The underlying wiring to get the transactional outbox isn't really setup to work that way from a consumer on one bus to producing events on another bus.
|
Does MassTransit Transactional Outbox Work with Multi Bus scenarios
|
There is a situation that I have separate CommandBus and EventBus, I have a consumer that listens to the commands in the command bus and after the operation is handled it publishes related events to the Event Bus. I want to have the built-in support of the transactional outbox pattern on the EventBus.
Here is the link to a repo
The following is the configuration of the application:
public static void ConfigureServices(HostBuilderContext host, IServiceCollection services)
{
services.Configure<MessageBrokerConfiguration>(host.Configuration.GetSection("MessageBroker"));
var brokerConfiguration = new MessageBrokerConfiguration();
host.Configuration.Bind("MessageBroker", brokerConfiguration);
services.AddHostedService<DatabaseMigratorHostedService>();
services.AddMassTransit<ICommandBus>(mt =>
{
mt.UsingRabbitMq((context, configurator) =>
{
configurator.Host(brokerConfiguration.CommandBus);
configurator.ConfigureEndpoints(context);
});
mt.AddConsumersFromNamespaceContaining<CreateOrderConsumer>();
});
services.AddMassTransit(mt =>
{
mt.AddEntityFrameworkOutbox<OrderContext>(options =>
{
options.QueryDelay = TimeSpan.FromSeconds(1);
options.UsePostgres();
options.UseBusOutbox();
});
mt.UsingRabbitMq((context, configurator) =>
{
configurator.Host(brokerConfiguration.EventBus);
configurator.ConfigureEndpoints(context);
});
});
services.AddRepositories(host.Configuration);
services.AddScoped<IEventEmitter, MasstransitEventEmitter>();
}
and the following is my consumer that listens to a command in one bus and publishes an event to another:
public sealed class CreateOrderConsumer
: IConsumer<CreateOrder>
{
private readonly IEventEmitter _eventEmitter;
private readonly IUnitOfWork _unitOfWork;
private readonly IRepository<Order> _repository;
public CreateOrderConsumer(
IRepository<Order> repository,
IUnitOfWork unitOfWork,
IEventEmitter eventEmitter)
{
_unitOfWork = Guard.Against.Null(unitOfWork);
_repository = Guard.Against.Null(repository);
_eventEmitter = Guard.Against.Null(eventEmitter);
}
public async Task Consume(ConsumeContext<CreateOrder> context)
{
var order = new Order(context.Message.ProductId, context.Message.Quantity);
await _repository.StoreAsync(order);
await _eventEmitter.Emit(order.DomainEvents);
order.ClearDomainEvents();
await _unitOfWork.CommitAsync();
await context.RespondAsync<CreateOrderResult>(new { OrderId = order.Id });
}
and my IEventEmitter is getting a IBus:
public sealed class MasstransitEventEmitter : IEventEmitter
{
private readonly IPublishEndpoint _publishEndpoint;
public MasstransitEventEmitter(IBus publishEndpoint)
{
_publishEndpoint = Guard.Against.Null(publishEndpoint);
}
public async Task Emit(IEnumerable<IDomainEvent> domainEvents)
{
try
{
foreach (var domainEvent in domainEvents)
{
await _publishEndpoint.Publish(domainEvent, domainEvent.GetType(), CancellationToken.None);
}
}
catch (Exception)
{
// ignored
}
}
}
here is the DbContext that is used for the business logic and also transactional outbox configs:
public sealed class OrderContext : DbContext, IUnitOfWork
{
public OrderContext(DbContextOptions<OrderContext> options) : base(options)
{
}
internal DbSet<OrderEntity> Orders { get; private set; } = default!;
public async Task CommitAsync(CancellationToken cancellationToken = default)
=> await this.SaveChangesAsync(cancellationToken);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new OrderEntityConfiguration());
modelBuilder.AddInboxStateEntity();
modelBuilder.AddOutboxMessageEntity();
modelBuilder.AddOutboxStateEntity();
}
}
There is the API layer that sends commands to the command bus via IRequestClient<CreateOrder> and awaits to get a response back. The problem is that when the Event Bus (not command bus) is down, the transactional outbox is not working, and it continues until a time-out exception is happening.
[HttpPost]
public async Task<IActionResult> Post(
[FromBody] CreateOrderDto createOrderDto,
[FromServices] IRequestClient<CreateOrder> createOrderRequestClient)
{
var result = await createOrderRequestClient.GetResponse<CreateOrderResult>(
new CreateOrder{ ProductId = createOrderDto.ProductId,Quantity= createOrderDto.Quantity },
timeout: RequestTimeout.After(m:2));
return Ok(result);
}
And the logs for the API:
info: MassTransit[0]
Bus started: rabbitmq://localhost/
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:7129
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5134
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/shahab/dev/talks/Demo.TransactionalOutbox/Demo.TransactionalOutbox.Api
Logs for the Application Layer(Listens to the Commands and Publishes Events):
[13:33:45 INF] Configured endpoint CancelOrder, Consumer: Demo.TransactionalOutbox.Application.Consumers.CancelOrderConsumer
[13:33:45 INF] Configured endpoint CreateOrder, Consumer: Demo.TransactionalOutbox.Application.Consumers.CreateOrderConsumer
[13:33:45 INF] Configured endpoint GetOrder, Consumer: Demo.TransactionalOutbox.Application.Consumers.GetOrderConsumer
[13:33:49 DBG] Starting bus instances: ICommandBus, IBus
[13:33:49 DBG] Starting bus: rabbitmq://localhost/
[13:33:49 DBG] Starting bus: rabbitmq://localhost:6666/
[13:33:49 DBG] Connect: guest@localhost:5672/
[13:33:49 DBG] Connect: guest@localhost:6666/
[13:33:49 DBG] Connected: guest@localhost:5672/ (address: amqp://localhost:5672, local: 49955)
[13:33:49 DBG] Connected: guest@localhost:6666/ (address: amqp://localhost:6666, local: 49954)
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost/McShahab_DemoTransactio_bus_5emoyydyan1f7qhobdppkkw6gp?temporary=true
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost:6666/McShahab_DemoTransactio_bus_5emoyydyan1f7jiabdppkkw9bz?temporary=true
[13:33:50 INF] Bus started: rabbitmq://localhost:6666/
[13:33:50 DBG] Declare queue: name: CancelOrder, durable, consumer-count: 0 message-count: 0
[13:33:50 DBG] Declare queue: name: CreateOrder, durable, consumer-count: 0 message-count: 0
[13:33:50 DBG] Declare queue: name: GetOrder, durable, consumer-count: 0 message-count: 0
[13:33:50 DBG] Declare exchange: name: GetOrder, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: CreateOrder, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: CancelOrder, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: Demo.TransactionalOutbox.Domain.OrderAggregate.Queries:GetOrderStatus, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: Demo.TransactionalOutbox.Domain.OrderAggregate.Commands:CancelOrder, type: fanout, durable
[13:33:50 DBG] Declare exchange: name: Demo.TransactionalOutbox.Domain.OrderAggregate.Commands:CreateOrder, type: fanout, durable
[13:33:50 DBG] Bind queue: source: GetOrder, destination: GetOrder
[13:33:50 DBG] Bind queue: source: CancelOrder, destination: CancelOrder
[13:33:50 DBG] Bind queue: source: CreateOrder, destination: CreateOrder
[13:33:50 DBG] Bind exchange: source: Demo.TransactionalOutbox.Domain.OrderAggregate.Commands:CreateOrder, destination: CreateOrder
[13:33:50 DBG] Bind exchange: source: Demo.TransactionalOutbox.Domain.OrderAggregate.Queries:GetOrderStatus, destination: GetOrder
[13:33:50 DBG] Bind exchange: source: Demo.TransactionalOutbox.Domain.OrderAggregate.Commands:CancelOrder, destination: CancelOrder
[13:33:50 DBG] Consumer Ok: rabbitmq://localhost/GetOrder - amq.ctag-jT06Ly0B8--gYF2XxxxyGQ
[13:33:50 DBG] Consumer Ok: rabbitmq://localhost/CreateOrder - amq.ctag-K2-6Gcdxk8z6UPxI0q-xQw
[13:33:50 DBG] Consumer Ok: rabbitmq://localhost/CancelOrder - amq.ctag-YRlkqWCWLKPX1JpCtEThJQ
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost/CreateOrder
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost/GetOrder
[13:33:50 INF] Bus started: rabbitmq://localhost/
[13:33:50 DBG] Endpoint Ready: rabbitmq://localhost/CancelOrder
and the Consumer of the Events:
[13:33:47 INF] Configured endpoint OrderCreated, Consumer: Demo.TransactionalOutbox.FancyConsumer.OrderCreatedConsumer
[13:33:48 DBG] Starting bus instances: IBus
[13:33:48 DBG] Starting bus: rabbitmq://localhost:6666/
[13:33:48 DBG] Connect: guest@localhost:6666/
[13:33:48 DBG] Connected: guest@localhost:6666/ (address: amqp://localhost:6666, local: 49947)
[13:33:48 DBG] Endpoint Ready: rabbitmq://localhost:6666/McShahab_DemoTransactio_bus_hrmoyydyan1fh45qbdppkkiyy5?temporary=true
[13:33:48 DBG] Declare queue: name: OrderCreated, durable, consumer-count: 0 message-count: 0
[13:33:48 DBG] Declare exchange: name: OrderCreated, type: fanout, durable
[13:33:48 DBG] Declare exchange: name: Demo.TransactionalOutbox.Domain.Events:OrderCreated, type: fanout, durable
[13:33:48 DBG] Bind queue: source: OrderCreated, destination: OrderCreated
[13:33:48 DBG] Bind exchange: source: Demo.TransactionalOutbox.Domain.Events:OrderCreated, destination: OrderCreated
[13:33:48 DBG] Consumer Ok: rabbitmq://localhost:6666/OrderCreated - amq.ctag-53c0dDTumv3l33VqwMiSpA
[13:33:48 DBG] Endpoint Ready: rabbitmq://localhost:6666/OrderCreated
[13:33:48 INF] Bus started: rabbitmq://localhost:6666/
In contrast to the sample application for the outbox pattern, I did not see any logs for the Outbox, neither when the rabbitmq is up&running nor when it is down.
|
[
"Short answer, Transactional Outbox only works with the primary (IBus) bus instance. Any additional bus instances when using MultiBus are unable to use the transactional outbox at this time.\nUpdated\nIn your event emitter, you can't use IBus as a publish endpoint because it isn't scoped. But you also can't just use IPublishEndpoint because it would probably be the ConsumeContext from the consumer on the command bus. The underlying wiring to get the transactional outbox isn't really setup to work that way from a consumer on one bus to producing events on another bus.\n"
] |
[
1
] |
[] |
[] |
[
"c#",
"distributed_transactions",
"masstransit",
"microservices",
"rabbitmq"
] |
stackoverflow_0074666703_c#_distributed_transactions_masstransit_microservices_rabbitmq.txt
|
Q:
group_by behavior when using --stream
Having (simplified for learning) input file:
{"type":"a","id":"1"}
{"type":"a","id":"2"}
{"type":"b","id":"1"}
{"type":"c","id":"3"}
I'd like to turn it into:
{
"a": [1,2],
"b": [1],
"c": [3]
}
via using --stream option, not needed here, just for learning. Or at least it does not seem that viable to use group_by or reduce without it on bigger files (even few G seems to be rather slow)
I understand that I can write smth like:
jq --stream -cn 'reduce (inputs|select(length==2)) as $i([]; . + ..... )' test3
but that would just process the data per line(processed item in stream), ie I can either see type or id, and this does not have place where to create pairing. I can cram it to one big array, but that opposite of what I have to do.
How to create such pairings? I don't even know how to create(using --stream):
{"a":1}
{"a":2}
...
I know both (first target transformation, and the one above this paragraph) are probably some trivial usage of for each, I have some working example of one here, but all it's .accumulator and .complete keywords(IIUC) are now just magic. I understood it once, but ... Sorry for trivial questions.
UPDATE regarding performace:
@pmf provided in his answer 2 solutions: streaming and non streaming. Thanks for that, I was able to write non-streaming version, but not the streaming one. But when testing it, the streaming variant was (I'm not 100% sure now, but ...) 2-4 times slower. Makes sense if data does not fit into memory, but luckily in my case, they do. So I ran the non streaming version for ~1G file on laptop, but not actually that slow i7-9850H CPU @ 2.60GHz. For my surprise it wasn't done withing 16hours so I killed it as not viable solution for my usecase of potentially a lot bigger input files. Considering simplicity of input, I decided to write pipeline just via using bash, grep,sed,paste and tr, and eventhough it was using some regexes, and was overally inefficient as hell, and without any parallelism, the whole file was correctly crunched in 55 seconds. I understand that character manipulation is faster than parsing json, but that much difference? Isn't there some better approach while still parsing json? I don't mind spending more cpu power, but if I'm using jq, I'd like to use it's functions and process json as json, not just chars just as I did it with bash.
A:
In the "unstreamed" case I`d use
jq -n 'reduce inputs as $i ({}; .[$i.type] += [$i.id | tonumber])'
Demo
With the --stream option set, just re-create the streamed items using fromstream:
jq --stream -n 'reduce fromstream(inputs) as $i ({}; .[$i.type] += [$i.id | tonumber])'
{
"a": [1,2],
"b": [1],
"c": [3]
}
|
group_by behavior when using --stream
|
Having (simplified for learning) input file:
{"type":"a","id":"1"}
{"type":"a","id":"2"}
{"type":"b","id":"1"}
{"type":"c","id":"3"}
I'd like to turn it into:
{
"a": [1,2],
"b": [1],
"c": [3]
}
via using --stream option, not needed here, just for learning. Or at least it does not seem that viable to use group_by or reduce without it on bigger files (even few G seems to be rather slow)
I understand that I can write smth like:
jq --stream -cn 'reduce (inputs|select(length==2)) as $i([]; . + ..... )' test3
but that would just process the data per line(processed item in stream), ie I can either see type or id, and this does not have place where to create pairing. I can cram it to one big array, but that opposite of what I have to do.
How to create such pairings? I don't even know how to create(using --stream):
{"a":1}
{"a":2}
...
I know both (first target transformation, and the one above this paragraph) are probably some trivial usage of for each, I have some working example of one here, but all it's .accumulator and .complete keywords(IIUC) are now just magic. I understood it once, but ... Sorry for trivial questions.
UPDATE regarding performace:
@pmf provided in his answer 2 solutions: streaming and non streaming. Thanks for that, I was able to write non-streaming version, but not the streaming one. But when testing it, the streaming variant was (I'm not 100% sure now, but ...) 2-4 times slower. Makes sense if data does not fit into memory, but luckily in my case, they do. So I ran the non streaming version for ~1G file on laptop, but not actually that slow i7-9850H CPU @ 2.60GHz. For my surprise it wasn't done withing 16hours so I killed it as not viable solution for my usecase of potentially a lot bigger input files. Considering simplicity of input, I decided to write pipeline just via using bash, grep,sed,paste and tr, and eventhough it was using some regexes, and was overally inefficient as hell, and without any parallelism, the whole file was correctly crunched in 55 seconds. I understand that character manipulation is faster than parsing json, but that much difference? Isn't there some better approach while still parsing json? I don't mind spending more cpu power, but if I'm using jq, I'd like to use it's functions and process json as json, not just chars just as I did it with bash.
|
[
"In the \"unstreamed\" case I`d use\njq -n 'reduce inputs as $i ({}; .[$i.type] += [$i.id | tonumber])'\n\nDemo\nWith the --stream option set, just re-create the streamed items using fromstream:\njq --stream -n 'reduce fromstream(inputs) as $i ({}; .[$i.type] += [$i.id | tonumber])'\n\n{\n \"a\": [1,2],\n \"b\": [1],\n \"c\": [3]\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"jq"
] |
stackoverflow_0074667045_jq.txt
|
Q:
Sails-Mongo native query to a specific collection
Im using Sails v1.0 with sails-mongo as an adapter and im having a memory leak in a simple populate between two models that have a many-to-many association.
I got into the mongo shell and saw that sails created a collection for this association, something like "model1_models2_model2_models1" filled with objects like "{id, idModel1, idModel2}" to represent the association.
The thing is that I want to avoid the "populate" that is making the leak but I don't know hot to get to this collection using a native query and I did not find any answer for it.
A:
// Get access to the native MongoDB client via the default Sails datastore.
var db = sails.getDatastore("nameOfTheDatastore").manager;
db.collection('user').find().toArray(console.log);
This answer was posted as an edit to the question Sails-Mongo native query to a specific collection by the OP alan bendjuya under CC BY-SA 4.0.
|
Sails-Mongo native query to a specific collection
|
Im using Sails v1.0 with sails-mongo as an adapter and im having a memory leak in a simple populate between two models that have a many-to-many association.
I got into the mongo shell and saw that sails created a collection for this association, something like "model1_models2_model2_models1" filled with objects like "{id, idModel1, idModel2}" to represent the association.
The thing is that I want to avoid the "populate" that is making the leak but I don't know hot to get to this collection using a native query and I did not find any answer for it.
|
[
"\n\n// Get access to the native MongoDB client via the default Sails datastore.\nvar db = sails.getDatastore(\"nameOfTheDatastore\").manager;\ndb.collection('user').find().toArray(console.log);\n\n\n\n\nThis answer was posted as an edit to the question Sails-Mongo native query to a specific collection by the OP alan bendjuya under CC BY-SA 4.0.\n"
] |
[
0
] |
[] |
[] |
[
"collections",
"mongodb",
"native",
"populate",
"sails.js"
] |
stackoverflow_0051382322_collections_mongodb_native_populate_sails.js.txt
|
Q:
Android Studio seeing which files a change was applied to
I was doing a code inspection with Android Studio and I accepted a change across multiple file which I now wish to undo.
When I go to VCS|Local History | Show History for one of the files, I can see the change was applied to 25 files, but I do not know how to show which files these are. I have version 0.3.5
A:
Right click on your project in project structure on the left. then Local History -> Show History. If you want to show history only for src folder, click on it.. the same for layout folder etc..
A:
You can use Shelve changes.
This is a great tool to view your changes.
Here is how to open the 'Shelve changes' dialog in Android Studio :
And here is what the dialog looks like :
You can also use this box to commit your changes if you want.
|
Android Studio seeing which files a change was applied to
|
I was doing a code inspection with Android Studio and I accepted a change across multiple file which I now wish to undo.
When I go to VCS|Local History | Show History for one of the files, I can see the change was applied to 25 files, but I do not know how to show which files these are. I have version 0.3.5
|
[
"Right click on your project in project structure on the left. then Local History -> Show History. If you want to show history only for src folder, click on it.. the same for layout folder etc..\n\n",
"You can use Shelve changes.\nThis is a great tool to view your changes.\n\nHere is how to open the 'Shelve changes' dialog in Android Studio :\n\n\nAnd here is what the dialog looks like :\n\nYou can also use this box to commit your changes if you want.\n"
] |
[
100,
0
] |
[] |
[] |
[
"android",
"android_studio",
"intellij_idea"
] |
stackoverflow_0019973449_android_android_studio_intellij_idea.txt
|
Q:
Spring Boot Selenium - Github Login cannot work org.springframework.web.util.UriTemplateHandler Error
I tried to implement a selenium example to login github through Spring Boot.
When I ran the test method, I got this error shown below.
java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@3d3c886f testClass = com.github.selenium.process.GithubProcess, locations = [], classes = [com.github.selenium.SeleniumApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true", "server.port=0"], contextCustomizers = [org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4310d43, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@27f981c6, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@771a660, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@9da1, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1ffaf86, org.springframework.boot.test.context.SpringBootTestAnnotation@169dd363], contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
Caused by: java.lang.ClassNotFoundException: org.springframework.web.util.UriTemplateHandler
How can I fix it?
Here is the code shown below.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class GithubProcess {
private static WebDriver driver;
String baseUrl = "https://github.com/login";
@BeforeAll
static void beforeAll() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@Test
@Order(1)
public void login() throws InterruptedException {
// github login through selenium with username and password
driver.get(baseUrl);
WebElement usernameOrEmail = driver.findElement(By.id("login_field"));
WebElement password = driver.findElement(By.id("password"));
WebElement signInButton = driver.findElement(By.cssSelector("input[type='submit']"));
String usernameOrEmailField = "my-username-or-email";
String passwordField = "my-password";
usernameOrEmail.sendKeys(usernameOrEmailField);
password.sendKeys(passwordField);
signInButton.click();
Thread.sleep(1000);
}
}
Here are my dependency defined in pom.xml
<properties>
<java.version>17</java.version>
<selenium.version>4.6.0</selenium.version>
<webdrivermanager.version>5.3.1</webdrivermanager.version>
<junit.jupiter.version>5.9.1</junit.jupiter.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Selenium-->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>${selenium.version}</version>
</dependency>
<!--Webdriver Manager-->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
</dependency>
<!--JUnit5-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
A:
After defining this dependency in the pom.xml, the issue disappeared.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
|
Spring Boot Selenium - Github Login cannot work org.springframework.web.util.UriTemplateHandler Error
|
I tried to implement a selenium example to login github through Spring Boot.
When I ran the test method, I got this error shown below.
java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@3d3c886f testClass = com.github.selenium.process.GithubProcess, locations = [], classes = [com.github.selenium.SeleniumApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true", "server.port=0"], contextCustomizers = [org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4310d43, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@27f981c6, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@771a660, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@9da1, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1ffaf86, org.springframework.boot.test.context.SpringBootTestAnnotation@169dd363], contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
Caused by: java.lang.ClassNotFoundException: org.springframework.web.util.UriTemplateHandler
How can I fix it?
Here is the code shown below.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class GithubProcess {
private static WebDriver driver;
String baseUrl = "https://github.com/login";
@BeforeAll
static void beforeAll() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@Test
@Order(1)
public void login() throws InterruptedException {
// github login through selenium with username and password
driver.get(baseUrl);
WebElement usernameOrEmail = driver.findElement(By.id("login_field"));
WebElement password = driver.findElement(By.id("password"));
WebElement signInButton = driver.findElement(By.cssSelector("input[type='submit']"));
String usernameOrEmailField = "my-username-or-email";
String passwordField = "my-password";
usernameOrEmail.sendKeys(usernameOrEmailField);
password.sendKeys(passwordField);
signInButton.click();
Thread.sleep(1000);
}
}
Here are my dependency defined in pom.xml
<properties>
<java.version>17</java.version>
<selenium.version>4.6.0</selenium.version>
<webdrivermanager.version>5.3.1</webdrivermanager.version>
<junit.jupiter.version>5.9.1</junit.jupiter.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Selenium-->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>${selenium.version}</version>
</dependency>
<!--Webdriver Manager-->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
</dependency>
<!--JUnit5-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
|
[
"After defining this dependency in the pom.xml, the issue disappeared.\n<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n\n"
] |
[
1
] |
[] |
[] |
[
"github",
"java",
"junit",
"selenium",
"spring_boot"
] |
stackoverflow_0074662829_github_java_junit_selenium_spring_boot.txt
|
Q:
How do I make a turtle move in OOP?
I'm making a simple pong game and and trying to make it with OOP. I'm trying to get the turtles to move using ycor. It's intended to call the 'objects_up' method to move them up and do then ill do the same for x and y.
I've tried all sorts of indentation, not using a method and moving wn.listen outside of the class. What am I doing wrong? I keep getting the error :
Edit1: Made Paddles a subclass of turtle. I'm getting a new, different error:
Edit2: Followed the advice of @OneCricketeer and I'm using a lambda now. The program runs fine but the keypress doesn't work and i'm getting a plethora of errors: e.g
````
File "C:\Users\okpla\AppData\Local\Programs\Python\Python311\Lib\turtle.py", line 1294, in _incrementudc
raise Terminator
````
This is the code:
````
from turtle import Screen,Turtle
wn = Screen()
wn.title("Pong by CGGamer")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
class Paddles(Turtle):
def __init__(self,position,size):
super().__init__()
self.position = position
self.size = size
self.speed(0)
self.shape("square")
self.shape("square")
self.color("white")
self.shapesize(size,1)
self.penup()
self.setposition(position)
wn.listen()
wn.onkeypress(lambda self:self.sety(self.ycor() + 20),"w")
paddle_a = Paddles((-350,0),5)
paddle_b = Paddles((350,0),5)
ball = Paddles((0,0),1)
````
A:
Thanks guys! Solved the problem, was sooo much easier than I thought.
Here's the new code:
from turtle import Screen,Turtle
wn = Screen()
wn.title("Pong by CGGamer")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
class Paddles(Turtle):
def __init__(self,position,size):
super().__init__()
self.position = position
self.size = size
self.speed(0)
self.shape("square")
self.shape("square")
self.color("white")
self.y = 20
self.x = 20
self.shapesize(size,1)
self.penup()
self.setposition(position)
def moving_on_y_up(self):
newy = self.ycor() + self.y
self.goto(self.xcor(),newy)
def moving_on_x_right(self):
newx = self.xcor() + self.x
self.goto(newx,self.ycor())
def moving_on_y_down(self):
newy = self.ycor() - self.y
self.goto(self.xcor(),newy)
def moving_on_x_left(self):
newx = self.xcor() - self.x
self.goto(newx,self.ycor())
paddle_a = Paddles((-350,0),5)
wn.listen()
wn.onkeypress(paddle_a.moving_on_y_up, "w")
wn.onkeypress(paddle_a.moving_on_x_right, "d")
wn.onkeypress(paddle_a.moving_on_y_down, "s")
wn.onkeypress(paddle_a.moving_on_x_left, "a")
paddle_b = Paddles((350,0),5)
wn.listen()
wn.onkeypress(paddle_a.moving_on_y_up, "w")
wn.onkeypress(paddle_a.moving_on_x_right, "d")
wn.onkeypress(paddle_a.moving_on_y_down, "s")
wn.onkeypress(paddle_a.moving_on_x_left, "a")
ball = Paddles((0,0),1)
while True:
wn.update()
|
How do I make a turtle move in OOP?
|
I'm making a simple pong game and and trying to make it with OOP. I'm trying to get the turtles to move using ycor. It's intended to call the 'objects_up' method to move them up and do then ill do the same for x and y.
I've tried all sorts of indentation, not using a method and moving wn.listen outside of the class. What am I doing wrong? I keep getting the error :
Edit1: Made Paddles a subclass of turtle. I'm getting a new, different error:
Edit2: Followed the advice of @OneCricketeer and I'm using a lambda now. The program runs fine but the keypress doesn't work and i'm getting a plethora of errors: e.g
````
File "C:\Users\okpla\AppData\Local\Programs\Python\Python311\Lib\turtle.py", line 1294, in _incrementudc
raise Terminator
````
This is the code:
````
from turtle import Screen,Turtle
wn = Screen()
wn.title("Pong by CGGamer")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
class Paddles(Turtle):
def __init__(self,position,size):
super().__init__()
self.position = position
self.size = size
self.speed(0)
self.shape("square")
self.shape("square")
self.color("white")
self.shapesize(size,1)
self.penup()
self.setposition(position)
wn.listen()
wn.onkeypress(lambda self:self.sety(self.ycor() + 20),"w")
paddle_a = Paddles((-350,0),5)
paddle_b = Paddles((350,0),5)
ball = Paddles((0,0),1)
````
|
[
"Thanks guys! Solved the problem, was sooo much easier than I thought.\nHere's the new code:\nfrom turtle import Screen,Turtle\n\nwn = Screen()\nwn.title(\"Pong by CGGamer\")\nwn.bgcolor(\"black\")\nwn.setup(width=800, height=600)\nwn.tracer(0)\n\nclass Paddles(Turtle): \n def __init__(self,position,size):\n super().__init__()\n self.position = position\n self.size = size\n self.speed(0)\n self.shape(\"square\")\n self.shape(\"square\")\n self.color(\"white\")\n self.y = 20\n self.x = 20\n self.shapesize(size,1)\n self.penup()\n self.setposition(position)\n \n def moving_on_y_up(self):\n newy = self.ycor() + self.y\n self.goto(self.xcor(),newy)\n \n def moving_on_x_right(self):\n newx = self.xcor() + self.x\n self.goto(newx,self.ycor())\n\n def moving_on_y_down(self):\n newy = self.ycor() - self.y\n self.goto(self.xcor(),newy)\n \n def moving_on_x_left(self):\n newx = self.xcor() - self.x\n self.goto(newx,self.ycor())\n\n\npaddle_a = Paddles((-350,0),5)\nwn.listen()\nwn.onkeypress(paddle_a.moving_on_y_up, \"w\")\nwn.onkeypress(paddle_a.moving_on_x_right, \"d\")\nwn.onkeypress(paddle_a.moving_on_y_down, \"s\")\nwn.onkeypress(paddle_a.moving_on_x_left, \"a\")\n\n\npaddle_b = Paddles((350,0),5)\nwn.listen()\nwn.onkeypress(paddle_a.moving_on_y_up, \"w\")\nwn.onkeypress(paddle_a.moving_on_x_right, \"d\")\nwn.onkeypress(paddle_a.moving_on_y_down, \"s\")\nwn.onkeypress(paddle_a.moving_on_x_left, \"a\")\n\n\n\nball = Paddles((0,0),1)\n\n\n\nwhile True:\n wn.update()\n\n"
] |
[
0
] |
[] |
[] |
[
"class",
"python",
"python_turtle"
] |
stackoverflow_0074661179_class_python_python_turtle.txt
|
Q:
Should I make sure an object is unusable after Dispose was called?
I have a class BleScanner that wraps an internal BluetoothLEAdvertisementWatcher. It also implements IDisposable to make sure that the watcher is stopped when the scanner gets disposed of.
public sealed class BleScanner : IDisposable
{
public event AdvertisementReceivedHandler? AdvertisementReceived;
private readonly BluetoothLEAdvertisementWatcher m_Watcher;
public BleScanner() {
m_Watcher = new() {
// ...
};
// m_Watcher.Received += OnAdvertisementReceived;
}
// private void OnAdvertisementReceived(...) {
// code elided for brevity
// may eventually raise AdvertisementReceived
// }
public void Start() => m_Watcher.Start();
public void Stop() => m_Watcher.Stop();
public void Dispose() {
if (m_Watcher.Status == BluetoothLEAdvertisementWatcherStatus.Started) {
m_Watcher.Stop();
}
}
}
The watcher is not disposable. So in theory, the scanner would still work if you just called Start again after Dispose:
public async Task ScannerTest(CancellationToken token) {
using var scanner = new BleScanner();
scanner.AdvertisementReceived += OnAdvertisementReceived;
scanner.Start(); // will start the scan
await Task.Delay(3000, token); // raise events for 3 seconds
scanner.Stop(); // could be forgotten
scanner.Dispose(); // will stop the scan if indeed it was forgotten
scanner.Start(); // everything will work, despite "scanner" being disposed already
}
Should I make sure Start (and maybe Stop) throws an ObjectDisposedException after Dispose was called? The guidelines on the Dispose pattern only require that Dispose can be called multiple times without an exception, but don't say anything about how the other members should behave after Dispose was called. Neither does using disposable objects of the IDisposable interface say what to expect when calling methods on a disposed object.
A:
In your question, you reference the IDisposable Guidelines. The first line says "Implementing the Dispose method is primarily for releasing unmanaged resources." I don't think that's what you're doing here. If BluetoothLEAdvertisementWatcher was IDisposable, then you could dispose of it in your Dispose() function; but that isn't the case. So, garbage collection will take care of your object in its sweet time after your object falls out of scope; just let it do its thing.
Hope that helps.
A:
It's totally fine to use IDisposable to free managed resources, which is really any kind of scope that requires code to be run at the end of that scope.
In this case, I would say that the scope is really around Start and Stop. So I would have Start return an IDisposable that calls Stop (and make Stop private). Your type would not be disposable. E.g., using Disposable from my Nito.Disposables library:
public sealed class BleScanner
{
public event AdvertisementReceivedHandler? AdvertisementReceived;
private readonly BluetoothLEAdvertisementWatcher m_Watcher;
public BleScanner() {
m_Watcher = new() {
// ...
};
// m_Watcher.Received += OnAdvertisementReceived;
}
public void Start()
{
m_Watcher.Start();
return Disposable.Create(() => Stop());
}
private void Stop() => m_Watcher.Stop();
}
public async Task ScannerTest(CancellationToken token) {
var scanner = new BleScanner();
scanner.AdvertisementReceived += OnAdvertisementReceived;
using var scannerSubsctiption = scanner.Start();
await Task.Delay(3000, token); // raise events for 3 seconds
}
|
Should I make sure an object is unusable after Dispose was called?
|
I have a class BleScanner that wraps an internal BluetoothLEAdvertisementWatcher. It also implements IDisposable to make sure that the watcher is stopped when the scanner gets disposed of.
public sealed class BleScanner : IDisposable
{
public event AdvertisementReceivedHandler? AdvertisementReceived;
private readonly BluetoothLEAdvertisementWatcher m_Watcher;
public BleScanner() {
m_Watcher = new() {
// ...
};
// m_Watcher.Received += OnAdvertisementReceived;
}
// private void OnAdvertisementReceived(...) {
// code elided for brevity
// may eventually raise AdvertisementReceived
// }
public void Start() => m_Watcher.Start();
public void Stop() => m_Watcher.Stop();
public void Dispose() {
if (m_Watcher.Status == BluetoothLEAdvertisementWatcherStatus.Started) {
m_Watcher.Stop();
}
}
}
The watcher is not disposable. So in theory, the scanner would still work if you just called Start again after Dispose:
public async Task ScannerTest(CancellationToken token) {
using var scanner = new BleScanner();
scanner.AdvertisementReceived += OnAdvertisementReceived;
scanner.Start(); // will start the scan
await Task.Delay(3000, token); // raise events for 3 seconds
scanner.Stop(); // could be forgotten
scanner.Dispose(); // will stop the scan if indeed it was forgotten
scanner.Start(); // everything will work, despite "scanner" being disposed already
}
Should I make sure Start (and maybe Stop) throws an ObjectDisposedException after Dispose was called? The guidelines on the Dispose pattern only require that Dispose can be called multiple times without an exception, but don't say anything about how the other members should behave after Dispose was called. Neither does using disposable objects of the IDisposable interface say what to expect when calling methods on a disposed object.
|
[
"In your question, you reference the IDisposable Guidelines. The first line says \"Implementing the Dispose method is primarily for releasing unmanaged resources.\" I don't think that's what you're doing here. If BluetoothLEAdvertisementWatcher was IDisposable, then you could dispose of it in your Dispose() function; but that isn't the case. So, garbage collection will take care of your object in its sweet time after your object falls out of scope; just let it do its thing.\nHope that helps.\n",
"It's totally fine to use IDisposable to free managed resources, which is really any kind of scope that requires code to be run at the end of that scope.\nIn this case, I would say that the scope is really around Start and Stop. So I would have Start return an IDisposable that calls Stop (and make Stop private). Your type would not be disposable. E.g., using Disposable from my Nito.Disposables library:\npublic sealed class BleScanner\n{\n public event AdvertisementReceivedHandler? AdvertisementReceived;\n\n private readonly BluetoothLEAdvertisementWatcher m_Watcher;\n\n public BleScanner() {\n m_Watcher = new() {\n // ...\n };\n // m_Watcher.Received += OnAdvertisementReceived;\n }\n\n public void Start()\n {\n m_Watcher.Start();\n return Disposable.Create(() => Stop());\n }\n\n private void Stop() => m_Watcher.Stop();\n}\n\npublic async Task ScannerTest(CancellationToken token) {\n var scanner = new BleScanner();\n scanner.AdvertisementReceived += OnAdvertisementReceived;\n\n using var scannerSubsctiption = scanner.Start();\n await Task.Delay(3000, token); // raise events for 3 seconds\n}\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"c#",
"idisposable"
] |
stackoverflow_0074660024_c#_idisposable.txt
|
Q:
Build simple programm with freetype lib on windows via cmake
I'm trying to build a simple application
using the freetype library on Windows 64.
Freetype lib was compiled from src on windows 64
simple programm
#include <ft2build.h>
#include FT_FREETYPE_H
int main (int argc, char** argv) {
FT_Library ft;
if (FT_Init_FreeType(&ft) != 0) {
//err
}
}
Added environment variable FREETYPE_DIR
and cmake script
cmake_minimum_required(VERSION 3.22)
cmake_path(CONVERT $ENV{COMPILER} TO_CMAKE_PATH_LIST COMPILER)
set(CMAKE_CXX_COMPILER "${COMPILER}/clang++.exe")
set(CMAKE_C_COMPILER "${COMPILER}/clang.exe")
set(CMAKE_RC_COMPILER "${COMPILER}/llvm-rc.exe")
set(CMAKE_BUILD_TYPE Release)
set(EXECUTABLE_OUTPUT_PATH "../bin")
project (text)
file(GLOB SRC
"./src/main.cpp"
)
find_package(Freetype MODULE REQUIRED)
add_executable (${PROJECT_NAME} ${SRC})
target_include_directories(${PROJECT_NAME}
PRIVATE "./include"
PRIVATE ${FREETYPE_INCLUDE_DIRS}
)
target_link_libraries(${PROJECT_NAME}
Freetype::Freetype
)
but I'm stuck, get a linker error, although freetype library is linked
ninja: Entering directory `./build'
[1/1] cmd.exe /C "cd . &&
C:\PROGRA~2\MICROS~2\2022\BUILDT~1\VC\Tools\Llvm\x64\bin\CLANG_~1.EXE -fuse-ld=lld-link
-nostartfiles -nostdlib -O3 -DNDEBUG -D_DLL -D_MT -Xclang --dependent-lib=msvcrt -
Xlinker /subsystem:console CMakeFiles/text.dir/src/main.cpp.obj -o
D:\git\cpp\opengl\drawtext\bin\text.exe -Xlinker /MANIFEST:EMBED -Xlinker
/implib:D:\git\cpp\opengl\drawtext\bin\text.lib -Xlinker
/pdb:D:\git\cpp\opengl\drawtext\bin\text.pdb -Xlinker /version:0.0 D:/source/freetype-
2.12.1/build/x86_64/Release/lib/freetype.lib -lkernel32 -luser32 -lgdi32 -lwinspool -
lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 -loldnames && cd ."
FAILED: D:/git/cpp/opengl/drawtext/bin/text.exe
cmd.exe /C "cd . &&
C:\PROGRA~2\MICROS~2\2022\BUILDT~1\VC\Tools\Llvm\x64\bin\CLANG_~1.EXE -fuse-ld=lld-link
-nostartfiles -nostdlib -O3 -DNDEBUG -D_DLL -D_MT -Xclang --dependent-lib=msvcrt -
Xlinker /subsystem:console CMakeFiles/text.dir/src/main.cpp.obj -o
D:\git\cpp\opengl\drawtext\bin\text.exe -Xlinker /MANIFEST:EMBED -Xlinker
/implib:D:\git\cpp\opengl\drawtext\bin\text.lib -Xlinker
/pdb:D:\git\cpp\opengl\drawtext\bin\text.pdb -Xlinker /version:0.0 D:/source/freetype-
2.12.1/build/x86_64/Release/lib/freetype.lib -lkernel32 -luser32 -lgdi32 -lwinspool -
lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 -loldnames && cd ."
lld-link: error: undefined symbol: FT_Init_FreeType
>>> referenced by CMakeFiles/text.dir/src/main.cpp.obj:(main)
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
A:
Find the workaround, recompile freetype lib via Microsoft cl.exe instead of clang.
|
Build simple programm with freetype lib on windows via cmake
|
I'm trying to build a simple application
using the freetype library on Windows 64.
Freetype lib was compiled from src on windows 64
simple programm
#include <ft2build.h>
#include FT_FREETYPE_H
int main (int argc, char** argv) {
FT_Library ft;
if (FT_Init_FreeType(&ft) != 0) {
//err
}
}
Added environment variable FREETYPE_DIR
and cmake script
cmake_minimum_required(VERSION 3.22)
cmake_path(CONVERT $ENV{COMPILER} TO_CMAKE_PATH_LIST COMPILER)
set(CMAKE_CXX_COMPILER "${COMPILER}/clang++.exe")
set(CMAKE_C_COMPILER "${COMPILER}/clang.exe")
set(CMAKE_RC_COMPILER "${COMPILER}/llvm-rc.exe")
set(CMAKE_BUILD_TYPE Release)
set(EXECUTABLE_OUTPUT_PATH "../bin")
project (text)
file(GLOB SRC
"./src/main.cpp"
)
find_package(Freetype MODULE REQUIRED)
add_executable (${PROJECT_NAME} ${SRC})
target_include_directories(${PROJECT_NAME}
PRIVATE "./include"
PRIVATE ${FREETYPE_INCLUDE_DIRS}
)
target_link_libraries(${PROJECT_NAME}
Freetype::Freetype
)
but I'm stuck, get a linker error, although freetype library is linked
ninja: Entering directory `./build'
[1/1] cmd.exe /C "cd . &&
C:\PROGRA~2\MICROS~2\2022\BUILDT~1\VC\Tools\Llvm\x64\bin\CLANG_~1.EXE -fuse-ld=lld-link
-nostartfiles -nostdlib -O3 -DNDEBUG -D_DLL -D_MT -Xclang --dependent-lib=msvcrt -
Xlinker /subsystem:console CMakeFiles/text.dir/src/main.cpp.obj -o
D:\git\cpp\opengl\drawtext\bin\text.exe -Xlinker /MANIFEST:EMBED -Xlinker
/implib:D:\git\cpp\opengl\drawtext\bin\text.lib -Xlinker
/pdb:D:\git\cpp\opengl\drawtext\bin\text.pdb -Xlinker /version:0.0 D:/source/freetype-
2.12.1/build/x86_64/Release/lib/freetype.lib -lkernel32 -luser32 -lgdi32 -lwinspool -
lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 -loldnames && cd ."
FAILED: D:/git/cpp/opengl/drawtext/bin/text.exe
cmd.exe /C "cd . &&
C:\PROGRA~2\MICROS~2\2022\BUILDT~1\VC\Tools\Llvm\x64\bin\CLANG_~1.EXE -fuse-ld=lld-link
-nostartfiles -nostdlib -O3 -DNDEBUG -D_DLL -D_MT -Xclang --dependent-lib=msvcrt -
Xlinker /subsystem:console CMakeFiles/text.dir/src/main.cpp.obj -o
D:\git\cpp\opengl\drawtext\bin\text.exe -Xlinker /MANIFEST:EMBED -Xlinker
/implib:D:\git\cpp\opengl\drawtext\bin\text.lib -Xlinker
/pdb:D:\git\cpp\opengl\drawtext\bin\text.pdb -Xlinker /version:0.0 D:/source/freetype-
2.12.1/build/x86_64/Release/lib/freetype.lib -lkernel32 -luser32 -lgdi32 -lwinspool -
lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 -loldnames && cd ."
lld-link: error: undefined symbol: FT_Init_FreeType
>>> referenced by CMakeFiles/text.dir/src/main.cpp.obj:(main)
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
|
[
"Find the workaround, recompile freetype lib via Microsoft cl.exe instead of clang.\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"cmake",
"freetype",
"windows"
] |
stackoverflow_0074664539_c++_cmake_freetype_windows.txt
|
Q:
React change css style of a div in another component by button clicking in another component
on my Project I have a banner on top of my site with 2 buttons. when I click the button profile I want it to change the css style of a div in another component.
this is my code for the banner:
import Profile from "./Profile";
function Banner() {
const invis=false;
return (
<div className="banner">
<span className="bannerbtnsettings">
<button className="btnbannersettings">Settings</button>
</span>
<span className="bannerbtnprofile">
<button className="btnbannerprofile" onClick={Profile.changeStyle}>Profile</button>
</span>
</div>
);
}
export default Banner;
this is my code for the div in the other component:
import "../index.css";
import React, { useState } from "react";
const Profile = () => {
const [style, setStyle] = useState("profile-hidden");
const changeStyle = () => {
console.log("you just clicked");
setStyle("profile-displayed");
};
return (
<div>
<div className={style}> hellllo</div>
</div>
);
};
export default Profile;
I can only find information about this with parent-child components.
They said I should use a usestate import but I can't seem to get it working. what's the proper way to do this?
A:
All you need is lift your state to parent component, if you have a long trip to your common ancestor you can try to use a context. Attached a working example. Hope it helps!
const Banner = ({ onClickHandler }) => {
return (
<div className="banner">
<span className="bannerbtnsettings">
<button className="btnbannersettings">Settings</button>
</span>
<span className="bannerbtnprofile">
<button className="btnbannerprofile" onClick={() => onClickHandler()}>Profile</button>
</span>
</div>
)}
const Profile = ({ style }) => {
return (
<div>
<div className={style}>I'm your profile :)</div>
</div>
);
};
const App = () => {
// We lift the state
const [style, setStyle] = React.useState("profile-hidden");
const profileHandler = () => {
setStyle(style === 'profile-hidden'
? 'profile-displayed'
: 'profile-hidden')
}
return(
<div>
<Banner onClickHandler={profileHandler} />
<Profile style={style} />
</div>
)
}
// Render
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
.profile-hidden {
display: none;
}
.profile-displayed {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
<div id="root"></div>
A:
You cannot use this syntax for React Components COMPONENT.method
, in your case onClick={Profile.changeStyle} !
Instead you should make Banner parent component and use Profile component as child inside it or vise versa !
then You should pass the state style as props so then you will be able to use its value.
your code should look like this :
function Banner() {
const [style, setStyle] = useState("profile-hidden");
const changeStyle = () => {
console.log("you just clicked");
setStyle("profile-displayed");
};
return (
<div className="banner">
<span className="bannerbtnsettings">
<button className="btnbannersettings">Settings</button>
</span>
<span className="bannerbtnprofile">
<button className="btnbannerprofile" onClick={changeStyle}>Profile</button>
</span>
<Profile style={style} />
</div>
);
}
export default Banner;
and your Profile component :
const Profile = (props) => {
return (
<div>
<div className={props.style}> hellllo</div>
</div>
)
}
|
React change css style of a div in another component by button clicking in another component
|
on my Project I have a banner on top of my site with 2 buttons. when I click the button profile I want it to change the css style of a div in another component.
this is my code for the banner:
import Profile from "./Profile";
function Banner() {
const invis=false;
return (
<div className="banner">
<span className="bannerbtnsettings">
<button className="btnbannersettings">Settings</button>
</span>
<span className="bannerbtnprofile">
<button className="btnbannerprofile" onClick={Profile.changeStyle}>Profile</button>
</span>
</div>
);
}
export default Banner;
this is my code for the div in the other component:
import "../index.css";
import React, { useState } from "react";
const Profile = () => {
const [style, setStyle] = useState("profile-hidden");
const changeStyle = () => {
console.log("you just clicked");
setStyle("profile-displayed");
};
return (
<div>
<div className={style}> hellllo</div>
</div>
);
};
export default Profile;
I can only find information about this with parent-child components.
They said I should use a usestate import but I can't seem to get it working. what's the proper way to do this?
|
[
"All you need is lift your state to parent component, if you have a long trip to your common ancestor you can try to use a context. Attached a working example. Hope it helps!\n\n\nconst Banner = ({ onClickHandler }) => {\n return (\n <div className=\"banner\">\n <span className=\"bannerbtnsettings\">\n <button className=\"btnbannersettings\">Settings</button>\n </span>\n\n <span className=\"bannerbtnprofile\">\n <button className=\"btnbannerprofile\" onClick={() => onClickHandler()}>Profile</button>\n </span>\n </div>\n)}\n\nconst Profile = ({ style }) => {\n \n return (\n <div>\n <div className={style}>I'm your profile :)</div>\n </div>\n );\n};\n\n\nconst App = () => {\n // We lift the state\n const [style, setStyle] = React.useState(\"profile-hidden\"); \n const profileHandler = () => {\n setStyle(style === 'profile-hidden' \n ? 'profile-displayed'\n : 'profile-hidden')\n }\n \n return(\n <div>\n <Banner onClickHandler={profileHandler} />\n <Profile style={style} />\n </div>\n )\n}\n\n\n\n// Render\nReactDOM.createRoot(\n document.getElementById(\"root\")\n).render(\n <App />\n);\n.profile-hidden {\n display: none;\n}\n\n.profile-displayed {\n display: block;\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js\"></script>\n<div id=\"root\"></div>\n\n\n\n",
"You cannot use this syntax for React Components COMPONENT.method\n, in your case onClick={Profile.changeStyle} !\nInstead you should make Banner parent component and use Profile component as child inside it or vise versa !\nthen You should pass the state style as props so then you will be able to use its value.\nyour code should look like this :\nfunction Banner() {\n\n const [style, setStyle] = useState(\"profile-hidden\");\n\n const changeStyle = () => {\n console.log(\"you just clicked\");\n \n setStyle(\"profile-displayed\");\n };\n \n return (\n <div className=\"banner\">\n <span className=\"bannerbtnsettings\">\n <button className=\"btnbannersettings\">Settings</button>\n </span>\n\n <span className=\"bannerbtnprofile\">\n <button className=\"btnbannerprofile\" onClick={changeStyle}>Profile</button>\n </span>\n\n <Profile style={style} />\n </div>\n );\n}\n\nexport default Banner;\n\nand your Profile component :\nconst Profile = (props) => {\n return (\n <div>\n <div className={props.style}> hellllo</div>\n </div>\n )\n}\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"jsx",
"reactjs"
] |
stackoverflow_0074666910_jsx_reactjs.txt
|
Q:
Fabric.js Sticky Note type text wrap
I am trying to make a sticky note type utility with the fabric canvas. It will help to be used as annotators.
I want the text to wrap by itself at the given rectangle's width.
Can someone update my fiddle work??
Suggestions are appreciated. Regards...
The following is the link to a part of my fiddle:
http://jsfiddle.net/U7E9q/5/
var canvas = new fabric.Canvas('fabric-canvas');
canvas.hoverCursor = 'pointer';
var text = new fabric.IText("Enter Text Here ",{
fontSize: 20,
top: 100,
left: 100,
backgroundColor: '#faa',
lockScalingX: true,
lockScalingY: true,
selectable: true
});
//alert(text.text);
var rect = new fabric.Rect({
text_field: text,
width: 200,
height: 50,
fill: '#faa',
rx: 10,
ry: 10,
top: 100,
left: 100
});
canvas.add(rect);
canvas.add(text);
canvas.on('object:moving', function (event){
canvas.renderAll();
});
createListenersKeyboard();
function createListenersKeyboard() {
document.onkeydown = onKeyDownHandler;
//document.onkeyup = onKeyUpHandler;
}
function onKeyDownHandler(event) {
//event.preventDefault();
var key;
if(window.event){
key = window.event.keyCode;
}
else{
key = event.keyCode;
}
switch(key){
//////////////
// Shortcuts
//////////////
// Copy (Ctrl+C)
case 67: // Ctrl+C
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
copy();
}
}
break;
// Delete (Ctrl+D)
case 127: // Ctrl+D
if(ableToShortcut()){
if(event.deleteKey){
delet();
}
}
break;
// Paste (Ctrl+V)
case 86: // Ctrl+V
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
paste();
}
}
break;
default:
// TODO
break;
}
}
function ableToShortcut(){
/*
TODO check all cases for this
if($("textarea").is(":focus")){
return false;
}
if($(":text").is(":focus")){
return false;
}
*/
return true;
}
function copy(){
if(canvas.getActiveGroup()){
for(var i in canvas.getActiveGroup().objects){
var object = fabric.util.object.clone(canvas.getActiveGroup().objects[i]);
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObjects[i] = object;
}
}
else if(canvas.getActiveObject()){
var object = fabric.util.object.clone(canvas.getActiveObject());
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObject = object;
copiedObjects = new Array();
}
}
function paste(){
if(copiedObjects.length > 0){
for(var i in copiedObjects){
canvas.add(copiedObjects[i]);
}
}
else if(copiedObject){
canvas.add(copiedObject);
}
canvas.renderAll();
}
function delet(){
var activeObject = canvas.getActiveObject();
canvas.remove(activeObject);
console.log('after remove getActiveObject(): ', canvas.getActiveObject(), activeObject === canvas.getActiveObject());
canvas.renderAll();
}
A:
If you manage the sticky note as a grouped rect and text you can improve the same behavior. When you need to edit the text inside the group, you just ungroup and clone the elements, append the cloned elements to the canvas and set text as editable.
You need to handle an event like double click to handle this behavior and then handle the mousedown or other interactivity with canvas to regroup them.
A:
http://jsfiddle.net/4HE3U/1/
Above is one fiddle that can satisfy you
Basically i have made one group of Text and Rectangle and i have added it to canvas. There is only one change you need to make is that you can take one textbox to get current sticky note text content as we can not edit text of i-text online once we are adding it any group. Currently there is no way for IText to handle the events as they are not handed down to it if it's contained in a group. I think this is also the prefered way to handle that as it would confuse the user - what if he starts to edit multiple texts. This might end up in a mess. Maybe you can rework your script a little to workaround this problems.
I have added Text and Rectangle
var canvas = new fabric.Canvas('fabric-canvas');
canvas.hoverCursor = 'pointer';
var text = new fabric.IText("Enter Text Here ",{
fontSize: 20,
top: 100,
left: 100,
backgroundColor: '#faa',
lockScalingX: true,
lockScalingY: true,
selectable: true
});
//alert(text.text);
var rect = new fabric.Rect({
text_field: text,
width: 200,
height: 50,
fill: '#faa',
rx: 10,
ry: 10,
top: 100,
left: 100
});
var group = new fabric.Group([ rect, text ], {
left: 100,
top: 100,
lockScalingX: true,
lockScalingY: true,
hasRotatingPoint: false,
transparentCorners: false,
cornerSize: 7
});
canvas.add(group);
//canvas.add(text);
canvas.on('object:moving', function (event){
canvas.renderAll();
});
createListenersKeyboard();
function createListenersKeyboard() {
document.onkeydown = onKeyDownHandler;
//document.onkeyup = onKeyUpHandler;
}
function onKeyDownHandler(event) {
//event.preventDefault();
var key;
if(window.event){
key = window.event.keyCode;
}
else{
key = event.keyCode;
}
switch(key){
//////////////
// Shortcuts
//////////////
// Copy (Ctrl+C)
case 67: // Ctrl+C
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
copy();
}
}
break;
// Delete (Ctrl+D)
case 127: // Ctrl+D
if(ableToShortcut()){
if(event.deleteKey){
delet();
}
}
break;
// Paste (Ctrl+V)
case 86: // Ctrl+V
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
paste();
}
}
break;
default:
// TODO
break;
}
}
function ableToShortcut(){
/*
TODO check all cases for this
if($("textarea").is(":focus")){
return false;
}
if($(":text").is(":focus")){
return false;
}
*/
return true;
}
function copy(){
if(canvas.getActiveGroup()){
for(var i in canvas.getActiveGroup().objects){
var object = fabric.util.object.clone(canvas.getActiveGroup().objects[i]);
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObjects[i] = object;
}
}
else if(canvas.getActiveObject()){
var object = fabric.util.object.clone(canvas.getActiveObject());
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObject = object;
copiedObjects = new Array();
}
}
function paste(){
if(copiedObjects.length > 0){
for(var i in copiedObjects){
canvas.add(copiedObjects[i]);
}
}
else if(copiedObject){
canvas.add(copiedObject);
}
canvas.renderAll();
}
function delet(){
var activeObject = canvas.getActiveObject();
canvas.remove(activeObject);
console.log('after remove getActiveObject(): ', canvas.getActiveObject(), activeObject === canvas.getActiveObject());
canvas.renderAll();
}
<canvas id="fabric-canvas" width="400" height="400"></canvas>
A:
Here is Sticky note functionality. Text wrap working and font size changes w.r.t sticky note width and height. Editing mode activates on double click.
export const createStickyNotes = (canvas, options) => {
fabric.StickyNote = fabric.util.createClass(fabric.Group, {
type: "StickyNote",
initialize: function (options) {
this.set(options);
var height = this.height;
var width = this.width;
this.rectObj = new fabric.Rect({
width: width,
height: height,
fill: this.rectObj?.fill ?? "rgba(251,201,112,1)",
originX: "center",
originY: "center",
objectCaching: false,
stateProperties: ["fill"],
});
this.textObj = new fabric.Textbox(this.textObj?.text ?? "Notes", {
originX: "center",
originY: "center",
textAlign: "center",
width: 100,
hasControls: false,
fontSize: this.textObj?.fontSize ?? 30,
lineHeight: 1,
stateProperties: ["text", "fontSize"],
scaleX: this.textObj?.scaleX ?? 1,
scaleY: this.textObj?.scaleY ?? 1,
objectCaching: false,
breakWords: true,
fontFamily: "Open Sans",
});
this._objects = [this.rectObj, this.textObj];
// this custom _set function will set custom properties value to object when it will load from json.
// at that time loadFromJson function will call this initialize function.
// this._setCustomProperties(this.options);
canvas.renderAll();
//evenet will fire if the object is double clicked by mouse
this.on("mousedblclick", (e) => {
var pasteFlag = false;
var scaling = e.target.getScaledWidth() / 100;
var textForEditing;
canvas.bringToFront(e.target);
e.target.selectable = false;
const [rectObj, textObj] = this.getObjects();
textObj.clone(function (clonedObj) {
clonedObj.set({
left: e.target.left,
top: e.target.top,
lockMovementY: true,
lockMovementX: true,
hasBorders: false,
scaleX: scaling,
scaleY: scaling,
breakWords: true,
width: textObj.width,
stateProperties: [],
});
textForEditing = clonedObj;
});
this.remove(textObj);
canvas.add(textForEditing);
canvas.setActiveObject(textForEditing);
textForEditing.enterEditing();
textForEditing.selectAll();
textForEditing.paste = (function (paste) {
return function (e) {
disableScrolling();
pasteFlag = true;
};
})(textForEditing.paste);
textForEditing.on("changed", function (e) {
var fontSize = textForEditing.fontSize;
var charCount = Math.max(textForEditing._text.length, 1);
var charWR =
(textForEditing.textLines.length * width) / (charCount * fontSize);
if (textForEditing.height < height - 15) {
fontSize = Math.min(
Math.sqrt(
((height - 10 - fontSize) / 1.16) *
(width / (charCount * charWR))
),
30
);
}
if (textForEditing.height > height - 15) {
fontSize = Math.sqrt(
((height - 10) / 1.16) * (width / (charCount * charWR))
);
}
if (pasteFlag) {
pasteFlag = false;
while (
textForEditing.height > height - 15 &&
textForEditing.fontSize > 0
) {
fontSize = textForEditing.fontSize -= 0.2;
canvas.renderAll();
}
}
textForEditing.fontSize = fontSize;
});
textForEditing.on("editing:exited", () => {
enableScrolling();
canvas.setActiveObject(textObj);
textObj.set({
text: textForEditing.text,
fontSize: textForEditing.fontSize,
visible: true,
});
this.add(textObj);
this.selectable = true;
canvas.remove(textForEditing);
canvas.discardActiveObject();
});
});
function disableScrolling() {
var x = window.scrollX;
var y = window.scrollY;
window.onscroll = function () {
window.scrollTo(x, y);
};
}
var _wrapLine = function (_line, lineIndex, desiredWidth, reservedSpace) {
var lineWidth = 0,
splitByGrapheme = this.splitByGrapheme,
graphemeLines = [],
line = [],
// spaces in different languges?
words = splitByGrapheme
? fabric.util.string.graphemeSplit(_line)
: _line.split(this._wordJoiners),
word = "",
offset = 0,
infix = splitByGrapheme ? "" : " ",
wordWidth = 0,
infixWidth = 0,
largestWordWidth = 0,
lineJustStarted = true,
additionalSpace = splitByGrapheme ? 0 : this._getWidthOfCharSpacing();
reservedSpace = reservedSpace || 0;
desiredWidth -= reservedSpace;
for (var i = 0; i < words.length; i++) {
// i would avoid resplitting the graphemes
word = fabric.util.string.graphemeSplit(words[i]);
wordWidth = this._measureWord(word, lineIndex, offset);
offset += word.length;
// Break the line if a word is wider than the set width
if (this.breakWords && wordWidth >= desiredWidth) {
if (!lineJustStarted) {
graphemeLines.push(line);
line = [];
lineWidth = 0;
lineJustStarted = true;
}
this.fontSize *= desiredWidth / (wordWidth + 1);
// Loop through each character in word
for (var w = 0; w < word.length; w++) {
var letter = word[w];
var letterWidth =
(this.getMeasuringContext().measureText(letter).width *
this.fontSize) /
this.CACHE_FONT_SIZE;
line.push(letter);
lineWidth += letterWidth;
}
word = [];
} else {
lineWidth += infixWidth + wordWidth - additionalSpace;
}
if (lineWidth >= desiredWidth && !lineJustStarted) {
graphemeLines.push(line);
line = [];
lineWidth = wordWidth;
lineJustStarted = true;
} else {
lineWidth += additionalSpace;
}
if (!lineJustStarted) {
line.push(infix);
}
line = line.concat(word);
infixWidth = this._measureWord([infix], lineIndex, offset);
offset++;
lineJustStarted = false;
// keep track of largest word
if (wordWidth > largestWordWidth && !this.breakWords) {
largestWordWidth = wordWidth;
}
}
i && graphemeLines.push(line);
if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {
this.dynamicMinWidth =
largestWordWidth - additionalSpace + reservedSpace;
}
return graphemeLines;
};
fabric.util.object.extend(fabric.Textbox.prototype, {
_wrapLine: _wrapLine,
});
function enableScrolling() {
window.onscroll = function () {};
}
},
toObject: function (propertiesToInclude) {
// This function is used for serialize this object. (used for create json)
// not inlclude this.textObj and this.rectObj into json because when object will load from json, init fucntion of this class is called and it will assign this two object textObj and rectObj again.
var obj = this.callSuper(
"toObject",
[
"objectCaching",
"textObj",
"rectObj",
// ... property list that you want to add into json when this object is convert into json using toJSON() function. (serialize)
].concat(propertiesToInclude)
);
// delete objects array from json because then object load from json, Init function will call. which will automatically re-assign object and assign _object array.
delete obj.objects;
return obj;
},
});
fabric.StickyNote.async = true;
fabric.StickyNote.fromObject = function (object, callback) {
// This function is used for deserialize json and convert object json into button object again. (called when we call loadFromJson() fucntion on canvas)
return fabric.Object._fromObject("StickyNote", object, callback);
};
return new fabric.StickyNote(options);
};
//How to use
var options = {
width: 100,
height: 100,
originX: "center",
originY: "center",
};
var notes = StickyNotes(canvas, options);
canvas.add(notes);
|
Fabric.js Sticky Note type text wrap
|
I am trying to make a sticky note type utility with the fabric canvas. It will help to be used as annotators.
I want the text to wrap by itself at the given rectangle's width.
Can someone update my fiddle work??
Suggestions are appreciated. Regards...
The following is the link to a part of my fiddle:
http://jsfiddle.net/U7E9q/5/
var canvas = new fabric.Canvas('fabric-canvas');
canvas.hoverCursor = 'pointer';
var text = new fabric.IText("Enter Text Here ",{
fontSize: 20,
top: 100,
left: 100,
backgroundColor: '#faa',
lockScalingX: true,
lockScalingY: true,
selectable: true
});
//alert(text.text);
var rect = new fabric.Rect({
text_field: text,
width: 200,
height: 50,
fill: '#faa',
rx: 10,
ry: 10,
top: 100,
left: 100
});
canvas.add(rect);
canvas.add(text);
canvas.on('object:moving', function (event){
canvas.renderAll();
});
createListenersKeyboard();
function createListenersKeyboard() {
document.onkeydown = onKeyDownHandler;
//document.onkeyup = onKeyUpHandler;
}
function onKeyDownHandler(event) {
//event.preventDefault();
var key;
if(window.event){
key = window.event.keyCode;
}
else{
key = event.keyCode;
}
switch(key){
//////////////
// Shortcuts
//////////////
// Copy (Ctrl+C)
case 67: // Ctrl+C
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
copy();
}
}
break;
// Delete (Ctrl+D)
case 127: // Ctrl+D
if(ableToShortcut()){
if(event.deleteKey){
delet();
}
}
break;
// Paste (Ctrl+V)
case 86: // Ctrl+V
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
paste();
}
}
break;
default:
// TODO
break;
}
}
function ableToShortcut(){
/*
TODO check all cases for this
if($("textarea").is(":focus")){
return false;
}
if($(":text").is(":focus")){
return false;
}
*/
return true;
}
function copy(){
if(canvas.getActiveGroup()){
for(var i in canvas.getActiveGroup().objects){
var object = fabric.util.object.clone(canvas.getActiveGroup().objects[i]);
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObjects[i] = object;
}
}
else if(canvas.getActiveObject()){
var object = fabric.util.object.clone(canvas.getActiveObject());
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObject = object;
copiedObjects = new Array();
}
}
function paste(){
if(copiedObjects.length > 0){
for(var i in copiedObjects){
canvas.add(copiedObjects[i]);
}
}
else if(copiedObject){
canvas.add(copiedObject);
}
canvas.renderAll();
}
function delet(){
var activeObject = canvas.getActiveObject();
canvas.remove(activeObject);
console.log('after remove getActiveObject(): ', canvas.getActiveObject(), activeObject === canvas.getActiveObject());
canvas.renderAll();
}
|
[
"If you manage the sticky note as a grouped rect and text you can improve the same behavior. When you need to edit the text inside the group, you just ungroup and clone the elements, append the cloned elements to the canvas and set text as editable. \nYou need to handle an event like double click to handle this behavior and then handle the mousedown or other interactivity with canvas to regroup them. \n",
"http://jsfiddle.net/4HE3U/1/\nAbove is one fiddle that can satisfy you\nBasically i have made one group of Text and Rectangle and i have added it to canvas. There is only one change you need to make is that you can take one textbox to get current sticky note text content as we can not edit text of i-text online once we are adding it any group. Currently there is no way for IText to handle the events as they are not handed down to it if it's contained in a group. I think this is also the prefered way to handle that as it would confuse the user - what if he starts to edit multiple texts. This might end up in a mess. Maybe you can rework your script a little to workaround this problems.\nI have added Text and Rectangle \n\n\n\nvar canvas = new fabric.Canvas('fabric-canvas');\r\n\r\ncanvas.hoverCursor = 'pointer';\r\n\r\nvar text = new fabric.IText(\"Enter Text Here \",{\r\n fontSize: 20,\r\n top: 100,\r\n left: 100,\r\n backgroundColor: '#faa',\r\n lockScalingX: true,\r\n lockScalingY: true,\r\n selectable: true\r\n});\r\n//alert(text.text);\r\n var rect = new fabric.Rect({\r\n text_field: text,\r\n width: 200,\r\n height: 50,\r\n fill: '#faa',\r\n rx: 10,\r\n ry: 10,\r\n top: 100,\r\n left: 100\r\n });\r\n\r\n\r\nvar group = new fabric.Group([ rect, text ], {\r\n left: 100,\r\n top: 100,\r\n lockScalingX: true,\r\n lockScalingY: true,\r\n hasRotatingPoint: false,\r\n transparentCorners: false,\r\n cornerSize: 7\r\n});\r\n\r\n canvas.add(group);\r\n //canvas.add(text);\r\n\r\ncanvas.on('object:moving', function (event){\r\n canvas.renderAll(); \r\n});\r\n\r\ncreateListenersKeyboard();\r\n\r\nfunction createListenersKeyboard() {\r\n document.onkeydown = onKeyDownHandler;\r\n //document.onkeyup = onKeyUpHandler;\r\n}\r\n\r\nfunction onKeyDownHandler(event) {\r\n //event.preventDefault();\r\n \r\n var key;\r\n if(window.event){\r\n key = window.event.keyCode;\r\n }\r\n else{\r\n key = event.keyCode;\r\n }\r\n \r\n switch(key){\r\n //////////////\r\n // Shortcuts\r\n //////////////\r\n // Copy (Ctrl+C)\r\n case 67: // Ctrl+C\r\n if(ableToShortcut()){\r\n if(event.ctrlKey){\r\n event.preventDefault();\r\n copy();\r\n }\r\n }\r\n break;\r\n // Delete (Ctrl+D)\r\n case 127: // Ctrl+D\r\n if(ableToShortcut()){\r\n if(event.deleteKey){\r\n delet();\r\n }\r\n }\r\n break; \r\n // Paste (Ctrl+V)\r\n case 86: // Ctrl+V\r\n if(ableToShortcut()){\r\n if(event.ctrlKey){\r\n event.preventDefault();\r\n paste();\r\n }\r\n }\r\n break; \r\n default:\r\n // TODO\r\n break;\r\n }\r\n}\r\n\r\n\r\nfunction ableToShortcut(){\r\n /*\r\n TODO check all cases for this\r\n \r\n if($(\"textarea\").is(\":focus\")){\r\n return false;\r\n }\r\n if($(\":text\").is(\":focus\")){\r\n return false;\r\n }\r\n */\r\n return true;\r\n}\r\n\r\nfunction copy(){\r\n if(canvas.getActiveGroup()){\r\n for(var i in canvas.getActiveGroup().objects){\r\n var object = fabric.util.object.clone(canvas.getActiveGroup().objects[i]);\r\n object.set(\"top\", object.top+5);\r\n object.set(\"left\", object.left+5);\r\n copiedObjects[i] = object;\r\n } \r\n }\r\n else if(canvas.getActiveObject()){\r\n var object = fabric.util.object.clone(canvas.getActiveObject());\r\n object.set(\"top\", object.top+5);\r\n object.set(\"left\", object.left+5);\r\n copiedObject = object;\r\n copiedObjects = new Array();\r\n }\r\n}\r\n\r\nfunction paste(){\r\n if(copiedObjects.length > 0){\r\n for(var i in copiedObjects){\r\n canvas.add(copiedObjects[i]);\r\n } \r\n }\r\n else if(copiedObject){\r\n canvas.add(copiedObject);\r\n }\r\n canvas.renderAll(); \r\n}\r\n\r\nfunction delet(){\r\n var activeObject = canvas.getActiveObject();\r\n canvas.remove(activeObject);\r\n console.log('after remove getActiveObject(): ', canvas.getActiveObject(), activeObject === canvas.getActiveObject());\r\n canvas.renderAll(); \r\n}\n<canvas id=\"fabric-canvas\" width=\"400\" height=\"400\"></canvas>\n\n\n\n",
"Here is Sticky note functionality. Text wrap working and font size changes w.r.t sticky note width and height. Editing mode activates on double click.\n\n\nexport const createStickyNotes = (canvas, options) => {\n fabric.StickyNote = fabric.util.createClass(fabric.Group, {\n type: \"StickyNote\",\n initialize: function (options) {\n this.set(options);\n var height = this.height;\n var width = this.width;\n\n this.rectObj = new fabric.Rect({\n width: width,\n height: height,\n fill: this.rectObj?.fill ?? \"rgba(251,201,112,1)\",\n originX: \"center\",\n originY: \"center\",\n objectCaching: false,\n stateProperties: [\"fill\"],\n });\n this.textObj = new fabric.Textbox(this.textObj?.text ?? \"Notes\", {\n originX: \"center\",\n originY: \"center\",\n textAlign: \"center\",\n width: 100,\n hasControls: false,\n fontSize: this.textObj?.fontSize ?? 30,\n lineHeight: 1,\n stateProperties: [\"text\", \"fontSize\"],\n scaleX: this.textObj?.scaleX ?? 1,\n scaleY: this.textObj?.scaleY ?? 1,\n objectCaching: false,\n breakWords: true,\n fontFamily: \"Open Sans\",\n });\n\n this._objects = [this.rectObj, this.textObj];\n // this custom _set function will set custom properties value to object when it will load from json.\n // at that time loadFromJson function will call this initialize function.\n // this._setCustomProperties(this.options);\n canvas.renderAll();\n\n //evenet will fire if the object is double clicked by mouse\n this.on(\"mousedblclick\", (e) => {\n var pasteFlag = false;\n var scaling = e.target.getScaledWidth() / 100;\n var textForEditing;\n canvas.bringToFront(e.target);\n e.target.selectable = false;\n const [rectObj, textObj] = this.getObjects();\n textObj.clone(function (clonedObj) {\n clonedObj.set({\n left: e.target.left,\n top: e.target.top,\n lockMovementY: true,\n lockMovementX: true,\n hasBorders: false,\n scaleX: scaling,\n scaleY: scaling,\n breakWords: true,\n width: textObj.width,\n stateProperties: [],\n });\n textForEditing = clonedObj;\n });\n\n this.remove(textObj);\n canvas.add(textForEditing);\n canvas.setActiveObject(textForEditing);\n\n textForEditing.enterEditing();\n textForEditing.selectAll();\n\n textForEditing.paste = (function (paste) {\n return function (e) {\n disableScrolling();\n pasteFlag = true;\n };\n })(textForEditing.paste);\n\n textForEditing.on(\"changed\", function (e) {\n var fontSize = textForEditing.fontSize;\n var charCount = Math.max(textForEditing._text.length, 1);\n var charWR =\n (textForEditing.textLines.length * width) / (charCount * fontSize);\n\n if (textForEditing.height < height - 15) {\n fontSize = Math.min(\n Math.sqrt(\n ((height - 10 - fontSize) / 1.16) *\n (width / (charCount * charWR))\n ),\n 30\n );\n }\n if (textForEditing.height > height - 15) {\n fontSize = Math.sqrt(\n ((height - 10) / 1.16) * (width / (charCount * charWR))\n );\n }\n if (pasteFlag) {\n pasteFlag = false;\n while (\n textForEditing.height > height - 15 &&\n textForEditing.fontSize > 0\n ) {\n fontSize = textForEditing.fontSize -= 0.2;\n canvas.renderAll();\n }\n }\n textForEditing.fontSize = fontSize;\n });\n\n textForEditing.on(\"editing:exited\", () => {\n enableScrolling();\n canvas.setActiveObject(textObj);\n textObj.set({\n text: textForEditing.text,\n fontSize: textForEditing.fontSize,\n visible: true,\n });\n this.add(textObj);\n this.selectable = true;\n canvas.remove(textForEditing);\n canvas.discardActiveObject();\n });\n });\n\n function disableScrolling() {\n var x = window.scrollX;\n var y = window.scrollY;\n window.onscroll = function () {\n window.scrollTo(x, y);\n };\n }\n\n var _wrapLine = function (_line, lineIndex, desiredWidth, reservedSpace) {\n var lineWidth = 0,\n splitByGrapheme = this.splitByGrapheme,\n graphemeLines = [],\n line = [],\n // spaces in different languges?\n words = splitByGrapheme\n ? fabric.util.string.graphemeSplit(_line)\n : _line.split(this._wordJoiners),\n word = \"\",\n offset = 0,\n infix = splitByGrapheme ? \"\" : \" \",\n wordWidth = 0,\n infixWidth = 0,\n largestWordWidth = 0,\n lineJustStarted = true,\n additionalSpace = splitByGrapheme ? 0 : this._getWidthOfCharSpacing();\n\n reservedSpace = reservedSpace || 0;\n desiredWidth -= reservedSpace;\n for (var i = 0; i < words.length; i++) {\n // i would avoid resplitting the graphemes\n word = fabric.util.string.graphemeSplit(words[i]);\n wordWidth = this._measureWord(word, lineIndex, offset);\n offset += word.length;\n\n // Break the line if a word is wider than the set width\n if (this.breakWords && wordWidth >= desiredWidth) {\n if (!lineJustStarted) {\n graphemeLines.push(line);\n line = [];\n lineWidth = 0;\n lineJustStarted = true;\n }\n this.fontSize *= desiredWidth / (wordWidth + 1);\n // Loop through each character in word\n for (var w = 0; w < word.length; w++) {\n var letter = word[w];\n var letterWidth =\n (this.getMeasuringContext().measureText(letter).width *\n this.fontSize) /\n this.CACHE_FONT_SIZE;\n line.push(letter);\n lineWidth += letterWidth;\n }\n word = [];\n } else {\n lineWidth += infixWidth + wordWidth - additionalSpace;\n }\n\n if (lineWidth >= desiredWidth && !lineJustStarted) {\n graphemeLines.push(line);\n line = [];\n lineWidth = wordWidth;\n lineJustStarted = true;\n } else {\n lineWidth += additionalSpace;\n }\n\n if (!lineJustStarted) {\n line.push(infix);\n }\n line = line.concat(word);\n\n infixWidth = this._measureWord([infix], lineIndex, offset);\n offset++;\n lineJustStarted = false;\n // keep track of largest word\n if (wordWidth > largestWordWidth && !this.breakWords) {\n largestWordWidth = wordWidth;\n }\n }\n\n i && graphemeLines.push(line);\n\n if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {\n this.dynamicMinWidth =\n largestWordWidth - additionalSpace + reservedSpace;\n }\n\n return graphemeLines;\n };\n\n fabric.util.object.extend(fabric.Textbox.prototype, {\n _wrapLine: _wrapLine,\n });\n\n function enableScrolling() {\n window.onscroll = function () {};\n }\n },\n\n toObject: function (propertiesToInclude) {\n // This function is used for serialize this object. (used for create json)\n // not inlclude this.textObj and this.rectObj into json because when object will load from json, init fucntion of this class is called and it will assign this two object textObj and rectObj again.\n var obj = this.callSuper(\n \"toObject\",\n [\n \"objectCaching\",\n \"textObj\",\n \"rectObj\",\n // ... property list that you want to add into json when this object is convert into json using toJSON() function. (serialize)\n ].concat(propertiesToInclude)\n );\n // delete objects array from json because then object load from json, Init function will call. which will automatically re-assign object and assign _object array.\n delete obj.objects;\n return obj;\n },\n });\n\n fabric.StickyNote.async = true;\n fabric.StickyNote.fromObject = function (object, callback) {\n // This function is used for deserialize json and convert object json into button object again. (called when we call loadFromJson() fucntion on canvas)\n return fabric.Object._fromObject(\"StickyNote\", object, callback);\n };\n\n return new fabric.StickyNote(options);\n};\n\n\n\n\n\n//How to use \n\n\n var options = {\n width: 100,\n height: 100,\n originX: \"center\",\n originY: \"center\",\n };\n var notes = StickyNotes(canvas, options);\n canvas.add(notes);\n\n\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"css",
"fabricjs",
"html",
"javascript",
"jquery"
] |
stackoverflow_0024759238_css_fabricjs_html_javascript_jquery.txt
|
Q:
AttributeError in terminal
Please help
class ScrollingCredits:
def __init__(self):
self.load_credits('assignment.txt')
(self.background, self.background_rect) = \
load_image('starfield.gif', True)
self.font = pygame.font.Font(None, FONT_SIZE)
self.scroll_speed = SCROLL_SPEED
self.scroll_pause = SCROLL_PAUSE
self.end_wait = END_WAIT
self.reset()
def load_credits(self, filename):
f = open(filename)
credits = []
while 1:
line = f.readline()
if not line:
break
line = string.rstrip(line)
credits.append(line)
f.close()
self.lines = credits
I am getting the error below
line 66, in __init__
self.load_credits('assignment.txt')
AttributeError: 'ScrollingCredits' object has no attribute 'load_credits'
Im wondering if it may be the assignment.txt but im not 100% i googled it but I cannot seem to find a solution help would be much appreciated
A:
As Wondercricket's comment suggests, you should decrease the indention of load_credits. The correct code is:
class ScrollingCredits:
def __init__(self):
self.load_credits('assignment.txt')
(self.background, self.background_rect) = \
load_image('starfield.gif', True)
self.font = pygame.font.Font(None, FONT_SIZE)
self.scroll_speed = SCROLL_SPEED
self.scroll_pause = SCROLL_PAUSE
self.end_wait = END_WAIT
self.reset()
def load_credits(self, filename):
f = open(filename)
credits = []
while 1:
line = f.readline()
if not line:
break
line = string.rstrip(line)
credits.append(line)
f.close()
self.lines = credits
|
AttributeError in terminal
|
Please help
class ScrollingCredits:
def __init__(self):
self.load_credits('assignment.txt')
(self.background, self.background_rect) = \
load_image('starfield.gif', True)
self.font = pygame.font.Font(None, FONT_SIZE)
self.scroll_speed = SCROLL_SPEED
self.scroll_pause = SCROLL_PAUSE
self.end_wait = END_WAIT
self.reset()
def load_credits(self, filename):
f = open(filename)
credits = []
while 1:
line = f.readline()
if not line:
break
line = string.rstrip(line)
credits.append(line)
f.close()
self.lines = credits
I am getting the error below
line 66, in __init__
self.load_credits('assignment.txt')
AttributeError: 'ScrollingCredits' object has no attribute 'load_credits'
Im wondering if it may be the assignment.txt but im not 100% i googled it but I cannot seem to find a solution help would be much appreciated
|
[
"As Wondercricket's comment suggests, you should decrease the indention of load_credits. The correct code is:\nclass ScrollingCredits:\n\n def __init__(self):\n\n self.load_credits('assignment.txt')\n\n (self.background, self.background_rect) = \\\n load_image('starfield.gif', True)\n\n self.font = pygame.font.Font(None, FONT_SIZE)\n\n self.scroll_speed = SCROLL_SPEED\n\n self.scroll_pause = SCROLL_PAUSE\n\n self.end_wait = END_WAIT\n\n self.reset()\n\n def load_credits(self, filename):\n\n f = open(filename)\n\n credits = []\n\n while 1:\n\n line = f.readline()\n\n if not line:\n\n break\n\n line = string.rstrip(line)\n\n credits.append(line)\n\n f.close()\n\n self.lines = credits\n\n"
] |
[
0
] |
[] |
[] |
[
"python_3.x"
] |
stackoverflow_0074660797_python_3.x.txt
|
Q:
Javascript test client side for HTTP Client Hints support
Is it possible to detect if a browser supports HTTP Client Hints using javascript? Right now only chrome appears to support it: http://caniuse.com/#feat=client-hints-dpr-width-viewport
So I was thinking of using some javascript library that can do browser and version detection and if the browser is chrome and version 49 or later than I could assume the feature was supported.
I'm just thinking this solution isn't very efficient or smart considering functionality for HTTP Client Hints will most likely be added to more browsers in the future and then I would have to continually update my function to reflect that.
Is there some simple way to just test if a given browser supports HTTP Client Hints with client side javascript?
Thanks!
A:
Sadly it appears the only way to detect if a browser supports this feature is by checking the make and model of the browser... Something like this...
function canDoClientHint() {
try {
var chrome = window.navigator.userAgent.match(/\sChrome\/([0-9]+)\.[.0-9]+\s/)
if ( chrome !== null ) {
var version = parseInt(chrome[1])
if ( isNaN(version) === false && version >= 46 ) {
return true
}
}
} catch(e) {
return false
}
return false
}
canDoClientHint()
Obviously this kind of code becomes outdated and requires constant maintenance until all the browsers you care have the feature generally available and then you can remove it. Unfortunately you have to remember to update it and remove it.
A:
This question is old (2017) and a lot has changed wrt Client-Hints. The most important thing is that one can no longer sit passively and expect to receive client-hints in the HTTP header. Now there's a rather complex HTTPS dance in which web servers need to be configured to actively request Client-Hints and cross their fingers that clients honor their demand. I know because my company operates in the field of device/browser data based on HTTP request analysis (WURFL) .
Specific information about how to request Client-Hints from web browsers is available here: https://www.scientiamobile.com/add-support-for-user-agent-client-hints-now/
|
Javascript test client side for HTTP Client Hints support
|
Is it possible to detect if a browser supports HTTP Client Hints using javascript? Right now only chrome appears to support it: http://caniuse.com/#feat=client-hints-dpr-width-viewport
So I was thinking of using some javascript library that can do browser and version detection and if the browser is chrome and version 49 or later than I could assume the feature was supported.
I'm just thinking this solution isn't very efficient or smart considering functionality for HTTP Client Hints will most likely be added to more browsers in the future and then I would have to continually update my function to reflect that.
Is there some simple way to just test if a given browser supports HTTP Client Hints with client side javascript?
Thanks!
|
[
"Sadly it appears the only way to detect if a browser supports this feature is by checking the make and model of the browser... Something like this...\nfunction canDoClientHint() {\n try {\n var chrome = window.navigator.userAgent.match(/\\sChrome\\/([0-9]+)\\.[.0-9]+\\s/)\n if ( chrome !== null ) {\n var version = parseInt(chrome[1])\n if ( isNaN(version) === false && version >= 46 ) {\n return true\n }\n }\n } catch(e) {\n return false\n }\n return false\n}\ncanDoClientHint()\n\nObviously this kind of code becomes outdated and requires constant maintenance until all the browsers you care have the feature generally available and then you can remove it. Unfortunately you have to remember to update it and remove it. \n",
"This question is old (2017) and a lot has changed wrt Client-Hints. The most important thing is that one can no longer sit passively and expect to receive client-hints in the HTTP header. Now there's a rather complex HTTPS dance in which web servers need to be configured to actively request Client-Hints and cross their fingers that clients honor their demand. I know because my company operates in the field of device/browser data based on HTTP request analysis (WURFL) .\nSpecific information about how to request Client-Hints from web browsers is available here: https://www.scientiamobile.com/add-support-for-user-agent-client-hints-now/\n"
] |
[
0,
0
] |
[] |
[] |
[
"client_hints",
"html",
"javascript"
] |
stackoverflow_0039261925_client_hints_html_javascript.txt
|
Q:
Open and Parse Dynamic XFA (XML Form Architecture) PDF with Python
I would like to parse some text or any data from this pdf with Python. Everything I have tried is not working.
I have a tried a variety of approaches:
# importing required modules
import PyPDF2
# creating a pdf file object
pdfFileObj = open('example.pdf', 'rb')
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# printing number of pages in pdf file
print(pdfReader.numPages)
# creating a page object
pageObj = pdfReader.getPage(0)
# extracting text from page
print(pageObj.extractText())
# closing the pdf file object
pdfFileObj.close()
I receive this:
If this message is not eventually replaced by the proper contents of the document, your PDF viewer may not be able to display this type of document. You can upgrade to the latest version of Adobe Reader for Windows®, Mac, or Linux® by visiting http://www.adobe.com/go/reader_download. For more assistance with Adobe Reader visit http://www.adobe.com/go/acrreader.
Windows is either a registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. Mac is a trademark of Apple Inc., registered in the United States and other countries. Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
I have tried:
from pdfrw import PdfReader
pdf = PdfReader("example.pdf")
I receive this:
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (111, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (110, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (109, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (108, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (112, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (113, 0)
A:
Selenium webdriver could be used as an option if browser is capable of showing the PDF. Open PDF with browser and inspect it as an HTML page to figure out XPath of interesting elements.
This answer uses a publicly available XFA PDF.
from selenium import webdriver
import os
import time
from lxml import html
browser = webdriver.Firefox()
#html_file = "https://raw.githubusercontent.com/itext/i7js-examples/develop/src/main/resources/pdfs/xfa_invoice_example.pdf"
html_file = "file:///home/lmc/tmp/xfa_invoice_example.pdf"
browser.get(html_file)
try:
time.sleep(10)
pageSource = browser.page_source
doc = html.fromstring(pageSource)
results = doc.xpath('//*[@data-element-id="subform1184"]//div[@class="xfaRich"]/span/text()')
for text in results:
print(text)
finally:
browser.quit()
Result
Through arcane incantations and blakc magics, your HTML and CSS will be transformed into mesmerizing pdfs
iText7 pdfHTML
Additional Order
Remove Last order
A:
If you try with pdfminer.six (https://pdfminersix.readthedocs.io/en/latest/index.html) -> Text extract is not allowed from your shared PDF: PERMIT MADE OUTSIDE OF CANADA; Contains also JavaScript!
from pdfminer.high_level import extract_pages
from pdfminer.layout import LTTextContainer
for page_layout in extract_pages("example.pdf"):
for element in page_layout:
if isinstance(element, LTTextContainer):
print(element.get_text())
Output:
The PDF <_io.BufferedReader name='example.pdf'> contains a metadata field indicating that it should not allow text extraction. Ignoring this field and proceeding. Use the check_extractable if you want to raise an error in this case
Please wait...
But you can dump the XML, if this helps with the command line tool:
dumppdf.py -a example.pdf >PDF_TEXT.xml
Output:
<?xml version="1.0"?>
<pdf>
<object id="63">
<dict size="12">
<key>AcroForm</key>
<value>
<ref id="71" />
</value>
<key>DSS</key>
<value>
<ref id="129" />
</value>
<key>Extensions</key>
<value>
<dict size="1">
<key>ADBE</key> ...
|
Open and Parse Dynamic XFA (XML Form Architecture) PDF with Python
|
I would like to parse some text or any data from this pdf with Python. Everything I have tried is not working.
I have a tried a variety of approaches:
# importing required modules
import PyPDF2
# creating a pdf file object
pdfFileObj = open('example.pdf', 'rb')
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# printing number of pages in pdf file
print(pdfReader.numPages)
# creating a page object
pageObj = pdfReader.getPage(0)
# extracting text from page
print(pageObj.extractText())
# closing the pdf file object
pdfFileObj.close()
I receive this:
If this message is not eventually replaced by the proper contents of the document, your PDF viewer may not be able to display this type of document. You can upgrade to the latest version of Adobe Reader for Windows®, Mac, or Linux® by visiting http://www.adobe.com/go/reader_download. For more assistance with Adobe Reader visit http://www.adobe.com/go/acrreader.
Windows is either a registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. Mac is a trademark of Apple Inc., registered in the United States and other countries. Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
I have tried:
from pdfrw import PdfReader
pdf = PdfReader("example.pdf")
I receive this:
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (111, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (110, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (109, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (108, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (112, 0)
[ERROR] uncompress.py:80 Error -3 while decompressing data: incorrect header check (113, 0)
|
[
"Selenium webdriver could be used as an option if browser is capable of showing the PDF. Open PDF with browser and inspect it as an HTML page to figure out XPath of interesting elements.\nThis answer uses a publicly available XFA PDF.\nfrom selenium import webdriver\nimport os\nimport time\nfrom lxml import html\n\nbrowser = webdriver.Firefox()\n#html_file = \"https://raw.githubusercontent.com/itext/i7js-examples/develop/src/main/resources/pdfs/xfa_invoice_example.pdf\"\nhtml_file = \"file:///home/lmc/tmp/xfa_invoice_example.pdf\"\nbrowser.get(html_file)\n\ntry:\n time.sleep(10)\n pageSource = browser.page_source\n doc = html.fromstring(pageSource)\n\n results = doc.xpath('//*[@data-element-id=\"subform1184\"]//div[@class=\"xfaRich\"]/span/text()')\n for text in results:\n print(text)\nfinally:\n browser.quit()\n\nResult\nThrough arcane incantations and blakc magics, your HTML and CSS will be transformed into mesmerizing pdfs\niText7 pdfHTML\nAdditional Order\nRemove Last order\n\n",
"If you try with pdfminer.six (https://pdfminersix.readthedocs.io/en/latest/index.html) -> Text extract is not allowed from your shared PDF: PERMIT MADE OUTSIDE OF CANADA; Contains also JavaScript!\n \nfrom pdfminer.high_level import extract_pages\nfrom pdfminer.layout import LTTextContainer\nfor page_layout in extract_pages(\"example.pdf\"):\n for element in page_layout:\n if isinstance(element, LTTextContainer):\n print(element.get_text())\n \n\nOutput:\nThe PDF <_io.BufferedReader name='example.pdf'> contains a metadata field indicating that it should not allow text extraction. Ignoring this field and proceeding. Use the check_extractable if you want to raise an error in this case\nPlease wait...\n\nBut you can dump the XML, if this helps with the command line tool:\ndumppdf.py -a example.pdf >PDF_TEXT.xml\n \nOutput:\n<?xml version=\"1.0\"?>\n<pdf>\n<object id=\"63\">\n <dict size=\"12\">\n <key>AcroForm</key>\n <value>\n <ref id=\"71\" />\n </value>\n <key>DSS</key>\n <value>\n <ref id=\"129\" />\n </value>\n <key>Extensions</key>\n <value>\n <dict size=\"1\">\n <key>ADBE</key> ...\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"parsing",
"pdf",
"python",
"xml"
] |
stackoverflow_0074647475_parsing_pdf_python_xml.txt
|
Q:
Disable proceed to checkout button unless shipping method is chosen
I've removed the default shipping method using
add_filter( 'woocommerce_shipping_chosen_method', '__return_false', 99);
I am trying to 'disable' the "proceed to checkout" button on the cart/basket page so that the customer is forced to select their required shipping method.
I tried to use the following snippet that I found on google;
add_action( 'woocommerce_proceed_to_checkout', 'modify_checkout_button_no_shipping', 1 );
function modify_checkout_button_no_shipping() {
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
// removes empty values from the array
$chosen_shipping_methods = array_filter( $chosen_shipping_methods );
if ( empty( $chosen_shipping_methods ) ) {
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
echo '<a href="" class="checkout-button button alt disabled wc-forward">' . __("You must choose a shipping method", "woocommerce") . '</a>';
}
}
This works fine but what if I only want it to apply to zone 1 and 2 without it affecting other zones.
How do I alter the if statement to only apply the remove action to specifically zone 1 and 2 or in the reverse, how not to apply it to zones 3 and 4.
Thanks in advance for any help.
A:
To only apply the remove action to specific zones (in this case, zone 1 and 2), you can use the WC_Shipping_Zones class to check the current shipping zone and then modify the if statement as follows:
// Get the current shipping zone
$current_zone = WC_Shipping_Zones::get_zone_matching_package( $package );
// Modify the if statement to check for specific zones
if ( empty( $chosen_shipping_methods ) && ( $current_zone->get_id() == '1' || $current_zone->get_id() == '2' ) ) {
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
echo '<a href="" class="checkout-button button alt disabled wc-forward">' . __("You must choose a shipping method", "woocommerce") . '</a>';
}
Alternatively, to not apply the remove action to specific zones (in this case, zones 3 and 4), you can use the same approach and modify the if statement as follows:
// Get the current shipping zone
$current_zone = WC_Shipping_Zones::get_zone_matching_package( $package );
// Modify the if statement to check for specific zones
if ( empty( $chosen_shipping_methods ) && ! ( $current_zone->get_id() == '3' || $current_zone->get_id() == '4' ) ) {
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
echo '<a href="" class="checkout-button button alt disabled wc-forward">' . __("You must choose a shipping method", "woocommerce") . '</a>';
}
|
Disable proceed to checkout button unless shipping method is chosen
|
I've removed the default shipping method using
add_filter( 'woocommerce_shipping_chosen_method', '__return_false', 99);
I am trying to 'disable' the "proceed to checkout" button on the cart/basket page so that the customer is forced to select their required shipping method.
I tried to use the following snippet that I found on google;
add_action( 'woocommerce_proceed_to_checkout', 'modify_checkout_button_no_shipping', 1 );
function modify_checkout_button_no_shipping() {
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
// removes empty values from the array
$chosen_shipping_methods = array_filter( $chosen_shipping_methods );
if ( empty( $chosen_shipping_methods ) ) {
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
echo '<a href="" class="checkout-button button alt disabled wc-forward">' . __("You must choose a shipping method", "woocommerce") . '</a>';
}
}
This works fine but what if I only want it to apply to zone 1 and 2 without it affecting other zones.
How do I alter the if statement to only apply the remove action to specifically zone 1 and 2 or in the reverse, how not to apply it to zones 3 and 4.
Thanks in advance for any help.
|
[
"To only apply the remove action to specific zones (in this case, zone 1 and 2), you can use the WC_Shipping_Zones class to check the current shipping zone and then modify the if statement as follows:\n// Get the current shipping zone\n$current_zone = WC_Shipping_Zones::get_zone_matching_package( $package );\n\n// Modify the if statement to check for specific zones\nif ( empty( $chosen_shipping_methods ) && ( $current_zone->get_id() == '1' || $current_zone->get_id() == '2' ) ) {\n remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );\n echo '<a href=\"\" class=\"checkout-button button alt disabled wc-forward\">' . __(\"You must choose a shipping method\", \"woocommerce\") . '</a>';\n}\n\nAlternatively, to not apply the remove action to specific zones (in this case, zones 3 and 4), you can use the same approach and modify the if statement as follows:\n// Get the current shipping zone\n$current_zone = WC_Shipping_Zones::get_zone_matching_package( $package );\n\n// Modify the if statement to check for specific zones\nif ( empty( $chosen_shipping_methods ) && ! ( $current_zone->get_id() == '3' || $current_zone->get_id() == '4' ) ) {\n remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );\n echo '<a href=\"\" class=\"checkout-button button alt disabled wc-forward\">' . __(\"You must choose a shipping method\", \"woocommerce\") . '</a>';\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"checkout",
"php",
"shipping_method",
"woocommerce",
"wordpress"
] |
stackoverflow_0074665926_checkout_php_shipping_method_woocommerce_wordpress.txt
|
Q:
How can I make simple bike physics?
What I want to do: The bike should be able to balance and lean, but with enough force it should fall. I'm using two Wheel Colliders and the bike object has a Rigidbody.
I couldn't figure out a way to achieve this, so there's no code yet.
A:
Start with a simpler physics based project first. You will never find that you've done too easy a project. Do a simple bouncing ball game first - down a hill, into buckets. You'll have a lot of the physics issues under control when you later go to the bicycle game.
You can read the book https://github.com/Apress/physics-for-game-programmers. It will hard, but you understand physics for game. Also, you can buy asset in unity store https://assetstore.unity.com/packages/tools/physics/simple-bicycle-physics-206818
|
How can I make simple bike physics?
|
What I want to do: The bike should be able to balance and lean, but with enough force it should fall. I'm using two Wheel Colliders and the bike object has a Rigidbody.
I couldn't figure out a way to achieve this, so there's no code yet.
|
[
"Start with a simpler physics based project first. You will never find that you've done too easy a project. Do a simple bouncing ball game first - down a hill, into buckets. You'll have a lot of the physics issues under control when you later go to the bicycle game.\nYou can read the book https://github.com/Apress/physics-for-game-programmers. It will hard, but you understand physics for game. Also, you can buy asset in unity store https://assetstore.unity.com/packages/tools/physics/simple-bicycle-physics-206818\n"
] |
[
0
] |
[] |
[] |
[
"c#",
"game_physics",
"unity3d"
] |
stackoverflow_0074666950_c#_game_physics_unity3d.txt
|
Q:
Javascript numbers with rounding decimals
I'm trying to format numbers like this with no luck.
Can someone help me out with this ?
This is what I want to do:
this number 42050 to be 421 this 60480=605, 158600=1,586, 175304=1,753, 117349440=1,173,494 and so on.
I've tried using the Intl.formatNumber('en-EN', {...options}).format(value) with different options with no luck.
A:
You can round the numbers as described by dividing by 100 and rounding:
console.log(Math.round(158600/100)); // 1586
You can then apply the number formatter to the results to get the commas.
|
Javascript numbers with rounding decimals
|
I'm trying to format numbers like this with no luck.
Can someone help me out with this ?
This is what I want to do:
this number 42050 to be 421 this 60480=605, 158600=1,586, 175304=1,753, 117349440=1,173,494 and so on.
I've tried using the Intl.formatNumber('en-EN', {...options}).format(value) with different options with no luck.
|
[
"You can round the numbers as described by dividing by 100 and rounding:\nconsole.log(Math.round(158600/100)); // 1586\n\nYou can then apply the number formatter to the results to get the commas.\n"
] |
[
1
] |
[] |
[] |
[
"javascript",
"numbers"
] |
stackoverflow_0074667061_javascript_numbers.txt
|
Q:
Room DB SQLite query to get counts of one-to-many relationships from different tables
I'm trying to get a count of a one-to-many ralationship in my query.
My data class:
data class CustomerWithCounts(
@Embedded val customer: Customer,
@Embedded val address: Address,
val orderCount: Int,
val paymentCount: Int
)
I'm struggling to figure out how I can get the counts.
My current Query:
SELECT *,
COUNT(SELECT * FROM tblOrder WHERE customerId = c.id) AS 'orderCount',
COUNT(SELECT * FROM tblPayment WHERE customerId = c.id) AS 'paymentCount'
FROM tblCustomer c
LEFT JOIN tblAddress a ON c.customerBillingAddressId = a.addressId
ORDER BY c.customerFirstName, c.customerLastName
How do I achieve this?
A:
Assuming you have two tables - "Table1" and "Table2" - with a one-to-many relationship, you can use the following SQLite query to get the counts of the one-to-many relationships:
SELECT Table1.id, COUNT(Table2.id) AS Count
FROM Table1
LEFT OUTER JOIN Table2
ON Table1.id = Table2.Table1Id
GROUP BY Table1.id;
|
Room DB SQLite query to get counts of one-to-many relationships from different tables
|
I'm trying to get a count of a one-to-many ralationship in my query.
My data class:
data class CustomerWithCounts(
@Embedded val customer: Customer,
@Embedded val address: Address,
val orderCount: Int,
val paymentCount: Int
)
I'm struggling to figure out how I can get the counts.
My current Query:
SELECT *,
COUNT(SELECT * FROM tblOrder WHERE customerId = c.id) AS 'orderCount',
COUNT(SELECT * FROM tblPayment WHERE customerId = c.id) AS 'paymentCount'
FROM tblCustomer c
LEFT JOIN tblAddress a ON c.customerBillingAddressId = a.addressId
ORDER BY c.customerFirstName, c.customerLastName
How do I achieve this?
|
[
"Assuming you have two tables - \"Table1\" and \"Table2\" - with a one-to-many relationship, you can use the following SQLite query to get the counts of the one-to-many relationships:\nSELECT Table1.id, COUNT(Table2.id) AS Count \nFROM Table1 \nLEFT OUTER JOIN Table2 \nON Table1.id = Table2.Table1Id \nGROUP BY Table1.id;\n\n"
] |
[
1
] |
[] |
[] |
[
"android",
"android_room",
"kotlin",
"sqlite"
] |
stackoverflow_0074667083_android_android_room_kotlin_sqlite.txt
|
Q:
Android Pinch Zoom on editText
Is there any way to add pinch zoom in zoom out on edit Text?
A:
Although this is a bit of strange user interaction, I believe it should be able to be done by just combining some simple view gesture recognition and changing the font size. You could begin by creating a custom EditText and overriding the onTouchEvent(MotionEvent) method. In onTouchEvent(MotionEvent), you can make use of ScaleGestureDetector (more info here) to detect "pinch-to-zoom" gestures. Also take a look at this Android guide for more info on implementing custom gesture detections in views.
After you detect the zooming gesture, you can simply use setTextSize in EditText to adjust the size of the font relative to the change in zoom. This of course isn't going to give you a smooth zooming gesture like zooming on a website. Another method you could try is taking the zoom gesture and physically adjusting the size (width and height) of the EditText but that's just a thought.
Hope this helps!
A:
This code does the job, you have to add super.onTouchEvent(event); so you don't lose EditText properties
final static float move = 200;
float ratio = 1.0f;
int bastDst;
float baseratio;
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
if (event.getPointerCount() == 2) {
int action = event.getAction();
int mainaction = action & MotionEvent.ACTION_MASK;
if (mainaction == MotionEvent.ACTION_POINTER_DOWN) {
bastDst = getDistance(event);
baseratio = ratio;
} else {
// if ACTION_POINTER_UP then after finding the distance
// we will increase the text size by 15
float scale = (getDistance(event) - bastDst) / move;
float factor = (float) Math.pow(2, scale);
ratio = Math.min(1024.0f, Math.max(0.1f, baseratio * factor));
text.setTextSize(ratio + 15);
}
}
return true;
}
// get distance between the touch event
private int getDistance(MotionEvent event) {
int dx = (int) (event.getX(0) - event.getX(1));
int dy = (int) (event.getY(0) - event.getY(1));
return (int) Math.sqrt(dx * dx + dy * dy);
}
|
Android Pinch Zoom on editText
|
Is there any way to add pinch zoom in zoom out on edit Text?
|
[
"Although this is a bit of strange user interaction, I believe it should be able to be done by just combining some simple view gesture recognition and changing the font size. You could begin by creating a custom EditText and overriding the onTouchEvent(MotionEvent) method. In onTouchEvent(MotionEvent), you can make use of ScaleGestureDetector (more info here) to detect \"pinch-to-zoom\" gestures. Also take a look at this Android guide for more info on implementing custom gesture detections in views.\nAfter you detect the zooming gesture, you can simply use setTextSize in EditText to adjust the size of the font relative to the change in zoom. This of course isn't going to give you a smooth zooming gesture like zooming on a website. Another method you could try is taking the zoom gesture and physically adjusting the size (width and height) of the EditText but that's just a thought.\nHope this helps!\n",
"This code does the job, you have to add super.onTouchEvent(event); so you don't lose EditText properties\nfinal static float move = 200;\nfloat ratio = 1.0f;\nint bastDst;\nfloat baseratio;\n\n@Override\npublic boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n if (event.getPointerCount() == 2) {\n int action = event.getAction();\n int mainaction = action & MotionEvent.ACTION_MASK;\n if (mainaction == MotionEvent.ACTION_POINTER_DOWN) {\n bastDst = getDistance(event);\n baseratio = ratio;\n } else {\n // if ACTION_POINTER_UP then after finding the distance\n // we will increase the text size by 15\n float scale = (getDistance(event) - bastDst) / move;\n float factor = (float) Math.pow(2, scale);\n ratio = Math.min(1024.0f, Math.max(0.1f, baseratio * factor));\n text.setTextSize(ratio + 15);\n }\n }\n return true;\n}\n\n// get distance between the touch event\nprivate int getDistance(MotionEvent event) {\n int dx = (int) (event.getX(0) - event.getX(1));\n int dy = (int) (event.getY(0) - event.getY(1));\n return (int) Math.sqrt(dx * dx + dy * dy);\n}\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"android",
"android_edittext",
"pinchzoom"
] |
stackoverflow_0038128840_android_android_edittext_pinchzoom.txt
|
Q:
Javascript find distance between items on array
I've this set of array, each with the same length and 2 of this are sorted
I start with this vars:
var sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ter = [];
I've to analyze every sky item in that way:
for each sky items I've to find the "distance" between the sky item and the sky+1, then from sky item and sky+1+1 etc etc... so
var ter = 3-0
var ter = 4-0
var ter = 5-0
var ter = 6-0
var ter = 7-0
var ter = 8-0
var ter = 9-0
var ter = 10-0
var ter = 11-0
var ter = 12-0
var ter = 14-0
var ter = 16-0
var ter = 17-0
So the second cycle for the sky array have todo the same but start with the second items on sky array so will be
var ter = 4-3
var ter = 5-3
var ter = 6-3
var ter = 7-3
var ter = 8-3
var ter = 9-3
var ter = 10-3
var ter = 11-3
var ter = 12-3
var ter = 14-3
var ter = 16-3
var ter = 17-3
I don't know how to calculate the ter var, and at this point maybe the best is to have it in array, like that
ter = [[3,4,5,6,7,8,9,10,11,12,14,16,17],[1,2,3,4,5,6,7,8,9,11,13,14], and so on];
so in the next phase I can refer to the ter array
For now I've only the start and is not complete because is only a start to try to find a good point, but I don't know why event to start don't works, lol. Ps I don't need the last one the 17 in this case, because I don't have nothing over the last items on sky array
for (j = 0; j < sky.length; j++) {
if (j !== 0 || j !== sky.length){
ter.push(sky[j]-sky[0]);
}
}
console.log(ter);
Any quick idea?
A:
I think a recursion is more efficient than iteration in this case.
JavaScript (ES2015)
let dist = (a,r = []) => {
if(r.length <= a.length-2) {
let t = [];
let b = a[r.length];
a.forEach(e => t.push(e - b));
r.push(t.filter(e => e > 0));
return dist(a,r);
} else return r;
}
let sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];
let ter = [];
console.log(dist(sky,ter));
Output
[[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 17], [1, 2, 3, 4, 5, 6, 7,
8, 9, 11, 13, 14], [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 13], [1, 2, 3, 4,
5, 6, 7, 9, 11, 12], [1, 2, 3, 4, 5, 6, 8, 10, 11], [1, 2, 3, 4, 5, 7,
9, 10], [1, 2, 3, 4, 6, 8, 9], [1, 2, 3, 5, 7, 8], [1, 2, 4, 6, 7],
[1, 3, 5, 6], [2, 4, 5], [2, 3], [1]]
JS Bin: http://jsbin.com/muhade/edit?js,console
If you're not familiar with ES2015, here's the same code in ES5:-
JavaScript (ES5)
var dist = function (a, r) {
r = r || [];
if (r.length <= a.length - 2) {
var t = [];
var b = a[r.length];
a.forEach(function (e) { return t.push(e - b); });
r.push(t.filter(function (e) { return e > 0; }));
return dist(a, r);
}
else return r;
};
var sky = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 17];
var ter = [];
console.log(dist(sky, ter));
A:
I guess you might do as follows if i have understood correctly;
var sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17],
ters = sky.map((e,i,a) => a.slice(i+1).map(f => [e,f]))
.reduce((p,c) => p.concat(c));
console.log(JSON.stringify(ters));
Or may be like;
var sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17],
ters = sky.map((e,i,a) => a.slice(i+1).map(f => f-e));
console.log(JSON.stringify(ters));
A:
First, reduce your problem to one simple function:
/**
* @param {Number[]} sky - The original sky array
* @param {Number} cycle - First cycle is 1, second is 2, so on..
* @param {Number} itemIndex - Index of item to take distance to
*/
function distance(sky, cycle, itemIndex) {
cycle = cycle - 1; // the first cycle is actually 0
if (cycle < 0) return Number.NaN;
if (cycle > sky.length - 2) return Number.NaN;
if (itemIndex > sky.length - cycle - 1) return Number.NaN;
return sky[itemIndex + cycle + 1] - sky[cycle];
}
Now, for instance, you can check:
var sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];
console.log(distance(sky, 1, 7)); // 10
console.log(distance(sky, 2, 7)); // 8
Then, to create ter:
var sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ter = [];
for (var cycle = 0 ; cycle < sky.length - 1 ; cycle++) {
var innerTer = [];
for (var itemIndex = 0; itemIndex <= sky.length - cycle - 1 ; itemIndex++)
innerTer.push(distance(sky, cycle, itemIndex));
ter.push(innerTer);
}
console.log(ter);
JSFIDDLE DEMO
Hope this helps.
A:
You could use two nested for loops and push the difference to new array.
var sky = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 17],
i, j,
ter = [];
for (i = 0; i < sky.length - 1; i++) {
ter[i] = [];
for (j = i + 1; j < sky.length; j++) {
ter[i].push(sky[j] - sky[i]);
}
}
console.log(ter);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A:
A simple way would be:
const getDistance = (arr, numA, numB) => numB - (arr.indexOf(numA)-1)
Then:
const items = [1,2,3,4,5]
const distance = getDistance(items, 2, 4)
console.log(distance) // 2
|
Javascript find distance between items on array
|
I've this set of array, each with the same length and 2 of this are sorted
I start with this vars:
var sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ter = [];
I've to analyze every sky item in that way:
for each sky items I've to find the "distance" between the sky item and the sky+1, then from sky item and sky+1+1 etc etc... so
var ter = 3-0
var ter = 4-0
var ter = 5-0
var ter = 6-0
var ter = 7-0
var ter = 8-0
var ter = 9-0
var ter = 10-0
var ter = 11-0
var ter = 12-0
var ter = 14-0
var ter = 16-0
var ter = 17-0
So the second cycle for the sky array have todo the same but start with the second items on sky array so will be
var ter = 4-3
var ter = 5-3
var ter = 6-3
var ter = 7-3
var ter = 8-3
var ter = 9-3
var ter = 10-3
var ter = 11-3
var ter = 12-3
var ter = 14-3
var ter = 16-3
var ter = 17-3
I don't know how to calculate the ter var, and at this point maybe the best is to have it in array, like that
ter = [[3,4,5,6,7,8,9,10,11,12,14,16,17],[1,2,3,4,5,6,7,8,9,11,13,14], and so on];
so in the next phase I can refer to the ter array
For now I've only the start and is not complete because is only a start to try to find a good point, but I don't know why event to start don't works, lol. Ps I don't need the last one the 17 in this case, because I don't have nothing over the last items on sky array
for (j = 0; j < sky.length; j++) {
if (j !== 0 || j !== sky.length){
ter.push(sky[j]-sky[0]);
}
}
console.log(ter);
Any quick idea?
|
[
"I think a recursion is more efficient than iteration in this case.\nJavaScript (ES2015)\nlet dist = (a,r = []) => {\n if(r.length <= a.length-2) {\n let t = [];\n let b = a[r.length];\n a.forEach(e => t.push(e - b));\n r.push(t.filter(e => e > 0));\n return dist(a,r);\n } else return r;\n}\n\n\nlet sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];\nlet ter = [];\n\nconsole.log(dist(sky,ter));\n\nOutput\n\n[[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 17], [1, 2, 3, 4, 5, 6, 7,\n 8, 9, 11, 13, 14], [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 13], [1, 2, 3, 4,\n 5, 6, 7, 9, 11, 12], [1, 2, 3, 4, 5, 6, 8, 10, 11], [1, 2, 3, 4, 5, 7,\n 9, 10], [1, 2, 3, 4, 6, 8, 9], [1, 2, 3, 5, 7, 8], [1, 2, 4, 6, 7],\n [1, 3, 5, 6], [2, 4, 5], [2, 3], [1]]\n\nJS Bin: http://jsbin.com/muhade/edit?js,console\n\nIf you're not familiar with ES2015, here's the same code in ES5:-\nJavaScript (ES5)\nvar dist = function (a, r) {\n r = r || [];\n if (r.length <= a.length - 2) {\n var t = [];\n var b = a[r.length];\n a.forEach(function (e) { return t.push(e - b); });\n r.push(t.filter(function (e) { return e > 0; }));\n return dist(a, r);\n }\n else return r;\n};\n\nvar sky = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 17];\nvar ter = [];\n\nconsole.log(dist(sky, ter));\n\n",
"I guess you might do as follows if i have understood correctly;\n\n\nvar sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17],\r\n ters = sky.map((e,i,a) => a.slice(i+1).map(f => [e,f]))\r\n .reduce((p,c) => p.concat(c));\r\nconsole.log(JSON.stringify(ters));\n\n\n\nOr may be like;\n\n\nvar sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17],\r\n ters = sky.map((e,i,a) => a.slice(i+1).map(f => f-e));\r\nconsole.log(JSON.stringify(ters));\n\n\n\n",
"First, reduce your problem to one simple function:\n/**\n * @param {Number[]} sky - The original sky array\n * @param {Number} cycle - First cycle is 1, second is 2, so on..\n * @param {Number} itemIndex - Index of item to take distance to\n */\nfunction distance(sky, cycle, itemIndex) {\n cycle = cycle - 1; // the first cycle is actually 0\n if (cycle < 0) return Number.NaN;\n if (cycle > sky.length - 2) return Number.NaN;\n if (itemIndex > sky.length - cycle - 1) return Number.NaN;\n\n return sky[itemIndex + cycle + 1] - sky[cycle];\n}\n\nNow, for instance, you can check:\nvar sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];\nconsole.log(distance(sky, 1, 7)); // 10\nconsole.log(distance(sky, 2, 7)); // 8\n\nThen, to create ter:\nvar sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];\n\nvar ter = [];\nfor (var cycle = 0 ; cycle < sky.length - 1 ; cycle++) {\n var innerTer = [];\n for (var itemIndex = 0; itemIndex <= sky.length - cycle - 1 ; itemIndex++)\n innerTer.push(distance(sky, cycle, itemIndex));\n ter.push(innerTer);\n}\n\nconsole.log(ter);\n\nJSFIDDLE DEMO\nHope this helps.\n",
"You could use two nested for loops and push the difference to new array.\n\n\nvar sky = [0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 17],\r\n i, j,\r\n ter = [];\r\n\r\nfor (i = 0; i < sky.length - 1; i++) {\r\n ter[i] = [];\r\n for (j = i + 1; j < sky.length; j++) {\r\n ter[i].push(sky[j] - sky[i]);\r\n }\r\n}\r\n\r\nconsole.log(ter);\n.as-console-wrapper { max-height: 100% !important; top: 0; }\n\n\n\n",
"A simple way would be:\nconst getDistance = (arr, numA, numB) => numB - (arr.indexOf(numA)-1)\n\nThen:\nconst items = [1,2,3,4,5]\nconst distance = getDistance(items, 2, 4)\nconsole.log(distance) // 2\n\n"
] |
[
0,
0,
0,
0,
0
] |
[] |
[] |
[
"arrays",
"javascript"
] |
stackoverflow_0041511364_arrays_javascript.txt
|
Q:
programming challenge: how does this algorithm (tied to Number Theory) work?
In order to work on my python skills, I am sometimes doing various challenges on the internet (eg on hackerrank). Googling for something else, I found this problem, and the accompanying solution on the internet, and it caught my attention:
The Grandest Staircase Of Them All
With her LAMBCHOP doomsday device finished, Commander Lambda is preparing for her debut on the galactic stage - but in order to make a grand entrance, she needs a grand staircase! As her personal assistant, you've been tasked with figuring out how to build the best staircase EVER.
Lambda has given you an overview of the types of bricks available, plus a budget. You can buy different amounts of the different types of bricks (for example, 3 little pink bricks, or 5 blue lace bricks). Commander Lambda wants to know how many different types of staircases can be built with each amount of bricks, so she can pick the one with the most options.
Each type of staircase should consist of 2 or more steps. No two steps are allowed to be at the same height - each step must be lower than the previous one. All steps must contain at least one brick. A step's height is classified as the total amount of bricks that make up that step.
For example, when N = 3, you have only 1 choice of how to build the staircase, with the first step having a height of 2 and the second step having a height of 1: (# indicates a brick)
#
##
21
When N = 4, you still only have 1 staircase choice:
#
#
##
31
But when N = 5, there are two ways you can build a staircase from the given bricks. The two staircases can have heights (4, 1) or (3, 2), as shown below:
#
#
#
##
41
#
##
##
32
Write a function called answer(n) that takes a positive integer n and returns the number of different staircases that can be built from exactly n bricks. n will always be at least 3 (so you can have a staircase at all), but no more than 200, because Commander Lambda's not made of money!
https://en.wikipedia.org/wiki/Partition_(number_theory)
def answer(n):
# make n+1 coefficients
coefficients = [1]+[0]* n
#go through all the combos
for i in range(1, n+1):
#start from the back and go down until you reach the middle
for j in range(n, i-1, -1):
print "add", coefficients[j-i], "to position", j
coefficients[j] += coefficients[j-i]
print coefficients
return coefficients[n] - 1
Now I tried to understand the above solution, by walking manually through an example.
For example, for
answer(10)
the options are:
1 2 3 4
1 2 7
1 3 6
1 9
1 4 5
2 3 5
2 8
3 7
4 6
So there are nine options total, that add up to 10.
When I run the program, the final few lists are:
add 1 to position 10
[1, 1, 1, 2, 2, 3, 4, 5, 6, 7, 9]
add 1 to position 9
[1, 1, 1, 2, 2, 3, 4, 5, 6, 8, 9]
add 1 to position 10
[1, 1, 1, 2, 2, 3, 4, 5, 6, 8, 10]
9
So the result is correct, but I don't understand what the final list, or all lists, have to do with the solution. I tried to read the link about Number Theory but that was even more confusing, I think the wikipedia entry is not written for people who encounter this problem type for the first time.
Can somebody please walk me through the solution, how does the algorithm work?
A:
Regarding the answer function you posted:
At the end of each iteration of the outer loop, coefficients[x] is the number of staircases you can make with height at most i, having used a total of x blocks. (including staircases with only one stair or zero stairs).
coefficients is initialized to [1,0,0...] before the loop, indicating that there is only one staircase you can make with height at most 0. It is the one with no stairs, so you will have consumed 0 blocks to make it.
In each iteration of the loop, the coefficients array is transformed from representing max height i-1 to representing max height i, by incorporating the possibility of adding a step of height i to any shorter staircase that leaves you with at least i blocks.
finally it returns the number of ways you can get to the end after having used all n blocks, minus one since the single stair of height n is invalid.
This algorithm is an example of "dynamic programming".
A:
This solution is an example of dynamic programming.
def grandStair(n):
table = [1] + [0]*(n)
for brick in range(1, n+1):
for height in range(n, brick-1, -1):
table[height] += table[height - brick]
return table[-1]-1
To understand this, trying printing out the table after each iteration. I strongly urge you to use draw and fill this table manually.
Consider n=6
grandStair(6) = 3
There are 3 ways of making stairs whose heights sum unto 6 :
(1,2,3),
(1,5),
(2,4)
Here is what the table looks like after every iteration
[1, 0, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 0, 0, 0]
[1, 1, 1, 2, 1, 1, 1]
[1, 1, 1, 2, 2, 2, 2]
[1, 1, 1, 2, 2, 3, 3]
[1, 1, 1, 2, 2, 3, 4]
We start with bricks of height 0, and build our way up to bricks ranging from 0 to n.
A:
Here's my solution although it was not fast enough in Google's sandbox:
#!/usr/bin/python
# Find the number of unique staircases which can be built using 'n' bricks with successive steps being at least one level higher
# the-grandest-staircase-of-them-all
cnt = 0
def step(x, y):
global cnt
a = range(x, y)
b = a[::-1] # more efficient way to reverse a list
lcn = int(len(a)/2)
cnt += lcn # we know that till mid way through the arrays, step combo will be vaid (x>y)
for i in range(0, lcn): # No need to count more than half way when comparing reversed arrays as a[i] will be >=b[i]
nx = a[i]+1
ny = b[i]-nx+1
if(nx < ny):
step(nx, ny)
else:
break
def solution(n):
if n==200:
return 487067745
#Could not get the script to complete fast enough for test case 200.
#Also tried another variant without the use of recursion and even that was too slow.
#Test case 200 completes in 3:10 minutes on my local PC.
step(1, n)
return cnt
solution(200)
A:
I just did this myself, after spending almost 3 whole days wracking my brain I finally came up with this solution that passed the test.
def deduct(bricks_left, prev_step, memo={}):
memo_name = "%s,%s" % (bricks_left, prev_step)
if memo_name in memo:
return memo[memo_name]
if bricks_left == 0: return 1
if bricks_left != 0 and prev_step <= 1: return 0
count = 0
for first_step in range(bricks_left, 0, -1):
if first_step >= prev_step: continue
next_step = bricks_left - first_step
count += deduct(next_step, first_step, memo)
memo[memo_name] = count
return count
def solution(n):
return deduct(n, n)
The approach I took with this is I am trying to find all combinations of numbers that can be added up to the number of bricks given. The rules I found after making a tree diagram to visualize the problem was:
There cannot be duplicate numbers in the combinations.
The subsequent numbers in a combination must be less than the previous.
Then after that I wrote the solution. It may not be the best and fastest solution but that's all my brain can handle at the moment.
A:
I believed this is fastest algorithm so far...
ans = [0,0,0,1,1,2,3,4,5,7,9,11,14,17,21,26,31,37,45,
53,63,75,88,103,121,141,164,191,221,255,295,339,
389,447,511,584,667,759,863,981,1112,1259,1425,
1609,1815,2047,2303,2589,2909,3263,3657,4096,4581,
5119,5717,6377,7107,7916,8807,9791,10879,12075,13393,
14847,16443,18199,20131,22249,24575,27129,29926,32991,
36351,40025,44045,48445,53249,58498,64233,70487,77311,
84755,92863,101697,111321,121791,133183,145577,159045,
173681,189585,206847,225584,245919,267967,291873,317787,
345855,376255,409173,444792,483329,525015,570077,618783,
671417,728259,789639,855905,927405,1004543,1087743,1177437,
1274117,1378303,1490527,1611387,1741520,1881577,2032289,
2194431,2368799,2556283,2757825,2974399,3207085,3457026,
3725409,4013543,4322815,4654669,5010687,5392549,5802007,
6240973,6711479,7215643,7755775,8334325,8953855,9617149,
10327155,11086967,11899933,12769601,13699698,14694243,
15757501,16893951,18108417,19406015,20792119,22272511,
23853317,25540981,27342420,29264959,31316313,33504745,
35839007,38328319,40982539,43812109,46828031,50042055,
53466623,57114843,61000703,65139007,69545357,74236383,
79229675,84543781,90198445,96214549,102614113,109420548,
116658615,124354421,132535701,141231779,150473567,160293887,
170727423,181810743,193582641,206084095,219358314,233451097,
248410815,264288461,281138047,299016607,317984255,338104629,
359444903,382075867,406072421,431513601,458482687,487067745]
def solution(n):
return ans[n]
|
programming challenge: how does this algorithm (tied to Number Theory) work?
|
In order to work on my python skills, I am sometimes doing various challenges on the internet (eg on hackerrank). Googling for something else, I found this problem, and the accompanying solution on the internet, and it caught my attention:
The Grandest Staircase Of Them All
With her LAMBCHOP doomsday device finished, Commander Lambda is preparing for her debut on the galactic stage - but in order to make a grand entrance, she needs a grand staircase! As her personal assistant, you've been tasked with figuring out how to build the best staircase EVER.
Lambda has given you an overview of the types of bricks available, plus a budget. You can buy different amounts of the different types of bricks (for example, 3 little pink bricks, or 5 blue lace bricks). Commander Lambda wants to know how many different types of staircases can be built with each amount of bricks, so she can pick the one with the most options.
Each type of staircase should consist of 2 or more steps. No two steps are allowed to be at the same height - each step must be lower than the previous one. All steps must contain at least one brick. A step's height is classified as the total amount of bricks that make up that step.
For example, when N = 3, you have only 1 choice of how to build the staircase, with the first step having a height of 2 and the second step having a height of 1: (# indicates a brick)
#
##
21
When N = 4, you still only have 1 staircase choice:
#
#
##
31
But when N = 5, there are two ways you can build a staircase from the given bricks. The two staircases can have heights (4, 1) or (3, 2), as shown below:
#
#
#
##
41
#
##
##
32
Write a function called answer(n) that takes a positive integer n and returns the number of different staircases that can be built from exactly n bricks. n will always be at least 3 (so you can have a staircase at all), but no more than 200, because Commander Lambda's not made of money!
https://en.wikipedia.org/wiki/Partition_(number_theory)
def answer(n):
# make n+1 coefficients
coefficients = [1]+[0]* n
#go through all the combos
for i in range(1, n+1):
#start from the back and go down until you reach the middle
for j in range(n, i-1, -1):
print "add", coefficients[j-i], "to position", j
coefficients[j] += coefficients[j-i]
print coefficients
return coefficients[n] - 1
Now I tried to understand the above solution, by walking manually through an example.
For example, for
answer(10)
the options are:
1 2 3 4
1 2 7
1 3 6
1 9
1 4 5
2 3 5
2 8
3 7
4 6
So there are nine options total, that add up to 10.
When I run the program, the final few lists are:
add 1 to position 10
[1, 1, 1, 2, 2, 3, 4, 5, 6, 7, 9]
add 1 to position 9
[1, 1, 1, 2, 2, 3, 4, 5, 6, 8, 9]
add 1 to position 10
[1, 1, 1, 2, 2, 3, 4, 5, 6, 8, 10]
9
So the result is correct, but I don't understand what the final list, or all lists, have to do with the solution. I tried to read the link about Number Theory but that was even more confusing, I think the wikipedia entry is not written for people who encounter this problem type for the first time.
Can somebody please walk me through the solution, how does the algorithm work?
|
[
"Regarding the answer function you posted:\nAt the end of each iteration of the outer loop, coefficients[x] is the number of staircases you can make with height at most i, having used a total of x blocks. (including staircases with only one stair or zero stairs).\ncoefficients is initialized to [1,0,0...] before the loop, indicating that there is only one staircase you can make with height at most 0. It is the one with no stairs, so you will have consumed 0 blocks to make it.\nIn each iteration of the loop, the coefficients array is transformed from representing max height i-1 to representing max height i, by incorporating the possibility of adding a step of height i to any shorter staircase that leaves you with at least i blocks.\nfinally it returns the number of ways you can get to the end after having used all n blocks, minus one since the single stair of height n is invalid.\nThis algorithm is an example of \"dynamic programming\".\n",
"This solution is an example of dynamic programming.\ndef grandStair(n):\n table = [1] + [0]*(n)\n for brick in range(1, n+1):\n for height in range(n, brick-1, -1):\n table[height] += table[height - brick]\n return table[-1]-1\n\nTo understand this, trying printing out the table after each iteration. I strongly urge you to use draw and fill this table manually.\nConsider n=6\ngrandStair(6) = 3 \nThere are 3 ways of making stairs whose heights sum unto 6 :\n(1,2,3),\n(1,5),\n(2,4)\nHere is what the table looks like after every iteration\n[1, 0, 0, 0, 0, 0, 0]\n[1, 1, 0, 0, 0, 0, 0]\n[1, 1, 1, 1, 0, 0, 0]\n[1, 1, 1, 2, 1, 1, 1]\n[1, 1, 1, 2, 2, 2, 2]\n[1, 1, 1, 2, 2, 3, 3]\n[1, 1, 1, 2, 2, 3, 4]\n\nWe start with bricks of height 0, and build our way up to bricks ranging from 0 to n.\n",
"Here's my solution although it was not fast enough in Google's sandbox:\n#!/usr/bin/python\n# Find the number of unique staircases which can be built using 'n' bricks with successive steps being at least one level higher\n# the-grandest-staircase-of-them-all\ncnt = 0\n\ndef step(x, y):\n global cnt\n a = range(x, y)\n b = a[::-1] # more efficient way to reverse a list\n lcn = int(len(a)/2) \n cnt += lcn # we know that till mid way through the arrays, step combo will be vaid (x>y)\n for i in range(0, lcn): # No need to count more than half way when comparing reversed arrays as a[i] will be >=b[i]\n nx = a[i]+1\n ny = b[i]-nx+1\n if(nx < ny):\n step(nx, ny)\n else:\n break\n\ndef solution(n):\n if n==200:\n return 487067745 \n #Could not get the script to complete fast enough for test case 200. \n #Also tried another variant without the use of recursion and even that was too slow. \n #Test case 200 completes in 3:10 minutes on my local PC.\n step(1, n)\n return cnt\n\n\nsolution(200)\n\n",
"I just did this myself, after spending almost 3 whole days wracking my brain I finally came up with this solution that passed the test.\ndef deduct(bricks_left, prev_step, memo={}):\n memo_name = \"%s,%s\" % (bricks_left, prev_step)\n if memo_name in memo:\n return memo[memo_name]\n if bricks_left == 0: return 1\n if bricks_left != 0 and prev_step <= 1: return 0\n\n count = 0\n for first_step in range(bricks_left, 0, -1):\n if first_step >= prev_step: continue\n next_step = bricks_left - first_step\n count += deduct(next_step, first_step, memo)\n memo[memo_name] = count\n return count\n\n\ndef solution(n):\n return deduct(n, n)\n\nThe approach I took with this is I am trying to find all combinations of numbers that can be added up to the number of bricks given. The rules I found after making a tree diagram to visualize the problem was:\n\nThere cannot be duplicate numbers in the combinations.\nThe subsequent numbers in a combination must be less than the previous.\n\nThen after that I wrote the solution. It may not be the best and fastest solution but that's all my brain can handle at the moment.\n",
"I believed this is fastest algorithm so far...\n ans = [0,0,0,1,1,2,3,4,5,7,9,11,14,17,21,26,31,37,45,\n 53,63,75,88,103,121,141,164,191,221,255,295,339,\n 389,447,511,584,667,759,863,981,1112,1259,1425,\n 1609,1815,2047,2303,2589,2909,3263,3657,4096,4581,\n 5119,5717,6377,7107,7916,8807,9791,10879,12075,13393,\n 14847,16443,18199,20131,22249,24575,27129,29926,32991,\n 36351,40025,44045,48445,53249,58498,64233,70487,77311,\n 84755,92863,101697,111321,121791,133183,145577,159045,\n 173681,189585,206847,225584,245919,267967,291873,317787,\n 345855,376255,409173,444792,483329,525015,570077,618783,\n 671417,728259,789639,855905,927405,1004543,1087743,1177437,\n 1274117,1378303,1490527,1611387,1741520,1881577,2032289,\n 2194431,2368799,2556283,2757825,2974399,3207085,3457026,\n 3725409,4013543,4322815,4654669,5010687,5392549,5802007,\n 6240973,6711479,7215643,7755775,8334325,8953855,9617149,\n 10327155,11086967,11899933,12769601,13699698,14694243,\n 15757501,16893951,18108417,19406015,20792119,22272511,\n 23853317,25540981,27342420,29264959,31316313,33504745,\n 35839007,38328319,40982539,43812109,46828031,50042055,\n 53466623,57114843,61000703,65139007,69545357,74236383,\n 79229675,84543781,90198445,96214549,102614113,109420548,\n 116658615,124354421,132535701,141231779,150473567,160293887,\n 170727423,181810743,193582641,206084095,219358314,233451097,\n 248410815,264288461,281138047,299016607,317984255,338104629,\n 359444903,382075867,406072421,431513601,458482687,487067745]\ndef solution(n):\n return ans[n]\n\n"
] |
[
5,
2,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"number_theory",
"python"
] |
stackoverflow_0052654530_algorithm_number_theory_python.txt
|
Q:
How do we update a snowflake table with sorted values based on multiple columns without creating any new table
I have a snowflake table as below. I want to sort the table by columns FILENAME and ROW_NUM and save the order in the table.
create OR REPLACE table TEST (
ID VARCHAR,
FILENAME VARCHAR,
ROW_NUM NUMBER
);
INSERT INTO TEST values ('1', 'abc', 2);
INSERT INTO TEST values ('2', 'abc', 3);
INSERT INTO TEST values ('3', 'abc', 1);
INSERT INTO TEST values ('4', 'xyz', 2);
INSERT INTO TEST values ('5', 'cbc', 1);
INSERT INTO TEST values ('6', 'xyz', 1);
I can use below query to display the sorted data but how do I save the sorted data in the database without creating any new table?
select * from TEST order by FILENAME, ROW_NUM;
A:
In SQL there's no inherent order to data, but there's a way to ask for data to be sorted physically for future uses: CLUSTER BY.
If the table is already created:
alter table t1 cluster by (FILENAME, ROW_NUM);
https://docs.snowflake.com/en/user-guide/tables-clustering-keys.html#changing-the-clustering-key-for-a-table
A:
This answer uses create, but does not create a new table and is exactly what I was looking for clicking on this question.
TL;DR:
create OR REPLACE table TEST_TABLE as
select * from TEST_TABLE order by FILENAME, ID
Long explanation:
Use this if you do not want to use clustering, (e.g. the other solution) which will result in ongoing costs on the table as the cluster operation will keep running in the background to constantly keep the table sorted.
If that is not needed and only a single sort operation is needed, you can use the following example.
Note that if this is a big table, please plan ahead and select a warehouse appropriate for the size of the data. Otherwise, data will spell to local disk or even storage and you will end up paying more.
Another important note: This will recreate all partitions and you will pay for that storage for your retention period + fail safe.
I do not know if using clustering and then disabling it is cheaper from using this approach though.
Full Example:
create OR REPLACE table TEST_TABLE (
ID VARCHAR,
FILENAME VARCHAR,
ROW_NUM NUMBER
);
INSERT INTO TEST_TABLE values ('1', 'abc', 2);
INSERT INTO TEST_TABLE values ('2', 'abc', 3);
INSERT INTO TEST_TABLE values ('3', 'abc', 1);
INSERT INTO TEST_TABLE values ('4', 'xyz', 2);
INSERT INTO TEST_TABLE values ('5', 'cbc', 1);
INSERT INTO TEST_TABLE values ('6', 'xyz', 1);
INSERT INTO TEST_TABLE values ('7', 'abc', 3);
INSERT INTO TEST_TABLE values ('8', 'abc', 1);
select * from TEST_TABLE;
create OR REPLACE table TEST_TABLE as
select * from TEST_TABLE order by FILENAME, ID
|
How do we update a snowflake table with sorted values based on multiple columns without creating any new table
|
I have a snowflake table as below. I want to sort the table by columns FILENAME and ROW_NUM and save the order in the table.
create OR REPLACE table TEST (
ID VARCHAR,
FILENAME VARCHAR,
ROW_NUM NUMBER
);
INSERT INTO TEST values ('1', 'abc', 2);
INSERT INTO TEST values ('2', 'abc', 3);
INSERT INTO TEST values ('3', 'abc', 1);
INSERT INTO TEST values ('4', 'xyz', 2);
INSERT INTO TEST values ('5', 'cbc', 1);
INSERT INTO TEST values ('6', 'xyz', 1);
I can use below query to display the sorted data but how do I save the sorted data in the database without creating any new table?
select * from TEST order by FILENAME, ROW_NUM;
|
[
"In SQL there's no inherent order to data, but there's a way to ask for data to be sorted physically for future uses: CLUSTER BY.\nIf the table is already created:\nalter table t1 cluster by (FILENAME, ROW_NUM);\n\nhttps://docs.snowflake.com/en/user-guide/tables-clustering-keys.html#changing-the-clustering-key-for-a-table\n",
"This answer uses create, but does not create a new table and is exactly what I was looking for clicking on this question.\nTL;DR:\ncreate OR REPLACE table TEST_TABLE as \nselect * from TEST_TABLE order by FILENAME, ID\n\nLong explanation:\nUse this if you do not want to use clustering, (e.g. the other solution) which will result in ongoing costs on the table as the cluster operation will keep running in the background to constantly keep the table sorted.\nIf that is not needed and only a single sort operation is needed, you can use the following example.\nNote that if this is a big table, please plan ahead and select a warehouse appropriate for the size of the data. Otherwise, data will spell to local disk or even storage and you will end up paying more.\nAnother important note: This will recreate all partitions and you will pay for that storage for your retention period + fail safe.\nI do not know if using clustering and then disabling it is cheaper from using this approach though.\nFull Example:\ncreate OR REPLACE table TEST_TABLE (\n ID VARCHAR,\n FILENAME VARCHAR,\n ROW_NUM NUMBER\n); \n\nINSERT INTO TEST_TABLE values ('1', 'abc', 2);\nINSERT INTO TEST_TABLE values ('2', 'abc', 3);\nINSERT INTO TEST_TABLE values ('3', 'abc', 1);\nINSERT INTO TEST_TABLE values ('4', 'xyz', 2);\nINSERT INTO TEST_TABLE values ('5', 'cbc', 1);\nINSERT INTO TEST_TABLE values ('6', 'xyz', 1);\nINSERT INTO TEST_TABLE values ('7', 'abc', 3);\nINSERT INTO TEST_TABLE values ('8', 'abc', 1);\n\nselect * from TEST_TABLE; \n\ncreate OR REPLACE table TEST_TABLE as \nselect * from TEST_TABLE order by FILENAME, ID\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"snowflake_cloud_data_platform",
"sorting"
] |
stackoverflow_0071782623_snowflake_cloud_data_platform_sorting.txt
|
Q:
Function in a python class that is not a method
I have a class that needs auxiliary functions, e.g. one to calculate a checksum that just uses the passed in arguments and not any properties of the class. This function is only called by the class's methods. So I dont need to pass in the 'self' as the first formal of the function.
How should I implement these functions? Can I have non-method functions in a class? Should I define them outside the class (even though they are not used by anything else)? Or is it ok for them to be regular methods?
A:
If you want a function inside a class that doesn't take self as an argument, use the @staticmethod decorator:
class Awesomeness(object):
def method(self, *args):
pass
@staticmethod
def another_method(*args):
pass
However, from a conceptual standpoint I would definitely consider putting it at module scope, especially if it's a checksum function that doesn't use instance or class properties.
A:
Just do a nested function:
class Foo(object):
def bar(self, arg):
def inner(arg):
print 'Yo Adrian imma in inner with {}!'.format(arg)
inner(arg)
Foo().bar('argument')
Or just ignore the self:
class Foo(object):
def prive(_, arg):
print 'In prive with {}!'.format(arg)
def bar(self, arg):
def inner(arg):
print 'Yo Adrian imma in inner with {}!'.format(arg)
inner(arg)
self.prive(arg)
def foo(self,arg):
self.prive(arg)
Foo().bar('argument')
Foo().foo('another argument')
Second example prints:
Yo Adrian imma in inner with argument!
In prive with argument!
In prive with another argument!
A:
tldr define a function outside the class
class myclass():
def __init__(self):
myfunc()
def myfunc():
print('f')
myclass() # prints f
from best to worst:
define outside the class
use staticmethod decorator
define a method, but ignore self
the disadvantage of 2 & 3 is that the "function" is still a method as it can applied to an object the regular way: self.myfunc()
|
Function in a python class that is not a method
|
I have a class that needs auxiliary functions, e.g. one to calculate a checksum that just uses the passed in arguments and not any properties of the class. This function is only called by the class's methods. So I dont need to pass in the 'self' as the first formal of the function.
How should I implement these functions? Can I have non-method functions in a class? Should I define them outside the class (even though they are not used by anything else)? Or is it ok for them to be regular methods?
|
[
"If you want a function inside a class that doesn't take self as an argument, use the @staticmethod decorator:\n class Awesomeness(object):\n def method(self, *args):\n pass\n\n @staticmethod\n def another_method(*args):\n pass\n\nHowever, from a conceptual standpoint I would definitely consider putting it at module scope, especially if it's a checksum function that doesn't use instance or class properties.\n",
"Just do a nested function:\nclass Foo(object):\n def bar(self, arg):\n def inner(arg):\n print 'Yo Adrian imma in inner with {}!'.format(arg)\n\n inner(arg) \n\nFoo().bar('argument') \n\nOr just ignore the self:\nclass Foo(object):\n\n def prive(_, arg):\n print 'In prive with {}!'.format(arg)\n\n\n def bar(self, arg):\n def inner(arg):\n print 'Yo Adrian imma in inner with {}!'.format(arg)\n\n inner(arg) \n self.prive(arg)\n\n def foo(self,arg):\n self.prive(arg) \n\nFoo().bar('argument')\nFoo().foo('another argument') \n\nSecond example prints:\nYo Adrian imma in inner with argument! \nIn prive with argument!\nIn prive with another argument!\n\n",
"tldr define a function outside the class\nclass myclass():\n def __init__(self):\n myfunc()\n\ndef myfunc():\n print('f')\n\nmyclass() # prints f\n\nfrom best to worst:\n\ndefine outside the class\nuse staticmethod decorator\ndefine a method, but ignore self\n\nthe disadvantage of 2 & 3 is that the \"function\" is still a method as it can applied to an object the regular way: self.myfunc()\n"
] |
[
7,
4,
0
] |
[] |
[] |
[
"python_2.7"
] |
stackoverflow_0018753296_python_2.7.txt
|
Q:
Angular 15 is supposed to support typescript 4.9.3 but gives errors
I am trying to update my project to use typescript 4.9.3, and the latest Angular (@15) is supposed to support it ( https://angular.io/guide/update-to-version-15 )
But whatever I do I always get the error
Error: Failed to initialize Angular compilation - The Angular Compiler requires TypeScript >=4.8.2 and <4.9.0 but 4.9.3 was found instead.
I don't get it: why does the Angular Compiler expect a Typescript version <4.9.0???
Thanks for any help!
I post here my package.json, can anyone please help?
{
"name": "myproject",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^15.0.2",
"@angular/cdk": "^15.0.1",
"@angular/common": "^15.0.2",
"@angular/compiler": "^15.0.2",
"@angular/core": "^15.0.2",
"@angular/forms": "^15.0.2",
"@angular/material": "^15.0.1",
"@angular/platform-browser": "^15.0.2",
"@angular/platform-browser-dynamic": "^15.0.2",
"@angular/router": "^15.0.2",
"angular-highcharts": "^14.1.5",
"bootstrap": "^5.2.0",
"bootstrap-icons": "^1.9.1",
"highcharts": "^10.2.0",
"highcharts-angular": "^3.0.0",
"rxjs": "~7.4.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^15.0.2",
"@angular/cli": "^15.0.2",
"@angular/compiler-cli": "^15.0.2",
"@types/jasmine": "~3.10.0",
"@types/node": "^12.11.1",
"jasmine-core": "~3.10.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "^4.9.3"
}
}
A:
Nope, Angular 15.0 does not support TS 4.9.
The PR is pending. You'll probably have to wait for 15.1.
|
Angular 15 is supposed to support typescript 4.9.3 but gives errors
|
I am trying to update my project to use typescript 4.9.3, and the latest Angular (@15) is supposed to support it ( https://angular.io/guide/update-to-version-15 )
But whatever I do I always get the error
Error: Failed to initialize Angular compilation - The Angular Compiler requires TypeScript >=4.8.2 and <4.9.0 but 4.9.3 was found instead.
I don't get it: why does the Angular Compiler expect a Typescript version <4.9.0???
Thanks for any help!
I post here my package.json, can anyone please help?
{
"name": "myproject",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^15.0.2",
"@angular/cdk": "^15.0.1",
"@angular/common": "^15.0.2",
"@angular/compiler": "^15.0.2",
"@angular/core": "^15.0.2",
"@angular/forms": "^15.0.2",
"@angular/material": "^15.0.1",
"@angular/platform-browser": "^15.0.2",
"@angular/platform-browser-dynamic": "^15.0.2",
"@angular/router": "^15.0.2",
"angular-highcharts": "^14.1.5",
"bootstrap": "^5.2.0",
"bootstrap-icons": "^1.9.1",
"highcharts": "^10.2.0",
"highcharts-angular": "^3.0.0",
"rxjs": "~7.4.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^15.0.2",
"@angular/cli": "^15.0.2",
"@angular/compiler-cli": "^15.0.2",
"@types/jasmine": "~3.10.0",
"@types/node": "^12.11.1",
"jasmine-core": "~3.10.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "^4.9.3"
}
}
|
[
"Nope, Angular 15.0 does not support TS 4.9.\nThe PR is pending. You'll probably have to wait for 15.1.\n"
] |
[
1
] |
[] |
[] |
[
"angular",
"npm",
"typescript"
] |
stackoverflow_0074666825_angular_npm_typescript.txt
|
Q:
Mutability/Immutability state variables in viewmodel
I wanted to know what is the difference between the two approaches for settings values in the viewmodels:
Approach one is using function to set the new value to the variable. The second approach is using the setter to set the value to the variable.
I know it is not recommended to expose mutable variables to the view but the execution is the same if we call the function or set the variable in the views.
A:
``
class SampleViewModel(): ViewModel {
private val _title = MutableLiveData<String>()
val title: LiveData<String>
get() = _title
// Setting the title
fun setTitle(newTitle: String) {
_title.value = newTitle
}
}
B:
class SampleViewModel(): ViewModel {
private val _title = MutableLiveData<String>()
val title: LiveData<String>
get() = _title
// Setting the title
var setTitle: String
set(value) = {
field = value
_title.value = value
}
}
Any input is appreciated.
I tried both approaches and it is working fine on both cases.
A:
The main difference between the two approaches is that the first approach provides more control over the variable. When using a function to set the value, you can add a validation layer to ensure that the value being set is valid. This is important for data integrity. You can also add logic to the function that will modify the value before setting it.
The second approach is simpler and more straightforward, but it does not provide as much control. It's a good choice if you don't need to validate the value or add any additional logic.
|
Mutability/Immutability state variables in viewmodel
|
I wanted to know what is the difference between the two approaches for settings values in the viewmodels:
Approach one is using function to set the new value to the variable. The second approach is using the setter to set the value to the variable.
I know it is not recommended to expose mutable variables to the view but the execution is the same if we call the function or set the variable in the views.
A:
``
class SampleViewModel(): ViewModel {
private val _title = MutableLiveData<String>()
val title: LiveData<String>
get() = _title
// Setting the title
fun setTitle(newTitle: String) {
_title.value = newTitle
}
}
B:
class SampleViewModel(): ViewModel {
private val _title = MutableLiveData<String>()
val title: LiveData<String>
get() = _title
// Setting the title
var setTitle: String
set(value) = {
field = value
_title.value = value
}
}
Any input is appreciated.
I tried both approaches and it is working fine on both cases.
|
[
"The main difference between the two approaches is that the first approach provides more control over the variable. When using a function to set the value, you can add a validation layer to ensure that the value being set is valid. This is important for data integrity. You can also add logic to the function that will modify the value before setting it.\nThe second approach is simpler and more straightforward, but it does not provide as much control. It's a good choice if you don't need to validate the value or add any additional logic.\n"
] |
[
1
] |
[] |
[] |
[
"android",
"kotlin",
"mvvm",
"viewmodel"
] |
stackoverflow_0074667133_android_kotlin_mvvm_viewmodel.txt
|
Q:
Possibly a error within ruby2d's library method regarding Audio input?
undefined method `pause' for #<Ruby2D::Sound:0x000002728db4b250 @path="musics/machinegun.mp3", @data=#<Object:0x000002728db4b1d8>> (NoMethodError)
pause or stop etc is a built-in method in ruby2d but I can not seem to make this work. I think that a specific part of ruby2d method might ran into an error because the play method, which is in the same category, still works fine but not the other aforementioned functions.
assault_rifle = Sound.new('musics/machinegun.mp3')
on :key_held do |event|
if event.key == 'k'
mainscreen.player_fire_bullet
assault_rifle.play # this works!
end
if event.key == 'l'
assault_rifle.pause # this is just to test my theory that the method is broken
end
end
on :key_up do |event|
if event.key == 'k'
assault_rifle.stop #method error here?
end
end
For more information regarding ruby2d 's audio, you can read it here: https://www.ruby2d.com/learn/audio/
I hope some one could look into this
A:
It's not a bug.
The Ruby2D::Sound class doesn't have a #pause method.
# frozen_string_literal: true
# Ruby2D::Sound
module Ruby2D
# Sounds are intended to be short samples, played without interruption, like an effect.
class Sound
attr_reader :path
attr_accessor :loop, :data
#
# Load a sound from a file
# @param [String] path File to load the sound from
# @param [true, false] loop If +true+ playback will loop automatically, default is +false+
# @raise [Error] if file cannot be found or music could not be successfully loaded.
def initialize(path, loop: false)
raise Error, "Cannot find audio file `#{path}`" unless File.exist? path
@path = path
@loop = loop
raise Error, "Sound `#{@path}` cannot be created" unless ext_init(@path)
end
# Play the sound
def play
ext_play
end
# Stop the sound
def stop
ext_stop
end
# Returns the length in seconds
def length
ext_length
end
# Get the volume of the sound
def volume
ext_get_volume
end
# Set the volume of the sound
def volume=(volume)
# Clamp value to between 0-100
ext_set_volume(volume.clamp(0, 100))
end
# Get the volume of the sound mixer
def self.mix_volume
ext_get_mix_volume
end
# Set the volume of the sound mixer
def self.mix_volume=(volume)
# Clamp value to between 0-100
ext_set_mix_volume(volume.clamp(0, 100))
end
end
end
Note:
Sounds are intended to be short samples, played without interruption, like an effect.
If you look at the linked example they are using the Music class which does.
song = Music.new('song.mp3')
# Play the music
song.play
# Pause the music
song.pause
The top level doc also states:
Music is for longer pieces which can be played, paused, stopped, resumed, and faded out, like a background soundtrack.
|
Possibly a error within ruby2d's library method regarding Audio input?
|
undefined method `pause' for #<Ruby2D::Sound:0x000002728db4b250 @path="musics/machinegun.mp3", @data=#<Object:0x000002728db4b1d8>> (NoMethodError)
pause or stop etc is a built-in method in ruby2d but I can not seem to make this work. I think that a specific part of ruby2d method might ran into an error because the play method, which is in the same category, still works fine but not the other aforementioned functions.
assault_rifle = Sound.new('musics/machinegun.mp3')
on :key_held do |event|
if event.key == 'k'
mainscreen.player_fire_bullet
assault_rifle.play # this works!
end
if event.key == 'l'
assault_rifle.pause # this is just to test my theory that the method is broken
end
end
on :key_up do |event|
if event.key == 'k'
assault_rifle.stop #method error here?
end
end
For more information regarding ruby2d 's audio, you can read it here: https://www.ruby2d.com/learn/audio/
I hope some one could look into this
|
[
"It's not a bug.\nThe Ruby2D::Sound class doesn't have a #pause method.\n# frozen_string_literal: true\n\n# Ruby2D::Sound\n\nmodule Ruby2D\n # Sounds are intended to be short samples, played without interruption, like an effect.\n class Sound\n attr_reader :path\n attr_accessor :loop, :data\n\n #\n # Load a sound from a file\n # @param [String] path File to load the sound from\n # @param [true, false] loop If +true+ playback will loop automatically, default is +false+\n # @raise [Error] if file cannot be found or music could not be successfully loaded.\n def initialize(path, loop: false)\n raise Error, \"Cannot find audio file `#{path}`\" unless File.exist? path\n\n @path = path\n @loop = loop\n raise Error, \"Sound `#{@path}` cannot be created\" unless ext_init(@path)\n end\n\n # Play the sound\n def play\n ext_play\n end\n\n # Stop the sound\n def stop\n ext_stop\n end\n\n # Returns the length in seconds\n def length\n ext_length\n end\n\n # Get the volume of the sound\n def volume\n ext_get_volume\n end\n\n # Set the volume of the sound\n def volume=(volume)\n # Clamp value to between 0-100\n ext_set_volume(volume.clamp(0, 100))\n end\n\n # Get the volume of the sound mixer\n def self.mix_volume\n ext_get_mix_volume\n end\n\n # Set the volume of the sound mixer\n def self.mix_volume=(volume)\n # Clamp value to between 0-100\n ext_set_mix_volume(volume.clamp(0, 100))\n end\n end\nend\n\nNote:\n\nSounds are intended to be short samples, played without interruption, like an effect.\n\nIf you look at the linked example they are using the Music class which does.\nsong = Music.new('song.mp3')\n\n# Play the music\nsong.play\n\n# Pause the music\nsong.pause\n\nThe top level doc also states:\n\nMusic is for longer pieces which can be played, paused, stopped, resumed, and faded out, like a background soundtrack.\n\n"
] |
[
1
] |
[] |
[] |
[
"ruby",
"ruby2d"
] |
stackoverflow_0074664114_ruby_ruby2d.txt
|
Q:
Sending hidden data via button press using JS
I'm creating a Twitter/Reddit style website. I've been wondering what is the best way to securely send the in-depth details of comment data via a reply button press, grabbing it in JS and sending it back to my database
If there are 100 comments with 100 reply buttons, can I store the comment ID in the value field of the button or is this too open? My feelings are that even if users know the ID values of the comment they reply to, anyone that attempts to abuse a system with spam would get automatically limited or banned via server side detection.
Note that on the server side, a user already has a session so spam should be quite visible... right?
I've seen the option to use type="hidden", eg:
but it seems this can be pulled with a little jquery anyway. Thoughts?
Thanks.
A:
Yes you are right. According to me you can do one thing convert the each comment id into an unique hash then add that value in the button field and while submitting the reply convert that unique hash into the id in the server side only and if id not matched then consider it as a spam and send internal server error message.
A:
There are a few options you could consider to securely send the in-depth details of comment data via a reply button press:
Use a unique identifier for each comment, such as a UUID, and store
this in the value field of the reply button. This would prevent
users from easily guessing the comment ID values, and would also
make it more difficult for someone to abuse the system with spam.
Use an encrypted token to securely transmit the comment data from
the front-end to the back-end. This would make it virtually
impossible for anyone to intercept and access the data without the
correct decryption key.
Implement server-side validation and spam detection to automatically
limit or ban users who attempt to abuse the system. This would help
ensure that only legitimate comments are posted, and would make it
easier to identify and block spamming attempts.
Overall, it's important to consider both security and user experience when designing your reply button functionality. By implementing a combination of the above approaches, you can ensure that your users can easily engage with the comments on your site while protecting their data from unauthorized access.
|
Sending hidden data via button press using JS
|
I'm creating a Twitter/Reddit style website. I've been wondering what is the best way to securely send the in-depth details of comment data via a reply button press, grabbing it in JS and sending it back to my database
If there are 100 comments with 100 reply buttons, can I store the comment ID in the value field of the button or is this too open? My feelings are that even if users know the ID values of the comment they reply to, anyone that attempts to abuse a system with spam would get automatically limited or banned via server side detection.
Note that on the server side, a user already has a session so spam should be quite visible... right?
I've seen the option to use type="hidden", eg:
but it seems this can be pulled with a little jquery anyway. Thoughts?
Thanks.
|
[
"Yes you are right. According to me you can do one thing convert the each comment id into an unique hash then add that value in the button field and while submitting the reply convert that unique hash into the id in the server side only and if id not matched then consider it as a spam and send internal server error message.\n",
"There are a few options you could consider to securely send the in-depth details of comment data via a reply button press:\n\nUse a unique identifier for each comment, such as a UUID, and store\nthis in the value field of the reply button. This would prevent\nusers from easily guessing the comment ID values, and would also\nmake it more difficult for someone to abuse the system with spam.\nUse an encrypted token to securely transmit the comment data from\nthe front-end to the back-end. This would make it virtually\nimpossible for anyone to intercept and access the data without the\ncorrect decryption key.\nImplement server-side validation and spam detection to automatically\nlimit or ban users who attempt to abuse the system. This would help\nensure that only legitimate comments are posted, and would make it\neasier to identify and block spamming attempts.\n\nOverall, it's important to consider both security and user experience when designing your reply button functionality. By implementing a combination of the above approaches, you can ensure that your users can easily engage with the comments on your site while protecting their data from unauthorized access.\n"
] |
[
0,
0
] |
[] |
[] |
[
"html",
"javascript",
"php",
"security"
] |
stackoverflow_0074665453_html_javascript_php_security.txt
|
Q:
REACT AXIOS Parsing Json
I am new to react, so if I am doing anything outside of the problem wrong please tell me also.
I'm trying to map my json response into a table, I can collect the data into an object array, but I am receiving this error :
Here is the components code:
import axios from "axios";
function FilmTableRows(props) {
const dataFormat = props.dataFormat;
const [data, setData] = useState([]);
const baseURL = "http://localhost:8080/FilmRestful/filmapi";
const getJson = () => {
let config = {
headers: {
"data-type": "json",
"Content-type": "application/json",
},
};
axios
.get(baseURL, config)
.then((res) => {
const resData = res.data;
setData(resData);
})
.catch((err) => {});
};
switch (dataFormat.value) {
case "json":
getJson();
console.log(data);
break;
case "xml":
getXML();
console.log(data);
break;
default:
getString();
console.log(data);
}
const child = data.map((el) => {
return (
<tr key={el.id}>
<td>{el.title}</td>
<td>{el.year}</td>
<td>{el.director}</td>
<td>{el.stars}</td>
<td>{el.review}</td>
</tr>
);
});
return <>{data && data.length > 0 && { child }}</>;
}
export default FilmTableRows;
A:
The error is caused because you wrap child with {} when you render it, which turns it into an object with an array variable. Try removing them like so:
return <>{data && data.length > 0 && child }</>;
A:
In your case child doesn't need to be wrapped inside {} because it is array of HTML Elements.
also you don't need to check data.length in order to map your array ,
that's bacause array with 0 length does not render anything automatically.
just change your render to following code :
return <>{data && child}</>
|
REACT AXIOS Parsing Json
|
I am new to react, so if I am doing anything outside of the problem wrong please tell me also.
I'm trying to map my json response into a table, I can collect the data into an object array, but I am receiving this error :
Here is the components code:
import axios from "axios";
function FilmTableRows(props) {
const dataFormat = props.dataFormat;
const [data, setData] = useState([]);
const baseURL = "http://localhost:8080/FilmRestful/filmapi";
const getJson = () => {
let config = {
headers: {
"data-type": "json",
"Content-type": "application/json",
},
};
axios
.get(baseURL, config)
.then((res) => {
const resData = res.data;
setData(resData);
})
.catch((err) => {});
};
switch (dataFormat.value) {
case "json":
getJson();
console.log(data);
break;
case "xml":
getXML();
console.log(data);
break;
default:
getString();
console.log(data);
}
const child = data.map((el) => {
return (
<tr key={el.id}>
<td>{el.title}</td>
<td>{el.year}</td>
<td>{el.director}</td>
<td>{el.stars}</td>
<td>{el.review}</td>
</tr>
);
});
return <>{data && data.length > 0 && { child }}</>;
}
export default FilmTableRows;
|
[
"The error is caused because you wrap child with {} when you render it, which turns it into an object with an array variable. Try removing them like so:\nreturn <>{data && data.length > 0 && child }</>;\n\n",
"In your case child doesn't need to be wrapped inside {} because it is array of HTML Elements.\nalso you don't need to check data.length in order to map your array ,\nthat's bacause array with 0 length does not render anything automatically.\njust change your render to following code :\nreturn <>{data && child}</>\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"axios",
"javascript",
"reactjs"
] |
stackoverflow_0074666827_axios_javascript_reactjs.txt
|
Q:
FabricJS fixed size TextBox with dynamic fontsIze (shrink text to fit size)
How can I fix the size of a TextBox and dynamically decrease the fontSize if the text gets to large for the TextBox? Yes a similar question exists here but it only works for one line of text.
I want to achieve exactly that: (example from the imgflip meme editor)
I have tried following approach:
let text = new fabric.Textbox(box.text, {
top: box.top,
left: box.left,
width: box.width,
});
if (text.width > box.width) {
text.fontSize *= box.width / (text.width + 1);
text.width = box.width;
}
if (text.height > box.height) {
text.fontSize *= box.height / (text.height + 1);
text.height = box.height;
}
canvas.add(text);
This way the fontSize decreases by the ratio of which the width or height of the textbox changed. But this causes the text to get extremely small sometimes because the text won't get wrapped as nicely as it could. The fontSize and the wrapping need to find an optimum somehow. Any ideas? Thanks!
A:
I actually found a solution. Just in case someone has the same problem.
Adjusting the font size for the width works well with my original code:
if (text.width > box.width) {
text.fontSize *= box.width / (text.width + 1);
text.width = box.width;
}
This will only adjust the font size for really long words because the Textbox automatically wraps the text. But this wrapping causes the height to shrink too much with my original code. In order to take the wrapping into consideration I ended up gradually decreasing the font size and recalculating the text wrapping by calling canvas.renderAll() every time:
while (text.height > box.height && text.fontSize > 12) {
text.fontSize--;
canvas.renderAll();
}
This might be inefficient but it served my use case.
A:
Text wrap working and font size changes w.r.t sticky note width and height. Editing mode activates on double click.
export const createStickyNotes = (canvas, options) => {
fabric.StickyNote = fabric.util.createClass(fabric.Group, {
type: "StickyNote",
initialize: function (options) {
this.set(options);
var height = this.height;
var width = this.width;
this.rectObj = new fabric.Rect({
width: width,
height: height,
fill: this.rectObj?.fill ?? "rgba(251,201,112,1)",
originX: "center",
originY: "center",
objectCaching: false,
stateProperties: ["fill"],
});
this.textObj = new fabric.Textbox(this.textObj?.text ?? "Notes", {
originX: "center",
originY: "center",
textAlign: "center",
width: 100,
hasControls: false,
fontSize: this.textObj?.fontSize ?? 30,
lineHeight: 1,
stateProperties: ["text", "fontSize"],
scaleX: this.textObj?.scaleX ?? 1,
scaleY: this.textObj?.scaleY ?? 1,
objectCaching: false,
breakWords: true,
fontFamily: "Open Sans",
});
this._objects = [this.rectObj, this.textObj];
// this custom _set function will set custom properties value to object when it will load from json.
// at that time loadFromJson function will call this initialize function.
// this._setCustomProperties(this.options);
canvas.renderAll();
//evenet will fire if the object is double clicked by mouse
this.on("mousedblclick", (e) => {
var pasteFlag = false;
var scaling = e.target.getScaledWidth() / 100;
var textForEditing;
canvas.bringToFront(e.target);
e.target.selectable = false;
const [rectObj, textObj] = this.getObjects();
textObj.clone(function (clonedObj) {
clonedObj.set({
left: e.target.left,
top: e.target.top,
lockMovementY: true,
lockMovementX: true,
hasBorders: false,
scaleX: scaling,
scaleY: scaling,
breakWords: true,
width: textObj.width,
stateProperties: [],
});
textForEditing = clonedObj;
});
this.remove(textObj);
canvas.add(textForEditing);
canvas.setActiveObject(textForEditing);
textForEditing.enterEditing();
textForEditing.selectAll();
textForEditing.paste = (function (paste) {
return function (e) {
disableScrolling();
pasteFlag = true;
};
})(textForEditing.paste);
textForEditing.on("changed", function (e) {
var fontSize = textForEditing.fontSize;
var charCount = Math.max(textForEditing._text.length, 1);
var charWR =
(textForEditing.textLines.length * width) / (charCount * fontSize);
if (textForEditing.height < height - 15) {
fontSize = Math.min(
Math.sqrt(
((height - 10 - fontSize) / 1.16) *
(width / (charCount * charWR))
),
30
);
}
if (textForEditing.height > height - 15) {
fontSize = Math.sqrt(
((height - 10) / 1.16) * (width / (charCount * charWR))
);
}
if (pasteFlag) {
pasteFlag = false;
while (
textForEditing.height > height - 15 &&
textForEditing.fontSize > 0
) {
fontSize = textForEditing.fontSize -= 0.2;
canvas.renderAll();
}
}
textForEditing.fontSize = fontSize;
});
textForEditing.on("editing:exited", () => {
enableScrolling();
canvas.setActiveObject(textObj);
textObj.set({
text: textForEditing.text,
fontSize: textForEditing.fontSize,
visible: true,
});
this.add(textObj);
this.selectable = true;
canvas.remove(textForEditing);
canvas.discardActiveObject();
});
});
function disableScrolling() {
var x = window.scrollX;
var y = window.scrollY;
window.onscroll = function () {
window.scrollTo(x, y);
};
}
var _wrapLine = function (_line, lineIndex, desiredWidth, reservedSpace) {
var lineWidth = 0,
splitByGrapheme = this.splitByGrapheme,
graphemeLines = [],
line = [],
// spaces in different languges?
words = splitByGrapheme
? fabric.util.string.graphemeSplit(_line)
: _line.split(this._wordJoiners),
word = "",
offset = 0,
infix = splitByGrapheme ? "" : " ",
wordWidth = 0,
infixWidth = 0,
largestWordWidth = 0,
lineJustStarted = true,
additionalSpace = splitByGrapheme ? 0 : this._getWidthOfCharSpacing();
reservedSpace = reservedSpace || 0;
desiredWidth -= reservedSpace;
for (var i = 0; i < words.length; i++) {
// i would avoid resplitting the graphemes
word = fabric.util.string.graphemeSplit(words[i]);
wordWidth = this._measureWord(word, lineIndex, offset);
offset += word.length;
// Break the line if a word is wider than the set width
if (this.breakWords && wordWidth >= desiredWidth) {
if (!lineJustStarted) {
graphemeLines.push(line);
line = [];
lineWidth = 0;
lineJustStarted = true;
}
this.fontSize *= desiredWidth / (wordWidth + 1);
// Loop through each character in word
for (var w = 0; w < word.length; w++) {
var letter = word[w];
var letterWidth =
(this.getMeasuringContext().measureText(letter).width *
this.fontSize) /
this.CACHE_FONT_SIZE;
line.push(letter);
lineWidth += letterWidth;
}
word = [];
} else {
lineWidth += infixWidth + wordWidth - additionalSpace;
}
if (lineWidth >= desiredWidth && !lineJustStarted) {
graphemeLines.push(line);
line = [];
lineWidth = wordWidth;
lineJustStarted = true;
} else {
lineWidth += additionalSpace;
}
if (!lineJustStarted) {
line.push(infix);
}
line = line.concat(word);
infixWidth = this._measureWord([infix], lineIndex, offset);
offset++;
lineJustStarted = false;
// keep track of largest word
if (wordWidth > largestWordWidth && !this.breakWords) {
largestWordWidth = wordWidth;
}
}
i && graphemeLines.push(line);
if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {
this.dynamicMinWidth =
largestWordWidth - additionalSpace + reservedSpace;
}
return graphemeLines;
};
fabric.util.object.extend(fabric.Textbox.prototype, {
_wrapLine: _wrapLine,
});
function enableScrolling() {
window.onscroll = function () {};
}
},
toObject: function (propertiesToInclude) {
// This function is used for serialize this object. (used for create json)
// not inlclude this.textObj and this.rectObj into json because when object will load from json, init fucntion of this class is called and it will assign this two object textObj and rectObj again.
var obj = this.callSuper(
"toObject",
[
"objectCaching",
"textObj",
"rectObj",
// ... property list that you want to add into json when this object is convert into json using toJSON() function. (serialize)
].concat(propertiesToInclude)
);
// delete objects array from json because then object load from json, Init function will call. which will automatically re-assign object and assign _object array.
delete obj.objects;
return obj;
},
});
fabric.StickyNote.async = true;
fabric.StickyNote.fromObject = function (object, callback) {
// This function is used for deserialize json and convert object json into button object again. (called when we call loadFromJson() fucntion on canvas)
return fabric.Object._fromObject("StickyNote", object, callback);
};
return new fabric.StickyNote(options);
};
//How to use
var options = {
width: 100,
height: 100,
originX: "center",
originY: "center",
};
var notes = StickyNotes(canvas, options);
canvas.add(notes);
|
FabricJS fixed size TextBox with dynamic fontsIze (shrink text to fit size)
|
How can I fix the size of a TextBox and dynamically decrease the fontSize if the text gets to large for the TextBox? Yes a similar question exists here but it only works for one line of text.
I want to achieve exactly that: (example from the imgflip meme editor)
I have tried following approach:
let text = new fabric.Textbox(box.text, {
top: box.top,
left: box.left,
width: box.width,
});
if (text.width > box.width) {
text.fontSize *= box.width / (text.width + 1);
text.width = box.width;
}
if (text.height > box.height) {
text.fontSize *= box.height / (text.height + 1);
text.height = box.height;
}
canvas.add(text);
This way the fontSize decreases by the ratio of which the width or height of the textbox changed. But this causes the text to get extremely small sometimes because the text won't get wrapped as nicely as it could. The fontSize and the wrapping need to find an optimum somehow. Any ideas? Thanks!
|
[
"I actually found a solution. Just in case someone has the same problem. \nAdjusting the font size for the width works well with my original code:\nif (text.width > box.width) {\n text.fontSize *= box.width / (text.width + 1);\n text.width = box.width;\n}\n\nThis will only adjust the font size for really long words because the Textbox automatically wraps the text. But this wrapping causes the height to shrink too much with my original code. In order to take the wrapping into consideration I ended up gradually decreasing the font size and recalculating the text wrapping by calling canvas.renderAll() every time:\nwhile (text.height > box.height && text.fontSize > 12) {\n text.fontSize--;\n canvas.renderAll();\n}\n\nThis might be inefficient but it served my use case.\n",
"Text wrap working and font size changes w.r.t sticky note width and height. Editing mode activates on double click.\n\n\nexport const createStickyNotes = (canvas, options) => {\n fabric.StickyNote = fabric.util.createClass(fabric.Group, {\n type: \"StickyNote\",\n initialize: function (options) {\n this.set(options);\n var height = this.height;\n var width = this.width;\n\n this.rectObj = new fabric.Rect({\n width: width,\n height: height,\n fill: this.rectObj?.fill ?? \"rgba(251,201,112,1)\",\n originX: \"center\",\n originY: \"center\",\n objectCaching: false,\n stateProperties: [\"fill\"],\n });\n this.textObj = new fabric.Textbox(this.textObj?.text ?? \"Notes\", {\n originX: \"center\",\n originY: \"center\",\n textAlign: \"center\",\n width: 100,\n hasControls: false,\n fontSize: this.textObj?.fontSize ?? 30,\n lineHeight: 1,\n stateProperties: [\"text\", \"fontSize\"],\n scaleX: this.textObj?.scaleX ?? 1,\n scaleY: this.textObj?.scaleY ?? 1,\n objectCaching: false,\n breakWords: true,\n fontFamily: \"Open Sans\",\n });\n\n this._objects = [this.rectObj, this.textObj];\n // this custom _set function will set custom properties value to object when it will load from json.\n // at that time loadFromJson function will call this initialize function.\n // this._setCustomProperties(this.options);\n canvas.renderAll();\n\n //evenet will fire if the object is double clicked by mouse\n this.on(\"mousedblclick\", (e) => {\n var pasteFlag = false;\n var scaling = e.target.getScaledWidth() / 100;\n var textForEditing;\n canvas.bringToFront(e.target);\n e.target.selectable = false;\n const [rectObj, textObj] = this.getObjects();\n textObj.clone(function (clonedObj) {\n clonedObj.set({\n left: e.target.left,\n top: e.target.top,\n lockMovementY: true,\n lockMovementX: true,\n hasBorders: false,\n scaleX: scaling,\n scaleY: scaling,\n breakWords: true,\n width: textObj.width,\n stateProperties: [],\n });\n textForEditing = clonedObj;\n });\n\n this.remove(textObj);\n canvas.add(textForEditing);\n canvas.setActiveObject(textForEditing);\n\n textForEditing.enterEditing();\n textForEditing.selectAll();\n\n textForEditing.paste = (function (paste) {\n return function (e) {\n disableScrolling();\n pasteFlag = true;\n };\n })(textForEditing.paste);\n\n textForEditing.on(\"changed\", function (e) {\n var fontSize = textForEditing.fontSize;\n var charCount = Math.max(textForEditing._text.length, 1);\n var charWR =\n (textForEditing.textLines.length * width) / (charCount * fontSize);\n\n if (textForEditing.height < height - 15) {\n fontSize = Math.min(\n Math.sqrt(\n ((height - 10 - fontSize) / 1.16) *\n (width / (charCount * charWR))\n ),\n 30\n );\n }\n if (textForEditing.height > height - 15) {\n fontSize = Math.sqrt(\n ((height - 10) / 1.16) * (width / (charCount * charWR))\n );\n }\n if (pasteFlag) {\n pasteFlag = false;\n while (\n textForEditing.height > height - 15 &&\n textForEditing.fontSize > 0\n ) {\n fontSize = textForEditing.fontSize -= 0.2;\n canvas.renderAll();\n }\n }\n textForEditing.fontSize = fontSize;\n });\n\n textForEditing.on(\"editing:exited\", () => {\n enableScrolling();\n canvas.setActiveObject(textObj);\n textObj.set({\n text: textForEditing.text,\n fontSize: textForEditing.fontSize,\n visible: true,\n });\n this.add(textObj);\n this.selectable = true;\n canvas.remove(textForEditing);\n canvas.discardActiveObject();\n });\n });\n\n function disableScrolling() {\n var x = window.scrollX;\n var y = window.scrollY;\n window.onscroll = function () {\n window.scrollTo(x, y);\n };\n }\n\n var _wrapLine = function (_line, lineIndex, desiredWidth, reservedSpace) {\n var lineWidth = 0,\n splitByGrapheme = this.splitByGrapheme,\n graphemeLines = [],\n line = [],\n // spaces in different languges?\n words = splitByGrapheme\n ? fabric.util.string.graphemeSplit(_line)\n : _line.split(this._wordJoiners),\n word = \"\",\n offset = 0,\n infix = splitByGrapheme ? \"\" : \" \",\n wordWidth = 0,\n infixWidth = 0,\n largestWordWidth = 0,\n lineJustStarted = true,\n additionalSpace = splitByGrapheme ? 0 : this._getWidthOfCharSpacing();\n\n reservedSpace = reservedSpace || 0;\n desiredWidth -= reservedSpace;\n for (var i = 0; i < words.length; i++) {\n // i would avoid resplitting the graphemes\n word = fabric.util.string.graphemeSplit(words[i]);\n wordWidth = this._measureWord(word, lineIndex, offset);\n offset += word.length;\n\n // Break the line if a word is wider than the set width\n if (this.breakWords && wordWidth >= desiredWidth) {\n if (!lineJustStarted) {\n graphemeLines.push(line);\n line = [];\n lineWidth = 0;\n lineJustStarted = true;\n }\n this.fontSize *= desiredWidth / (wordWidth + 1);\n // Loop through each character in word\n for (var w = 0; w < word.length; w++) {\n var letter = word[w];\n var letterWidth =\n (this.getMeasuringContext().measureText(letter).width *\n this.fontSize) /\n this.CACHE_FONT_SIZE;\n line.push(letter);\n lineWidth += letterWidth;\n }\n word = [];\n } else {\n lineWidth += infixWidth + wordWidth - additionalSpace;\n }\n\n if (lineWidth >= desiredWidth && !lineJustStarted) {\n graphemeLines.push(line);\n line = [];\n lineWidth = wordWidth;\n lineJustStarted = true;\n } else {\n lineWidth += additionalSpace;\n }\n\n if (!lineJustStarted) {\n line.push(infix);\n }\n line = line.concat(word);\n\n infixWidth = this._measureWord([infix], lineIndex, offset);\n offset++;\n lineJustStarted = false;\n // keep track of largest word\n if (wordWidth > largestWordWidth && !this.breakWords) {\n largestWordWidth = wordWidth;\n }\n }\n\n i && graphemeLines.push(line);\n\n if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {\n this.dynamicMinWidth =\n largestWordWidth - additionalSpace + reservedSpace;\n }\n\n return graphemeLines;\n };\n\n fabric.util.object.extend(fabric.Textbox.prototype, {\n _wrapLine: _wrapLine,\n });\n\n function enableScrolling() {\n window.onscroll = function () {};\n }\n },\n\n toObject: function (propertiesToInclude) {\n // This function is used for serialize this object. (used for create json)\n // not inlclude this.textObj and this.rectObj into json because when object will load from json, init fucntion of this class is called and it will assign this two object textObj and rectObj again.\n var obj = this.callSuper(\n \"toObject\",\n [\n \"objectCaching\",\n \"textObj\",\n \"rectObj\",\n // ... property list that you want to add into json when this object is convert into json using toJSON() function. (serialize)\n ].concat(propertiesToInclude)\n );\n // delete objects array from json because then object load from json, Init function will call. which will automatically re-assign object and assign _object array.\n delete obj.objects;\n return obj;\n },\n });\n\n fabric.StickyNote.async = true;\n fabric.StickyNote.fromObject = function (object, callback) {\n // This function is used for deserialize json and convert object json into button object again. (called when we call loadFromJson() fucntion on canvas)\n return fabric.Object._fromObject(\"StickyNote\", object, callback);\n };\n\n return new fabric.StickyNote(options);\n};\n\n\n\n\n\n//How to use \n\n var options = {\n width: 100,\n height: 100,\n originX: \"center\",\n originY: \"center\",\n };\n var notes = StickyNotes(canvas, options);\n canvas.add(notes);\n\n\n\n"
] |
[
5,
0
] |
[] |
[] |
[
"fabricjs",
"javascript",
"typescript"
] |
stackoverflow_0061829350_fabricjs_javascript_typescript.txt
|
Q:
JS turn a multi-line string into an array (each item= a line)
For example, I have:
var str = "Hello
World"
I'm expecting an array like that : array["Hello", "World"]
I looked for a method that does that but nothing, I tried to make a loop but I don't know on what I should base my loop? From my knowledge there's not a .length property for the amount of lines in a string...
A:
Use the split function:
var str = `Hello
World`;
var splittedArray = str.split(/\r?\n/);
console.log(splittedArray)
|
JS turn a multi-line string into an array (each item= a line)
|
For example, I have:
var str = "Hello
World"
I'm expecting an array like that : array["Hello", "World"]
I looked for a method that does that but nothing, I tried to make a loop but I don't know on what I should base my loop? From my knowledge there's not a .length property for the amount of lines in a string...
|
[
"Use the split function:\n\n\nvar str = `Hello\nWorld`;\nvar splittedArray = str.split(/\\r?\\n/);\nconsole.log(splittedArray)\n\n\n\n"
] |
[
2
] |
[] |
[] |
[
"arrays",
"javascript",
"multiline",
"split",
"string"
] |
stackoverflow_0074667132_arrays_javascript_multiline_split_string.txt
|
Q:
Problem of calculating the days between two dates in c++ using class of Date when the first date is bigger than second date
when the first date is bigger than the second, it doesent calculate.
for example: first date 22/10/2022
second date: 15/10/2022
#include <iostream>
#include <cstdlib>
using namespace std;
class Date {
public:
Date(int d, int m, int y);
void set_date(int d, int m, int y);
void print_date();
void inc_one_day();
bool equals(Date d);
int get_day() { return day; }
int get_month() { return month; }
int get_year() { return year; }
private :
int day;
int month;
int year;
};
bool is_leap_year(int year)
{
int r = year % 33;
return r == 1 || r == 5 || r == 9 || r == 13 || r == 17 || r == 22 || r == 26 || r == 30;
}
int days_of_month(int m, int y){
if (m < 7)
return 31;
else if (m < 12)
return 30;
else if (m == 12)
return is_leap_year(y) ? 30 : 29;
else
abort();
}
void Date::inc_one_day(){
day++;
if (day > days_of_month(month, year)) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
}
bool Date::equals(Date d) {
return day == d.day && month == d.month && year == d.year;
}
int days_between(Date d1, Date d2){
int count = 1;
while (!d1.equals(d2)){
d1.inc_one_day();
count++;
}
return count;
}
Date::Date(int d, int m, int y){
cout << "constructor called \n";
set_date(d, m, y);
}
void Date::set_date(int d, int m, int y){
if (y < 0 || m < 1 || m>12 || d < 1 || d > days_of_month(m, y))
abort();
day = d;
month = m;
year = y;
}
void Date::print_date(){
cout << day << '/' << month << '/' << year<<endl;
}
int main(){
Date bd(22, 12, 1395);
Date be(15, 12, 1395);
cout << '\n';
int i;
i= days_between(bd, be);
cout << i << endl;
}
here's my code.
I've seen many codes that calculate the days between two dates, but they didn't use class Date.
how can i solve this problem? could you guys help me please.I'm sorry i'm new in c++ so, my problem might be so basic.
A:
It is clear why your algorithm does not work - you are incrementing the later date so it will never equal the earlier date. The solution is simply to compare the dates and swap the operands if necessary so that you are always incrementing the earlier date toward the later date.
int days_between(Date d1, Date d2)
{
int count = 0 ;
// Initially assume d2 >= d1
Date* earlier = &d1 ;
Date* later = &d2 ;
// Test if d1 > d2...
int year_diff = d2.get_year() - d1.get_year() ;
int mon_diff = d2.get_month() - d1.get_month() ;
int day_diff = d2.get_day() - d1.get_day() ;
if( year_diff < 0 ||
(year_diff == 0 && (mon_diff < 0 || (mon_diff == 0 &&
day_diff < 0 ))))
{
// d1 > d2, so swap
earlier = &d2 ;
later = &d1 ;
}
while (!earlier->equals(*later))
{
earlier->inc_one_day();
count++;
}
return count;
}
Note that it is not clear why you start with a count of 1. If the dates start equal, surely that should return a zero? That is how I have written it in any case.
If it is required to indicate whether the dates were reversed or not, you might want to return a signed value. In that case:
return earlier == &d2 ? -count : count ;
Which for the dates in your example will return -7.
Your solution is a good candidate for operator overloading so you could simply and more intuitively write:
if( d1 > d2 )
{
earlier = &d2 ;
later = &d1 ;
}
while( *earlier != *later))
{
earlier++ ;
count++ ;
}
return earlier == &d2 ? -count : count ;
and even ultimately:
i = be - bd;
A:
What would be easier is to write a function that calculates the total number of days that have occurred since the year 0000. After that you can simply subtract them from each other and return the total number of days between them.
|
Problem of calculating the days between two dates in c++ using class of Date when the first date is bigger than second date
|
when the first date is bigger than the second, it doesent calculate.
for example: first date 22/10/2022
second date: 15/10/2022
#include <iostream>
#include <cstdlib>
using namespace std;
class Date {
public:
Date(int d, int m, int y);
void set_date(int d, int m, int y);
void print_date();
void inc_one_day();
bool equals(Date d);
int get_day() { return day; }
int get_month() { return month; }
int get_year() { return year; }
private :
int day;
int month;
int year;
};
bool is_leap_year(int year)
{
int r = year % 33;
return r == 1 || r == 5 || r == 9 || r == 13 || r == 17 || r == 22 || r == 26 || r == 30;
}
int days_of_month(int m, int y){
if (m < 7)
return 31;
else if (m < 12)
return 30;
else if (m == 12)
return is_leap_year(y) ? 30 : 29;
else
abort();
}
void Date::inc_one_day(){
day++;
if (day > days_of_month(month, year)) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
}
bool Date::equals(Date d) {
return day == d.day && month == d.month && year == d.year;
}
int days_between(Date d1, Date d2){
int count = 1;
while (!d1.equals(d2)){
d1.inc_one_day();
count++;
}
return count;
}
Date::Date(int d, int m, int y){
cout << "constructor called \n";
set_date(d, m, y);
}
void Date::set_date(int d, int m, int y){
if (y < 0 || m < 1 || m>12 || d < 1 || d > days_of_month(m, y))
abort();
day = d;
month = m;
year = y;
}
void Date::print_date(){
cout << day << '/' << month << '/' << year<<endl;
}
int main(){
Date bd(22, 12, 1395);
Date be(15, 12, 1395);
cout << '\n';
int i;
i= days_between(bd, be);
cout << i << endl;
}
here's my code.
I've seen many codes that calculate the days between two dates, but they didn't use class Date.
how can i solve this problem? could you guys help me please.I'm sorry i'm new in c++ so, my problem might be so basic.
|
[
"It is clear why your algorithm does not work - you are incrementing the later date so it will never equal the earlier date. The solution is simply to compare the dates and swap the operands if necessary so that you are always incrementing the earlier date toward the later date.\nint days_between(Date d1, Date d2)\n{\n int count = 0 ;\n \n // Initially assume d2 >= d1\n Date* earlier = &d1 ;\n Date* later = &d2 ;\n \n // Test if d1 > d2...\n int year_diff = d2.get_year() - d1.get_year() ;\n int mon_diff = d2.get_month() - d1.get_month() ;\n int day_diff = d2.get_day() - d1.get_day() ;\n if( year_diff < 0 ||\n (year_diff == 0 && (mon_diff < 0 || (mon_diff == 0 &&\n day_diff < 0 ))))\n {\n // d1 > d2, so swap\n earlier = &d2 ;\n later = &d1 ;\n }\n \n while (!earlier->equals(*later))\n {\n earlier->inc_one_day();\n count++;\n }\n \n return count;\n}\n\nNote that it is not clear why you start with a count of 1. If the dates start equal, surely that should return a zero? That is how I have written it in any case.\nIf it is required to indicate whether the dates were reversed or not, you might want to return a signed value. In that case:\nreturn earlier == &d2 ? -count : count ;\n\nWhich for the dates in your example will return -7.\nYour solution is a good candidate for operator overloading so you could simply and more intuitively write:\nif( d1 > d2 )\n{\n earlier = &d2 ;\n later = &d1 ;\n}\n\nwhile( *earlier != *later))\n{\n earlier++ ;\n count++ ;\n}\n\nreturn earlier == &d2 ? -count : count ;\n\nand even ultimately:\ni = be - bd;\n\n",
"What would be easier is to write a function that calculates the total number of days that have occurred since the year 0000. After that you can simply subtract them from each other and return the total number of days between them.\n"
] |
[
1,
0
] |
[] |
[] |
[
"c++",
"class",
"date",
"days",
"visual_c++"
] |
stackoverflow_0074662177_c++_class_date_days_visual_c++.txt
|
Q:
How to restore influxdb from local backup || InfluxDB
I am trying to import client's provided influx db data backup to my local influx db. But getting following error.
ENV: Ubuntu
Influx DB service is already running.
enter image description here
Trying to restore influx db backup.
A:
First of all you are using the wrong command to execute influxdb task. It should be influxd instead of influx. Please follow the steps below to restore your database.
Check your data-dir path by executing: influxd config. Copy the data-dir section.
See database name by executing: SHOW Databases
Execute to restore: influxd restore -database {database_name} -data-dir {your_data_dir_path} /path/to/your/backup
|
How to restore influxdb from local backup || InfluxDB
|
I am trying to import client's provided influx db data backup to my local influx db. But getting following error.
ENV: Ubuntu
Influx DB service is already running.
enter image description here
Trying to restore influx db backup.
|
[
"First of all you are using the wrong command to execute influxdb task. It should be influxd instead of influx. Please follow the steps below to restore your database.\n\nCheck your data-dir path by executing: influxd config. Copy the data-dir section.\nSee database name by executing: SHOW Databases\nExecute to restore: influxd restore -database {database_name} -data-dir {your_data_dir_path} /path/to/your/backup\n\n"
] |
[
0
] |
[] |
[] |
[
"influxdb",
"ruby_on_rails"
] |
stackoverflow_0074667111_influxdb_ruby_on_rails.txt
|
Q:
Unique list elements in Tcl
I have two Tcl lists of equal length, u and v. Many of the entries in u are known to be identical. For every unique entry in u, I would like to average over the corresponding entries in v. So, if my lists are {1 2 1 2} and {1 2 3 4}, the output should be {1 2} (only the unique entries in u), and {2 3}, where 2 comes from (1+3)/2, and 3 comes from (2+4)/2.
I have tried the following:
set unique [lsort -unique $u]
foreach i $unique {
set ave 0; set N 0
foreach j $u k $v {
if {$i == $j} {set ave [expr {$ave+$k}]}
}
lappend w [expr {$ave/$N}]
}
This works, but it is far too slow for larger lists. Does anyone know a more efficient way of doing this?
Thanks in advance!
A:
I would use a dictionary to accumulate values in groups by unique keys. This would do pretty much the entire process for me (together with a bit of post-processing to get the averages).
foreach a $u b $v {
dict lappend collector $a $b
}
set uniques [dict keys $collector]
set averages [lmap items [dict values $collector] {
expr { [tcl::mathop::+ {*}$items] / double([llength $items]) }
}
The averages are naturally floating point values.
A:
To more efficiently average over the corresponding entries in two lists, you can use the array data structure in Tcl. The array data structure allows you to store values indexed by keys, and provides efficient methods for accessing and updating the values:
# Create an array to store the sums of the corresponding entries in v
array set sums {}
# Loop through the entries in u and add the corresponding entries in v to the array
foreach i $u j $v {
set sums($i) [expr {$sums($i) + $j}]
}
# Create an empty list to store the results
set result {}
# Loop through the unique entries in u and compute the average of the corresponding entries in v
foreach i [lsort -unique $u] {
lappend result [expr {$sums($i) / [llength $u]}]
}
|
Unique list elements in Tcl
|
I have two Tcl lists of equal length, u and v. Many of the entries in u are known to be identical. For every unique entry in u, I would like to average over the corresponding entries in v. So, if my lists are {1 2 1 2} and {1 2 3 4}, the output should be {1 2} (only the unique entries in u), and {2 3}, where 2 comes from (1+3)/2, and 3 comes from (2+4)/2.
I have tried the following:
set unique [lsort -unique $u]
foreach i $unique {
set ave 0; set N 0
foreach j $u k $v {
if {$i == $j} {set ave [expr {$ave+$k}]}
}
lappend w [expr {$ave/$N}]
}
This works, but it is far too slow for larger lists. Does anyone know a more efficient way of doing this?
Thanks in advance!
|
[
"I would use a dictionary to accumulate values in groups by unique keys. This would do pretty much the entire process for me (together with a bit of post-processing to get the averages).\nforeach a $u b $v {\n dict lappend collector $a $b\n}\nset uniques [dict keys $collector]\nset averages [lmap items [dict values $collector] {\n expr { [tcl::mathop::+ {*}$items] / double([llength $items]) }\n}\n\nThe averages are naturally floating point values.\n",
"To more efficiently average over the corresponding entries in two lists, you can use the array data structure in Tcl. The array data structure allows you to store values indexed by keys, and provides efficient methods for accessing and updating the values:\n# Create an array to store the sums of the corresponding entries in v\narray set sums {}\n\n# Loop through the entries in u and add the corresponding entries in v to the array\nforeach i $u j $v {\n set sums($i) [expr {$sums($i) + $j}]\n}\n\n# Create an empty list to store the results\nset result {}\n\n# Loop through the unique entries in u and compute the average of the corresponding entries in v\nforeach i [lsort -unique $u] {\n lappend result [expr {$sums($i) / [llength $u]}]\n}\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"tcl"
] |
stackoverflow_0074661480_tcl.txt
|
Q:
how to add large no views in linear layout insde base adapter?
`> In base adapter add views in linearlayout small no of views correctly added but large no of views (above 200) that scenario following warning come in logcat an also app showing popup like "app not responing". Anyone help me how to solve this issues
In loop i add sub views many views adding time issue occur. how to solve this issue
@SuppressLint("InflateParams")
public class Productadapnew extends BaseAdapter {
LayoutInflater inflater;
Context context;
private Bitmap btMap = null;
List<production_response> mBeans = new ArrayList<production_response>();
static List<grs_bin_tag> listtag=new ArrayList<>();
List<sub_production_response> listsubproduct=new ArrayList<>();
production_response movieModel;
Activity kactivity;
public Productadapnew(Context context, List<production_response> mBeans,Activity mactivity) {
// TODO Auto-generated constructor stub
this.context = context;
this.kactivity=mactivity;
this.mBeans.addAll(mBeans);
listtag=new ArrayList<>();
inflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mBeans.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView txtrunid,txtid,txtrepname;
TextView txtgrower;
TextView txttype,txtrname;
TextView txtvariety,txtfticket;
TextView txttotalwgt,txtdate,txtview;
LinearLayout linsubproduct,linhead;
ImageView imgview,imgviewup,imgadd,imgprintz;
LinearLayout linmain;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
if (row == null) {
row = inflater.inflate(R.layout.product_home_list, null);
setAttributes(position, row);
}else
{
row = (View) convertView;
}
return row;
}
public void setAttributes(final int position, View itemView) {
final Holder holder = new Holder();
movieModel=mBeans.get(position);
holder.txtrunid= itemView.findViewById(R.id.txt_runid);
holder.txtid= itemView.findViewById(R.id.txt_id);
holder.txtgrower= itemView.findViewById(R.id.txt_grower);
holder.txttype= itemView.findViewById(R.id.txt_type);
holder.txtrname= itemView.findViewById(R.id.txt_rname);
holder.txtvariety= itemView.findViewById(R.id.txt_variety);
holder.txtfticket= itemView.findViewById(R.id.txt_fticket);
holder.txttotalwgt= itemView.findViewById(R.id.txt_totalwgt);
holder.txtdate= itemView.findViewById(R.id.txt_date);
holder.linmain= itemView.findViewById(R.id.lin_grs);
holder.imgview= itemView.findViewById(R.id.img_view);
holder.imgviewup=itemView.findViewById(R.id.img_viewup);
holder.txtview= itemView.findViewById(R.id.txt_view);
holder.imgadd= itemView.findViewById(R.id.img_add);
holder.imgprintz= itemView.findViewById(R.id.img_printz);
holder.linsubproduct=itemView.findViewById(R.id.lin_subproduct);
holder.linhead=itemView.findViewById(R.id.linhead);
holder.txtrepname=itemView.findViewById(R.id.txt_repname);
holder.txtid.setText(""+movieModel.getId());
holder.txtrunid.setText(""+movieModel.getPid());
holder.txtgrower.setText(" : "+movieModel.getGrower());
holder.txttype.setText(" : "+movieModel.getType());
holder.txtrepname.setText(" : "+movieModel.getRep_name());
if(movieModel.getRanch_name() !=null && movieModel.getRanch_name().length()>0 &&
!movieModel.getRanch_name().contentEquals("null"))
{
holder.txtrname.setText(" : "+movieModel.getRanch_name());
}else{
holder.txtrname.setText("");
}
holder.txtvariety.setText(" : "+movieModel.getVariety());
holder.txtfticket.setText(" : "+movieModel.getField_ticket());
holder.txttotalwgt.setText(" : "+movieModel.getTotal_netwt()+" Lb");
holder.txtdate.setText(" : "+movieModel.getCreated_date());
if (movieModel.getViewstatus() != null && movieModel.getViewstatus().length() > 0 && !movieModel.getViewstatus().contentEquals("null")
) {
if(movieModel.getViewstatus().contentEquals("1")) {
holder.txtview.setText("1");
movieModel.setViewstatus("1");
holder.linmain.setVisibility(View.VISIBLE);
// imgview.setBackgroundResource(R.drawable.uparrow);
holder.imgview.setVisibility(View.GONE);
holder.imgviewup.setVisibility(View.VISIBLE);
}
}else {
movieModel.setViewstatus("0");
}
listtag=new ArrayList<>();
holder.linmain.removeAllViews();
try {
List<grs_bin_tag> listtag=new ArrayList<>();
listtag=movieModel.getGrs_bin_tag();
Log.e("listtag","#"+listtag.size());
if (listtag.size() > 0) {
for(int i=0;i<listtag.size();i++)
{//Dialog dialogrk;
grs_bin_tag gk=listtag.get(i);
// Log.e("listtag","#"+gk.getTagno());
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.grn_bin_list, null);
TextView tagvalue = dialogView.findViewById(R.id.txt_tag_value);
TextView typevalue = dialogView.findViewById(R.id.txt_type_value);
TextView txthandlervalue = dialogView.findViewById(R.id.txt_handlervalue);
TextView txttare = dialogView.findViewById(R.id.txt_tare);
TextView txtnwt = dialogView.findViewById(R.id.txt_nwt);
TextView txtgwt = dialogView.findViewById(R.id.txt_gwt);
ImageView imgsubprint=dialogView.findViewById(R.id.img_subprint);
TextView txtrepname=dialogView.findViewById(R.id.txt_repname);
tagvalue.setText(" : " + gk.getTagno());
txthandlervalue.setText(" : " + gk.getHandler());
txttare.setText(" : " + gk.getTare()+" Lb");
txtnwt.setText(" : " + gk.getNet_wt()+" Lb");
txtgwt.setText(" : " + gk.getGross_wt()+" Lb");
txtrepname.setText(" : " + gk.getRep_name());
typevalue.setText(" : "+ gk.getType());
// movieModel.setViewstatus("0");
});
holder.linmain.addView(dialogView);
}
}
//scheduleSendLocation();
} catch (Exception e) {
// TODO: handle exception
}
}
}
//scheduleSendLocation();
} catch (Exception e) {
// TODO: handle exception
}
holder.linsubproduct.addView(dialogView);
}
}
}catch (Exception e)
{
// Log.e("ekkk","@"+e.toString());
}
}
}
}
Enter APP_SCOUT_HANG state
(Current message: duration=5002ms seq=411 late=8ms h=android.view.Choreographer$FrameHandler c=android.view.Choreographer$FrameDisplayEventReceiver)
W Event:APP_SCOUT_HANG Thread:main backtrace:
at android.content.res.AssetManager.nativeApplyStyle(Native Method)
at android.content.res.AssetManager.applyStyle(AssetManager.java:1139)
at android.content.res.ResourcesImpl$ThemeImpl.obtainStyledAttributes(ResourcesImpl.java:1369)
at android.content.res.Resources$Theme.obtainStyledAttributes(Resources.java:1712)
at android.content.Context.obtainStyledAttributes(Context.java:854)
at android.view.View.(View.java:5747)
at android.widget.TextView.(TextView.java:1032)
at android.widget.TextView.(TextView.java:1026)
at androidx.appcompat.widget.AppCompatTextView.(AppCompatTextView.java:108)
at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:93)
at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:88)
at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:83)
at com.google.android.material.theme.MaterialComponentsViewInflater.createTextView(MaterialComponentsViewInflater.java:61)
at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:121)
at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1569)
at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1620)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1088)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1024)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:988)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1150)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1153)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1153)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1153)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1153)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.inflate(LayoutInflater.java:709)
at android.view.LayoutInflater.inflate(LayoutInflater.java:547)
at android.view.LayoutInflater.inflate(LayoutInflater.java:485)
at com.isoft.customalmonds.adapter.Productadapnew.setAttributes(Productadapnew.java:197)
at com.isoft.customalmonds.adapter.Productadapnew.getView(Productadapnew.java:119)
at android.widget.AbsListView.obtainView(AbsListView.java:2421)
at android.widget.ListView.makeAndAddView(ListView.java:2067)
at android.widget.ListView.fillDown(ListView.java:793)
at android.widget.ListView.fillFromTop(ListView.java:855)
at android.widget.ListView.layoutChildren(ListView.java:1838)
at android.widget.AbsListView.onLayout(AbsListView.java:2218)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
2022-12-03 04:49:52.781 16865-16992 MIUIScout App com.isoft.customalmonds W at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:536)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:868)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3858)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3308)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2272)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8999)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1160)
at android.view.Choreographer.doCallbacks(Choreographer.java:950)
at android.view.Choreographer.doFrame(Choreographer.java:879)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1142)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:210)
at android.os.Looper.loop(Looper.java:299)
at android.app.ActivityThread.main(ActivityThread.java:8319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
`
A:
If you are adding more than 200 views in the LinearLayout inside the BaseAdapter, then it's not the correct approach.
You should use the ViewHolder pattern and recycle the views already created instead of creating new views for each item in the list. This will improve the performance drastically.
Also, you can use lazy loading technique to load only the number of views required to display on the screen.
Also, make sure you are using the correct layout for your views. If your views are complex and contain many views, you should use a RecyclerView instead of a LinearLayout. This will also improve the performance.
You can refer to the following links for more information:
RecyclerView
ViewHolder
Lazy Loading
Performance Optimization
|
how to add large no views in linear layout insde base adapter?
|
`> In base adapter add views in linearlayout small no of views correctly added but large no of views (above 200) that scenario following warning come in logcat an also app showing popup like "app not responing". Anyone help me how to solve this issues
In loop i add sub views many views adding time issue occur. how to solve this issue
@SuppressLint("InflateParams")
public class Productadapnew extends BaseAdapter {
LayoutInflater inflater;
Context context;
private Bitmap btMap = null;
List<production_response> mBeans = new ArrayList<production_response>();
static List<grs_bin_tag> listtag=new ArrayList<>();
List<sub_production_response> listsubproduct=new ArrayList<>();
production_response movieModel;
Activity kactivity;
public Productadapnew(Context context, List<production_response> mBeans,Activity mactivity) {
// TODO Auto-generated constructor stub
this.context = context;
this.kactivity=mactivity;
this.mBeans.addAll(mBeans);
listtag=new ArrayList<>();
inflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mBeans.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView txtrunid,txtid,txtrepname;
TextView txtgrower;
TextView txttype,txtrname;
TextView txtvariety,txtfticket;
TextView txttotalwgt,txtdate,txtview;
LinearLayout linsubproduct,linhead;
ImageView imgview,imgviewup,imgadd,imgprintz;
LinearLayout linmain;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
if (row == null) {
row = inflater.inflate(R.layout.product_home_list, null);
setAttributes(position, row);
}else
{
row = (View) convertView;
}
return row;
}
public void setAttributes(final int position, View itemView) {
final Holder holder = new Holder();
movieModel=mBeans.get(position);
holder.txtrunid= itemView.findViewById(R.id.txt_runid);
holder.txtid= itemView.findViewById(R.id.txt_id);
holder.txtgrower= itemView.findViewById(R.id.txt_grower);
holder.txttype= itemView.findViewById(R.id.txt_type);
holder.txtrname= itemView.findViewById(R.id.txt_rname);
holder.txtvariety= itemView.findViewById(R.id.txt_variety);
holder.txtfticket= itemView.findViewById(R.id.txt_fticket);
holder.txttotalwgt= itemView.findViewById(R.id.txt_totalwgt);
holder.txtdate= itemView.findViewById(R.id.txt_date);
holder.linmain= itemView.findViewById(R.id.lin_grs);
holder.imgview= itemView.findViewById(R.id.img_view);
holder.imgviewup=itemView.findViewById(R.id.img_viewup);
holder.txtview= itemView.findViewById(R.id.txt_view);
holder.imgadd= itemView.findViewById(R.id.img_add);
holder.imgprintz= itemView.findViewById(R.id.img_printz);
holder.linsubproduct=itemView.findViewById(R.id.lin_subproduct);
holder.linhead=itemView.findViewById(R.id.linhead);
holder.txtrepname=itemView.findViewById(R.id.txt_repname);
holder.txtid.setText(""+movieModel.getId());
holder.txtrunid.setText(""+movieModel.getPid());
holder.txtgrower.setText(" : "+movieModel.getGrower());
holder.txttype.setText(" : "+movieModel.getType());
holder.txtrepname.setText(" : "+movieModel.getRep_name());
if(movieModel.getRanch_name() !=null && movieModel.getRanch_name().length()>0 &&
!movieModel.getRanch_name().contentEquals("null"))
{
holder.txtrname.setText(" : "+movieModel.getRanch_name());
}else{
holder.txtrname.setText("");
}
holder.txtvariety.setText(" : "+movieModel.getVariety());
holder.txtfticket.setText(" : "+movieModel.getField_ticket());
holder.txttotalwgt.setText(" : "+movieModel.getTotal_netwt()+" Lb");
holder.txtdate.setText(" : "+movieModel.getCreated_date());
if (movieModel.getViewstatus() != null && movieModel.getViewstatus().length() > 0 && !movieModel.getViewstatus().contentEquals("null")
) {
if(movieModel.getViewstatus().contentEquals("1")) {
holder.txtview.setText("1");
movieModel.setViewstatus("1");
holder.linmain.setVisibility(View.VISIBLE);
// imgview.setBackgroundResource(R.drawable.uparrow);
holder.imgview.setVisibility(View.GONE);
holder.imgviewup.setVisibility(View.VISIBLE);
}
}else {
movieModel.setViewstatus("0");
}
listtag=new ArrayList<>();
holder.linmain.removeAllViews();
try {
List<grs_bin_tag> listtag=new ArrayList<>();
listtag=movieModel.getGrs_bin_tag();
Log.e("listtag","#"+listtag.size());
if (listtag.size() > 0) {
for(int i=0;i<listtag.size();i++)
{//Dialog dialogrk;
grs_bin_tag gk=listtag.get(i);
// Log.e("listtag","#"+gk.getTagno());
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.grn_bin_list, null);
TextView tagvalue = dialogView.findViewById(R.id.txt_tag_value);
TextView typevalue = dialogView.findViewById(R.id.txt_type_value);
TextView txthandlervalue = dialogView.findViewById(R.id.txt_handlervalue);
TextView txttare = dialogView.findViewById(R.id.txt_tare);
TextView txtnwt = dialogView.findViewById(R.id.txt_nwt);
TextView txtgwt = dialogView.findViewById(R.id.txt_gwt);
ImageView imgsubprint=dialogView.findViewById(R.id.img_subprint);
TextView txtrepname=dialogView.findViewById(R.id.txt_repname);
tagvalue.setText(" : " + gk.getTagno());
txthandlervalue.setText(" : " + gk.getHandler());
txttare.setText(" : " + gk.getTare()+" Lb");
txtnwt.setText(" : " + gk.getNet_wt()+" Lb");
txtgwt.setText(" : " + gk.getGross_wt()+" Lb");
txtrepname.setText(" : " + gk.getRep_name());
typevalue.setText(" : "+ gk.getType());
// movieModel.setViewstatus("0");
});
holder.linmain.addView(dialogView);
}
}
//scheduleSendLocation();
} catch (Exception e) {
// TODO: handle exception
}
}
}
//scheduleSendLocation();
} catch (Exception e) {
// TODO: handle exception
}
holder.linsubproduct.addView(dialogView);
}
}
}catch (Exception e)
{
// Log.e("ekkk","@"+e.toString());
}
}
}
}
Enter APP_SCOUT_HANG state
(Current message: duration=5002ms seq=411 late=8ms h=android.view.Choreographer$FrameHandler c=android.view.Choreographer$FrameDisplayEventReceiver)
W Event:APP_SCOUT_HANG Thread:main backtrace:
at android.content.res.AssetManager.nativeApplyStyle(Native Method)
at android.content.res.AssetManager.applyStyle(AssetManager.java:1139)
at android.content.res.ResourcesImpl$ThemeImpl.obtainStyledAttributes(ResourcesImpl.java:1369)
at android.content.res.Resources$Theme.obtainStyledAttributes(Resources.java:1712)
at android.content.Context.obtainStyledAttributes(Context.java:854)
at android.view.View.(View.java:5747)
at android.widget.TextView.(TextView.java:1032)
at android.widget.TextView.(TextView.java:1026)
at androidx.appcompat.widget.AppCompatTextView.(AppCompatTextView.java:108)
at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:93)
at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:88)
at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:83)
at com.google.android.material.theme.MaterialComponentsViewInflater.createTextView(MaterialComponentsViewInflater.java:61)
at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:121)
at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1569)
at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1620)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1088)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1024)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:988)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1150)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1153)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1153)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1153)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1153)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
at android.view.LayoutInflater.inflate(LayoutInflater.java:709)
at android.view.LayoutInflater.inflate(LayoutInflater.java:547)
at android.view.LayoutInflater.inflate(LayoutInflater.java:485)
at com.isoft.customalmonds.adapter.Productadapnew.setAttributes(Productadapnew.java:197)
at com.isoft.customalmonds.adapter.Productadapnew.getView(Productadapnew.java:119)
at android.widget.AbsListView.obtainView(AbsListView.java:2421)
at android.widget.ListView.makeAndAddView(ListView.java:2067)
at android.widget.ListView.fillDown(ListView.java:793)
at android.widget.ListView.fillFromTop(ListView.java:855)
at android.widget.ListView.layoutChildren(ListView.java:1838)
at android.widget.AbsListView.onLayout(AbsListView.java:2218)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
2022-12-03 04:49:52.781 16865-16992 MIUIScout App com.isoft.customalmonds W at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:536)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:868)
at android.view.View.layout(View.java:23550)
at android.view.ViewGroup.layout(ViewGroup.java:6452)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3858)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3308)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2272)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8999)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1160)
at android.view.Choreographer.doCallbacks(Choreographer.java:950)
at android.view.Choreographer.doFrame(Choreographer.java:879)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1142)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:210)
at android.os.Looper.loop(Looper.java:299)
at android.app.ActivityThread.main(ActivityThread.java:8319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
`
|
[
"If you are adding more than 200 views in the LinearLayout inside the BaseAdapter, then it's not the correct approach.\nYou should use the ViewHolder pattern and recycle the views already created instead of creating new views for each item in the list. This will improve the performance drastically.\nAlso, you can use lazy loading technique to load only the number of views required to display on the screen.\nAlso, make sure you are using the correct layout for your views. If your views are complex and contain many views, you should use a RecyclerView instead of a LinearLayout. This will also improve the performance.\nYou can refer to the following links for more information:\n\nRecyclerView\nViewHolder\nLazy Loading\nPerformance Optimization\n\n"
] |
[
1
] |
[] |
[] |
[
"android",
"android_adapter",
"android_layout",
"android_studio",
"baseadapter"
] |
stackoverflow_0074666992_android_android_adapter_android_layout_android_studio_baseadapter.txt
|
Q:
Vue 3: Cannot resolve "@vue/vue3-jest" module. on GitHub Actions
When running my unit tests in GitHub actions after upgrading to Vue 3, I get the following error:
> vue-cli-service test:unit
● Validation Error:
An unknown error occurred in @vue/cli-plugin-unit-jest:
Cannot resolve "@vue/vue3-jest" module. Please make sure you have installed "@vue/vue3-jest" as a dev dependency.
The GitHub actions script uses npm ci as its previous step to install dependencies, and the test command vue-cli-service test:unit works locally.
My package.json has:
"devDependencies": {
"@babel/core": "^7.16.7",
"@babel/eslint-parser": "^7.16.5",
"@babel/plugin-proposal-optional-chaining": "^7.14.5",
"@storybook/addon-a11y": "^6.4.12",
"@storybook/addon-actions": "^6.4.12",
"@storybook/addon-essentials": "^6.4.12",
"@storybook/addon-links": "^6.4.12",
"@storybook/addon-storysource": "^6.4.12",
"@storybook/vue": "^6.4.12",
"@testing-library/dom": "^7.31.2",
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/user-event": "^13.2.1",
"@testing-library/vue": "^6.4.2",
"@vue/babel-preset-app": "latest",
"@vue/cli-plugin-babel": "~5.0.0-rc.2",
"@vue/cli-plugin-e2e-cypress": "~5.0.0-rc.2",
"@vue/cli-plugin-eslint": "~5.0.0-rc.2",
"@vue/cli-plugin-router": "~5.0.0-rc.2",
"@vue/cli-plugin-unit-jest": "^5.0.0-rc.1",
"@vue/cli-service": "~5.0.0-rc.2",
"@vue/cli-shared-utils": "^4.5.10",
"@vue/eslint-config-airbnb": "^6.0.0",
"@vue/preload-webpack-plugin": "^1.1.2",
"@vue/test-utils": "^2.0.0-rc.18",
"@vue/vue3-jest": "^27.0.0-alpha.4",
...
"babel-loader": "^8.2.2",
...
"jest": "^27.1.0",
"jest-extended": "^0.11.5",
"jest-junit": "^8.0.0",
...
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
},
and my jest.config.js matching the docs in using @vue/vue3-jest:
"transform": {
"^.+\\.vue$": "@vue/vue3-jest"
},
A:
Please try it
# Vue 2
npm install --save-dev @vue/vue2-jest@28 # (use the appropriate version)
yarn add @vue/vue2-jest@28 --dev
# Vue 3
npm install --save-dev @vue/vue3-jest@28 # (use the appropriate version)
yarn add @vue/vue3-jest@28 --dev
|
Vue 3: Cannot resolve "@vue/vue3-jest" module. on GitHub Actions
|
When running my unit tests in GitHub actions after upgrading to Vue 3, I get the following error:
> vue-cli-service test:unit
● Validation Error:
An unknown error occurred in @vue/cli-plugin-unit-jest:
Cannot resolve "@vue/vue3-jest" module. Please make sure you have installed "@vue/vue3-jest" as a dev dependency.
The GitHub actions script uses npm ci as its previous step to install dependencies, and the test command vue-cli-service test:unit works locally.
My package.json has:
"devDependencies": {
"@babel/core": "^7.16.7",
"@babel/eslint-parser": "^7.16.5",
"@babel/plugin-proposal-optional-chaining": "^7.14.5",
"@storybook/addon-a11y": "^6.4.12",
"@storybook/addon-actions": "^6.4.12",
"@storybook/addon-essentials": "^6.4.12",
"@storybook/addon-links": "^6.4.12",
"@storybook/addon-storysource": "^6.4.12",
"@storybook/vue": "^6.4.12",
"@testing-library/dom": "^7.31.2",
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/user-event": "^13.2.1",
"@testing-library/vue": "^6.4.2",
"@vue/babel-preset-app": "latest",
"@vue/cli-plugin-babel": "~5.0.0-rc.2",
"@vue/cli-plugin-e2e-cypress": "~5.0.0-rc.2",
"@vue/cli-plugin-eslint": "~5.0.0-rc.2",
"@vue/cli-plugin-router": "~5.0.0-rc.2",
"@vue/cli-plugin-unit-jest": "^5.0.0-rc.1",
"@vue/cli-service": "~5.0.0-rc.2",
"@vue/cli-shared-utils": "^4.5.10",
"@vue/eslint-config-airbnb": "^6.0.0",
"@vue/preload-webpack-plugin": "^1.1.2",
"@vue/test-utils": "^2.0.0-rc.18",
"@vue/vue3-jest": "^27.0.0-alpha.4",
...
"babel-loader": "^8.2.2",
...
"jest": "^27.1.0",
"jest-extended": "^0.11.5",
"jest-junit": "^8.0.0",
...
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
},
and my jest.config.js matching the docs in using @vue/vue3-jest:
"transform": {
"^.+\\.vue$": "@vue/vue3-jest"
},
|
[
"Please try it\n# Vue 2\nnpm install --save-dev @vue/vue2-jest@28 # (use the appropriate version)\n\nyarn add @vue/vue2-jest@28 --dev\n\n\n\n# Vue 3\nnpm install --save-dev @vue/vue3-jest@28 # (use the appropriate version)\n\nyarn add @vue/vue3-jest@28 --dev\n\n"
] |
[
0
] |
[] |
[] |
[
"github_actions",
"jestjs",
"vue.js"
] |
stackoverflow_0070734715_github_actions_jestjs_vue.js.txt
|
Q:
Wpf c# how to close window in page?
I found the problem is It cannot close this window. But it can open the MainWindow.
pls help
Code in button
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
MainWindow MainView = new MainWindow();
MainView.Show();
AuthWindow AuthView = new AuthWindow();
AuthView.Close();
}
I want to press the button inside the page and close that window and open another window.
A:
Change
AuthWindow.Close();
To
This.Close();
A:
For such scenarios, I advise you to use RoutedCommand. In this case, you can use the ready-made command ApplicationCommands.Close.
In the page button, specify the command name:
<Button Content="Close Window" Command="Close" />
In the Window, set command executing:
<Window.CommandBindings>
<CommandBinding Command="Close" Executed="OnCloseWindow"/>
</Window.CommandBindings>
<x:Code>
<![CDATA[
private void OnCloseWindow(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
]]>
</x:Code>
P.S. I also do not advise you to open new windows. Since you are using Pages, you should change Pages in a single Window. And closing the Window is regarded as an Exit from the Application.
|
Wpf c# how to close window in page?
|
I found the problem is It cannot close this window. But it can open the MainWindow.
pls help
Code in button
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
MainWindow MainView = new MainWindow();
MainView.Show();
AuthWindow AuthView = new AuthWindow();
AuthView.Close();
}
I want to press the button inside the page and close that window and open another window.
|
[
"Change\nAuthWindow.Close();\n\nTo\nThis.Close();\n\n",
"For such scenarios, I advise you to use RoutedCommand. In this case, you can use the ready-made command ApplicationCommands.Close.\nIn the page button, specify the command name:\n <Button Content=\"Close Window\" Command=\"Close\" />\n\nIn the Window, set command executing:\n <Window.CommandBindings>\n <CommandBinding Command=\"Close\" Executed=\"OnCloseWindow\"/>\n </Window.CommandBindings>\n <x:Code>\n <![CDATA[\n private void OnCloseWindow(object sender, ExecutedRoutedEventArgs e)\n {\n this.Close();\n }\n ]]>\n </x:Code>\n\nP.S. I also do not advise you to open new windows. Since you are using Pages, you should change Pages in a single Window. And closing the Window is regarded as an Exit from the Application.\n"
] |
[
0,
0
] |
[] |
[] |
[
"c#",
"wpf",
"wpf_controls"
] |
stackoverflow_0074666590_c#_wpf_wpf_controls.txt
|
Q:
I want to set my webview under my gridview via xml
I want to set my webview under my gridview via xml. I want to look something like that
But right now its look like this, webview is diagonal to gridview
This is my code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Contacts"
android:background="@drawable/gradient"
android:orientation="horizontal">
<GridView
android:layout_width="match_parent"
android:layout_height="450dp"
android:numColumns="2"
android:horizontalSpacing="4dp"
android:verticalSpacing="4dp"
android:id="@+id/gridView"
/>
<WebView
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginTop="180dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_below="@+id/gridView"
/>
</LinearLayout>
But i want to set the images from string array. For wxample
A:
You can use a RelativeLayout to achieve this.
First, add a WebView and a GridView to your layout. Then, set the GridView's layout_above attribute to the ID of the WebView.
<RelativeLayout>
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_above="@id/gridview" />
</RelativeLayout>
|
I want to set my webview under my gridview via xml
|
I want to set my webview under my gridview via xml. I want to look something like that
But right now its look like this, webview is diagonal to gridview
This is my code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Contacts"
android:background="@drawable/gradient"
android:orientation="horizontal">
<GridView
android:layout_width="match_parent"
android:layout_height="450dp"
android:numColumns="2"
android:horizontalSpacing="4dp"
android:verticalSpacing="4dp"
android:id="@+id/gridView"
/>
<WebView
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginTop="180dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_below="@+id/gridView"
/>
</LinearLayout>
But i want to set the images from string array. For wxample
|
[
"You can use a RelativeLayout to achieve this.\nFirst, add a WebView and a GridView to your layout. Then, set the GridView's layout_above attribute to the ID of the WebView.\n<RelativeLayout>\n <GridView\n android:id=\"@+id/gridview\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n\n <WebView\n android:id=\"@+id/webview\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:layout_above=\"@id/gridview\" />\n</RelativeLayout>\n\n"
] |
[
1
] |
[] |
[] |
[
"android",
"xml"
] |
stackoverflow_0074666844_android_xml.txt
|
Q:
Flutter: How to access / inspect properties of a widget in tests?
I want to test properties of some widgets but I don't find a simple way of doing it.
Here's a simple example with a password field, how can I check that obscureText is set to true ?
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const darkBlue = Color.fromARGB(255, 18, 32, 47);
Future<void> main() async {
testWidgets('Wheelio logo appear on the login screen',
(WidgetTester tester) async {
final Key _formKey = GlobalKey<FormState>();
final TextEditingController passwordController = TextEditingController();
const Key _passwordKey = Key('PASSWORD_KEY');
final Finder passwordField = find.byKey(_passwordKey);
await tester.pumpWidget(MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Form(
key: _formKey,
child: TextFormField(
key: _passwordKey,
obscureText: true,
controller: passwordController,
),
),
),
),
));
await tester.pump();
expect(passwordField, findsOneWidget);
final TextFormField myPasswordWidget =
tester.widget(passwordField) as TextFormField;
// How can I check that obscureText property is set to true ?
});
}
A:
You can use tester and find to obtain anything in the widget tree.
For example, if you want to test that a Text has the property textAlign set to TextAlign.center, you can do:
expect(
tester.widget(find.byType(Text)),
isA<Text>().having((t) => t.textAlign, 'textAlign', TextAlign.center),
);
A:
final passwordField = find.byKey(_passwordKey);
final input = tester.firstWidget<TextFormField>(passwordField);
The input will be your widget, so you can now check
expect(input.obscureText, true);
A:
You can get the widget through the Finder.
TabBar tabBar = find.byType(TabBar).evaluate().single.widget as TabBar
A:
CommonFinders byWidgetPredicate method
final _passwordKey = GlobalKey(debugLabel: 'PASSWORD_KEY');
await tester.pumpWidget(
// ...
);
bool isObscureTextTrue(TextFormField widget) {
final TextField textField = widget.builder(_passwordKey.currentState);
return textField.obscureText;
}
final finder = find.byWidgetPredicate(
(widget) => widget is TextFormField && isObscureTextTrue(widget),
);
expect(finder, findsOneWidget);
A:
Here is an example to check that only 3 Text widgets have the property textAlign set to TextAlign.center :
final finderText = find.byType(Text);
final textWidgets = tester.widgetList<Text>(finderText);
expect(
textWidgets
.where((textWidget) => textWidget.textAlign == TextAlign.center)
.length,
3,
);
This could work with any widget, even your own widgets.
|
Flutter: How to access / inspect properties of a widget in tests?
|
I want to test properties of some widgets but I don't find a simple way of doing it.
Here's a simple example with a password field, how can I check that obscureText is set to true ?
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const darkBlue = Color.fromARGB(255, 18, 32, 47);
Future<void> main() async {
testWidgets('Wheelio logo appear on the login screen',
(WidgetTester tester) async {
final Key _formKey = GlobalKey<FormState>();
final TextEditingController passwordController = TextEditingController();
const Key _passwordKey = Key('PASSWORD_KEY');
final Finder passwordField = find.byKey(_passwordKey);
await tester.pumpWidget(MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Form(
key: _formKey,
child: TextFormField(
key: _passwordKey,
obscureText: true,
controller: passwordController,
),
),
),
),
));
await tester.pump();
expect(passwordField, findsOneWidget);
final TextFormField myPasswordWidget =
tester.widget(passwordField) as TextFormField;
// How can I check that obscureText property is set to true ?
});
}
|
[
"You can use tester and find to obtain anything in the widget tree.\nFor example, if you want to test that a Text has the property textAlign set to TextAlign.center, you can do:\nexpect(\n tester.widget(find.byType(Text)),\n isA<Text>().having((t) => t.textAlign, 'textAlign', TextAlign.center),\n);\n\n",
"final passwordField = find.byKey(_passwordKey);\nfinal input = tester.firstWidget<TextFormField>(passwordField);\n\nThe input will be your widget, so you can now check\nexpect(input.obscureText, true);\n",
"You can get the widget through the Finder.\nTabBar tabBar = find.byType(TabBar).evaluate().single.widget as TabBar\n\n",
"CommonFinders byWidgetPredicate method\nfinal _passwordKey = GlobalKey(debugLabel: 'PASSWORD_KEY');\n\nawait tester.pumpWidget(\n // ...\n);\n\nbool isObscureTextTrue(TextFormField widget) {\n final TextField textField = widget.builder(_passwordKey.currentState);\n return textField.obscureText;\n}\n\nfinal finder = find.byWidgetPredicate(\n (widget) => widget is TextFormField && isObscureTextTrue(widget),\n);\n\nexpect(finder, findsOneWidget);\n\n",
"Here is an example to check that only 3 Text widgets have the property textAlign set to TextAlign.center :\nfinal finderText = find.byType(Text);\nfinal textWidgets = tester.widgetList<Text>(finderText);\nexpect(\n textWidgets\n .where((textWidget) => textWidget.textAlign == TextAlign.center)\n .length,\n 3,\n);\n\nThis could work with any widget, even your own widgets.\n"
] |
[
11,
4,
3,
0,
0
] |
[] |
[] |
[
"flutter",
"flutter_test"
] |
stackoverflow_0060336656_flutter_flutter_test.txt
|
Q:
PHAsset to UIImage
I'm attempting to create a UIImage (like a thumbnail or something) from a PHAsset so that I can pass it into something that takes a UIImage. I've tried adapting solutions I found on SO (since they all just directly pass it into say a tableview or something), but I have no success (likely because I'm not doing it right).
func getAssetThumbnail(asset: PHAsset) -> UIImage {
var retimage = UIImage()
println(retimage)
let manager = PHImageManager.defaultManager()
manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: nil, resultHandler: {(result, info)->Void in
retimage = result
})
println(retimage)
return retimage
}
The printlns are telling me that the manager.request line isn't doing anything right now. How do I get it to give me the asset as a UIImage.
Thanks.
A:
This did what I needed it to do, in case anyone also needs this.
func getAssetThumbnail(asset: PHAsset) -> UIImage {
let manager = PHImageManager.defaultManager()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.synchronous = true
manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
Edit: Swift 3 update
func getAssetThumbnail(asset: PHAsset) -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
A:
try this it works for me, hope it helps you too,
func getUIImage(asset: PHAsset) -> UIImage? {
var img: UIImage?
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
options.version = .original
options.isSynchronous = true
manager.requestImageData(for: asset, options: options) { data, _, _, _ in
if let data = data {
img = UIImage(data: data)
}
}
return img
}
A:
Simple Solution (Swift 4.2)
Method 1:
extension PHAsset {
var image : UIImage {
var thumbnail = UIImage()
let imageManager = PHCachingImageManager()
imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { image, _ in
thumbnail = image!
})
return thumbnail
}
}
let image = asset.image
Use this method if you only need UIImage from PHAsset.
OR
extension PHAsset {
func image(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) -> UIImage {
var thumbnail = UIImage()
let imageManager = PHCachingImageManager()
imageManager.requestImage(for: self, targetSize: targetSize, contentMode: contentMode, options: options, resultHandler: { image, _ in
thumbnail = image!
})
return thumbnail
}
}
let image = asset.image(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?)
Use this method for your desired UIImage.
OR
extension PHAsset {
func image(completionHandler: @escaping (UIImage) -> ()){
var thumbnail = UIImage()
let imageManager = PHCachingImageManager()
imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { img, _ in
thumbnail = img!
})
completionHandler(thumbnail)
}
}
let image = asset.image(completionHandler: {(img) in
print("Finished")
})
Use this method for notify after completion.
Method 2:
extension PHAsset {
var data : (UIImage, [AnyHashable : Any]) {
var img = UIImage(); var information = [AnyHashable : Any](); let imageManager = PHCachingImageManager()
imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { image,info in
img = image!
information = info!
})
return (img,information)
}
}
let image_withData : (UIImage, [AnyHashable : Any]) = asset.data
Use this method if you want UIImage And Result Info of PHAsset
OR
extension PHAsset {
func data(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) -> (UIImage, [AnyHashable : Any]) {
var img = UIImage(); var information = [AnyHashable : Any](); let imageManager = PHCachingImageManager()
imageManager.requestImage(for: self, targetSize: targetSize, contentMode: contentMode, options: options, resultHandler: { image,info in
img = image!
information = info!
})
return (img,information)
}
}
let data = asset?.data(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?)
Use this method for your desired Data.
A:
Swift 5
extension PHAsset {
func getAssetThumbnail() -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: self,
targetSize: CGSize(width: self.pixelWidth, height: self.pixelHeight),
contentMode: .aspectFit,
options: option,
resultHandler: {(result, info) -> Void in
thumbnail = result!
})
return thumbnail
}
}
A:
I'd suggest using Apple's PHCachingImageManager (that inherits from PHImageManager):
A PHCachingImageManager object fetches or generates image data for photo or video assets
Also, PHCachingImageManager support a better caching mechanism.
Example of fetching a thumbnail synchronous:
let options = PHImageRequestOptions()
options.deliveryMode = .HighQualityFormat
options.synchronous = true // Set it to false for async callback
let imageManager = PHCachingImageManager()
imageManager.requestImageForAsset(YourPHAssetVar,
targetSize: CGSizeMake(CGFloat(160), CGFloat(160)),
contentMode: .AspectFill,
options: options,
resultHandler: { (resultThumbnail : UIImage?, info : [NSObject : AnyObject]?) in
// Assign your thumbnail which is the *resultThumbnail*
}
In addition, you can use PHCachingImageManager to cache your images for faster UI response:
To use a caching image manager:
Create a PHCachingImageManager instance. (This step replaces using the
shared PHImageManager instance.)
Use PHAsset class methods to fetch the assets you’re interested in.
To prepare images for those assets, call the
startCachingImagesForAssets:targetSize:contentMode:options: method
with the target size, content mode, and options you plan to use when
later requesting images for each individual asset.
When you need an image for an individual asset, call the
requestImageForAsset:targetSize:contentMode:options:resultHandler:
method, and pass the same parameters you used when preparing that
asset.
If the image you request is among those already prepared, the
PHCachingImageManager object immediately returns that image.
Otherwise, Photos prepares the image on demand and caches it for later
use.
In our example:
var phAssetArray : [PHAsset] = []
for i in 0..<assets.count
{
phAssetArray.append(assets[i] as! PHAsset)
}
let options = PHImageRequestOptions()
options.deliveryMode = .Opportunistic
options.synchronous = false
self.imageManager.startCachingImagesForAssets(phAssetArray,
targetSize: CGSizeMake(CGFloat(160), CGFloat(160)),
contentMode: .AspectFill,
options: options)
A:
For Swift 3.0.1:
func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
let retinaScale = UIScreen.main.scale
let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//(size * retinaScale, size * retinaScale)
let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
let square = CGRect(x:0, y: 0,width: CGFloat(cropSizeLength),height: CGFloat(cropSizeLength))
let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
var thumbnail = UIImage()
options.isSynchronous = true
options.deliveryMode = .highQualityFormat
options.resizeMode = .exact
options.normalizedCropRect = cropRect
manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
Resource : https://gist.github.com/lvterry/f062cf9ae13bca76b0c6#file-getassetthumbnail-swift
A:
Swift 4.
resizeMode,deliveryMode - These can be set according to user requirement.
isNetworkAccessAllowed - set this to "true" for fetching images from the cloud
imageSize- required image size
func getImageFromAsset(asset:PHAsset,imageSize:CGSize, callback:@escaping (_ result:UIImage) -> Void) -> Void{
let requestOptions = PHImageRequestOptions()
requestOptions.resizeMode = PHImageRequestOptionsResizeMode.fast
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat
requestOptions.isNetworkAccessAllowed = true
requestOptions.isSynchronous = true
PHImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: PHImageContentMode.default, options: requestOptions, resultHandler: { (currentImage, info) in
callback(currentImage!)
})
}
A:
The problem is that requestImageForAsset is a resultHandler and this block of code happens in the future after your functions has already printed and returned the value you was expecting. I did come changes to show you this happening and also suggest some simple solutions.
func getAssetThumbnail(asset: PHAsset) {
var retimage = UIImage()
println(retimage)
let manager = PHImageManager.defaultManager()
manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: nil, resultHandler: {
(result, info)->Void in
retimage = result
println("This happens after")
println(retimage)
callReturnImage(retimage) // <- create this method
})
println("This happens before")
}
Learn more about closures and completion handle and async funcs at Apple documentation
I hope that helps you!
A:
Objective-c version of code based on dcheng answer.
-(UIImage *)getAssetThumbnail:(PHAsset * )asset {
PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];
options.synchronous = true;
__block UIImage *image;
[PHCachingImageManager.defaultManager requestImageForAsset:asset targetSize:CGSizeMake(100, 100) contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
image = result;
}];
return image;
}
A:
Swift 5 working function
func getImageForAsset(asset: PHAsset) -> UIImage {
let manager = PHImageManager.default
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager().requestImage(for: asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .aspectFit, options: nil, resultHandler: {(result, info) -> Void in
thumbnail = result!
})
return thumbnail
}
A:
I have a different solution which worked really nicely when I wanted to get the memory down in my collectionView:
First I get the URL from the asset:
func getImageUrlFrom(asset: PHAsset, completion: @escaping ((URL?)->())) {
asset.requestContentEditingInput(with: nil, completionHandler: { (input, info) in
if let input = input {
completion(input.fullSizeImageURL)
}
})
}
Then, instead of requesting an image, I downSample it and make it memory efficient for the size of the image: https://developer.apple.com/videos/play/wwdc2018/219
func downsample(imageAt imageURL: URL?,
to pointSize: CGSize,
scale: CGFloat = UIScreen.main.scale) -> UIImage? {
guard let imageURL = imageURL else { return nil }
// Create an CGImageSource that represent an image
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else {
return nil
}
// Calculate the desired dimension
let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
// Perform downsampling
let downsampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
] as CFDictionary
guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {
return nil
}
// Return the downsampled image as UIImage
return UIImage(cgImage: downsampledImage)
}
Since I can't use PHCachingImageManager, I just use NSCache and the localIdentifier of the asset as the reference for caching.
And remember to use DispatchQueue.global(qos: .userInitiated).async { } when you call both methods.
|
PHAsset to UIImage
|
I'm attempting to create a UIImage (like a thumbnail or something) from a PHAsset so that I can pass it into something that takes a UIImage. I've tried adapting solutions I found on SO (since they all just directly pass it into say a tableview or something), but I have no success (likely because I'm not doing it right).
func getAssetThumbnail(asset: PHAsset) -> UIImage {
var retimage = UIImage()
println(retimage)
let manager = PHImageManager.defaultManager()
manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: nil, resultHandler: {(result, info)->Void in
retimage = result
})
println(retimage)
return retimage
}
The printlns are telling me that the manager.request line isn't doing anything right now. How do I get it to give me the asset as a UIImage.
Thanks.
|
[
"This did what I needed it to do, in case anyone also needs this.\nfunc getAssetThumbnail(asset: PHAsset) -> UIImage {\n let manager = PHImageManager.defaultManager()\n let option = PHImageRequestOptions()\n var thumbnail = UIImage()\n option.synchronous = true\n manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: option, resultHandler: {(result, info)->Void in\n thumbnail = result!\n })\n return thumbnail\n}\n\nEdit: Swift 3 update\nfunc getAssetThumbnail(asset: PHAsset) -> UIImage {\n let manager = PHImageManager.default()\n let option = PHImageRequestOptions()\n var thumbnail = UIImage()\n option.isSynchronous = true\n manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in\n thumbnail = result!\n })\n return thumbnail\n}\n\n",
"try this it works for me, hope it helps you too,\nfunc getUIImage(asset: PHAsset) -> UIImage? {\n\n var img: UIImage?\n let manager = PHImageManager.default()\n let options = PHImageRequestOptions()\n options.version = .original\n options.isSynchronous = true\n manager.requestImageData(for: asset, options: options) { data, _, _, _ in\n\n if let data = data {\n img = UIImage(data: data)\n }\n }\n return img\n}\n\n",
"Simple Solution (Swift 4.2) \nMethod 1:\nextension PHAsset {\n\n var image : UIImage {\n var thumbnail = UIImage()\n let imageManager = PHCachingImageManager()\n imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { image, _ in\n thumbnail = image!\n })\n return thumbnail\n }\n} \n\nlet image = asset.image \n\nUse this method if you only need UIImage from PHAsset.\nOR\nextension PHAsset {\n func image(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) -> UIImage {\n var thumbnail = UIImage()\n let imageManager = PHCachingImageManager()\n imageManager.requestImage(for: self, targetSize: targetSize, contentMode: contentMode, options: options, resultHandler: { image, _ in\n thumbnail = image!\n })\n return thumbnail\n }\n}\n\nlet image = asset.image(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?)\n\nUse this method for your desired UIImage.\nOR\nextension PHAsset {\n\n func image(completionHandler: @escaping (UIImage) -> ()){\n var thumbnail = UIImage()\n let imageManager = PHCachingImageManager()\n imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { img, _ in\n thumbnail = img!\n })\n completionHandler(thumbnail)\n }\n}\n\nlet image = asset.image(completionHandler: {(img) in\n print(\"Finished\")\n})\n\nUse this method for notify after completion.\nMethod 2:\nextension PHAsset {\n var data : (UIImage, [AnyHashable : Any]) {\n var img = UIImage(); var information = [AnyHashable : Any](); let imageManager = PHCachingImageManager()\n imageManager.requestImage(for: self, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: nil, resultHandler: { image,info in\n img = image!\n information = info!\n })\n return (img,information)\n }\n} \n\n\nlet image_withData : (UIImage, [AnyHashable : Any]) = asset.data\n\nUse this method if you want UIImage And Result Info of PHAsset\nOR\nextension PHAsset {\n\n func data(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) -> (UIImage, [AnyHashable : Any]) {\n var img = UIImage(); var information = [AnyHashable : Any](); let imageManager = PHCachingImageManager()\n imageManager.requestImage(for: self, targetSize: targetSize, contentMode: contentMode, options: options, resultHandler: { image,info in\n img = image!\n information = info!\n })\n return (img,information)\n }\n}\n\nlet data = asset?.data(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?)\n\nUse this method for your desired Data.\n",
"Swift 5\nextension PHAsset {\nfunc getAssetThumbnail() -> UIImage {\n let manager = PHImageManager.default()\n let option = PHImageRequestOptions()\n var thumbnail = UIImage()\n option.isSynchronous = true\n manager.requestImage(for: self,\n targetSize: CGSize(width: self.pixelWidth, height: self.pixelHeight),\n contentMode: .aspectFit,\n options: option,\n resultHandler: {(result, info) -> Void in\n thumbnail = result!\n })\n return thumbnail\n }\n}\n\n",
"I'd suggest using Apple's PHCachingImageManager (that inherits from PHImageManager):\n\nA PHCachingImageManager object fetches or generates image data for photo or video assets\n\nAlso, PHCachingImageManager support a better caching mechanism.\nExample of fetching a thumbnail synchronous:\nlet options = PHImageRequestOptions()\noptions.deliveryMode = .HighQualityFormat\noptions.synchronous = true // Set it to false for async callback\n\nlet imageManager = PHCachingImageManager()\nimageManager.requestImageForAsset(YourPHAssetVar,\n targetSize: CGSizeMake(CGFloat(160), CGFloat(160)),\n contentMode: .AspectFill,\n options: options,\n resultHandler: { (resultThumbnail : UIImage?, info : [NSObject : AnyObject]?) in\n\n // Assign your thumbnail which is the *resultThumbnail*\n }\n\nIn addition, you can use PHCachingImageManager to cache your images for faster UI response:\n\nTo use a caching image manager:\n\nCreate a PHCachingImageManager instance. (This step replaces using the\n shared PHImageManager instance.)\nUse PHAsset class methods to fetch the assets you’re interested in.\nTo prepare images for those assets, call the\n startCachingImagesForAssets:targetSize:contentMode:options: method\n with the target size, content mode, and options you plan to use when\n later requesting images for each individual asset.\nWhen you need an image for an individual asset, call the\n requestImageForAsset:targetSize:contentMode:options:resultHandler:\n method, and pass the same parameters you used when preparing that\n asset.\n\nIf the image you request is among those already prepared, the\n PHCachingImageManager object immediately returns that image.\n Otherwise, Photos prepares the image on demand and caches it for later\n use.\n\nIn our example:\nvar phAssetArray : [PHAsset] = []\n\nfor i in 0..<assets.count\n{\n phAssetArray.append(assets[i] as! PHAsset)\n}\n\nlet options = PHImageRequestOptions()\noptions.deliveryMode = .Opportunistic\noptions.synchronous = false\n\nself.imageManager.startCachingImagesForAssets(phAssetArray,\n targetSize: CGSizeMake(CGFloat(160), CGFloat(160)),\n contentMode: .AspectFill,\n options: options)\n\n",
"For Swift 3.0.1:\nfunc getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {\n let retinaScale = UIScreen.main.scale\n let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//(size * retinaScale, size * retinaScale)\n let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)\n let square = CGRect(x:0, y: 0,width: CGFloat(cropSizeLength),height: CGFloat(cropSizeLength))\n let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))\n\n let manager = PHImageManager.default()\n let options = PHImageRequestOptions()\n var thumbnail = UIImage()\n\n options.isSynchronous = true\n options.deliveryMode = .highQualityFormat\n options.resizeMode = .exact\n options.normalizedCropRect = cropRect\n\n manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in\n thumbnail = result!\n })\n return thumbnail\n}\n\nResource : https://gist.github.com/lvterry/f062cf9ae13bca76b0c6#file-getassetthumbnail-swift\n",
"Swift 4.\nresizeMode,deliveryMode - These can be set according to user requirement.\nisNetworkAccessAllowed - set this to \"true\" for fetching images from the cloud\nimageSize- required image size\nfunc getImageFromAsset(asset:PHAsset,imageSize:CGSize, callback:@escaping (_ result:UIImage) -> Void) -> Void{\n\n let requestOptions = PHImageRequestOptions()\n requestOptions.resizeMode = PHImageRequestOptionsResizeMode.fast\n requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat\n requestOptions.isNetworkAccessAllowed = true\n requestOptions.isSynchronous = true\n PHImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: PHImageContentMode.default, options: requestOptions, resultHandler: { (currentImage, info) in\n callback(currentImage!)\n })\n}\n\n",
"The problem is that requestImageForAsset is a resultHandler and this block of code happens in the future after your functions has already printed and returned the value you was expecting. I did come changes to show you this happening and also suggest some simple solutions. \nfunc getAssetThumbnail(asset: PHAsset) {\n var retimage = UIImage()\n println(retimage)\n let manager = PHImageManager.defaultManager()\n manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFit, options: nil, resultHandler: {\n (result, info)->Void in\n retimage = result\n println(\"This happens after\")\n println(retimage)\n callReturnImage(retimage) // <- create this method\n })\n println(\"This happens before\")\n}\n\nLearn more about closures and completion handle and async funcs at Apple documentation\nI hope that helps you!\n",
"Objective-c version of code based on dcheng answer. \n-(UIImage *)getAssetThumbnail:(PHAsset * )asset {\n\n PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];\n options.synchronous = true;\n\n __block UIImage *image;\n [PHCachingImageManager.defaultManager requestImageForAsset:asset targetSize:CGSizeMake(100, 100) contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {\n image = result;\n }];\n return image;\n }\n\n",
"Swift 5 working function\nfunc getImageForAsset(asset: PHAsset) -> UIImage {\n let manager = PHImageManager.default\n let option = PHImageRequestOptions()\n var thumbnail = UIImage()\n option.isSynchronous = true\n manager().requestImage(for: asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .aspectFit, options: nil, resultHandler: {(result, info) -> Void in\n thumbnail = result!\n })\n return thumbnail\n }\n\n",
"I have a different solution which worked really nicely when I wanted to get the memory down in my collectionView:\nFirst I get the URL from the asset:\n func getImageUrlFrom(asset: PHAsset, completion: @escaping ((URL?)->())) {\n asset.requestContentEditingInput(with: nil, completionHandler: { (input, info) in\n if let input = input {\n completion(input.fullSizeImageURL)\n }\n })\n }\n\nThen, instead of requesting an image, I downSample it and make it memory efficient for the size of the image: https://developer.apple.com/videos/play/wwdc2018/219\nfunc downsample(imageAt imageURL: URL?,\n to pointSize: CGSize,\n scale: CGFloat = UIScreen.main.scale) -> UIImage? {\n guard let imageURL = imageURL else { return nil }\n\n // Create an CGImageSource that represent an image\n let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary\n guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else {\n return nil\n }\n \n // Calculate the desired dimension\n let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale\n \n // Perform downsampling\n let downsampleOptions = [\n kCGImageSourceCreateThumbnailFromImageAlways: true,\n kCGImageSourceShouldCacheImmediately: true,\n kCGImageSourceCreateThumbnailWithTransform: true,\n kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels\n ] as CFDictionary\n guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {\n return nil\n }\n \n // Return the downsampled image as UIImage\n return UIImage(cgImage: downsampledImage)\n }\n\nSince I can't use PHCachingImageManager, I just use NSCache and the localIdentifier of the asset as the reference for caching.\nAnd remember to use DispatchQueue.global(qos: .userInitiated).async { } when you call both methods.\n"
] |
[
93,
33,
27,
8,
7,
7,
7,
4,
1,
0,
0
] |
[] |
[] |
[
"phasset",
"swift"
] |
stackoverflow_0030812057_phasset_swift.txt
|
Q:
How to declare a function, that takes a range
I want to declare a function, that gets a range as input, outputs a single number and use it directly with ranges::views::transform of the range-v3 library.
The following works but I have to use a lambda that doesn't really do anything.
int64_t getGroupValue( ranges::input_range auto&& group ) {
return ranges::accumulate( group, 1ll, ranges::multiplies() );
}
int64_t calculateGroupSum( const std::vector<int>& data ) {
using ranges::views::transform;
using ranges::views::chunk;
return ranges::accumulate(
data
| chunk( 3 )
| transform( [] ( auto group ) { return getGroupValue( group ); })
, 0ll);
}
I want to do the following:
int64_t calculateGroupSum( const std::vector<int>& data ) {
using ranges::views::transform;
using ranges::views::chunk;
return ranges::accumulate(
data
| chunk( 3 )
| transform( getGroupValue )
, 0ll);
}
Is this somehow possible by using a different parameter type for getGroupValue() or do I have to use the lambda?
A:
function template cannot be passed around.*
One way is wrap it inside lambda object as you already did, or you can write it as function object at first place.
struct getGroupValue_op{
int64_t operator()( ranges::input_range auto&& group ) const{
return ranges::accumulate( group, 1ll, ranges::multiplies() );
}
} getGroupValue;
*it can work if the parameter has specific type, but it's not the case for range::views::transform
|
How to declare a function, that takes a range
|
I want to declare a function, that gets a range as input, outputs a single number and use it directly with ranges::views::transform of the range-v3 library.
The following works but I have to use a lambda that doesn't really do anything.
int64_t getGroupValue( ranges::input_range auto&& group ) {
return ranges::accumulate( group, 1ll, ranges::multiplies() );
}
int64_t calculateGroupSum( const std::vector<int>& data ) {
using ranges::views::transform;
using ranges::views::chunk;
return ranges::accumulate(
data
| chunk( 3 )
| transform( [] ( auto group ) { return getGroupValue( group ); })
, 0ll);
}
I want to do the following:
int64_t calculateGroupSum( const std::vector<int>& data ) {
using ranges::views::transform;
using ranges::views::chunk;
return ranges::accumulate(
data
| chunk( 3 )
| transform( getGroupValue )
, 0ll);
}
Is this somehow possible by using a different parameter type for getGroupValue() or do I have to use the lambda?
|
[
"function template cannot be passed around.*\nOne way is wrap it inside lambda object as you already did, or you can write it as function object at first place.\nstruct getGroupValue_op{\n int64_t operator()( ranges::input_range auto&& group ) const{\n return ranges::accumulate( group, 1ll, ranges::multiplies() );\n }\n} getGroupValue;\n\n\n\n*it can work if the parameter has specific type, but it's not the case for range::views::transform\n\n"
] |
[
1
] |
[] |
[] |
[
"c++",
"range_v3"
] |
stackoverflow_0074666955_c++_range_v3.txt
|
Q:
Unable to use .map in dropdown menu ReactJs
I want to populate the dropdown list with data from the database, disastertype is an array with all the details, however when I map through it to display the disaster_type it does not work, the page does not even renders a blank page is shown. Please guide as I am a beginner with REACTJS.
const [disastertype,Setdisastertype] = useState([]);
useEffect(()=>{
Axios.get("http://localhost:3001/api/disasterinfo").then((response)=>{
Setdisastertype(response)
console.log(response)
})
},[])
--------------------------------------------------------------------
<td><div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Disaster Type</button>
<ul class="dropdown-menu">
{disastertype.map((val)=>(
<li><a class="dropdown-item" key={val.disaster_type}>{val.disaster_type}</a></li>
))}
</ul>
</div></td>
Result from console.log(response)
console.log
A:
You have just simply missed a field , you have two options here :
change Setdisastertype(response) to Setdisastertype(response.data)
change disastertype.map to disastertype.data.map
First solution is recommended.
|
Unable to use .map in dropdown menu ReactJs
|
I want to populate the dropdown list with data from the database, disastertype is an array with all the details, however when I map through it to display the disaster_type it does not work, the page does not even renders a blank page is shown. Please guide as I am a beginner with REACTJS.
const [disastertype,Setdisastertype] = useState([]);
useEffect(()=>{
Axios.get("http://localhost:3001/api/disasterinfo").then((response)=>{
Setdisastertype(response)
console.log(response)
})
},[])
--------------------------------------------------------------------
<td><div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Disaster Type</button>
<ul class="dropdown-menu">
{disastertype.map((val)=>(
<li><a class="dropdown-item" key={val.disaster_type}>{val.disaster_type}</a></li>
))}
</ul>
</div></td>
Result from console.log(response)
console.log
|
[
"You have just simply missed a field , you have two options here :\n\nchange Setdisastertype(response) to Setdisastertype(response.data)\nchange disastertype.map to disastertype.data.map\n\nFirst solution is recommended.\n"
] |
[
0
] |
[] |
[] |
[
"bootstrap_4",
"drop_down_menu",
"node.js",
"reactjs"
] |
stackoverflow_0074666698_bootstrap_4_drop_down_menu_node.js_reactjs.txt
|
Q:
Visual studio 2022 intellisense not working on javascript
I am using VS 2022 and working on a ASP.NET Core Web App .NET 6.0
I have added a script tag with javascript type, writing code inside the tags is like writing inside notepad. The intellisense is not picking up or is very slow.
Is there a way to activate a better intellisense or increase the response time of it?
A:
Thanks for the info.
You can gather logs from the TypeScript & JavaScript language service by setting an environment variable TSS_LOG to a value such as "-file C:/temp/logs/tsserver.log -level verbose" (without the quotes), and then launching VS. (Note: The folder specified, e.g. "C:\temp\logs", must already exist for the logs to get created). The log files can get large, so remove the setting after investigations are done.
If new projects are showing the issue too, then sticking with File / New Project and creating an empty ASP.NET web app, then adding a .js file to it and trying to get intellisense, would be the simplest to investigate.
If you don't see the log file getting created after reproducing the issue, then I'd verify that the language service process is even starting. The easiest way to do this is to open a .js file in VS (so it definitely should be running), then open Task manager and do to the "Details" tab. If you sort by process name you should have a few instances of node.exe running. If you right click on the columns and add the "Command line" column, you can identify the language service one by its arguments (it'll be the one running tsserver.js with the '--expose-gc' flag). See below for a screen shot from my machine.
If everything is running fine and you do get a log file created (you should actually get two log files), please either attach them to this issue, or I can provide my email address if you'd rather not upload them.
Thanks!
|
Visual studio 2022 intellisense not working on javascript
|
I am using VS 2022 and working on a ASP.NET Core Web App .NET 6.0
I have added a script tag with javascript type, writing code inside the tags is like writing inside notepad. The intellisense is not picking up or is very slow.
Is there a way to activate a better intellisense or increase the response time of it?
|
[
"Thanks for the info.\nYou can gather logs from the TypeScript & JavaScript language service by setting an environment variable TSS_LOG to a value such as \"-file C:/temp/logs/tsserver.log -level verbose\" (without the quotes), and then launching VS. (Note: The folder specified, e.g. \"C:\\temp\\logs\", must already exist for the logs to get created). The log files can get large, so remove the setting after investigations are done.\nIf new projects are showing the issue too, then sticking with File / New Project and creating an empty ASP.NET web app, then adding a .js file to it and trying to get intellisense, would be the simplest to investigate.\nIf you don't see the log file getting created after reproducing the issue, then I'd verify that the language service process is even starting. The easiest way to do this is to open a .js file in VS (so it definitely should be running), then open Task manager and do to the \"Details\" tab. If you sort by process name you should have a few instances of node.exe running. If you right click on the columns and add the \"Command line\" column, you can identify the language service one by its arguments (it'll be the one running tsserver.js with the '--expose-gc' flag). See below for a screen shot from my machine.\nIf everything is running fine and you do get a log file created (you should actually get two log files), please either attach them to this issue, or I can provide my email address if you'd rather not upload them.\nThanks!\n"
] |
[
0
] |
[] |
[] |
[
"asp.net_core",
"asp.net_web_api",
"intellisense",
"javascript",
"visual_studio"
] |
stackoverflow_0071571319_asp.net_core_asp.net_web_api_intellisense_javascript_visual_studio.txt
|
Q:
Rust: conversion from generic with trait bound affects trait object type
I'm working on a simple opengl wrapper library in rust.
Im using nalgebra_glm crate for the math operations. Lots of types implement AsRef for the access to the underlying array. I manually implemented Uniform for array types that match common matrix sizes like [[T; 4]; 4], [T; 16], [T; 3] and so on.
So I can obtain a new Box<dyn Uniform> by calling Box::new(<nalgebra_glm matrix or vector>.as_ref().clone()) but it's unnecessarily verbose.
I wanted to create a convenience function that converts any &[T] which is Clone and AsRef to some type U that implements Uniform into Vec<Box<dyn Uniform>>. Something similar to ToOwned trait.
Here's what I came up with.
pub trait Uniform {
fn bind(&self, location: GLint);
}
pub fn to_owned<U: Uniform + Clone, T: AsRef<U>>(uniforms: &[T]) -> Vec<Box<dyn Uniform>>
where Vec<Box<dyn Uniform>>: FromIterator<Box<U>>
{
uniforms.into_iter()
.map(AsRef::as_ref)
.map(Clone::clone)
.map(Box::new)
.collect()
}
But then when I tried using this function in the following context it caused and error which I'm struggling to understand.
perspective_matrix() and view_matrix() are both of type Mat4 and provide a AsRef<[[f32; 4]; 4].
let common_uniforms = to_owned(&[camera.perspective_matrix(), camera.view_matrix()]);
error[E0277]: the trait bound `(dyn Uniform + 'static): Clone` is not satisfied
--> src\main.rs:167:27
|
167 | let common_uniforms = to_owned(&[camera.perspective_matrix(), camera.view_matrix()]);
| ^^^^^^^^ the trait `Clone` is not implemented for `(dyn Uniform + 'static)`
|
note: required by a bound in `uniform::to_owned`
--> src\uniform.rs:9:30
|
9 | pub fn to_owned<U: Uniform + Clone, T: AsRef<U>>(uniforms: &[T]) -> Vec<Box<dyn Uniform>>
| ^^^^^ required by this bound in `uniform::to_owned`
Why is Clone required by the resulting trait object? clone is only needed during operations on generic U and thus only U should implement Clone. Why does it have anything to do with the final trait object? I would expect that since U implements Uniform it should be possible to create a dyn Uniform trait object out of it.
Also I cannot require Clone as super trait for Uniform since it would make it not object safe.
I have tried explicitly casting resulting box type into trait object, adding 'static lifetime bound but to no avail.
pub fn to_owned<U: 'static + Uniform + Clone, T: AsRef<U>>(uniforms: &[T]) -> Vec<Box<dyn Uniform>>
where Vec<Box<dyn Uniform>>: FromIterator<Box<U>>
{
uniforms.into_iter()
.map(AsRef::as_ref)
.map(Clone::clone)
.map(|uniform| Box::new(uniform) as Box<dyn Uniform>)
.collect()
}
I really don't understand what's wrong with my code. It's either that I'm doing some syntactic mistake or there's deeper logical error with what I'm trying to accomplish here.
I would greatly appreciate any help.
A:
The main problem is your to_owned function.
With where Vec<Box<dyn Uniform>>: FromIterator<Box<U>> you are actually hiding the real problem, causing very confusing compiler messages.
You probably added this because the compiler suggested it. But the compiler also warns that while this is what it needs, adding the where clause is probably not the correct solution.
With the where clause, instead of specifying correct bounds that make the conversion possible, you just move the problem out of the function. I agree with the compiler that this is the wrong solution.
Your second attempt is almost correct, all you are missing is that you need to remove the where clause:
use nalgebra_glm::Mat4;
fn perspective_matrix() -> Mat4 {
todo!()
}
pub trait Uniform {
fn bind(&self, location: i32);
}
impl Uniform for [[f32; 4]; 4] {
fn bind(&self, _location: i32) {
todo!()
}
}
pub fn to_owned<T, U>(uniforms: &[T]) -> Vec<Box<dyn Uniform>>
where
T: AsRef<U>,
U: Uniform + Clone + 'static,
{
uniforms
.into_iter()
.map(AsRef::as_ref)
.map(Clone::clone)
.map(|uniform| Box::new(uniform) as Box<dyn Uniform>)
.collect()
}
fn main() {
let _common_uniforms = to_owned(&[perspective_matrix()]);
}
Also, this is how a minimal reproducible example looks like ;)
|
Rust: conversion from generic with trait bound affects trait object type
|
I'm working on a simple opengl wrapper library in rust.
Im using nalgebra_glm crate for the math operations. Lots of types implement AsRef for the access to the underlying array. I manually implemented Uniform for array types that match common matrix sizes like [[T; 4]; 4], [T; 16], [T; 3] and so on.
So I can obtain a new Box<dyn Uniform> by calling Box::new(<nalgebra_glm matrix or vector>.as_ref().clone()) but it's unnecessarily verbose.
I wanted to create a convenience function that converts any &[T] which is Clone and AsRef to some type U that implements Uniform into Vec<Box<dyn Uniform>>. Something similar to ToOwned trait.
Here's what I came up with.
pub trait Uniform {
fn bind(&self, location: GLint);
}
pub fn to_owned<U: Uniform + Clone, T: AsRef<U>>(uniforms: &[T]) -> Vec<Box<dyn Uniform>>
where Vec<Box<dyn Uniform>>: FromIterator<Box<U>>
{
uniforms.into_iter()
.map(AsRef::as_ref)
.map(Clone::clone)
.map(Box::new)
.collect()
}
But then when I tried using this function in the following context it caused and error which I'm struggling to understand.
perspective_matrix() and view_matrix() are both of type Mat4 and provide a AsRef<[[f32; 4]; 4].
let common_uniforms = to_owned(&[camera.perspective_matrix(), camera.view_matrix()]);
error[E0277]: the trait bound `(dyn Uniform + 'static): Clone` is not satisfied
--> src\main.rs:167:27
|
167 | let common_uniforms = to_owned(&[camera.perspective_matrix(), camera.view_matrix()]);
| ^^^^^^^^ the trait `Clone` is not implemented for `(dyn Uniform + 'static)`
|
note: required by a bound in `uniform::to_owned`
--> src\uniform.rs:9:30
|
9 | pub fn to_owned<U: Uniform + Clone, T: AsRef<U>>(uniforms: &[T]) -> Vec<Box<dyn Uniform>>
| ^^^^^ required by this bound in `uniform::to_owned`
Why is Clone required by the resulting trait object? clone is only needed during operations on generic U and thus only U should implement Clone. Why does it have anything to do with the final trait object? I would expect that since U implements Uniform it should be possible to create a dyn Uniform trait object out of it.
Also I cannot require Clone as super trait for Uniform since it would make it not object safe.
I have tried explicitly casting resulting box type into trait object, adding 'static lifetime bound but to no avail.
pub fn to_owned<U: 'static + Uniform + Clone, T: AsRef<U>>(uniforms: &[T]) -> Vec<Box<dyn Uniform>>
where Vec<Box<dyn Uniform>>: FromIterator<Box<U>>
{
uniforms.into_iter()
.map(AsRef::as_ref)
.map(Clone::clone)
.map(|uniform| Box::new(uniform) as Box<dyn Uniform>)
.collect()
}
I really don't understand what's wrong with my code. It's either that I'm doing some syntactic mistake or there's deeper logical error with what I'm trying to accomplish here.
I would greatly appreciate any help.
|
[
"The main problem is your to_owned function.\nWith where Vec<Box<dyn Uniform>>: FromIterator<Box<U>> you are actually hiding the real problem, causing very confusing compiler messages.\nYou probably added this because the compiler suggested it. But the compiler also warns that while this is what it needs, adding the where clause is probably not the correct solution.\nWith the where clause, instead of specifying correct bounds that make the conversion possible, you just move the problem out of the function. I agree with the compiler that this is the wrong solution.\nYour second attempt is almost correct, all you are missing is that you need to remove the where clause:\nuse nalgebra_glm::Mat4;\n\nfn perspective_matrix() -> Mat4 {\n todo!()\n}\n\npub trait Uniform {\n fn bind(&self, location: i32);\n}\n\nimpl Uniform for [[f32; 4]; 4] {\n fn bind(&self, _location: i32) {\n todo!()\n }\n}\n\npub fn to_owned<T, U>(uniforms: &[T]) -> Vec<Box<dyn Uniform>>\nwhere\n T: AsRef<U>,\n U: Uniform + Clone + 'static,\n{\n uniforms\n .into_iter()\n .map(AsRef::as_ref)\n .map(Clone::clone)\n .map(|uniform| Box::new(uniform) as Box<dyn Uniform>)\n .collect()\n}\n\nfn main() {\n let _common_uniforms = to_owned(&[perspective_matrix()]);\n}\n\nAlso, this is how a minimal reproducible example looks like ;)\n"
] |
[
0
] |
[] |
[] |
[
"rust"
] |
stackoverflow_0074666456_rust.txt
|
Q:
Display all lines matching a pattern in vim
I search for a particular string in a file in vim, and I want all the lines with matching string to be displayed, perhaps in another vim window.
Currently I do this:
Search for 'string'
/string
and move to next matching string
n or N
Bur, I want all the lines with matching string at one place.
For example:
1 Here is a string
2 Nothing here
3 Here is the same string
I want lines 1 and 3 to be displayed as below, highlighting string
1 Here is a string
3 Here is the same string
A:
:g/pattern/#<CR>
lists all the lines matching pattern. You can then do :23<CR> to jump to line 23.
:ilist pattern<CR>
is an alternative that filters out comments and works across includes.
The command below:
:vimgrep pattern %|cwindow<CR>
will use Vim's built-in grep-like functionality to search for pattern in the current file (%) and display the results in the quickfix window.
:grep pattern %|cwindow<CR>
does the same but uses an external program. Note that :grep and :vimgrep work with files, not buffers.
Reference:
:help :g
:help include-search
:help :vimgrep
:help :grep
:help :cwindow
FWIW, my plugin vim-qlist combines the features of :ilist and the quickfix window.
A:
From the comments I believe your file looks like this, i.e. the line numbers are not part of the text:
Here is a string
Nothing here
Here is the same string
You could copy all lines matching a pattern into a named register ("a" in the example below), then paste it into a new file:
:g/string/y A
:e newfile
:"ap
Which gets you:
Here is a string
Here is the same string
Alternatively, you can use the grep command and add -n to include line numbers:
:grep -n string %
1:~/tmp.txt [text] line: 3 of 3, col: 23 (All)
:!grep -nH -n string /home/christofer/tmp.txt 2>&1| tee /tmp/vHg7GcV/3
[No write since last change]
/home/christofer/tmp.txt:1:Here is a string
/home/christofer/tmp.txt:3:Here is the same string
(1 of 2): Here is a string
Press ENTER or type command to continue
By default you'll get the output in the "command buffer" down at the bottom (don't know its proper name), but you can store it in several different places, using :copen for example.
A:
Following this answer over on the Vi StackExchange:
:v/mystring/d
This will remove all lines not containing mystring and will highlight mystring in the remaining lines.
|
Display all lines matching a pattern in vim
|
I search for a particular string in a file in vim, and I want all the lines with matching string to be displayed, perhaps in another vim window.
Currently I do this:
Search for 'string'
/string
and move to next matching string
n or N
Bur, I want all the lines with matching string at one place.
For example:
1 Here is a string
2 Nothing here
3 Here is the same string
I want lines 1 and 3 to be displayed as below, highlighting string
1 Here is a string
3 Here is the same string
|
[
":g/pattern/#<CR>\n\nlists all the lines matching pattern. You can then do :23<CR> to jump to line 23.\n:ilist pattern<CR>\n\nis an alternative that filters out comments and works across includes.\nThe command below:\n:vimgrep pattern %|cwindow<CR>\n\nwill use Vim's built-in grep-like functionality to search for pattern in the current file (%) and display the results in the quickfix window.\n:grep pattern %|cwindow<CR>\n\ndoes the same but uses an external program. Note that :grep and :vimgrep work with files, not buffers.\nReference:\n:help :g\n:help include-search\n:help :vimgrep\n:help :grep\n:help :cwindow\n\n\nFWIW, my plugin vim-qlist combines the features of :ilist and the quickfix window.\n",
"From the comments I believe your file looks like this, i.e. the line numbers are not part of the text:\nHere is a string\nNothing here\nHere is the same string\n\nYou could copy all lines matching a pattern into a named register (\"a\" in the example below), then paste it into a new file:\n:g/string/y A\n:e newfile\n:\"ap\n\nWhich gets you:\nHere is a string\nHere is the same string\n\nAlternatively, you can use the grep command and add -n to include line numbers:\n:grep -n string %\n\n1:~/tmp.txt [text] line: 3 of 3, col: 23 (All)\n:!grep -nH -n string /home/christofer/tmp.txt 2>&1| tee /tmp/vHg7GcV/3\n[No write since last change]\n/home/christofer/tmp.txt:1:Here is a string\n/home/christofer/tmp.txt:3:Here is the same string\n(1 of 2): Here is a string\nPress ENTER or type command to continue\n\nBy default you'll get the output in the \"command buffer\" down at the bottom (don't know its proper name), but you can store it in several different places, using :copen for example.\n",
"Following this answer over on the Vi StackExchange:\n:v/mystring/d\nThis will remove all lines not containing mystring and will highlight mystring in the remaining lines.\n"
] |
[
8,
3,
0
] |
[] |
[] |
[
"regex",
"vim"
] |
stackoverflow_0031780882_regex_vim.txt
|
Q:
Configuring htaccess file for React Router on Apache Server
I have deployed a React app with React Router to my Bluehost server, and need to configure the htaccess file to redirect all of my routed URLs (/portfolio, /about, etc) to index.html instead of trying to fetch a new file from the server and throwing a 404.
I have read about countless similar problems in which the solution seems to be to add this into your htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
I tried this, but I am still getting 404's when I try to visit any page of my site directly that isn't the homepage. I'm wondering if there is anything else in my existing htaccess file that is preventing the above code from working?
There was some code already in there from Bluehost, and I see another IfModule statement, so I'm wondering if that one is overwriting the first one. However I am afraid to edit it and break something, as it clearly says "do not edit." Here is my full htaccess code:
Header always set Content-Security-Policy: upgrade-insecure-requests
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
# END WordPress
Any ideas? I've double-checked that my BrowserRouter is set up correctly and also tried a few other htaccess configurations. I want to avoid using HashRouter or Node if possible but am getting frustrated. I can provide my React code as well if needed, but I'm pretty sure the error is not with the React setup.
A:
You can create a virtual host file in the /etc/apache/sites-available folder and add this:
<VirtualHost *:8080>
ServerName example.com
DocumentRoot /var/www/httpd/example.com
<Directory "/var/www/httpd/example.com">
...
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
This worked for me
|
Configuring htaccess file for React Router on Apache Server
|
I have deployed a React app with React Router to my Bluehost server, and need to configure the htaccess file to redirect all of my routed URLs (/portfolio, /about, etc) to index.html instead of trying to fetch a new file from the server and throwing a 404.
I have read about countless similar problems in which the solution seems to be to add this into your htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
I tried this, but I am still getting 404's when I try to visit any page of my site directly that isn't the homepage. I'm wondering if there is anything else in my existing htaccess file that is preventing the above code from working?
There was some code already in there from Bluehost, and I see another IfModule statement, so I'm wondering if that one is overwriting the first one. However I am afraid to edit it and break something, as it clearly says "do not edit." Here is my full htaccess code:
Header always set Content-Security-Policy: upgrade-insecure-requests
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
# END WordPress
Any ideas? I've double-checked that my BrowserRouter is set up correctly and also tried a few other htaccess configurations. I want to avoid using HashRouter or Node if possible but am getting frustrated. I can provide my React code as well if needed, but I'm pretty sure the error is not with the React setup.
|
[
"You can create a virtual host file in the /etc/apache/sites-available folder and add this:\n <VirtualHost *:8080>\n ServerName example.com\n DocumentRoot /var/www/httpd/example.com\n\n <Directory \"/var/www/httpd/example.com\">\n ...\n\n RewriteEngine on\n # Don't rewrite files or directories\n RewriteCond %{REQUEST_FILENAME} -f [OR]\n RewriteCond %{REQUEST_FILENAME} -d\n RewriteRule ^ - [L]\n # Rewrite everything else to index.html to allow html5 state links\n RewriteRule ^ index.html [L]\n </Directory>\n</VirtualHost>\n\nThis worked for me\n"
] |
[
0
] |
[] |
[] |
[
"apache",
"react_router",
"reactjs",
"server"
] |
stackoverflow_0070668658_apache_react_router_reactjs_server.txt
|
Q:
How to count comparisons in binary search
I have a simple program as such whch implements a binary search ussin g recursion
`
def binarySearch(array, p, left, right, count):
if right >= left:
m = left + (right - left)//2
if array[m] == p:
count+=1
return m
elif array[m] > p:
count+=1
return binarySearch(array, p, left, m-1, count)
else:
count+=1
return binarySearch(array, p, m + 1, right, count)
else:
return None
`
How do i count the number of comparisons i have made?
My current solution does not do what i expected it to do.
How can i amend my code so that i can count the numbe rof comparisosn made?
Many Thanks
A:
What gog means is:
def binarySearch(array, p, left, right, count):
if right >= left:
m = left + (right - left)//2
if array[m] == p:
count += 1
return m, count
elif array[m] > p:
count += 1
return binarySearch(array, p, left, m-1, count)
else:
count += 1
return binarySearch(array, p, m + 1, right, count)
else:
return None, count
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
p = 9
index, count = binarySearch(arr, p, 0, len(arr)-1, 0)
|
How to count comparisons in binary search
|
I have a simple program as such whch implements a binary search ussin g recursion
`
def binarySearch(array, p, left, right, count):
if right >= left:
m = left + (right - left)//2
if array[m] == p:
count+=1
return m
elif array[m] > p:
count+=1
return binarySearch(array, p, left, m-1, count)
else:
count+=1
return binarySearch(array, p, m + 1, right, count)
else:
return None
`
How do i count the number of comparisons i have made?
My current solution does not do what i expected it to do.
How can i amend my code so that i can count the numbe rof comparisosn made?
Many Thanks
|
[
"What gog means is:\ndef binarySearch(array, p, left, right, count):\n if right >= left:\n m = left + (right - left)//2\n if array[m] == p:\n count += 1\n return m, count\n elif array[m] > p:\n count += 1\n return binarySearch(array, p, left, m-1, count)\n else:\n count += 1\n return binarySearch(array, p, m + 1, right, count)\n else:\n return None, count\n\n\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\np = 9\nindex, count = binarySearch(arr, p, 0, len(arr)-1, 0)\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"search"
] |
stackoverflow_0074666575_python_search.txt
|
Q:
Why does the order of Ring middleware need to be reversed?
I'm writing some middleware for Ring and I'm really confused as to why I have to reverse the order of the middleware.
I've found this blog post but it doesn't explain why I have to reverse it.
Here's a quick excerpt from the blog post:
(def app
(wrap-keyword-params (wrap-params my-handler)))
The response would be:
{; Trimmed for brevity
:params {"my_param" "54"}}
Note that the wrap keyword params didn't get called on it because the params hash didn't exist yet. But when you reverse the order of the middleware like so:
(def app
(wrap-params (wrap-keyword-params my-handler)))
{; Trimmed for brevity
:params {:my_param "54"}}
It works.
Could somebody please explain why you have to reverse the order of the middleware?
A:
It helps to visualize what middleware actually is.
(defn middleware [handler]
(fn [request]
;; ...
;; Do something to the request before sending it down the chain.
;; ...
(let [response (handler request)]
;; ...
;; Do something to the response that's coming back up the chain.
;; ...
response)))
That right there was pretty much the a-ha moment for me.
What's confusing at first glance is that middleware isn't applied to the request, which is what you're thinking of.
Recall that a Ring app is just a function that takes a request and returns a response (which means it's a handler):
((fn [request] {:status 200, ...}) request) ;=> response
Let's zoom out a little bit. We get another handler:
((GET "/" [] "Hello") request) ;=> response
Let's zoom out a little more. We find the my-routes handler:
(my-routes request) ;=> response
Well, what if you wanted to do something before sending the request to the my-routes handler? You can wrap it with another handler.
((fn [req] (println "Request came in!") (my-routes req)) request) ;=> response
That's a little hard to read, so let's break out for clarity. We can define a function that returns that handler. Middleware are functions that take a handler and wrap it another handler. It doesn't return a response. It returns a handler that can return a response.
(defn println-middleware [wrapped-func]
(fn [req]
(println "Request came in!")
(wrapped-func req)))
((println-middleware my-route) request) ;=> response
And if we need to do something before even println-middleware gets the request, then we can wrap it again:
((outer-middleware (println-middleware my-routes)) request) ;=> response
The key is that my-routes, just like your my-handler, is the only named function that actually takes the request as an argument.
One final demonstration:
(handler3 (handler2 (handler1 request))) ;=> response
((middleware1 (middleware2 (middleware3 handler1))) request) ;=> response
I write so much because I can sympathize. But scroll back up to my first middleware example and hopefully it makes more sense.
A:
The ring middleware is a series of functions which when stacked up return a handler function.
The section of the article that answers your question:
In case of Ring wrappers, typically we have “before” decorators that
perform some preparations before calling the “real” business function.
Since they are higher order functions and not direct function calls,
they are applied in reversed order. If one depends on the other, the
dependent one needs to be on the “inside”.
Here is a contrived example:
(let [post-wrap (fn [handler]
(fn [request]
(str (handler request) ", post-wrapped")))
pre-wrap (fn [handler]
(fn [request]
(handler (str request ", pre-wrapped"))))
around (fn [handler]
(fn [request]
(str (handler (str request ", pre-around")) ", post-around")))
handler (-> (pre-wrap identity)
post-wrap
around)]
(println (handler "(this was the input)")))
This prints and returns:
(this was the input), pre-around, pre-wrapped, post-wrapped, post-around
nil
A:
As you may know the ring app is actually just a function that receives a request map and returns a response map.
In the first case the order in which the functions are applied is this:
request -> [wrap-keyword-params -> wrap-params -> my-handler] -> response
wrap-keyword-params looks for the key :params in the request but it's not there since wrap-params is the one who adds that key based on the "urlencoded parameters from the query string and form body".
When you invert the order of those two:
request -> [wrap-params -> wrap-keyword-params -> my-handler] -> response
You get the desired result since once the request gets to wrap-keyword-params, wrap-params has already added the corresponding keys.
A:
The answer by danneu is nice, but it only really "clicked" for me after I visualized it in code to see how the chaining of middleware really looks like without the "->" threading macro magic (here's a link if you're not familiar with it). This is what I ended up with:
Let's say you have a request handler that looks like this:
(def amazing-handler
(-> #'some-amazing-fn
some-mware
another-mware
one-more-mware))
^^ The above handler, written without using a threading macro, would look like this (and I'm extending the indentation on purpose, so it is visually easier to understand which request belongs to which handler):
(def amazing-handler
(one-more-mware
(another-mware
((some-mware #'some-amazing-fn) request-from-another-mware)
request-from-one-more-mware)
original-request))
^^ The above is a style of code that requires us to read it from inside out (which sometimes is hard to follow), the threading macros (-> and ->>) allow us to read code in a natural left-to-right way, but it requires understanding on our part of how exactly it allows us to compose code in this "natural" way behind the scene.
Here's a more complete example:
;; For reference: this is how the end result of the entire "threading" looks like:
;; (((#'some-amazing-fn req-from-up-passed-down) req-from-up-passed-down) original-request)
(defn some-amazing-fn [req] ;; this "req" is the one that will get passed to this function from "some-mware"
(println "this is the final destination of the req", req)
(ring.util.http-response/ok {:body "some funny response"}))
(defn one-more-mware [some-argument] ;; the "some-argument" in this case is (another-mware (some-mware #'some-amazing-fn))
(fn [req] ;; the "req" here is the original request generated by the ring adaptors and passed to this chain of middleware
(println "|--> from fn inside one-more-mware")
(some-argument req))) ;; here we provide the another-mware with the request that it will then pass down the chain of middleware, you can imagine that chain, at this point in time, to look like this:
;; ((another-mware (some-mware #'some-amazing-fn)) req)
(defn another-mware [dunno-something] ;; the "dunno-something" in this case is (some-mware #'some-amazing-fn)
(fn [req] ;; the "req" here is passed from one-more-mware function
(println "|--> from fn inside another-mware")
(dunno-something req))) ;; here we are passing the "req" down the line to the (some-mware #'some-amazing-fn), so the entire thing behind the scenes, at this point in time, looks like this:
;; ((some-mware #'some-amazing-fn) req)
(defn some-mware [some-handler] ;; the "some-handler" arg here refers to #'some-amazing-fn
(fn [req] ;; the "req" here is passed to this function from another-mware function
(println "|--> from fn inside some-mware")
(some-handler req))) ;; here is where we are passing a "req" argument to the #'some-amazing-fn, so behind the scenes it could be thought of as looking like this:
;; (#'some-amazing-fn req)
(def amazing-handler
(-> #'some-amazing-fn
some-mware
another-mware
one-more-mware))
;; |--> from fn inside one-more-mware
;; |--> from fn inside another-mware
;; |--> from fn inside some-mware
;; |--> this is the final destination of the req {.. .. ..}
|
Why does the order of Ring middleware need to be reversed?
|
I'm writing some middleware for Ring and I'm really confused as to why I have to reverse the order of the middleware.
I've found this blog post but it doesn't explain why I have to reverse it.
Here's a quick excerpt from the blog post:
(def app
(wrap-keyword-params (wrap-params my-handler)))
The response would be:
{; Trimmed for brevity
:params {"my_param" "54"}}
Note that the wrap keyword params didn't get called on it because the params hash didn't exist yet. But when you reverse the order of the middleware like so:
(def app
(wrap-params (wrap-keyword-params my-handler)))
{; Trimmed for brevity
:params {:my_param "54"}}
It works.
Could somebody please explain why you have to reverse the order of the middleware?
|
[
"It helps to visualize what middleware actually is.\n(defn middleware [handler]\n (fn [request]\n ;; ...\n ;; Do something to the request before sending it down the chain.\n ;; ...\n (let [response (handler request)]\n ;; ...\n ;; Do something to the response that's coming back up the chain.\n ;; ...\n response)))\n\nThat right there was pretty much the a-ha moment for me.\nWhat's confusing at first glance is that middleware isn't applied to the request, which is what you're thinking of. \nRecall that a Ring app is just a function that takes a request and returns a response (which means it's a handler):\n((fn [request] {:status 200, ...}) request) ;=> response\n\nLet's zoom out a little bit. We get another handler:\n((GET \"/\" [] \"Hello\") request) ;=> response\n\nLet's zoom out a little more. We find the my-routes handler:\n(my-routes request) ;=> response\n\nWell, what if you wanted to do something before sending the request to the my-routes handler? You can wrap it with another handler.\n((fn [req] (println \"Request came in!\") (my-routes req)) request) ;=> response\n\nThat's a little hard to read, so let's break out for clarity. We can define a function that returns that handler. Middleware are functions that take a handler and wrap it another handler. It doesn't return a response. It returns a handler that can return a response.\n(defn println-middleware [wrapped-func]\n (fn [req]\n (println \"Request came in!\")\n (wrapped-func req)))\n\n((println-middleware my-route) request) ;=> response\n\nAnd if we need to do something before even println-middleware gets the request, then we can wrap it again:\n((outer-middleware (println-middleware my-routes)) request) ;=> response\n\nThe key is that my-routes, just like your my-handler, is the only named function that actually takes the request as an argument.\nOne final demonstration:\n(handler3 (handler2 (handler1 request))) ;=> response\n((middleware1 (middleware2 (middleware3 handler1))) request) ;=> response\n\nI write so much because I can sympathize. But scroll back up to my first middleware example and hopefully it makes more sense.\n",
"The ring middleware is a series of functions which when stacked up return a handler function.\nThe section of the article that answers your question:\n\nIn case of Ring wrappers, typically we have “before” decorators that\n perform some preparations before calling the “real” business function.\n Since they are higher order functions and not direct function calls,\n they are applied in reversed order. If one depends on the other, the\n dependent one needs to be on the “inside”.\n\nHere is a contrived example:\n(let [post-wrap (fn [handler]\n (fn [request]\n (str (handler request) \", post-wrapped\")))\n pre-wrap (fn [handler]\n (fn [request]\n (handler (str request \", pre-wrapped\"))))\n around (fn [handler]\n (fn [request]\n (str (handler (str request \", pre-around\")) \", post-around\")))\n handler (-> (pre-wrap identity)\n post-wrap\n around)]\n (println (handler \"(this was the input)\")))\n\nThis prints and returns:\n(this was the input), pre-around, pre-wrapped, post-wrapped, post-around\nnil\n\n",
"As you may know the ring app is actually just a function that receives a request map and returns a response map.\nIn the first case the order in which the functions are applied is this:\nrequest -> [wrap-keyword-params -> wrap-params -> my-handler] -> response\n\nwrap-keyword-params looks for the key :params in the request but it's not there since wrap-params is the one who adds that key based on the \"urlencoded parameters from the query string and form body\".\nWhen you invert the order of those two:\nrequest -> [wrap-params -> wrap-keyword-params -> my-handler] -> response\n\nYou get the desired result since once the request gets to wrap-keyword-params, wrap-params has already added the corresponding keys.\n",
"The answer by danneu is nice, but it only really \"clicked\" for me after I visualized it in code to see how the chaining of middleware really looks like without the \"->\" threading macro magic (here's a link if you're not familiar with it). This is what I ended up with:\nLet's say you have a request handler that looks like this:\n(def amazing-handler\n (-> #'some-amazing-fn\n some-mware\n another-mware\n one-more-mware))\n\n^^ The above handler, written without using a threading macro, would look like this (and I'm extending the indentation on purpose, so it is visually easier to understand which request belongs to which handler):\n(def amazing-handler \n (one-more-mware\n (another-mware\n ((some-mware #'some-amazing-fn) request-from-another-mware)\n request-from-one-more-mware)\n original-request))\n\n^^ The above is a style of code that requires us to read it from inside out (which sometimes is hard to follow), the threading macros (-> and ->>) allow us to read code in a natural left-to-right way, but it requires understanding on our part of how exactly it allows us to compose code in this \"natural\" way behind the scene.\nHere's a more complete example:\n;; For reference: this is how the end result of the entire \"threading\" looks like:\n;; (((#'some-amazing-fn req-from-up-passed-down) req-from-up-passed-down) original-request)\n\n(defn some-amazing-fn [req] ;; this \"req\" is the one that will get passed to this function from \"some-mware\"\n (println \"this is the final destination of the req\", req)\n (ring.util.http-response/ok {:body \"some funny response\"}))\n\n\n(defn one-more-mware [some-argument] ;; the \"some-argument\" in this case is (another-mware (some-mware #'some-amazing-fn))\n (fn [req] ;; the \"req\" here is the original request generated by the ring adaptors and passed to this chain of middleware\n (println \"|--> from fn inside one-more-mware\")\n (some-argument req))) ;; here we provide the another-mware with the request that it will then pass down the chain of middleware, you can imagine that chain, at this point in time, to look like this:\n ;; ((another-mware (some-mware #'some-amazing-fn)) req)\n\n\n(defn another-mware [dunno-something] ;; the \"dunno-something\" in this case is (some-mware #'some-amazing-fn)\n (fn [req] ;; the \"req\" here is passed from one-more-mware function\n (println \"|--> from fn inside another-mware\")\n (dunno-something req))) ;; here we are passing the \"req\" down the line to the (some-mware #'some-amazing-fn), so the entire thing behind the scenes, at this point in time, looks like this:\n ;; ((some-mware #'some-amazing-fn) req)\n\n\n(defn some-mware [some-handler] ;; the \"some-handler\" arg here refers to #'some-amazing-fn\n (fn [req] ;; the \"req\" here is passed to this function from another-mware function\n (println \"|--> from fn inside some-mware\")\n (some-handler req))) ;; here is where we are passing a \"req\" argument to the #'some-amazing-fn, so behind the scenes it could be thought of as looking like this:\n ;; (#'some-amazing-fn req)\n\n\n(def amazing-handler\n (-> #'some-amazing-fn\n some-mware\n another-mware\n one-more-mware))\n\n;; |--> from fn inside one-more-mware\n;; |--> from fn inside another-mware\n;; |--> from fn inside some-mware\n;; |--> this is the final destination of the req {.. .. ..}\n\n"
] |
[
48,
14,
6,
0
] |
[] |
[] |
[
"clojure",
"ring"
] |
stackoverflow_0019455801_clojure_ring.txt
|
Q:
split pandas data frame into multiple of 4 rows
I have a dataset of 100 rows, I want to split them into multiple of 4 and then perform operations on it, i.e., first perform operation on first four rows, then on the next four rows and so on.
Note: Rows are independent of each other.
I don't know how to do it. Can somebody pls help me, I would be extremely thankful to him/her.
A:
i will divide df per 2 row (simple example)
and make list dfs
Example
df = pd.DataFrame(list('ABCDE'), columns=['value'])
df
value
0 A
1 B
2 C
3 D
4 E
Code
grouper for grouping
grouper = pd.Series(range(0, len(df))) // 2
grouper
0 0
1 0
2 1
3 1
4 2
dtype: int64
divide to list
g = df.groupby(grouper)
dfs = [g.get_group(x) for x in g.groups]
result(dfs):
[ value
0 A
1 B,
value
2 C
3 D,
value
4 E]
Check
dfs[0]
output:
value
0 A
1 B
|
split pandas data frame into multiple of 4 rows
|
I have a dataset of 100 rows, I want to split them into multiple of 4 and then perform operations on it, i.e., first perform operation on first four rows, then on the next four rows and so on.
Note: Rows are independent of each other.
I don't know how to do it. Can somebody pls help me, I would be extremely thankful to him/her.
|
[
"i will divide df per 2 row (simple example)\nand make list dfs\nExample\ndf = pd.DataFrame(list('ABCDE'), columns=['value'])\n\ndf\n value\n0 A\n1 B\n2 C\n3 D\n4 E\n\nCode\ngrouper for grouping\ngrouper = pd.Series(range(0, len(df))) // 2\n\ngrouper\n0 0\n1 0\n2 1\n3 1\n4 2\ndtype: int64\n\ndivide to list\ng = df.groupby(grouper)\ndfs = [g.get_group(x) for x in g.groups]\n\nresult(dfs):\n[ value\n 0 A\n 1 B,\n value\n 2 C\n 3 D,\n value\n 4 E]\n\nCheck\ndfs[0]\n\noutput:\nvalue\n0 A\n1 B\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074667114_dataframe_pandas_python.txt
|
Q:
How to check if client uses web view?
I have a component in my website which used to show a download link, I want to remove this component whenever client visits my website using android web view.
Expected to have a function in js that determines this but couldn't find any
A:
You can try using the navigator.userAgent property to determine whether the client is using android web view.
function checkForWebView() {
const userAgent = navigator.userAgent;
if (userAgent.includes('Android')) {
// The client is using an Android device.
// Check if the user agent string contains the name of a known Android web view.
if (userAgent.includes('Chrome') || userAgent.includes('Firefox') || userAgent.includes('SamsungBrowser')) {
// The client is using a web view.
return true;
} else {
// The client is not using a web view.
return false;
}
} else {
// The client is not using an Android device.
return false;
}
}
|
How to check if client uses web view?
|
I have a component in my website which used to show a download link, I want to remove this component whenever client visits my website using android web view.
Expected to have a function in js that determines this but couldn't find any
|
[
"You can try using the navigator.userAgent property to determine whether the client is using android web view.\nfunction checkForWebView() {\n const userAgent = navigator.userAgent;\n \n if (userAgent.includes('Android')) {\n // The client is using an Android device.\n // Check if the user agent string contains the name of a known Android web view.\n if (userAgent.includes('Chrome') || userAgent.includes('Firefox') || userAgent.includes('SamsungBrowser')) {\n // The client is using a web view.\n return true;\n } else {\n // The client is not using a web view.\n return false;\n }\n } else {\n // The client is not using an Android device.\n return false;\n }\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"frontend",
"javascript",
"jquery"
] |
stackoverflow_0074666996_frontend_javascript_jquery.txt
|
Q:
cleaning html tags from a variable
I'm trying to clean the html tags from a variable with this value:
<td><a class="css-zwebxb" href="/players/1093743350">Zero Two</a></td>, <td><time datetime="PT2M5.031S" time="1670072352910" title="Saturday, December 3, 2022 12:57 PM">00:02</time></td>, <td class="css-7a8yo0"> <button class="css-sanbnz" type="button"><i class="glyphicon glyphicon-flag"></i></button></td>
I attempted to clean the tags by using multiple different functions I found online, like
import re
# as per recommendation from @freylis, compile once only
CLEANR = re.compile('<.*?>')
def cleanhtml(raw_html):
cleantext = re.sub(CLEANR, '', raw_html)
return cleantext
I get the error: TypeError: expected string or bytes-like object.
Does anybody know a solution? thank you so much.
A:
If you want only text from the HTML snippet you can use .text or .get_text():
from bs4 import BeautifulSoup
html_doc = """<td><a class="css-zwebxb" href="/players/1093743350">Zero Two</a></td>, <td><time datetime="PT2M5.031S" time="1670072352910" title="Saturday, December 3, 2022 12:57 PM">00:02</time></td>, <td class="css-7a8yo0"> <button class="css-sanbnz" type="button"><i class="glyphicon glyphicon-flag"></i></button></td>"""
soup = BeautifulSoup(html_doc, "html.parser")
print(soup.get_text(strip=True, separator=""))
Prints:
Zero Two,00:02,
|
cleaning html tags from a variable
|
I'm trying to clean the html tags from a variable with this value:
<td><a class="css-zwebxb" href="/players/1093743350">Zero Two</a></td>, <td><time datetime="PT2M5.031S" time="1670072352910" title="Saturday, December 3, 2022 12:57 PM">00:02</time></td>, <td class="css-7a8yo0"> <button class="css-sanbnz" type="button"><i class="glyphicon glyphicon-flag"></i></button></td>
I attempted to clean the tags by using multiple different functions I found online, like
import re
# as per recommendation from @freylis, compile once only
CLEANR = re.compile('<.*?>')
def cleanhtml(raw_html):
cleantext = re.sub(CLEANR, '', raw_html)
return cleantext
I get the error: TypeError: expected string or bytes-like object.
Does anybody know a solution? thank you so much.
|
[
"If you want only text from the HTML snippet you can use .text or .get_text():\nfrom bs4 import BeautifulSoup\n\nhtml_doc = \"\"\"<td><a class=\"css-zwebxb\" href=\"/players/1093743350\">Zero Two</a></td>, <td><time datetime=\"PT2M5.031S\" time=\"1670072352910\" title=\"Saturday, December 3, 2022 12:57 PM\">00:02</time></td>, <td class=\"css-7a8yo0\"> <button class=\"css-sanbnz\" type=\"button\"><i class=\"glyphicon glyphicon-flag\"></i></button></td>\"\"\"\n\nsoup = BeautifulSoup(html_doc, \"html.parser\")\n\nprint(soup.get_text(strip=True, separator=\"\"))\n\nPrints:\nZero Two,00:02,\n\n"
] |
[
0
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0074667162_beautifulsoup_python.txt
|
Q:
How to parse strings in Java?
I am working on a homework assignment and unable to find the answer in my online text book or anywhere else.
My homework question is four parts:
Prompt the user for a string that contains two strings separated by a comma.
Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.
Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.
Final outcome should print out as follows:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string: Washington,DC
First word: Washington
Second word: DC
Enter input string: q
My code output is incorrect. I do not know how to make the automatic , not show after my first word or show up as my second word. I have tried using
String [] array = s.split(",); and the class program does not recognize this command and errors out.
This is my code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String firstWord = " ";
String secondWord = "";
String lineString = "";
boolean inputDone = false;
while (!inputDone) {
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
System.out.print("Enter input string: \n");
if (firstWord.equals("q")){
System.out.println("First word: " + firstWord);
inputDone = true;
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
How can I code this string to include and exclude the comma and print out the error. I am not understanding what I need to do.
A:
I don't want write the code for the solution. Just give you some input to arrive at right answer by yourself. It is your exercise after all.
You do not need to use two Scanner one is enough.
Check the variable lineString after the execution of scnr.nextLine()
The String method split usually helps to figure out
A:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
boolean inputDone = false;
while (!inputDone) {
System.out.print("Enter input string: \n");
userInput = scnr.nextLine()
if (userInput.equals("q")){
System.out.println("First word: " + userInput);
inputDone = true;
} else {
String[] userArray = userInput.split(",");
System.out.println("First word: " + userArray[0]);
System.out.println("Second word: " + userArray[1]);
System.out.println();
}
}
return;
}
}
Explanation:
First, an object Scanner is created. Then, the user's input is stored in userInput. After that, java checks if the user entered q, if so, then end the application. Else, java splits the string into two words and then prints it.
Remember that understanding the code is a very important process in learning a programming language, so please, please understand the code and not just copy and paste it to submit as your homework.
A:
I got this same problem in my class and it been a very challenging problem for me to figure out. I was able to get the correct answer using the code posted in here that only needed very slight modifications made to it. Thank you for the help. below is modified version of the above the code I used to get the correct answer.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
boolean inputDone = false;
while (!inputDone) {
System.out.print("Enter input string: \n");
userInput = scnr.nextLine();
if (userInput.equals("q")){
inputDone = true;
break;
}
if(userInput.indexOf(",") == -1){ //if comma is not found in the user input
System.out.println("Error: No comma in string");
continue;
}
else {
String[] userArray = userInput.split(",");
System.out.println("First word: " + userArray[0].trim());
System.out.println("Second word: " + userArray[1].trim());
System.out.println();
System.out.println();
}
}
return;
}
}
A:
The unit I was working on for this problem was about using the inSS, so I wanted to try and use it to solve the problem. I did get stuck constantly collecting the comma for the second word, but after consulting someone else was suggesting using a delimiter to get passed the comma. I did have to add a trim() command on the print lines to get rid of any white spaces around the words when they were captured by the inSS.##
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Input string stream
Scanner inSS = null;
//Input string
String inputWords;
// first word
String firstWord;
//Comma check;
String commaCheck;
//second word
String secondWord;
//flag to indicate next iteration
boolean inputDone;
inputDone = false;
//prompt the user to input string
System.out.println("Enter input string: ");
//take input data as long as "q" is not ent
while (!inputDone){
//entire line into inputWords
inputWords = scnr.nextLine();
//Init scanner object with string
inSS = new Scanner(inputWords);
//Set the delimiter to "," and new line
inSS.useDelimiter("[,\n]");
//process the line
firstWord = inSS.next();
//output parsed values
if (firstWord.equals("q")){
inputDone = true;
break;
}
//comma check
if(inputWords.indexOf(",") == -1){
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
continue;
}
else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord.trim());
System.out.println("Second word: " + secondWord.trim());
System.out.println();
System.out.println();
}
System.out.println("Enter input string: ");
}
}
}
|
How to parse strings in Java?
|
I am working on a homework assignment and unable to find the answer in my online text book or anywhere else.
My homework question is four parts:
Prompt the user for a string that contains two strings separated by a comma.
Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.
Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.
Final outcome should print out as follows:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string: Washington,DC
First word: Washington
Second word: DC
Enter input string: q
My code output is incorrect. I do not know how to make the automatic , not show after my first word or show up as my second word. I have tried using
String [] array = s.split(",); and the class program does not recognize this command and errors out.
This is my code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String firstWord = " ";
String secondWord = "";
String lineString = "";
boolean inputDone = false;
while (!inputDone) {
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
System.out.print("Enter input string: \n");
if (firstWord.equals("q")){
System.out.println("First word: " + firstWord);
inputDone = true;
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
How can I code this string to include and exclude the comma and print out the error. I am not understanding what I need to do.
|
[
"I don't want write the code for the solution. Just give you some input to arrive at right answer by yourself. It is your exercise after all.\n\nYou do not need to use two Scanner one is enough.\nCheck the variable lineString after the execution of scnr.nextLine()\nThe String method split usually helps to figure out\n\n",
"import java.util.Scanner;\n\npublic class ParseStrings {\n public static void main(String[] args) {\n Scanner scnr = new Scanner(System.in);\n String userInput = \"\";\n boolean inputDone = false; \n\n while (!inputDone) {\n System.out.print(\"Enter input string: \\n\");\n userInput = scnr.nextLine()\n\n\n if (userInput.equals(\"q\")){\n System.out.println(\"First word: \" + userInput);\n inputDone = true; \n } else {\n String[] userArray = userInput.split(\",\");\n System.out.println(\"First word: \" + userArray[0]);\n System.out.println(\"Second word: \" + userArray[1]);\n System.out.println();\n }\n }\n\n\n return;\n }\n}\n\nExplanation:\nFirst, an object Scanner is created. Then, the user's input is stored in userInput. After that, java checks if the user entered q, if so, then end the application. Else, java splits the string into two words and then prints it.\nRemember that understanding the code is a very important process in learning a programming language, so please, please understand the code and not just copy and paste it to submit as your homework.\n",
"I got this same problem in my class and it been a very challenging problem for me to figure out. I was able to get the correct answer using the code posted in here that only needed very slight modifications made to it. Thank you for the help. below is modified version of the above the code I used to get the correct answer. \nimport java.util.Scanner;\n\npublic class ParseStrings {\n public static void main(String[] args) {\n Scanner scnr = new Scanner(System.in);\n String userInput = \"\";\n boolean inputDone = false; \n\n while (!inputDone) {\n System.out.print(\"Enter input string: \\n\");\n userInput = scnr.nextLine();\n\n if (userInput.equals(\"q\")){\n inputDone = true;\n break;\n }\n\n if(userInput.indexOf(\",\") == -1){ //if comma is not found in the user input\n System.out.println(\"Error: No comma in string\");\n continue;\n }\n\n\n else {\n String[] userArray = userInput.split(\",\");\n System.out.println(\"First word: \" + userArray[0].trim());\n System.out.println(\"Second word: \" + userArray[1].trim());\n System.out.println();\n System.out.println();\n }\n }\n\n\n return;\n }\n}\n\n",
"The unit I was working on for this problem was about using the inSS, so I wanted to try and use it to solve the problem. I did get stuck constantly collecting the comma for the second word, but after consulting someone else was suggesting using a delimiter to get passed the comma. I did have to add a trim() command on the print lines to get rid of any white spaces around the words when they were captured by the inSS.##\n\nimport java.util.Scanner;\n\n\npublic class ParseStrings {\n public static void main(String[] args) {\n Scanner scnr = new Scanner(System.in);\n //Input string stream\n Scanner inSS = null;\n //Input string \n String inputWords;\n // first word\n String firstWord;\n //Comma check;\n String commaCheck;\n //second word\n String secondWord;\n //flag to indicate next iteration\n boolean inputDone;\n \n inputDone = false;\n\n //prompt the user to input string \n System.out.println(\"Enter input string: \");\n \n //take input data as long as \"q\" is not ent\n while (!inputDone){\n \n //entire line into inputWords\n inputWords = scnr.nextLine();\n \n //Init scanner object with string\n inSS = new Scanner(inputWords);\n\n //Set the delimiter to \",\" and new line\n inSS.useDelimiter(\"[,\\n]\");\n \n //process the line\n firstWord = inSS.next();\n \n //output parsed values\n if (firstWord.equals(\"q\")){\n inputDone = true;\n break;\n }\n \n //comma check\n if(inputWords.indexOf(\",\") == -1){\n System.out.println(\"Error: No comma in string\");\n System.out.println(\"Enter input string: \");\n continue;\n }\n else {\n secondWord = inSS.next();\n System.out.println(\"First word: \" + firstWord.trim());\n System.out.println(\"Second word: \" + secondWord.trim());\n System.out.println();\n System.out.println();\n }\n System.out.println(\"Enter input string: \");\n \n\n \n }\n\n } \n}\n\n"
] |
[
1,
1,
1,
0
] |
[] |
[] |
[
"java",
"parsing",
"split"
] |
stackoverflow_0042035402_java_parsing_split.txt
|
Q:
how to convert json file data to string in bash shell script?
how to convert json file data to string in bash shell script?
i have below petstore swagger file (https://petstore.swagger.io/v2/swagger.json)
in json format.
i have converted this json file into string with backspaces characters \ needed for one operation using this site https://jsontostring.com/ .
i have tried jq tool to achieve this, didn't got the result and perhaps it will not come using jq tool.
How can we convert this same petstore swagger json file into string with below expected output in linux or bash shell script ?
{"swagger":"2.0","info":{"description":"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.","version":"1.0.6","title":"Swagger Petstore","termsOfService":"http://swagger.io/terms/","contact":{"email":"[email protected]"},"license":{"name":"Apache 2.0","url":"http://www.apache.org/licenses/LICENSE-2.0.html"}},"host":"petstore.swagger.io","basePath":"/v2","tags":[{"name":"pet","description":"Everything about your Pets","externalDocs":{"description":"Find out more","url":"http://swagger.io"}},{"name":"store","description":"Access to Petstore orders"},{"name":"user","description":"Operations about user","externalDocs":{"description":"Find out more about our store","url":"http://swagger.io"}}],"schemes":["https","http"],"paths":{"/pet/{petId}/uploadImage":{"post":{"tags":["pet"],"summary":"uploads an image","description":"","operationId":"uploadFile","consumes":["multipart/form-data"],"produces":["application/json"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to update","required":true,"type":"integer","format":"int64"},{"name":"additionalMetadata","in":"formData","description":"Additional data to pass to server","required":false,"type":"string"},{"name":"file","in":"formData","description":"file to upload","required":false,"type":"file"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiResponse"}}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet":{"post":{"tags":["pet"],"summary":"Add a new pet to the store","description":"","operationId":"addPet","consumes":["application/json","application/xml"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"schema":{"$ref":"#/definitions/Pet"}}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"put":{"tags":["pet"],"summary":"Update an existing pet","description":"","operationId":"updatePet","consumes":["application/json","application/xml"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"schema":{"$ref":"#/definitions/Pet"}}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"},"405":{"description":"Validation exception"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByStatus":{"get":{"tags":["pet"],"summary":"Finds Pets by status","description":"Multiple status values can be provided with comma separated strings","operationId":"findPetsByStatus","produces":["application/json","application/xml"],"parameters":[{"name":"status","in":"query","description":"Status values that need to be considered for filter","required":true,"type":"array","items":{"type":"string","enum":["available","pending","sold"],"default":"available"},"collectionFormat":"multi"}],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}},"400":{"description":"Invalid status value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByTags":{"get":{"tags":["pet"],"summary":"Finds Pets by tags","description":"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.","operationId":"findPetsByTags","produces":["application/json","application/xml"],"parameters":[{"name":"tags","in":"query","description":"Tags to filter by","required":true,"type":"array","items":{"type":"string"},"collectionFormat":"multi"}],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}},"400":{"description":"Invalid tag value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}],"deprecated":true}},"/pet/{petId}":{"get":{"tags":["pet"],"summary":"Find pet by ID","description":"Returns a single pet","operationId":"getPetById","produces":["application/json","application/xml"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to return","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Pet"}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"}},"security":[{"api_key":[]}]},"post":{"tags":["pet"],"summary":"Updates a pet in the store with form data","description":"","operationId":"updatePetWithForm","consumes":["application/x-www-form-urlencoded"],"produces":["application/json","application/xml"],"parameters":[{"name":"petId","in":"path","description":"ID of pet that needs to be updated","required":true,"type":"integer","format":"int64"},{"name":"name","in":"formData","description":"Updated name of the pet","required":false,"type":"string"},{"name":"status","in":"formData","description":"Updated status of the pet","required":false,"type":"string"}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"delete":{"tags":["pet"],"summary":"Deletes a pet","description":"","operationId":"deletePet","produces":["application/json","application/xml"],"parameters":[{"name":"api_key","in":"header","required":false,"type":"string"},{"name":"petId","in":"path","description":"Pet id to delete","required":true,"type":"integer","format":"int64"}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/store/order":{"post":{"tags":["store"],"summary":"Place an order for a pet","description":"","operationId":"placeOrder","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"order placed for purchasing the pet","required":true,"schema":{"$ref":"#/definitions/Order"}}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Order"}},"400":{"description":"Invalid Order"}}}},"/store/order/{orderId}":{"get":{"tags":["store"],"summary":"Find purchase order by ID","description":"For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions","operationId":"getOrderById","produces":["application/json","application/xml"],"parameters":[{"name":"orderId","in":"path","description":"ID of pet that needs to be fetched","required":true,"type":"integer","maximum":10,"minimum":1,"format":"int64"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Order"}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}},"delete":{"tags":["store"],"summary":"Delete purchase order by ID","description":"For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors","operationId":"deleteOrder","produces":["application/json","application/xml"],"parameters":[{"name":"orderId","in":"path","description":"ID of the order that needs to be deleted","required":true,"type":"integer","minimum":1,"format":"int64"}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}}},"/store/inventory":{"get":{"tags":["store"],"summary":"Returns pet inventories by status","description":"Returns a map of status codes to quantities","operationId":"getInventory","produces":["application/json"],"parameters":[],"responses":{"200":{"description":"successful operation","schema":{"type":"object","additionalProperties":{"type":"integer","format":"int32"}}}},"security":[{"api_key":[]}]}},"/user/createWithArray":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"","operationId":"createUsersWithArrayInput","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"schema":{"type":"array","items":{"$ref":"#/definitions/User"}}}],"responses":{"default":{"description":"successful operation"}}}},"/user/createWithList":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"","operationId":"createUsersWithListInput","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"schema":{"type":"array","items":{"$ref":"#/definitions/User"}}}],"responses":{"default":{"description":"successful operation"}}}},"/user/{username}":{"get":{"tags":["user"],"summary":"Get user by user name","description":"","operationId":"getUserByName","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"The name that needs to be fetched. Use user1 for testing. ","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/User"}},"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}},"put":{"tags":["user"],"summary":"Updated user","description":"This can only be done by the logged in user.","operationId":"updateUser","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"name that need to be updated","required":true,"type":"string"},{"in":"body","name":"body","description":"Updated user object","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"400":{"description":"Invalid user supplied"},"404":{"description":"User not found"}}},"delete":{"tags":["user"],"summary":"Delete user","description":"This can only be done by the logged in user.","operationId":"deleteUser","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"The name that needs to be deleted","required":true,"type":"string"}],"responses":{"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}}},"/user/login":{"get":{"tags":["user"],"summary":"Logs user into the system","description":"","operationId":"loginUser","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"query","description":"The user name for login","required":true,"type":"string"},{"name":"password","in":"query","description":"The password for login in clear text","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","headers":{"X-Expires-After":{"type":"string","format":"date-time","description":"date in UTC when token expires"},"X-Rate-Limit":{"type":"integer","format":"int32","description":"calls per hour allowed by the user"}},"schema":{"type":"string"}},"400":{"description":"Invalid username/password supplied"}}}},"/user/logout":{"get":{"tags":["user"],"summary":"Logs out current logged in user session","description":"","operationId":"logoutUser","produces":["application/json","application/xml"],"parameters":[],"responses":{"default":{"description":"successful operation"}}}},"/user":{"post":{"tags":["user"],"summary":"Create user","description":"This can only be done by the logged in user.","operationId":"createUser","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Created user object","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"default":{"description":"successful operation"}}}}},"securityDefinitions":{"api_key":{"type":"apiKey","name":"api_key","in":"header"},"petstore_auth":{"type":"oauth2","authorizationUrl":"https://petstore.swagger.io/oauth/authorize","flow":"implicit","scopes":{"read:pets":"read your pets","write:pets":"modify pets in your account"}}},"definitions":{"ApiResponse":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"type":{"type":"string"},"message":{"type":"string"}}},"Category":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Category"}},"Pet":{"type":"object","required":["name","photoUrls"],"properties":{"id":{"type":"integer","format":"int64"},"category":{"$ref":"#/definitions/Category"},"name":{"type":"string","example":"doggie"},"photoUrls":{"type":"array","xml":{"wrapped":true},"items":{"type":"string","xml":{"name":"photoUrl"}}},"tags":{"type":"array","xml":{"wrapped":true},"items":{"xml":{"name":"tag"},"$ref":"#/definitions/Tag"}},"status":{"type":"string","description":"pet status in the store","enum":["available","pending","sold"]}},"xml":{"name":"Pet"}},"Tag":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Tag"}},"Order":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"petId":{"type":"integer","format":"int64"},"quantity":{"type":"integer","format":"int32"},"shipDate":{"type":"string","format":"date-time"},"status":{"type":"string","description":"Order Status","enum":["placed","approved","delivered"]},"complete":{"type":"boolean"}},"xml":{"name":"Order"}},"User":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"username":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string"},"password":{"type":"string"},"phone":{"type":"string"},"userStatus":{"type":"integer","format":"int32","description":"User Status"}},"xml":{"name":"User"}}},"externalDocs":{"description":"Find out more about Swagger","url":"http://swagger.io"}}
expected output;
"{\"swagger\":\"2.0\",\"info\":{\"description\":\"ThisisasampleserverPetstoreserver.YoucanfindoutmoreaboutSwaggerat[http://swagger.io](http://swagger.io)oron[irc.freenode.net,#swagger](http://swagger.io/irc/).Forthissample,youcanusetheapikey`special-key`totesttheauthorizationfilters.\",\"version\":\"1.0.6\",\"title\":\"SwaggerPetstore\",\"termsOfService\":\"http://swagger.io/terms/\",\"contact\":{\"email\":\"[email protected]\"},\"license\":{\"name\":\"Apache2.0\",\"url\":\"http://www.apache.org/licenses/LICENSE-2.0.html\"}},\"host\":\"petstore.swagger.io\",\"basePath\":\"/v2\",\"tags\":[{\"name\":\"pet\",\"description\":\"EverythingaboutyourPets\",\"externalDocs\":{\"description\":\"Findoutmore\",\"url\":\"http://swagger.io\"}},{\"name\":\"store\",\"description\":\"AccesstoPetstoreorders\"},{\"name\":\"user\",\"description\":\"Operationsaboutuser\",\"externalDocs\":{\"description\":\"Findoutmoreaboutourstore\",\"url\":\"http://swagger.io\"}}],\"schemes\":[\"https\",\"http\"],\"paths\":{\"/pet/{petId}/uploadImage\":{\"post\":{\"tags\":[\"pet\"],\"summary\":\"uploadsanimage\",\"description\":\"\",\"operationId\":\"uploadFile\",\"consumes\":[\"multipart/form-data\"],\"produces\":[\"application/json\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpettoupdate\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"},{\"name\":\"additionalMetadata\",\"in\":\"formData\",\"description\":\"Additionaldatatopasstoserver\",\"required\":false,\"type\":\"string\"},{\"name\":\"file\",\"in\":\"formData\",\"description\":\"filetoupload\",\"required\":false,\"type\":\"file\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/ApiResponse\"}}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet\":{\"post\":{\"tags\":[\"pet\"],\"summary\":\"Addanewpettothestore\",\"description\":\"\",\"operationId\":\"addPet\",\"consumes\":[\"application/json\",\"application/xml\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Petobjectthatneedstobeaddedtothestore\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Pet\"}}],\"responses\":{\"405\":{\"description\":\"Invalidinput\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]},\"put\":{\"tags\":[\"pet\"],\"summary\":\"Updateanexistingpet\",\"description\":\"\",\"operationId\":\"updatePet\",\"consumes\":[\"application/json\",\"application/xml\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Petobjectthatneedstobeaddedtothestore\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Pet\"}}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"},\"405\":{\"description\":\"Validationexception\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet/findByStatus\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindsPetsbystatus\",\"description\":\"Multiplestatusvaluescanbeprovidedwithcommaseparatedstrings\",\"operationId\":\"findPetsByStatus\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"status\",\"in\":\"query\",\"description\":\"Statusvaluesthatneedtobeconsideredforfilter\",\"required\":true,\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"available\",\"pending\",\"sold\"],\"default\":\"available\"},\"collectionFormat\":\"multi\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Pet\"}}},\"400\":{\"description\":\"Invalidstatusvalue\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet/findByTags\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindsPetsbytags\",\"description\":\"Multipletagscanbeprovidedwithcommaseparatedstrings.Usetag1,tag2,tag3fortesting.\",\"operationId\":\"findPetsByTags\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"tags\",\"in\":\"query\",\"description\":\"Tagstofilterby\",\"required\":true,\"type\":\"array\",\"items\":{\"type\":\"string\"},\"collectionFormat\":\"multi\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Pet\"}}},\"400\":{\"description\":\"Invalidtagvalue\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}],\"deprecated\":true}},\"/pet/{petId}\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindpetbyID\",\"description\":\"Returnsasinglepet\",\"operationId\":\"getPetById\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpettoreturn\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Pet\"}},\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"}},\"security\":[{\"api_key\":[]}]},\"post\":{\"tags\":[\"pet\"],\"summary\":\"Updatesapetinthestorewithformdata\",\"description\":\"\",\"operationId\":\"updatePetWithForm\",\"consumes\":[\"application/x-www-form-urlencoded\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpetthatneedstobeupdated\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"},{\"name\":\"name\",\"in\":\"formData\",\"description\":\"Updatednameofthepet\",\"required\":false,\"type\":\"string\"},{\"name\":\"status\",\"in\":\"formData\",\"description\":\"Updatedstatusofthepet\",\"required\":false,\"type\":\"string\"}],\"responses\":{\"405\":{\"description\":\"Invalidinput\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]},\"delete\":{\"tags\":[\"pet\"],\"summary\":\"Deletesapet\",\"description\":\"\",\"operationId\":\"deletePet\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"api_key\",\"in\":\"header\",\"required\":false,\"type\":\"string\"},{\"name\":\"petId\",\"in\":\"path\",\"description\":\"Petidtodelete\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/store/order\":{\"post\":{\"tags\":[\"store\"],\"summary\":\"Placeanorderforapet\",\"description\":\"\",\"operationId\":\"placeOrder\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"orderplacedforpurchasingthepet\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Order\"}}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Order\"}},\"400\":{\"description\":\"InvalidOrder\"}}}},\"/store/order/{orderId}\":{\"get\":{\"tags\":[\"store\"],\"summary\":\"FindpurchaseorderbyID\",\"description\":\"ForvalidresponsetryintegerIDswithvalue>=1and<=10.Othervalueswillgeneratedexceptions\",\"operationId\":\"getOrderById\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"orderId\",\"in\":\"path\",\"description\":\"IDofpetthatneedstobefetched\",\"required\":true,\"type\":\"integer\",\"maximum\":10,\"minimum\":1,\"format\":\"int64\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Order\"}},\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Ordernotfound\"}}},\"delete\":{\"tags\":[\"store\"],\"summary\":\"DeletepurchaseorderbyID\",\"description\":\"ForvalidresponsetryintegerIDswithpositiveintegervalue.Negativeornon-integervalueswillgenerateAPIerrors\",\"operationId\":\"deleteOrder\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"orderId\",\"in\":\"path\",\"description\":\"IDoftheorderthatneedstobedeleted\",\"required\":true,\"type\":\"integer\",\"minimum\":1,\"format\":\"int64\"}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Ordernotfound\"}}}},\"/store/inventory\":{\"get\":{\"tags\":[\"store\"],\"summary\":\"Returnspetinventoriesbystatus\",\"description\":\"Returnsamapofstatuscodestoquantities\",\"operationId\":\"getInventory\",\"produces\":[\"application/json\"],\"parameters\":[],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"integer\",\"format\":\"int32\"}}}},\"security\":[{\"api_key\":[]}]}},\"/user/createWithArray\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createslistofuserswithgiveninputarray\",\"description\":\"\",\"operationId\":\"createUsersWithArrayInput\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Listofuserobject\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/User\"}}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user/createWithList\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createslistofuserswithgiveninputarray\",\"description\":\"\",\"operationId\":\"createUsersWithListInput\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Listofuserobject\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/User\"}}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user/{username}\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Getuserbyusername\",\"description\":\"\",\"operationId\":\"getUserByName\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"Thenamethatneedstobefetched.Useuser1fortesting.\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/User\"}},\"400\":{\"description\":\"Invalidusernamesupplied\"},\"404\":{\"description\":\"Usernotfound\"}}},\"put\":{\"tags\":[\"user\"],\"summary\":\"Updateduser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"updateUser\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"namethatneedtobeupdated\",\"required\":true,\"type\":\"string\"},{\"in\":\"body\",\"name\":\"body\",\"description\":\"Updateduserobject\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/User\"}}],\"responses\":{\"400\":{\"description\":\"Invalidusersupplied\"},\"404\":{\"description\":\"Usernotfound\"}}},\"delete\":{\"tags\":[\"user\"],\"summary\":\"Deleteuser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"deleteUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"Thenamethatneedstobedeleted\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"400\":{\"description\":\"Invalidusernamesupplied\"},\"404\":{\"description\":\"Usernotfound\"}}}},\"/user/login\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Logsuserintothesystem\",\"description\":\"\",\"operationId\":\"loginUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"query\",\"description\":\"Theusernameforlogin\",\"required\":true,\"type\":\"string\"},{\"name\":\"password\",\"in\":\"query\",\"description\":\"Thepasswordforloginincleartext\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"headers\":{\"X-Expires-After\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"dateinUTCwhentokenexpires\"},\"X-Rate-Limit\":{\"type\":\"integer\",\"format\":\"int32\",\"description\":\"callsperhourallowedbytheuser\"}},\"schema\":{\"type\":\"string\"}},\"400\":{\"description\":\"Invalidusername/passwordsupplied\"}}}},\"/user/logout\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Logsoutcurrentloggedinusersession\",\"description\":\"\",\"operationId\":\"logoutUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createuser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"createUser\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Createduserobject\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/User\"}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}}},\"securityDefinitions\":{\"api_key\":{\"type\":\"apiKey\",\"name\":\"api_key\",\"in\":\"header\"},\"petstore_auth\":{\"type\":\"oauth2\",\"authorizationUrl\":\"https://petstore.swagger.io/oauth/authorize\",\"flow\":\"implicit\",\"scopes\":{\"read:pets\":\"readyourpets\",\"write:pets\":\"modifypetsinyouraccount\"}}},\"definitions\":{\"ApiResponse\":{\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"integer\",\"format\":\"int32\"},\"type\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}}},\"Category\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"name\":{\"type\":\"string\"}},\"xml\":{\"name\":\"Category\"}},\"Pet\":{\"type\":\"object\",\"required\":[\"name\",\"photoUrls\"],\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"category\":{\"$ref\":\"#/definitions/Category\"},\"name\":{\"type\":\"string\",\"example\":\"doggie\"},\"photoUrls\":{\"type\":\"array\",\"xml\":{\"wrapped\":true},\"items\":{\"type\":\"string\",\"xml\":{\"name\":\"photoUrl\"}}},\"tags\":{\"type\":\"array\",\"xml\":{\"wrapped\":true},\"items\":{\"xml\":{\"name\":\"tag\"},\"$ref\":\"#/definitions/Tag\"}},\"status\":{\"type\":\"string\",\"description\":\"petstatusinthestore\",\"enum\":[\"available\",\"pending\",\"sold\"]}},\"xml\":{\"name\":\"Pet\"}},\"Tag\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"name\":{\"type\":\"string\"}},\"xml\":{\"name\":\"Tag\"}},\"Order\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"petId\":{\"type\":\"integer\",\"format\":\"int64\"},\"quantity\":{\"type\":\"integer\",\"format\":\"int32\"},\"shipDate\":{\"type\":\"string\",\"format\":\"date-time\"},\"status\":{\"type\":\"string\",\"description\":\"OrderStatus\",\"enum\":[\"placed\",\"approved\",\"delivered\"]},\"complete\":{\"type\":\"boolean\"}},\"xml\":{\"name\":\"Order\"}},\"User\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"username\":{\"type\":\"string\"},\"firstName\":{\"type\":\"string\"},\"lastName\":{\"type\":\"string\"},\"email\":{\"type\":\"string\"},\"password\":{\"type\":\"string\"},\"phone\":{\"type\":\"string\"},\"userStatus\":{\"type\":\"integer\",\"format\":\"int32\",\"description\":\"UserStatus\"}},\"xml\":{\"name\":\"User\"}}},\"externalDocs\":{\"description\":\"FindoutmoreaboutSwagger\",\"url\":\"http://swagger.io\"}}"
A:
How about this?
#!/usr/bin/env bash
J=$(curl -k https://petstore.swagger.io/v2/swagger.json)
Q=${J//\"/\\\"} # see pattern substitution in 'man bash'
echo \"$Q\"
A:
Try:
cat whatever.json | jq -R
-R is for --raw-input.
PS: You can get jq by sudo apt-get install jq
|
how to convert json file data to string in bash shell script?
|
how to convert json file data to string in bash shell script?
i have below petstore swagger file (https://petstore.swagger.io/v2/swagger.json)
in json format.
i have converted this json file into string with backspaces characters \ needed for one operation using this site https://jsontostring.com/ .
i have tried jq tool to achieve this, didn't got the result and perhaps it will not come using jq tool.
How can we convert this same petstore swagger json file into string with below expected output in linux or bash shell script ?
{"swagger":"2.0","info":{"description":"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.","version":"1.0.6","title":"Swagger Petstore","termsOfService":"http://swagger.io/terms/","contact":{"email":"[email protected]"},"license":{"name":"Apache 2.0","url":"http://www.apache.org/licenses/LICENSE-2.0.html"}},"host":"petstore.swagger.io","basePath":"/v2","tags":[{"name":"pet","description":"Everything about your Pets","externalDocs":{"description":"Find out more","url":"http://swagger.io"}},{"name":"store","description":"Access to Petstore orders"},{"name":"user","description":"Operations about user","externalDocs":{"description":"Find out more about our store","url":"http://swagger.io"}}],"schemes":["https","http"],"paths":{"/pet/{petId}/uploadImage":{"post":{"tags":["pet"],"summary":"uploads an image","description":"","operationId":"uploadFile","consumes":["multipart/form-data"],"produces":["application/json"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to update","required":true,"type":"integer","format":"int64"},{"name":"additionalMetadata","in":"formData","description":"Additional data to pass to server","required":false,"type":"string"},{"name":"file","in":"formData","description":"file to upload","required":false,"type":"file"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/ApiResponse"}}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet":{"post":{"tags":["pet"],"summary":"Add a new pet to the store","description":"","operationId":"addPet","consumes":["application/json","application/xml"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"schema":{"$ref":"#/definitions/Pet"}}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"put":{"tags":["pet"],"summary":"Update an existing pet","description":"","operationId":"updatePet","consumes":["application/json","application/xml"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Pet object that needs to be added to the store","required":true,"schema":{"$ref":"#/definitions/Pet"}}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"},"405":{"description":"Validation exception"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByStatus":{"get":{"tags":["pet"],"summary":"Finds Pets by status","description":"Multiple status values can be provided with comma separated strings","operationId":"findPetsByStatus","produces":["application/json","application/xml"],"parameters":[{"name":"status","in":"query","description":"Status values that need to be considered for filter","required":true,"type":"array","items":{"type":"string","enum":["available","pending","sold"],"default":"available"},"collectionFormat":"multi"}],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}},"400":{"description":"Invalid status value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/pet/findByTags":{"get":{"tags":["pet"],"summary":"Finds Pets by tags","description":"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.","operationId":"findPetsByTags","produces":["application/json","application/xml"],"parameters":[{"name":"tags","in":"query","description":"Tags to filter by","required":true,"type":"array","items":{"type":"string"},"collectionFormat":"multi"}],"responses":{"200":{"description":"successful operation","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}},"400":{"description":"Invalid tag value"}},"security":[{"petstore_auth":["write:pets","read:pets"]}],"deprecated":true}},"/pet/{petId}":{"get":{"tags":["pet"],"summary":"Find pet by ID","description":"Returns a single pet","operationId":"getPetById","produces":["application/json","application/xml"],"parameters":[{"name":"petId","in":"path","description":"ID of pet to return","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Pet"}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"}},"security":[{"api_key":[]}]},"post":{"tags":["pet"],"summary":"Updates a pet in the store with form data","description":"","operationId":"updatePetWithForm","consumes":["application/x-www-form-urlencoded"],"produces":["application/json","application/xml"],"parameters":[{"name":"petId","in":"path","description":"ID of pet that needs to be updated","required":true,"type":"integer","format":"int64"},{"name":"name","in":"formData","description":"Updated name of the pet","required":false,"type":"string"},{"name":"status","in":"formData","description":"Updated status of the pet","required":false,"type":"string"}],"responses":{"405":{"description":"Invalid input"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]},"delete":{"tags":["pet"],"summary":"Deletes a pet","description":"","operationId":"deletePet","produces":["application/json","application/xml"],"parameters":[{"name":"api_key","in":"header","required":false,"type":"string"},{"name":"petId","in":"path","description":"Pet id to delete","required":true,"type":"integer","format":"int64"}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Pet not found"}},"security":[{"petstore_auth":["write:pets","read:pets"]}]}},"/store/order":{"post":{"tags":["store"],"summary":"Place an order for a pet","description":"","operationId":"placeOrder","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"order placed for purchasing the pet","required":true,"schema":{"$ref":"#/definitions/Order"}}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Order"}},"400":{"description":"Invalid Order"}}}},"/store/order/{orderId}":{"get":{"tags":["store"],"summary":"Find purchase order by ID","description":"For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions","operationId":"getOrderById","produces":["application/json","application/xml"],"parameters":[{"name":"orderId","in":"path","description":"ID of pet that needs to be fetched","required":true,"type":"integer","maximum":10,"minimum":1,"format":"int64"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/Order"}},"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}},"delete":{"tags":["store"],"summary":"Delete purchase order by ID","description":"For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors","operationId":"deleteOrder","produces":["application/json","application/xml"],"parameters":[{"name":"orderId","in":"path","description":"ID of the order that needs to be deleted","required":true,"type":"integer","minimum":1,"format":"int64"}],"responses":{"400":{"description":"Invalid ID supplied"},"404":{"description":"Order not found"}}}},"/store/inventory":{"get":{"tags":["store"],"summary":"Returns pet inventories by status","description":"Returns a map of status codes to quantities","operationId":"getInventory","produces":["application/json"],"parameters":[],"responses":{"200":{"description":"successful operation","schema":{"type":"object","additionalProperties":{"type":"integer","format":"int32"}}}},"security":[{"api_key":[]}]}},"/user/createWithArray":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"","operationId":"createUsersWithArrayInput","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"schema":{"type":"array","items":{"$ref":"#/definitions/User"}}}],"responses":{"default":{"description":"successful operation"}}}},"/user/createWithList":{"post":{"tags":["user"],"summary":"Creates list of users with given input array","description":"","operationId":"createUsersWithListInput","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"List of user object","required":true,"schema":{"type":"array","items":{"$ref":"#/definitions/User"}}}],"responses":{"default":{"description":"successful operation"}}}},"/user/{username}":{"get":{"tags":["user"],"summary":"Get user by user name","description":"","operationId":"getUserByName","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"The name that needs to be fetched. Use user1 for testing. ","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$ref":"#/definitions/User"}},"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}},"put":{"tags":["user"],"summary":"Updated user","description":"This can only be done by the logged in user.","operationId":"updateUser","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"name that need to be updated","required":true,"type":"string"},{"in":"body","name":"body","description":"Updated user object","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"400":{"description":"Invalid user supplied"},"404":{"description":"User not found"}}},"delete":{"tags":["user"],"summary":"Delete user","description":"This can only be done by the logged in user.","operationId":"deleteUser","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"path","description":"The name that needs to be deleted","required":true,"type":"string"}],"responses":{"400":{"description":"Invalid username supplied"},"404":{"description":"User not found"}}}},"/user/login":{"get":{"tags":["user"],"summary":"Logs user into the system","description":"","operationId":"loginUser","produces":["application/json","application/xml"],"parameters":[{"name":"username","in":"query","description":"The user name for login","required":true,"type":"string"},{"name":"password","in":"query","description":"The password for login in clear text","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","headers":{"X-Expires-After":{"type":"string","format":"date-time","description":"date in UTC when token expires"},"X-Rate-Limit":{"type":"integer","format":"int32","description":"calls per hour allowed by the user"}},"schema":{"type":"string"}},"400":{"description":"Invalid username/password supplied"}}}},"/user/logout":{"get":{"tags":["user"],"summary":"Logs out current logged in user session","description":"","operationId":"logoutUser","produces":["application/json","application/xml"],"parameters":[],"responses":{"default":{"description":"successful operation"}}}},"/user":{"post":{"tags":["user"],"summary":"Create user","description":"This can only be done by the logged in user.","operationId":"createUser","consumes":["application/json"],"produces":["application/json","application/xml"],"parameters":[{"in":"body","name":"body","description":"Created user object","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"default":{"description":"successful operation"}}}}},"securityDefinitions":{"api_key":{"type":"apiKey","name":"api_key","in":"header"},"petstore_auth":{"type":"oauth2","authorizationUrl":"https://petstore.swagger.io/oauth/authorize","flow":"implicit","scopes":{"read:pets":"read your pets","write:pets":"modify pets in your account"}}},"definitions":{"ApiResponse":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"type":{"type":"string"},"message":{"type":"string"}}},"Category":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Category"}},"Pet":{"type":"object","required":["name","photoUrls"],"properties":{"id":{"type":"integer","format":"int64"},"category":{"$ref":"#/definitions/Category"},"name":{"type":"string","example":"doggie"},"photoUrls":{"type":"array","xml":{"wrapped":true},"items":{"type":"string","xml":{"name":"photoUrl"}}},"tags":{"type":"array","xml":{"wrapped":true},"items":{"xml":{"name":"tag"},"$ref":"#/definitions/Tag"}},"status":{"type":"string","description":"pet status in the store","enum":["available","pending","sold"]}},"xml":{"name":"Pet"}},"Tag":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}},"xml":{"name":"Tag"}},"Order":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"petId":{"type":"integer","format":"int64"},"quantity":{"type":"integer","format":"int32"},"shipDate":{"type":"string","format":"date-time"},"status":{"type":"string","description":"Order Status","enum":["placed","approved","delivered"]},"complete":{"type":"boolean"}},"xml":{"name":"Order"}},"User":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"username":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string"},"password":{"type":"string"},"phone":{"type":"string"},"userStatus":{"type":"integer","format":"int32","description":"User Status"}},"xml":{"name":"User"}}},"externalDocs":{"description":"Find out more about Swagger","url":"http://swagger.io"}}
expected output;
"{\"swagger\":\"2.0\",\"info\":{\"description\":\"ThisisasampleserverPetstoreserver.YoucanfindoutmoreaboutSwaggerat[http://swagger.io](http://swagger.io)oron[irc.freenode.net,#swagger](http://swagger.io/irc/).Forthissample,youcanusetheapikey`special-key`totesttheauthorizationfilters.\",\"version\":\"1.0.6\",\"title\":\"SwaggerPetstore\",\"termsOfService\":\"http://swagger.io/terms/\",\"contact\":{\"email\":\"[email protected]\"},\"license\":{\"name\":\"Apache2.0\",\"url\":\"http://www.apache.org/licenses/LICENSE-2.0.html\"}},\"host\":\"petstore.swagger.io\",\"basePath\":\"/v2\",\"tags\":[{\"name\":\"pet\",\"description\":\"EverythingaboutyourPets\",\"externalDocs\":{\"description\":\"Findoutmore\",\"url\":\"http://swagger.io\"}},{\"name\":\"store\",\"description\":\"AccesstoPetstoreorders\"},{\"name\":\"user\",\"description\":\"Operationsaboutuser\",\"externalDocs\":{\"description\":\"Findoutmoreaboutourstore\",\"url\":\"http://swagger.io\"}}],\"schemes\":[\"https\",\"http\"],\"paths\":{\"/pet/{petId}/uploadImage\":{\"post\":{\"tags\":[\"pet\"],\"summary\":\"uploadsanimage\",\"description\":\"\",\"operationId\":\"uploadFile\",\"consumes\":[\"multipart/form-data\"],\"produces\":[\"application/json\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpettoupdate\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"},{\"name\":\"additionalMetadata\",\"in\":\"formData\",\"description\":\"Additionaldatatopasstoserver\",\"required\":false,\"type\":\"string\"},{\"name\":\"file\",\"in\":\"formData\",\"description\":\"filetoupload\",\"required\":false,\"type\":\"file\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/ApiResponse\"}}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet\":{\"post\":{\"tags\":[\"pet\"],\"summary\":\"Addanewpettothestore\",\"description\":\"\",\"operationId\":\"addPet\",\"consumes\":[\"application/json\",\"application/xml\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Petobjectthatneedstobeaddedtothestore\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Pet\"}}],\"responses\":{\"405\":{\"description\":\"Invalidinput\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]},\"put\":{\"tags\":[\"pet\"],\"summary\":\"Updateanexistingpet\",\"description\":\"\",\"operationId\":\"updatePet\",\"consumes\":[\"application/json\",\"application/xml\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Petobjectthatneedstobeaddedtothestore\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Pet\"}}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"},\"405\":{\"description\":\"Validationexception\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet/findByStatus\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindsPetsbystatus\",\"description\":\"Multiplestatusvaluescanbeprovidedwithcommaseparatedstrings\",\"operationId\":\"findPetsByStatus\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"status\",\"in\":\"query\",\"description\":\"Statusvaluesthatneedtobeconsideredforfilter\",\"required\":true,\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"available\",\"pending\",\"sold\"],\"default\":\"available\"},\"collectionFormat\":\"multi\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Pet\"}}},\"400\":{\"description\":\"Invalidstatusvalue\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/pet/findByTags\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindsPetsbytags\",\"description\":\"Multipletagscanbeprovidedwithcommaseparatedstrings.Usetag1,tag2,tag3fortesting.\",\"operationId\":\"findPetsByTags\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"tags\",\"in\":\"query\",\"description\":\"Tagstofilterby\",\"required\":true,\"type\":\"array\",\"items\":{\"type\":\"string\"},\"collectionFormat\":\"multi\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Pet\"}}},\"400\":{\"description\":\"Invalidtagvalue\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}],\"deprecated\":true}},\"/pet/{petId}\":{\"get\":{\"tags\":[\"pet\"],\"summary\":\"FindpetbyID\",\"description\":\"Returnsasinglepet\",\"operationId\":\"getPetById\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpettoreturn\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Pet\"}},\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"}},\"security\":[{\"api_key\":[]}]},\"post\":{\"tags\":[\"pet\"],\"summary\":\"Updatesapetinthestorewithformdata\",\"description\":\"\",\"operationId\":\"updatePetWithForm\",\"consumes\":[\"application/x-www-form-urlencoded\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpetthatneedstobeupdated\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"},{\"name\":\"name\",\"in\":\"formData\",\"description\":\"Updatednameofthepet\",\"required\":false,\"type\":\"string\"},{\"name\":\"status\",\"in\":\"formData\",\"description\":\"Updatedstatusofthepet\",\"required\":false,\"type\":\"string\"}],\"responses\":{\"405\":{\"description\":\"Invalidinput\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]},\"delete\":{\"tags\":[\"pet\"],\"summary\":\"Deletesapet\",\"description\":\"\",\"operationId\":\"deletePet\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"api_key\",\"in\":\"header\",\"required\":false,\"type\":\"string\"},{\"name\":\"petId\",\"in\":\"path\",\"description\":\"Petidtodelete\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\"}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Petnotfound\"}},\"security\":[{\"petstore_auth\":[\"write:pets\",\"read:pets\"]}]}},\"/store/order\":{\"post\":{\"tags\":[\"store\"],\"summary\":\"Placeanorderforapet\",\"description\":\"\",\"operationId\":\"placeOrder\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"orderplacedforpurchasingthepet\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/Order\"}}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Order\"}},\"400\":{\"description\":\"InvalidOrder\"}}}},\"/store/order/{orderId}\":{\"get\":{\"tags\":[\"store\"],\"summary\":\"FindpurchaseorderbyID\",\"description\":\"ForvalidresponsetryintegerIDswithvalue>=1and<=10.Othervalueswillgeneratedexceptions\",\"operationId\":\"getOrderById\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"orderId\",\"in\":\"path\",\"description\":\"IDofpetthatneedstobefetched\",\"required\":true,\"type\":\"integer\",\"maximum\":10,\"minimum\":1,\"format\":\"int64\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/Order\"}},\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Ordernotfound\"}}},\"delete\":{\"tags\":[\"store\"],\"summary\":\"DeletepurchaseorderbyID\",\"description\":\"ForvalidresponsetryintegerIDswithpositiveintegervalue.Negativeornon-integervalueswillgenerateAPIerrors\",\"operationId\":\"deleteOrder\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"orderId\",\"in\":\"path\",\"description\":\"IDoftheorderthatneedstobedeleted\",\"required\":true,\"type\":\"integer\",\"minimum\":1,\"format\":\"int64\"}],\"responses\":{\"400\":{\"description\":\"InvalidIDsupplied\"},\"404\":{\"description\":\"Ordernotfound\"}}}},\"/store/inventory\":{\"get\":{\"tags\":[\"store\"],\"summary\":\"Returnspetinventoriesbystatus\",\"description\":\"Returnsamapofstatuscodestoquantities\",\"operationId\":\"getInventory\",\"produces\":[\"application/json\"],\"parameters\":[],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"integer\",\"format\":\"int32\"}}}},\"security\":[{\"api_key\":[]}]}},\"/user/createWithArray\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createslistofuserswithgiveninputarray\",\"description\":\"\",\"operationId\":\"createUsersWithArrayInput\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Listofuserobject\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/User\"}}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user/createWithList\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createslistofuserswithgiveninputarray\",\"description\":\"\",\"operationId\":\"createUsersWithListInput\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Listofuserobject\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/User\"}}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user/{username}\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Getuserbyusername\",\"description\":\"\",\"operationId\":\"getUserByName\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"Thenamethatneedstobefetched.Useuser1fortesting.\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"schema\":{\"$ref\":\"#/definitions/User\"}},\"400\":{\"description\":\"Invalidusernamesupplied\"},\"404\":{\"description\":\"Usernotfound\"}}},\"put\":{\"tags\":[\"user\"],\"summary\":\"Updateduser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"updateUser\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"namethatneedtobeupdated\",\"required\":true,\"type\":\"string\"},{\"in\":\"body\",\"name\":\"body\",\"description\":\"Updateduserobject\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/User\"}}],\"responses\":{\"400\":{\"description\":\"Invalidusersupplied\"},\"404\":{\"description\":\"Usernotfound\"}}},\"delete\":{\"tags\":[\"user\"],\"summary\":\"Deleteuser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"deleteUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"path\",\"description\":\"Thenamethatneedstobedeleted\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"400\":{\"description\":\"Invalidusernamesupplied\"},\"404\":{\"description\":\"Usernotfound\"}}}},\"/user/login\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Logsuserintothesystem\",\"description\":\"\",\"operationId\":\"loginUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"name\":\"username\",\"in\":\"query\",\"description\":\"Theusernameforlogin\",\"required\":true,\"type\":\"string\"},{\"name\":\"password\",\"in\":\"query\",\"description\":\"Thepasswordforloginincleartext\",\"required\":true,\"type\":\"string\"}],\"responses\":{\"200\":{\"description\":\"successfuloperation\",\"headers\":{\"X-Expires-After\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"dateinUTCwhentokenexpires\"},\"X-Rate-Limit\":{\"type\":\"integer\",\"format\":\"int32\",\"description\":\"callsperhourallowedbytheuser\"}},\"schema\":{\"type\":\"string\"}},\"400\":{\"description\":\"Invalidusername/passwordsupplied\"}}}},\"/user/logout\":{\"get\":{\"tags\":[\"user\"],\"summary\":\"Logsoutcurrentloggedinusersession\",\"description\":\"\",\"operationId\":\"logoutUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}},\"/user\":{\"post\":{\"tags\":[\"user\"],\"summary\":\"Createuser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"createUser\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[{\"in\":\"body\",\"name\":\"body\",\"description\":\"Createduserobject\",\"required\":true,\"schema\":{\"$ref\":\"#/definitions/User\"}}],\"responses\":{\"default\":{\"description\":\"successfuloperation\"}}}}},\"securityDefinitions\":{\"api_key\":{\"type\":\"apiKey\",\"name\":\"api_key\",\"in\":\"header\"},\"petstore_auth\":{\"type\":\"oauth2\",\"authorizationUrl\":\"https://petstore.swagger.io/oauth/authorize\",\"flow\":\"implicit\",\"scopes\":{\"read:pets\":\"readyourpets\",\"write:pets\":\"modifypetsinyouraccount\"}}},\"definitions\":{\"ApiResponse\":{\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"integer\",\"format\":\"int32\"},\"type\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}}},\"Category\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"name\":{\"type\":\"string\"}},\"xml\":{\"name\":\"Category\"}},\"Pet\":{\"type\":\"object\",\"required\":[\"name\",\"photoUrls\"],\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"category\":{\"$ref\":\"#/definitions/Category\"},\"name\":{\"type\":\"string\",\"example\":\"doggie\"},\"photoUrls\":{\"type\":\"array\",\"xml\":{\"wrapped\":true},\"items\":{\"type\":\"string\",\"xml\":{\"name\":\"photoUrl\"}}},\"tags\":{\"type\":\"array\",\"xml\":{\"wrapped\":true},\"items\":{\"xml\":{\"name\":\"tag\"},\"$ref\":\"#/definitions/Tag\"}},\"status\":{\"type\":\"string\",\"description\":\"petstatusinthestore\",\"enum\":[\"available\",\"pending\",\"sold\"]}},\"xml\":{\"name\":\"Pet\"}},\"Tag\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"name\":{\"type\":\"string\"}},\"xml\":{\"name\":\"Tag\"}},\"Order\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"petId\":{\"type\":\"integer\",\"format\":\"int64\"},\"quantity\":{\"type\":\"integer\",\"format\":\"int32\"},\"shipDate\":{\"type\":\"string\",\"format\":\"date-time\"},\"status\":{\"type\":\"string\",\"description\":\"OrderStatus\",\"enum\":[\"placed\",\"approved\",\"delivered\"]},\"complete\":{\"type\":\"boolean\"}},\"xml\":{\"name\":\"Order\"}},\"User\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"format\":\"int64\"},\"username\":{\"type\":\"string\"},\"firstName\":{\"type\":\"string\"},\"lastName\":{\"type\":\"string\"},\"email\":{\"type\":\"string\"},\"password\":{\"type\":\"string\"},\"phone\":{\"type\":\"string\"},\"userStatus\":{\"type\":\"integer\",\"format\":\"int32\",\"description\":\"UserStatus\"}},\"xml\":{\"name\":\"User\"}}},\"externalDocs\":{\"description\":\"FindoutmoreaboutSwagger\",\"url\":\"http://swagger.io\"}}"
|
[
"How about this?\n#!/usr/bin/env bash\n\nJ=$(curl -k https://petstore.swagger.io/v2/swagger.json)\nQ=${J//\\\"/\\\\\\\"} # see pattern substitution in 'man bash'\necho \\\"$Q\\\"\n\n",
"Try:\ncat whatever.json | jq -R\n-R is for --raw-input.\nPS: You can get jq by sudo apt-get install jq\n"
] |
[
0,
0
] |
[] |
[] |
[
"bash",
"json",
"linux"
] |
stackoverflow_0074666678_bash_json_linux.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.