id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
146a6e30484c7985aece21cedf4b9088635a061b
Stackoverflow Stackexchange Q: How to unhide filtered messages in Chrome developer Tools on a MAC I am in the developer view in Chrome ⌘ + shift+c. Under the console tab, it shows this message 7 items hidden by filters But the issue is I have no filters set. I tried right clicking and selecting 'Filter' but the unhide all is greyed out. And tried reseting the developer console.But it didnt work, how do i fix this ? A: Had the same issue and resolved now following the below steps. * *Right click in the browser and select Inspect *Go to Console *Click on the button shown in the screenshot and select Default from the dropdown menu.
Q: How to unhide filtered messages in Chrome developer Tools on a MAC I am in the developer view in Chrome ⌘ + shift+c. Under the console tab, it shows this message 7 items hidden by filters But the issue is I have no filters set. I tried right clicking and selecting 'Filter' but the unhide all is greyed out. And tried reseting the developer console.But it didnt work, how do i fix this ? A: Had the same issue and resolved now following the below steps. * *Right click in the browser and select Inspect *Go to Console *Click on the button shown in the screenshot and select Default from the dropdown menu. A: Onl following worked for me. Press Ctrl + Shift + P inside dev window type 'settings' in search field and open it click 'restore defaults and reload' in lower right corner A: All you need to do is to select either "Info" or "Verbase" option next to filter field to see the console log. A: For those for whom none of the mentioned solutions helped out, you can try following: While Console is opened press Ctrl+Shift+P and then a little window will pop up where you can run commands. One that concerns us is: Console Show messages from all contexts A: Right click on console area, Filter -> Unhide All, in filter option you will see all filters. Screenshot A: Check for a small input box above the console, You may have set a entered some text once as a filter and forgot to clear it. A: in your chrome console, click default levels -> enable/check all values refresh your page .. now it wont filter anything if you checked all... A: I had the same issue the other day. Go to the console in your dev tools and right click on an error message. Hover over 'filter' option, then select unhide all. console > right click error message > filter > unhide all A: You must close the "console sidebar" to enable the log level filter. DevTools has this sidebar closed by default, which is why "Restore to defaults" also works. A: I had same problem but selecting "info" or "verbose" didn´t unhide errors, what was hidding them for me was, "Hide network" inside console settings, was checked, so i just unchecked and no "items hidden by filters" showing anymore. A: There seems to be a bug in chrome, when adding filters via the rightclick context menu: Filter > Hide Messages from ... The only thing that worked for me, was to reset the entire debugger settings Settings (F1 on Windows) > DevTools > Restore defaults and reload A: You need to click on the circled X in the filter area, or focus the filter area and delete the text typed there. A: What really worked for me was to click on the settings button, right top of the console window, and unselect "Hide Network" and "Selected context only" My settings became like that:
stackoverflow
{ "language": "en", "length": 500, "provenance": "stackexchange_0000F.jsonl.gz:890557", "question_score": "120", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622318" }
933d8e900608bc6dda92266f5e1e7170fd5bb098
Stackoverflow Stackexchange Q: Function parameter to use interface's function signature I have a function signature in an interface which I'd like to use as the signature for a callback parameter in some class. export interface IGrid { gridFormat(gridCell: GridCell, grid: Grid): boolean } I'd like to do something like this: validateFormat(validator: IGrid.gridFormat) { // ... } Is this possible? A: Is this possible? Yes as shown below: export interface IGrid { gridFormat(gridCell: GridCell, grid: Grid): boolean } function validateFormat(validator: IGrid['gridFormat']) { // MAGIC // ... }
Q: Function parameter to use interface's function signature I have a function signature in an interface which I'd like to use as the signature for a callback parameter in some class. export interface IGrid { gridFormat(gridCell: GridCell, grid: Grid): boolean } I'd like to do something like this: validateFormat(validator: IGrid.gridFormat) { // ... } Is this possible? A: Is this possible? Yes as shown below: export interface IGrid { gridFormat(gridCell: GridCell, grid: Grid): boolean } function validateFormat(validator: IGrid['gridFormat']) { // MAGIC // ... } A: You may try something like the following: export interface IGrid { gridFormat(gridCell: GridCell, grid: Grid): boolean } declare let igrid: IGrid; export class Test { validateFormat(validator: typeof igrid.gridFormat) { // ... } } Additionally, you may also declare a type for the method like below declare type gridFormatMethodType = typeof igrid.gridFormat to avoid the cumbersome method signature for validateFormat validateFormat(validator: gridFormatMethodType){ ... } Hope this helps.
stackoverflow
{ "language": "en", "length": 151, "provenance": "stackexchange_0000F.jsonl.gz:890582", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622399" }
618141538079b5a156b919ddb0159994789cb65e
Stackoverflow Stackexchange Q: Object comprehension in javascript const obj = {} arr.map((e) => { obj[e.title] = e.someBool }) Is there a shorter way of doing the above in Javascript?
Q: Object comprehension in javascript const obj = {} arr.map((e) => { obj[e.title] = e.someBool }) Is there a shorter way of doing the above in Javascript?
stackoverflow
{ "language": "en", "length": 27, "provenance": "stackexchange_0000F.jsonl.gz:890615", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622481" }
18b9b08b25eadd744692176f58849f68e823309b
Stackoverflow Stackexchange Q: Youtube live streaming broadcast in android Im trying to develop an android application for youtube live streaming broadcast. Is it possible to stream live video from Android app to Youtube live channel on Youtube?. but i didn't get any link for broadcast live streaming. is there any way to implement? im looking for simple solution to do that. Thanks in advance A: https://github.com/pedroSG94/rtmp-rtsp-stream-client-java If you create the live event in your youtube dashboard(you can also create it using https://github.com/youtube/yt-watchme ), you can get the stream key for the broadcast. Using that stream key, you can directly broadcast video from the android app. Please have a look at the above github project. Answering the older question but it may be useful for someone.
Q: Youtube live streaming broadcast in android Im trying to develop an android application for youtube live streaming broadcast. Is it possible to stream live video from Android app to Youtube live channel on Youtube?. but i didn't get any link for broadcast live streaming. is there any way to implement? im looking for simple solution to do that. Thanks in advance A: https://github.com/pedroSG94/rtmp-rtsp-stream-client-java If you create the live event in your youtube dashboard(you can also create it using https://github.com/youtube/yt-watchme ), you can get the stream key for the broadcast. Using that stream key, you can directly broadcast video from the android app. Please have a look at the above github project. Answering the older question but it may be useful for someone.
stackoverflow
{ "language": "en", "length": 123, "provenance": "stackexchange_0000F.jsonl.gz:890628", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622525" }
84a692b5c5a8a14b4085a138a06a0321f2cb7983
Stackoverflow Stackexchange Q: ElasticSearch Delete by query not working in PHP I am using Elastic search 5.x and the following code is working fine: curl -XPOST "http://localhost:9200/test_index/test_info/_delete_by_query" -d' { "query": { "match": { "category_id": "21" } } }' But when I am trying the same in my php code, its not working: $client->deleteByQuery([ 'index' => 'test_index', 'type' => 'test_info', 'query' => [ 'match' => [ ['category_id' => 21] ] ] ]); A: You need to provide your query array inside body array of your parameters: $client->deleteByQuery([ 'index' => 'test_index', 'type' => 'test_info', 'body' => [ 'query' => [ 'match' => [ ['category_id' => 21] ] ] ] ]);
Q: ElasticSearch Delete by query not working in PHP I am using Elastic search 5.x and the following code is working fine: curl -XPOST "http://localhost:9200/test_index/test_info/_delete_by_query" -d' { "query": { "match": { "category_id": "21" } } }' But when I am trying the same in my php code, its not working: $client->deleteByQuery([ 'index' => 'test_index', 'type' => 'test_info', 'query' => [ 'match' => [ ['category_id' => 21] ] ] ]); A: You need to provide your query array inside body array of your parameters: $client->deleteByQuery([ 'index' => 'test_index', 'type' => 'test_info', 'body' => [ 'query' => [ 'match' => [ ['category_id' => 21] ] ] ] ]); A: this an old question, previous comments don't work anymore in 2020 : $client->deleteByQuery([ 'index' => 'test_index', (there were a type here) 'type' => 'test_info', 'body' => [ 'query' => [ 'match' => [ (there were an array here) ['category_id' => 21] ] ] ] ]); So the final code is : $client->deleteByQuery([ 'index' => 'test_index', 'body' => [ 'query' => [ 'match' => [ 'category_id' => 21 ] ] ]
stackoverflow
{ "language": "en", "length": 177, "provenance": "stackexchange_0000F.jsonl.gz:890658", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622618" }
e07b247b6623a714abbf430388815fe44a95fb56
Stackoverflow Stackexchange Q: How to Record Video from Background Service using Camera2 API? I am trying to record video from a Background Service without showing any preview. It is like this example but trying to do it with Camera2 API. I am trying to follow along with the android-Camera2Video sample code and trying to use that in the service. Which parts should I cut out / ignore - is it the part TexttureViewer part where it is previewed? I dont want to preview anything I just want to record it.
Q: How to Record Video from Background Service using Camera2 API? I am trying to record video from a Background Service without showing any preview. It is like this example but trying to do it with Camera2 API. I am trying to follow along with the android-Camera2Video sample code and trying to use that in the service. Which parts should I cut out / ignore - is it the part TexttureViewer part where it is previewed? I dont want to preview anything I just want to record it.
stackoverflow
{ "language": "en", "length": 88, "provenance": "stackexchange_0000F.jsonl.gz:890669", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622652" }
5cbd9edc45cdb5f48e7b1bcf94259efe039e53fd
Stackoverflow Stackexchange Q: How to call an API on left scroll and call another API on right scroll using Flat List (horizontal) in React Native? I have implemented Flat List (Horizontal) in React Native. I have used onEndReached and onEndReachedThreshold to call an API. So when I scroll right a API gets called, but am not able to scroll left and call a different API on that, as my initial page number is '0' so won't be able to do left scroll. So basically I need to set a page number for example as '3' so that i can scroll to left as well as right. And then my concern is how would I know that left scroll has been triggered or right to call different API's on both. The things which I have implemented right now for right scroll is as below : render() { return ( <FlatList horizontal pagingEnabled data={this.state.data} renderItem={({ item }) => ( <View> <Text> Details </Text> <ScrollView> <ListItem title={item.name.first} subtitle={item.email} /> <ListItem title={item.name.last} subtitle={item.email} /> <ListItem title={item.address} subtitle={item.email} /> </ScrollView> </View> )} keyExtractor={item => item.email} onRefresh={this.handleRefresh} refreshing={this.state.refreshing} onEndReached={this.handleRightLoadMore} onEndReachedThreshold={10} /> ); }
Q: How to call an API on left scroll and call another API on right scroll using Flat List (horizontal) in React Native? I have implemented Flat List (Horizontal) in React Native. I have used onEndReached and onEndReachedThreshold to call an API. So when I scroll right a API gets called, but am not able to scroll left and call a different API on that, as my initial page number is '0' so won't be able to do left scroll. So basically I need to set a page number for example as '3' so that i can scroll to left as well as right. And then my concern is how would I know that left scroll has been triggered or right to call different API's on both. The things which I have implemented right now for right scroll is as below : render() { return ( <FlatList horizontal pagingEnabled data={this.state.data} renderItem={({ item }) => ( <View> <Text> Details </Text> <ScrollView> <ListItem title={item.name.first} subtitle={item.email} /> <ListItem title={item.name.last} subtitle={item.email} /> <ListItem title={item.address} subtitle={item.email} /> </ScrollView> </View> )} keyExtractor={item => item.email} onRefresh={this.handleRefresh} refreshing={this.state.refreshing} onEndReached={this.handleRightLoadMore} onEndReachedThreshold={10} /> ); }
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:890713", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622811" }
ce80aecfd8865de5d77e52dae52e7300371006a5
Stackoverflow Stackexchange Q: Why am I getting "error: implicit declaration of function ‘fileno’" when I try to compile on Linux but not on a Mac As the title states, I am getting the following error: "implicit declaration of function ‘fileno’" when I try to compile on Linux but not on a Mac. I know I can fix it with the simple line int fileno(FILE *stream);, but I want to know why this happening. A: You should not declare functions provided by a system library. You should properly include an appropriate header. Since fileno is not a standard C function, it is not normally declared by in <stdio.h> . You have to define a suitable macro in order to enable the declaration. man fileno Requirements for glibc (see feature_test_macros(7)): fileno(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE Defining any of the the three macros before inclusion of should do the trick.
Q: Why am I getting "error: implicit declaration of function ‘fileno’" when I try to compile on Linux but not on a Mac As the title states, I am getting the following error: "implicit declaration of function ‘fileno’" when I try to compile on Linux but not on a Mac. I know I can fix it with the simple line int fileno(FILE *stream);, but I want to know why this happening. A: You should not declare functions provided by a system library. You should properly include an appropriate header. Since fileno is not a standard C function, it is not normally declared by in <stdio.h> . You have to define a suitable macro in order to enable the declaration. man fileno Requirements for glibc (see feature_test_macros(7)): fileno(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE Defining any of the the three macros before inclusion of should do the trick. A: If you remembered to include <stdio.h>, this warning indicates that your <stdio.h> does not declare this function. fileno is not a standard function. It is perfectly expected that some implementations do not provide it, especially if you are compiling in strict standard-compliant mode. If your code still links successfully, this almost certainly means that your Linux compiler settings direct your compiler to work in "strict" mode and thus force <stdio.h> to "hide" declaration of fileno. A: I wrote a simple program in my Ubuntu 16.04 machine. And it compiles well. #include <stdio.h> int main () { printf ("%d\n", fileno(stdout)); return 0; } I hope you know that fileno is present in <stdio.h>. If you have not included the header file, please do so and re-compile. I am not so sure why Mac version works. EDIT: I have not used C99 standard. I compiled using: gcc -Wall -Werror test.c
stackoverflow
{ "language": "en", "length": 297, "provenance": "stackexchange_0000F.jsonl.gz:890719", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622827" }
ad5db6fbe194b19785de5c8491d9ade94bd73b65
Stackoverflow Stackexchange Q: Getting a date x days back from a custom date in Scala I have a date key of type 20170501 which is in YYYYmmdd format. How can we get a date x days back from this date in Scala? This is what I have in program val runDate = 20170501 Now I want a date say 30 days back from this date. A: Using Scala/JVM/Java 8... scala> import java.time._ import java.time._ scala> import java.time.format._ import java.time.format._ scala> val formatter = DateTimeFormatter.ofPattern("yyyyMMdd") formatter: java.time.format.DateTimeFormatter = Value(YearOfEra,4,19,EXCEEDS_PAD)Value(MonthOfYear,2)Value(DayOfMonth,2) scala> val runDate = 20170501 runDate: Int = 20170501 scala> val runDay = LocalDate.parse(runDate.toString, formatter) runDay: java.time.LocalDate = 2017-05-01 scala> val runDayMinus30 = runDay.minusDays(30) runDayMinus30: java.time.LocalDate = 2017-04-01
Q: Getting a date x days back from a custom date in Scala I have a date key of type 20170501 which is in YYYYmmdd format. How can we get a date x days back from this date in Scala? This is what I have in program val runDate = 20170501 Now I want a date say 30 days back from this date. A: Using Scala/JVM/Java 8... scala> import java.time._ import java.time._ scala> import java.time.format._ import java.time.format._ scala> val formatter = DateTimeFormatter.ofPattern("yyyyMMdd") formatter: java.time.format.DateTimeFormatter = Value(YearOfEra,4,19,EXCEEDS_PAD)Value(MonthOfYear,2)Value(DayOfMonth,2) scala> val runDate = 20170501 runDate: Int = 20170501 scala> val runDay = LocalDate.parse(runDate.toString, formatter) runDay: java.time.LocalDate = 2017-05-01 scala> val runDayMinus30 = runDay.minusDays(30) runDayMinus30: java.time.LocalDate = 2017-04-01 A: You can also use joda-time API with which has really good functions like date.minusMonths date.minusYear date.minusDays date.minusHours date.minusMinutes Here is simple example usinf JodaTIme API ' import org.joda.time.format.DateTimeFormat val dtf = DateTimeFormat.forPattern("yyyyMMdd") val dt= "20170531" val date = dtf.parseDateTime(dt) println(date.minusDays(30)) Output: 2017-05-01T00:00:00.000+05:45 For this you need to use udf and create a DateTime object with your input format "YYYYmmdd" and do the operations. Hope this helps!
stackoverflow
{ "language": "en", "length": 181, "provenance": "stackexchange_0000F.jsonl.gz:890732", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622849" }
817e8b126d1eb99e505e3621538cfc847f30c22c
Stackoverflow Stackexchange Q: move 'tmp' directory not working when uploading image in laravel 5.4 When uploading my image it is saved to D:\xampp\tmp\phpD0E0.tmp directory. But I want to save it in public/uploads/banner. Anyone please help me. Here is my code: BannersController.php public function store(Request $request) { $requestData = $request->all(); if ($request->hasFile('banner_image')) { foreach($request['banner_image'] as $file){ $uploadPath = public_path('/uploads/banner'); $extension = $file->getClientOriginalExtension(); $fileName = rand(11111, 99999) . '.' . $extension; $file->move($uploadPath, $fileName); $requestData['banner_image'] = $fileName; } } Banner::create($requestData); Session::flash('flash_message', 'Banner added!'); return redirect('Banner/banners'); } A: Can you please revert that path to 'root' => storage_path('app/public') and just try with change line: $extension = $file->getClientOriginalExtension(); $fileName = rand(11111, 99999) . '.' . $extension; with this: $fileName = rand(11111, 99999) . '.' . $file->getClientOriginalName(); Hope this helps you.
Q: move 'tmp' directory not working when uploading image in laravel 5.4 When uploading my image it is saved to D:\xampp\tmp\phpD0E0.tmp directory. But I want to save it in public/uploads/banner. Anyone please help me. Here is my code: BannersController.php public function store(Request $request) { $requestData = $request->all(); if ($request->hasFile('banner_image')) { foreach($request['banner_image'] as $file){ $uploadPath = public_path('/uploads/banner'); $extension = $file->getClientOriginalExtension(); $fileName = rand(11111, 99999) . '.' . $extension; $file->move($uploadPath, $fileName); $requestData['banner_image'] = $fileName; } } Banner::create($requestData); Session::flash('flash_message', 'Banner added!'); return redirect('Banner/banners'); } A: Can you please revert that path to 'root' => storage_path('app/public') and just try with change line: $extension = $file->getClientOriginalExtension(); $fileName = rand(11111, 99999) . '.' . $extension; with this: $fileName = rand(11111, 99999) . '.' . $file->getClientOriginalName(); Hope this helps you.
stackoverflow
{ "language": "en", "length": 123, "provenance": "stackexchange_0000F.jsonl.gz:890736", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622863" }
914030aa4ca59c16906835451176310859b1c1a5
Stackoverflow Stackexchange Q: DocumentBuilderFactory doesn't have setFeature in JDK 1.8.0_121? While parsing the XML files my documentbuilder was looking for the DTD and sometimes it use to throw error (server crashes). So when I googled I got the following solution from here Ignoring the DTD while parsing XML (the solution which I used is with VOTE---90). Letter in my IDE show the following error. The method setFeature(String, boolean) is undefined for the type DocumentBuilderFactory Then I thought its the problem with my maven version then I found the following link. What is the jar file I should download and from where? Which says its inbuilt in JDK so that the IDE itself will suggest me the imports. My JDK version is java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) The code in class from jar file A: The answer to the following questing fixed this for me. Node.getTextContent() is undefined in Node Basically, you need to move JRE library to the top of your dependencies in eclipse.
Q: DocumentBuilderFactory doesn't have setFeature in JDK 1.8.0_121? While parsing the XML files my documentbuilder was looking for the DTD and sometimes it use to throw error (server crashes). So when I googled I got the following solution from here Ignoring the DTD while parsing XML (the solution which I used is with VOTE---90). Letter in my IDE show the following error. The method setFeature(String, boolean) is undefined for the type DocumentBuilderFactory Then I thought its the problem with my maven version then I found the following link. What is the jar file I should download and from where? Which says its inbuilt in JDK so that the IDE itself will suggest me the imports. My JDK version is java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) The code in class from jar file A: The answer to the following questing fixed this for me. Node.getTextContent() is undefined in Node Basically, you need to move JRE library to the top of your dependencies in eclipse.
stackoverflow
{ "language": "en", "length": 175, "provenance": "stackexchange_0000F.jsonl.gz:890766", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622975" }
d044685812b9d4a65fed008f5906bde59f7d660b
Stackoverflow Stackexchange Q: List all the mondays of this month I'm pretty new to bash and all the terminal in general - I've been messing around with cal and the date scripts wondering if there is anyway to list all the dates of monday of the current month . My thought process is going thru the cal command, listing out the dates and maybe cutting a column from that input. Is that possible ? A: You can do it with date command. Print 10 mondays since month ago: for x in $(seq 0 9) do date -d "$x monday 5 week ago" done And grep only current month. Full command: for x in $(seq 0 9); do; date -d "$x monday 5 week ago"; done | grep $(date +%b) Output: Mon Jun 5 00:00:00 MSK 2017 Mon Jun 12 00:00:00 MSK 2017 Mon Jun 19 00:00:00 MSK 2017 Mon Jun 26 00:00:00 MSK 2017
Q: List all the mondays of this month I'm pretty new to bash and all the terminal in general - I've been messing around with cal and the date scripts wondering if there is anyway to list all the dates of monday of the current month . My thought process is going thru the cal command, listing out the dates and maybe cutting a column from that input. Is that possible ? A: You can do it with date command. Print 10 mondays since month ago: for x in $(seq 0 9) do date -d "$x monday 5 week ago" done And grep only current month. Full command: for x in $(seq 0 9); do; date -d "$x monday 5 week ago"; done | grep $(date +%b) Output: Mon Jun 5 00:00:00 MSK 2017 Mon Jun 12 00:00:00 MSK 2017 Mon Jun 19 00:00:00 MSK 2017 Mon Jun 26 00:00:00 MSK 2017 A: Given: $ cal June 2017 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 You can do: $ cal | awk 'NF>5{print $2}' Mo 5 12 19 26 If you want something that will support any day of cal, use the field width (gawk only this): $ cal | gawk -v n=5 ' BEGIN{ FIELDWIDTHS = "3 3 3 3 3 3 3" } FNR>1{print $n}' Th 1 8 15 22 29 Or, as pointed out in comments: $ ncal | awk '/^Mo/' Mo 5 12 19 26 A: Combination of cal,cut commands to achieve the output. cal -h| cut -c'4,5' Remove the highlight and cut the characters which suits in the fields of monday. ncal | sed -n '/^Mo/p' The output as below: Mo 5 12 19 26
stackoverflow
{ "language": "en", "length": 310, "provenance": "stackexchange_0000F.jsonl.gz:890769", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44622980" }
8725c4f3ebec2b062ed72951e81a65afd523411c
Stackoverflow Stackexchange Q: how to populate chart in WebApi in .net core? I am creating .net core web Api application. i need to generate chart like bar,pie,etc using any chart library and save the chart as .jpg file.if any possible to do webapi in .netcore. A: You can use Highcharts, which is a new Rich javascript based chart library. With the use of high charts, you can create the interactive charts as per your requirement. Highcharts with .Net
Q: how to populate chart in WebApi in .net core? I am creating .net core web Api application. i need to generate chart like bar,pie,etc using any chart library and save the chart as .jpg file.if any possible to do webapi in .netcore. A: You can use Highcharts, which is a new Rich javascript based chart library. With the use of high charts, you can create the interactive charts as per your requirement. Highcharts with .Net
stackoverflow
{ "language": "en", "length": 76, "provenance": "stackexchange_0000F.jsonl.gz:890780", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623022" }
df3d60401c5fc8b56c2c71283fc6c7a1375e60ed
Stackoverflow Stackexchange Q: React Native: How can you prevent the delaying of network requests when android app is in background? When attempting to use fetch or websockets to send data when the app is in the background, react native is delaying the requests until the app comes back into the foreground. Does anyone know of a way to send immediately?
Q: React Native: How can you prevent the delaying of network requests when android app is in background? When attempting to use fetch or websockets to send data when the app is in the background, react native is delaying the requests until the app comes back into the foreground. Does anyone know of a way to send immediately?
stackoverflow
{ "language": "en", "length": 58, "provenance": "stackexchange_0000F.jsonl.gz:890829", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623174" }
58394370a4e09f873f41735bf7e2a556fc1669aa
Stackoverflow Stackexchange Q: angular4 how to call a function in a external js I have a jscript which displays a log to the console: x.js contains function open() { console.log('this a function'); } in index.html of my app <script src="x.js"></script> in my component declare var xJS : any;; @Component({ selector: 'employerfile', templateUrl: './employerfile.component.html' }) export class EmployerFileComponent ..... openURL() { xJS.open(); } } in html <a (click)="openURL()"> click </a> When I execute this code, I get an exception@ Original exception: xJS is not defined How can I call this external function? A: Importing your file like this <script src="x.js"></script> will not work. You have to import it in the following way: import * as xJS from './x.js'; If it will not work, the alternative way is to use System.import: declare var System: any; System.import('./x.js') .then(xJS => { xJS.open(); }); You can check the following SO post.
Q: angular4 how to call a function in a external js I have a jscript which displays a log to the console: x.js contains function open() { console.log('this a function'); } in index.html of my app <script src="x.js"></script> in my component declare var xJS : any;; @Component({ selector: 'employerfile', templateUrl: './employerfile.component.html' }) export class EmployerFileComponent ..... openURL() { xJS.open(); } } in html <a (click)="openURL()"> click </a> When I execute this code, I get an exception@ Original exception: xJS is not defined How can I call this external function? A: Importing your file like this <script src="x.js"></script> will not work. You have to import it in the following way: import * as xJS from './x.js'; If it will not work, the alternative way is to use System.import: declare var System: any; System.import('./x.js') .then(xJS => { xJS.open(); }); You can check the following SO post. A: You have to declare the name of the function you want to use in your angular component, as- declare var open: any; This basically tells the compiler that open exists somewhere, which will be then found in your js file. Also, to use the above method in your component, you will have to use this syntax- anyCustomMethodName/anyLifeCycleMethod() { new open(); } A: You should first import it like this: import * as xJS from 'xJS'; A: If your x.js file is not on your local machine or hosted on CDN or it is third-party library then you can't import it in above ways. Even System.import is deprecated. You can add your js file into index.html and call its functions using window global object as we do earlier.
stackoverflow
{ "language": "en", "length": 272, "provenance": "stackexchange_0000F.jsonl.gz:890885", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623348" }
4e09fef6b9558623303ad2cccc37dbb29b89c67b
Stackoverflow Stackexchange Q: npm execution stopped on windows I have a script to run mocha test cases defined in package.json as below: ... 'test': mocha tests/integration/ --opts mocha.opts -t 20000 ... the test will be running about 10 minutes. This script works fine in Mac and Linux but not in Windows10. When executing on windows10, the test cases are executing but after a few minutes the process gets stopped with below error messages: npm ERR! Windows_NT 10.0.15063 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "test:integration:win" npm ERR! node v7.10.0 npm ERR! npm v4.2.0 npm ERR! code ELIFECYCLE npm ERR! errno 3221225725 npm ERR! mycontroller@0.1.4 test:integration:win: `mocha tests/integration/ --opts mocha.opts -t 20000` npm ERR! Exit status 3221225725 npm ERR! This message has nothing to do with the test cases themselves. I believe they are related with environment. Does anyone know anything about this issue? This is a nodejs backend application.
Q: npm execution stopped on windows I have a script to run mocha test cases defined in package.json as below: ... 'test': mocha tests/integration/ --opts mocha.opts -t 20000 ... the test will be running about 10 minutes. This script works fine in Mac and Linux but not in Windows10. When executing on windows10, the test cases are executing but after a few minutes the process gets stopped with below error messages: npm ERR! Windows_NT 10.0.15063 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "test:integration:win" npm ERR! node v7.10.0 npm ERR! npm v4.2.0 npm ERR! code ELIFECYCLE npm ERR! errno 3221225725 npm ERR! mycontroller@0.1.4 test:integration:win: `mocha tests/integration/ --opts mocha.opts -t 20000` npm ERR! Exit status 3221225725 npm ERR! This message has nothing to do with the test cases themselves. I believe they are related with environment. Does anyone know anything about this issue? This is a nodejs backend application.
stackoverflow
{ "language": "en", "length": 148, "provenance": "stackexchange_0000F.jsonl.gz:890889", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623359" }
0b3f2872a841f8b145bb545fbddc05a5539d67c3
Stackoverflow Stackexchange Q: Is it possible to replace Android N's ART with Android M's? In AOSP 7 source tree, Is it be possible to use Android 6's art/ instead of the original Android 7's art/? I don't ever recall having seen such replacements before, but out of curisity is it possible? You may ask me why? The answer is all about xposed. Xposed doesn't currently support Android N yet, but works pretty good on M. So, my question would be: Is replacing N's ART with M's ART an option to enable Xposed on N? If the answer is no, please let me know the why. If this question is off-topic here, kindly tell me to move it to the SO's sister android.SX. A: I think it's not possible. Nougat internals are different than Marshmallow ones, so you can't simply get some system component from older Android and replace it.
Q: Is it possible to replace Android N's ART with Android M's? In AOSP 7 source tree, Is it be possible to use Android 6's art/ instead of the original Android 7's art/? I don't ever recall having seen such replacements before, but out of curisity is it possible? You may ask me why? The answer is all about xposed. Xposed doesn't currently support Android N yet, but works pretty good on M. So, my question would be: Is replacing N's ART with M's ART an option to enable Xposed on N? If the answer is no, please let me know the why. If this question is off-topic here, kindly tell me to move it to the SO's sister android.SX. A: I think it's not possible. Nougat internals are different than Marshmallow ones, so you can't simply get some system component from older Android and replace it.
stackoverflow
{ "language": "en", "length": 147, "provenance": "stackexchange_0000F.jsonl.gz:890901", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623401" }
db2b7842bfb38df9e88b2c3520d68ada355a184d
Stackoverflow Stackexchange Q: How do I test my Firebase Web app? I have a web app using Firebase Web (client Javascript SDK). How do I test Auth, Realtime Database triggers, including firebase.auth().onAuthStateChanged, firebase.database().ref(...).on and etc. I tried to use mockfirebase but it is not triggering onAuthStateChanged. A: The best way to do this is to create two (or multiple if required) firebase projects and use one for testing. This is also supported by firebase cli using "Deploy Targets". You can deploy to different firebase projects from the single firebase.json config file in your source control. For more information check this: https://firebase.google.com/docs/cli/targets
Q: How do I test my Firebase Web app? I have a web app using Firebase Web (client Javascript SDK). How do I test Auth, Realtime Database triggers, including firebase.auth().onAuthStateChanged, firebase.database().ref(...).on and etc. I tried to use mockfirebase but it is not triggering onAuthStateChanged. A: The best way to do this is to create two (or multiple if required) firebase projects and use one for testing. This is also supported by firebase cli using "Deploy Targets". You can deploy to different firebase projects from the single firebase.json config file in your source control. For more information check this: https://firebase.google.com/docs/cli/targets
stackoverflow
{ "language": "en", "length": 99, "provenance": "stackexchange_0000F.jsonl.gz:890927", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623502" }
f256005b3cf0b21a2399278915f95b62095d772e
Stackoverflow Stackexchange Q: What will happen to my postgres database, if I downgrade my PostgreSQL? I am using postgres 9.5. Suppose my system postgres got downgraded into 9.2. Will my old database works with newly installed postgres as it is?(backword compatibility) Or do I have to do some manual operations? In other words, say I have a postgres database works with the latest version. Can I use the same database in other systems which run other supported versions of postgres (but not the latest)? A: There is no supported way to downgrade PostgreSQL to a lower major release. You will have to pg_dumpall with 9.5 and then try to install the dump in 9.2. There will be error messages if the 9.5 dump uses features that were not present in 9.2 yet. In that case, edit the dump and fix it for 9.2.
Q: What will happen to my postgres database, if I downgrade my PostgreSQL? I am using postgres 9.5. Suppose my system postgres got downgraded into 9.2. Will my old database works with newly installed postgres as it is?(backword compatibility) Or do I have to do some manual operations? In other words, say I have a postgres database works with the latest version. Can I use the same database in other systems which run other supported versions of postgres (but not the latest)? A: There is no supported way to downgrade PostgreSQL to a lower major release. You will have to pg_dumpall with 9.5 and then try to install the dump in 9.2. There will be error messages if the 9.5 dump uses features that were not present in 9.2 yet. In that case, edit the dump and fix it for 9.2. A: Between major releases of postgresql, you will have to export your tables and database structure to older postgres version via pg_dump and pg_dumpall utilities. Then use the older version. This is the safest way. If downgrading is done between minor releases, then just replacing the executables when the server is down and restarting the server will be sufficient, as the data directory remains unchanged between minor releases.
stackoverflow
{ "language": "en", "length": 209, "provenance": "stackexchange_0000F.jsonl.gz:890931", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623507" }
10faf4cb498e2c0b661c20b0352487ce6a919988
Stackoverflow Stackexchange Q: Angular 2 inject service to Utilities class I have a Utilities class with some static methods on it. In one method I want to get an object and return a safe style of its image. The issue is I need to use the DomSanitizer service, and I am unable to use it in static method. Here is the code: export class Utilities{ constructor(private sanitizer:DomSanitizer){ } static getImageStyle(obj){ return this.sanitizer.bypassSecurityTrustStyle(`url(data:image/jpg;base64,${obj.image})`); } } Does this need to be done in a non-static method and I should create instance of the class every time I use this function? A: as you can see here static functions do not use the instance of the class. there for if you declare a service in the constructor it wont be available in static methods. why not just make Utilities also a service and add sanitizer:DomSanitizer to the utilies service constructor like you did?
Q: Angular 2 inject service to Utilities class I have a Utilities class with some static methods on it. In one method I want to get an object and return a safe style of its image. The issue is I need to use the DomSanitizer service, and I am unable to use it in static method. Here is the code: export class Utilities{ constructor(private sanitizer:DomSanitizer){ } static getImageStyle(obj){ return this.sanitizer.bypassSecurityTrustStyle(`url(data:image/jpg;base64,${obj.image})`); } } Does this need to be done in a non-static method and I should create instance of the class every time I use this function? A: as you can see here static functions do not use the instance of the class. there for if you declare a service in the constructor it wont be available in static methods. why not just make Utilities also a service and add sanitizer:DomSanitizer to the utilies service constructor like you did? A: you can pass Injector to the static function as a parameter and then use injector.get() to get instance of DomSanitizer. https://angular.io/guide/dependency-injection#appendix-working-with-injectors-directly
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:890937", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623543" }
e0c8e9970d5762eaa59f3f1890ffe9c209fe2a00
Stackoverflow Stackexchange Q: Turning iphone to an iBeacon from local notification I'm trying to turn my iPhone to an iBeacon, I've seen and tested it that I can do it when I open my app, but I have a question that if I can do it without unlocking the phone and simply by entering the region that there is iBeacon and then got notified on my phone when my phone is locked and then turn my phone to iBeacon just by one of the choices that I got in my notification(without unlocking my phone) so I'm just concerned if anyone knows that Bluetooth Manager and CLLocation work just when you unlocked your phone or it can be done without it. Thanks... A: Due to iOS restrictions, your app cannot act as an iBeacon in the background, only when it is in the foreground. The user would need to tap the notification to open your app before you can broadcast a beacon
Q: Turning iphone to an iBeacon from local notification I'm trying to turn my iPhone to an iBeacon, I've seen and tested it that I can do it when I open my app, but I have a question that if I can do it without unlocking the phone and simply by entering the region that there is iBeacon and then got notified on my phone when my phone is locked and then turn my phone to iBeacon just by one of the choices that I got in my notification(without unlocking my phone) so I'm just concerned if anyone knows that Bluetooth Manager and CLLocation work just when you unlocked your phone or it can be done without it. Thanks... A: Due to iOS restrictions, your app cannot act as an iBeacon in the background, only when it is in the foreground. The user would need to tap the notification to open your app before you can broadcast a beacon
stackoverflow
{ "language": "en", "length": 159, "provenance": "stackexchange_0000F.jsonl.gz:890941", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623558" }
95f69598234ab92c096dd46f54c6f9873cc90d91
Stackoverflow Stackexchange Q: react storybook addon knobs not showing I cant seem to be getting the @storybook addon knobs working? It doesnt seem to be decorating the actual story. Pretty much followed this My code below.. Im using getstorybook with create-react-app Using below packages: @storybook/addon-actions": "^3.1.2, @storybook/addon-info": "^3.1.4, @storybook/addon-knobs": "^3.1.2, @storybook/react": "^3.1.3 my setup //.storybook/addons.js import '@storybook/addon-knobs/register' //.config import { configure, setAddon, addDecorator } from '@storybook/react'; import infoAddon from '@storybook/addon-info'; setAddon(infoAddon); function loadStories() { require('../stories'); } configure(loadStories, module); //stories/index.js import React from 'react'; import { withKnobs, text, boolean, number } from '@storybook/addon-knobs'; import { storiesOf } from '@storybook/react'; const stories = storiesOf('Storybook Knobs', module); // Add the `withKnobs` decorator to add knobs support to your stories. // You can also configure `withKnobs` as a global decorator. stories.addDecorator(withKnobs); // Knobs for React props stories.add('with a button', () => ( <button disabled={boolean('Disabled', false)} > {text('Label', 'Hello Button')} </button> )) This should be a no brainer, but no suck luck. A: * *Hitting D on your keyboard toggles the layout // Ray Brown or * *You should also be able to expand the sidebar by clicking and dragging on the right side.
Q: react storybook addon knobs not showing I cant seem to be getting the @storybook addon knobs working? It doesnt seem to be decorating the actual story. Pretty much followed this My code below.. Im using getstorybook with create-react-app Using below packages: @storybook/addon-actions": "^3.1.2, @storybook/addon-info": "^3.1.4, @storybook/addon-knobs": "^3.1.2, @storybook/react": "^3.1.3 my setup //.storybook/addons.js import '@storybook/addon-knobs/register' //.config import { configure, setAddon, addDecorator } from '@storybook/react'; import infoAddon from '@storybook/addon-info'; setAddon(infoAddon); function loadStories() { require('../stories'); } configure(loadStories, module); //stories/index.js import React from 'react'; import { withKnobs, text, boolean, number } from '@storybook/addon-knobs'; import { storiesOf } from '@storybook/react'; const stories = storiesOf('Storybook Knobs', module); // Add the `withKnobs` decorator to add knobs support to your stories. // You can also configure `withKnobs` as a global decorator. stories.addDecorator(withKnobs); // Knobs for React props stories.add('with a button', () => ( <button disabled={boolean('Disabled', false)} > {text('Label', 'Hello Button')} </button> )) This should be a no brainer, but no suck luck. A: * *Hitting D on your keyboard toggles the layout // Ray Brown or * *You should also be able to expand the sidebar by clicking and dragging on the right side. A: Hope this helps someone, but for some reason my addons panel suddenly disappeared from view and I couldn't figure out how to get it back. I could see the addons markup being rendered in the "elements" pane in my dev tools - so I knew things were working. Somehow storybook stored a bad value in my localStorage['storybook-layout'] so that the addons were positioned waaaaayyy off screen. Running the following fixed it. localStorage.removeItem('storybook-layout') A: Try removing all the query string on the url eg. http://localhost:6006/?knob-is_block=false&knob-Disabled=false&knob-disabled=false&knob-Style%20lite=false&knob-show=true&knob-Size=md&knob-readOnly=false&knob-Style=default&knob-icon%20name=vertical&knob-Label=Hello%20Button&knob-Active=false&knob-is_loading=false&selectedKind=Button&selectedStory=default%20style&full=0&addons=0&stories=1&panelRight=0&addonPanel=storybooks%2Fstorybook-addon-knobs to http://localhost:6006 This worked for me. A: You probably need to create the addons.js file on the storybook config folder. (By default .storybook). Check the Docs for knobs you need to add the following: import '@storybook/addon-knobs/register'; A: In Storybook 6.5 I was facing the same issue after manually adding the addon: npm i @storybook/addon-knobs --dev All I needed to do is to go to the main.js file inside the .storybook folder and add the following: "addons": ["@storybook/addon-knobs"] Then I stopped the already running storybook in the terminal using ctrl/cmd + c and then re-run the storybook: npm run storybook Hope it helps. Thank you.
stackoverflow
{ "language": "en", "length": 376, "provenance": "stackexchange_0000F.jsonl.gz:890959", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623598" }
d910023ad47e5fc25fd3b615fcab36c08bd46b99
Stackoverflow Stackexchange Q: Lexical or processor issue: boost/config/user.hpp' file not found When i run my react native app in Xcode, it shows an error "boost/config/user.hpp' file not found" . And also when i run the application using the command "react-native run-ios" ,I got an error in terminal , "Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/sample2.app/Info.plist" Print: Entry, ":CFBundleIdentifier", Does Not Exist " . How can i solve this. I am a bigginer in react native app development. A: It's related to this boost package: ./node_modules/react-native/third-party/boost_1_63_0/boost/config * *Remove third-party folder from path: /node_modules/react-native/third-party/ *Re-run the Xcode project.
Q: Lexical or processor issue: boost/config/user.hpp' file not found When i run my react native app in Xcode, it shows an error "boost/config/user.hpp' file not found" . And also when i run the application using the command "react-native run-ios" ,I got an error in terminal , "Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/sample2.app/Info.plist" Print: Entry, ":CFBundleIdentifier", Does Not Exist " . How can i solve this. I am a bigginer in react native app development. A: It's related to this boost package: ./node_modules/react-native/third-party/boost_1_63_0/boost/config * *Remove third-party folder from path: /node_modules/react-native/third-party/ *Re-run the Xcode project. A: Do you have any updates to run on your machine/xcode? I had this issue when I had pending macOS Sierra updates to install. I installed the updates which caused my mac to restart, I then ran npm install and tried to build again and it succeeded. Versions: * *macOS Sierra: 10.12.6 *Xcode: 8.3.3 *react: 16.0.0-alpha.12 *react-native: 0.47.1 A: Some packages are not installed properly. Just delete node-modules forder with rm -rf node-modules and run again (npm install or yarn install).
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:890967", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623624" }
3c00a978f948b98027ecad6b29af2c2f1f309b03
Stackoverflow Stackexchange Q: vendor/autoload.php: failed to open stream I worked with a project using composer.But when i run the index file,system shows the following error, Warning: require_once(vendor/autoload.php): failed to open stream: No such file or directory in D:\xampp\htdocs\instagram_php\index.php on line 5 Fatal error: require_once(): Failed opening required 'vendor/autoload.php' (include_path='.;D:\xampp\php\PEAR') in D:\xampp\htdocs\instagram_php\index.php on line 5 I have installed composer from https://getcomposer.org/. What am doing wrong? A: You are using require_oncewith a relative path. It is possible but there are so many things that can go wrong that I usually avoid it. Where is the vendorfolder relative to index.php? I recommend using an absolute path. You can use the magic constants to determine it: require_once(__DIR__ . '/vendor/autoload.php'); NOTE: you can use /.. to go up the directory tree. NOTE2: __DIR__ requires php 5.3 or higher. You can use dirname(__FILE__) for older versions.
Q: vendor/autoload.php: failed to open stream I worked with a project using composer.But when i run the index file,system shows the following error, Warning: require_once(vendor/autoload.php): failed to open stream: No such file or directory in D:\xampp\htdocs\instagram_php\index.php on line 5 Fatal error: require_once(): Failed opening required 'vendor/autoload.php' (include_path='.;D:\xampp\php\PEAR') in D:\xampp\htdocs\instagram_php\index.php on line 5 I have installed composer from https://getcomposer.org/. What am doing wrong? A: You are using require_oncewith a relative path. It is possible but there are so many things that can go wrong that I usually avoid it. Where is the vendorfolder relative to index.php? I recommend using an absolute path. You can use the magic constants to determine it: require_once(__DIR__ . '/vendor/autoload.php'); NOTE: you can use /.. to go up the directory tree. NOTE2: __DIR__ requires php 5.3 or higher. You can use dirname(__FILE__) for older versions. A: Make sure vendor folder is there if not please Run following command:- composer install
stackoverflow
{ "language": "en", "length": 153, "provenance": "stackexchange_0000F.jsonl.gz:890970", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623636" }
8e3efe07b76ddb2981258cd30594a646ce7fc157
Stackoverflow Stackexchange Q: Variable becomes empty after resetting input field <input type="file" onchange="uploadFiles()" multiple/> After storing the input value in a variable and resetting the input field, the variable becomes empty function uploadFiles(){ var newFiles = $('input')[0].files; $('input').replaceWith($('input').val('').clone(true)); console.log(newFiles); // result == [] } Please how do I fix this? A: This is because your onchange event gets fired a second time when you reset the input field. Resetting the input field is considered a change. A way around this would be to temporarily disable the onchange events while you update the value. // remove the change handler $('input').off('change', uploadFiles); $('input').val(''); // re-establish the change handler $('input').on('change', uploadFiles); Note: it isn't a good idea to mix inline event handlers (onchange="whatever") with handlers in your script. You should just jQuery on().
Q: Variable becomes empty after resetting input field <input type="file" onchange="uploadFiles()" multiple/> After storing the input value in a variable and resetting the input field, the variable becomes empty function uploadFiles(){ var newFiles = $('input')[0].files; $('input').replaceWith($('input').val('').clone(true)); console.log(newFiles); // result == [] } Please how do I fix this? A: This is because your onchange event gets fired a second time when you reset the input field. Resetting the input field is considered a change. A way around this would be to temporarily disable the onchange events while you update the value. // remove the change handler $('input').off('change', uploadFiles); $('input').val(''); // re-establish the change handler $('input').on('change', uploadFiles); Note: it isn't a good idea to mix inline event handlers (onchange="whatever") with handlers in your script. You should just jQuery on(). A: $('input')[0].files gives you the FileList property of the input, which is attached to it. Changing the value of the input will result in changing the value of the property and all its assignments. You can work around the problem by adding the files to a separate array: var newFiles = $('input')[0].files; var filesArray = []; for(var i=0; i<newFiles.length; i++){ filesArray[i] = newFiles[i]; } $('input').replaceWith($('input').val('').clone(true)); console.log(newFiles); // result == [] console.log(filesArray); // result == [File] Demo Note: For security reasons, you may or may not use the Files as intended after changing the value of the original input. I haven't tested it though. If you can confirm or debunk, please comment.
stackoverflow
{ "language": "en", "length": 239, "provenance": "stackexchange_0000F.jsonl.gz:890977", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623680" }
0863e49dfe833658ac478fcc3bb8f5cf6ed66521
Stackoverflow Stackexchange Q: Getting sum of column using JPA repository I want to execute following Query using JPA repository implementation. Query:select sum(amount) from transactions where transaction_date_time between '2017-05-04 00:01:07' and '2017-05-04 23:03:07' and id=2; For finding I am using something like: public interface TransactionRepository extends JpaRepository<Transaction, Serializable>{ Transaction findById(Long id); } So for sum I need something like this: Double sumAmountByTransactionDateTimeBetweenAndMerchantId(Date from, Date to, Long merchantId); I don't want to use @Query. I just want to create method name which will do my job. So, this is not a duplicate. I tried with above function name but it is not doing my job.
Q: Getting sum of column using JPA repository I want to execute following Query using JPA repository implementation. Query:select sum(amount) from transactions where transaction_date_time between '2017-05-04 00:01:07' and '2017-05-04 23:03:07' and id=2; For finding I am using something like: public interface TransactionRepository extends JpaRepository<Transaction, Serializable>{ Transaction findById(Long id); } So for sum I need something like this: Double sumAmountByTransactionDateTimeBetweenAndMerchantId(Date from, Date to, Long merchantId); I don't want to use @Query. I just want to create method name which will do my job. So, this is not a duplicate. I tried with above function name but it is not doing my job.
stackoverflow
{ "language": "en", "length": 101, "provenance": "stackexchange_0000F.jsonl.gz:890990", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623731" }
f1e7c40d80945bbae68078c3ed660827e98206d1
Stackoverflow Stackexchange Q: timer for closing a program in cmd I want to make a bat file that starts a program(actually another bat) and close the program after a certain amount of time. my program is like this. -In 'Program_A.bat' @echo off set /p sec="Enter the amount of sec you want to run : " start Program_B.bat timeout /t %sec% tasakkill /F /IM cmd.exe I found It works well when I put little amount of time. like 10 seconds. But When I put 3600 or more, It doesn't kill the Program_B.bat properly. And I if I put 172800 secs in order to set 48 hours, it doesn't work. How can I manage these problems? A: killing just cmd.exe may kill windows, that you don't want to kill. You can give your application a unique title and kill it by that title. Also to work around the 100000 seconds limit of timeout, just timeout one hour in a loop: start "UniqueTitle" Program_B.bat for /l %%a in (1,1,48) do timeout 3600 >nul taskkill /fi "windowtitle eq UniqueTitle"
Q: timer for closing a program in cmd I want to make a bat file that starts a program(actually another bat) and close the program after a certain amount of time. my program is like this. -In 'Program_A.bat' @echo off set /p sec="Enter the amount of sec you want to run : " start Program_B.bat timeout /t %sec% tasakkill /F /IM cmd.exe I found It works well when I put little amount of time. like 10 seconds. But When I put 3600 or more, It doesn't kill the Program_B.bat properly. And I if I put 172800 secs in order to set 48 hours, it doesn't work. How can I manage these problems? A: killing just cmd.exe may kill windows, that you don't want to kill. You can give your application a unique title and kill it by that title. Also to work around the 100000 seconds limit of timeout, just timeout one hour in a loop: start "UniqueTitle" Program_B.bat for /l %%a in (1,1,48) do timeout 3600 >nul taskkill /fi "windowtitle eq UniqueTitle"
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:890998", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623749" }
33673fd78eaa78695cbf70b93f240a440dc9b090
Stackoverflow Stackexchange Q: JsDoc: Defining param type to be a type from an external module This seems like it should have an obvious answer but I can't find it. var mongoose = require('mongoose') /** * @param {Mongoose.Model} fooModel */ function ExecuteAQueryUsingModel(fooModel) { I am essentially trying to define the parameter to be a Mongoose.Model, a variable constructed with the mongoose model constructor. I don't know how to set the jsdoc types to be types defined externally like this. A: I may be on thin ice here, since I'm just a hobbyist, and I'm only using JSDoc to get IntelliSense in Visual Studio Code. This JSDoc solved my problem: /** @param {import("express").Response} expressResponse */ function send(expressResponse) { expressResponse.send('OK'); } I was not able to find the syntax in http://usejsdoc.org/tags-param.html so this could be specific to typescript. Here's where I found the idea: https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html Hope this gives some help although it may not be completely correct.
Q: JsDoc: Defining param type to be a type from an external module This seems like it should have an obvious answer but I can't find it. var mongoose = require('mongoose') /** * @param {Mongoose.Model} fooModel */ function ExecuteAQueryUsingModel(fooModel) { I am essentially trying to define the parameter to be a Mongoose.Model, a variable constructed with the mongoose model constructor. I don't know how to set the jsdoc types to be types defined externally like this. A: I may be on thin ice here, since I'm just a hobbyist, and I'm only using JSDoc to get IntelliSense in Visual Studio Code. This JSDoc solved my problem: /** @param {import("express").Response} expressResponse */ function send(expressResponse) { expressResponse.send('OK'); } I was not able to find the syntax in http://usejsdoc.org/tags-param.html so this could be specific to typescript. Here's where I found the idea: https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html Hope this gives some help although it may not be completely correct.
stackoverflow
{ "language": "en", "length": 152, "provenance": "stackexchange_0000F.jsonl.gz:891000", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623753" }
118dd9008a0556692332838c681b82209131162a
Stackoverflow Stackexchange Q: How to rename a GoCD pipeline? It does not seem to be possible to change the name of an existing pipeline anywhere in GoCD. As simple as it sounds, is there any way to rename a GoCD pipeline that doesn't require a long series of actions in the UI? The only way I was able to rename a pipeline is to clone it under a new name and then delete the old one. But deleting a pipeline also isn't straight-forward because is not possible to remove a pipeline that still belongs to some environment. Therefore, I first had to remove the pipeline from all environments and only then I was able to delete it. There are some similar discussions about renaming pipelines here and there but since they are like five years old I thought a simple pipeline rename must somehow be supported in the meantime... A: You'll have to change the pipeline name inside the Config XML. To get there, go to: Admin -> Config XML. You'll need to change this in two places on the config.
Q: How to rename a GoCD pipeline? It does not seem to be possible to change the name of an existing pipeline anywhere in GoCD. As simple as it sounds, is there any way to rename a GoCD pipeline that doesn't require a long series of actions in the UI? The only way I was able to rename a pipeline is to clone it under a new name and then delete the old one. But deleting a pipeline also isn't straight-forward because is not possible to remove a pipeline that still belongs to some environment. Therefore, I first had to remove the pipeline from all environments and only then I was able to delete it. There are some similar discussions about renaming pipelines here and there but since they are like five years old I thought a simple pipeline rename must somehow be supported in the meantime... A: You'll have to change the pipeline name inside the Config XML. To get there, go to: Admin -> Config XML. You'll need to change this in two places on the config. A: You can use gocd api call https://api.gocd.org/17.3.0/#edit-pipeline-config and just `$ curl 'https://ci.example.com/go/api/admin/pipelines/my_pipeline' \ -u 'username:password' \ -H 'Accept: application/vnd.go.cd.v3+json' \ -H 'Content-Type: application/json' \ -H 'If-Match: "e064ca0fe5d8a39602e19666454b8d77"' \ -X PUT \ -d '{ "name": "my_pipeline", }'` A: First you'll have to un-link that pipeline from pipeline dependency and environment. Then, you can go to 'Admin' > 'Config XML'and edit the name on XML file. "Save" and You're good to go!
stackoverflow
{ "language": "en", "length": 250, "provenance": "stackexchange_0000F.jsonl.gz:891002", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623756" }
4cd7d0e1db0bb8541a7e7ea107c2bf9b94fe2527
Stackoverflow Stackexchange Q: Ionic multiple splash screens I'm building an application with Ionic v1 and using the cordova splash-screen plug-in. I need to show a splash screen form a fixed set of images each time the app starts. Is there any way, clean or hackish to get multiple splash-screens? Thanks for any help. A: It's not possible with Cordova Splash Screen plugin but you can try this. First we will create array of images : $rootScope.image = ["img1.png","img2.png"]; And set/reset index for picking image : if(localStorage.getItem('sliderIndex')==null || localStorage.getItem('sliderIndex')==undefined || localStorage.getItem('sliderIndex')==5) localStorage.setItem('sliderIndex',0); Here is your view page <img src="img/{{image[imgIndex]}}" width="100%" height="100%"/> And set imgIndex's value : $scope.imgIndex = localStorage.getItem('sliderIndex'); And navigate the page after 3 sec, incrementing the index value : $timeout(function() { $location.path("/app/search"); var data = parseInt(localStorage.getItem('sliderIndex'))+1; localStorage.setItem('sliderIndex',data);},3000);
Q: Ionic multiple splash screens I'm building an application with Ionic v1 and using the cordova splash-screen plug-in. I need to show a splash screen form a fixed set of images each time the app starts. Is there any way, clean or hackish to get multiple splash-screens? Thanks for any help. A: It's not possible with Cordova Splash Screen plugin but you can try this. First we will create array of images : $rootScope.image = ["img1.png","img2.png"]; And set/reset index for picking image : if(localStorage.getItem('sliderIndex')==null || localStorage.getItem('sliderIndex')==undefined || localStorage.getItem('sliderIndex')==5) localStorage.setItem('sliderIndex',0); Here is your view page <img src="img/{{image[imgIndex]}}" width="100%" height="100%"/> And set imgIndex's value : $scope.imgIndex = localStorage.getItem('sliderIndex'); And navigate the page after 3 sec, incrementing the index value : $timeout(function() { $location.path("/app/search"); var data = parseInt(localStorage.getItem('sliderIndex'))+1; localStorage.setItem('sliderIndex',data);},3000); A: you have to maintain image displayed on splash screen in Local storage. e.g suppose images array contains [1.png,2.png,3.png,4.png,5.png] so when if I displayed 1.png first time then will save that in local storage and when next time splash screen gets appeared check that local storage and increment it by 1 and so on... till last image,if on last image set first image again
stackoverflow
{ "language": "en", "length": 190, "provenance": "stackexchange_0000F.jsonl.gz:891021", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623823" }
001a13ff48b9677809557227307921040156d94f
Stackoverflow Stackexchange Q: Angular Lazy Loading events for start/end loading Is there any events when ngModule starts/ends lazy loaded? I would need one of this events to also load some additional resources like translates. It would be also nice to display some animation, so user knows something is loading when it clicks for the first time on LazyLoaded route. A: Yes, there are two events RouteConfigLoadStart and RouteConfigLoadEnd that you can use like this: constructor(router:Router) { router.events.subscribe(event:Event => { if(event instanceof RouteConfigLoadStart) { } if(event instanceof RouteConfigLoadEnd) { } }); }
Q: Angular Lazy Loading events for start/end loading Is there any events when ngModule starts/ends lazy loaded? I would need one of this events to also load some additional resources like translates. It would be also nice to display some animation, so user knows something is loading when it clicks for the first time on LazyLoaded route. A: Yes, there are two events RouteConfigLoadStart and RouteConfigLoadEnd that you can use like this: constructor(router:Router) { router.events.subscribe(event:Event => { if(event instanceof RouteConfigLoadStart) { } if(event instanceof RouteConfigLoadEnd) { } }); }
stackoverflow
{ "language": "en", "length": 89, "provenance": "stackexchange_0000F.jsonl.gz:891025", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623835" }
91b94fccfdd3921ead5c2b1f3728a5f4d88b854f
Stackoverflow Stackexchange Q: How can I get device id for push notifications using firebase in android I found this solution and I think it is not the ID which is required for notification kindly tell me by some samples: import android.provider.Settings.Secure; private String androidIdd = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID); I guess I don't need an android id. I just want to get the device unique ID for Firebase Notification or GCM. A: Instead of using some third party tutorials I would prefer to take a look into the official Firebase Cloud Messaging documentation. If you have set up everything correctly you can just scroll to the topic Retrieve the current registration token When you need to retrieve the current token, call FirebaseInstanceId.getInstance().getToken(). This method returns null if the token has not yet been generated. In a nutshell: Call FirebaseInstanceId.getInstance().getToken() to reveive the current device token. EDIT: The command FirebaseInstanceId.getInstance().getToken() is deprecated. The same documentation mentions a new approach as below: FirebaseInstanceId.getInstance().getInstanceId() .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { if (!task.isSuccessful()) { Log.w(TAG, "getInstanceId failed", task.getException()); return; } // Get new Instance ID token String token = task.getResult().getToken(); } });
Q: How can I get device id for push notifications using firebase in android I found this solution and I think it is not the ID which is required for notification kindly tell me by some samples: import android.provider.Settings.Secure; private String androidIdd = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID); I guess I don't need an android id. I just want to get the device unique ID for Firebase Notification or GCM. A: Instead of using some third party tutorials I would prefer to take a look into the official Firebase Cloud Messaging documentation. If you have set up everything correctly you can just scroll to the topic Retrieve the current registration token When you need to retrieve the current token, call FirebaseInstanceId.getInstance().getToken(). This method returns null if the token has not yet been generated. In a nutshell: Call FirebaseInstanceId.getInstance().getToken() to reveive the current device token. EDIT: The command FirebaseInstanceId.getInstance().getToken() is deprecated. The same documentation mentions a new approach as below: FirebaseInstanceId.getInstance().getInstanceId() .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { if (!task.isSuccessful()) { Log.w(TAG, "getInstanceId failed", task.getException()); return; } // Get new Instance ID token String token = task.getResult().getToken(); } });
stackoverflow
{ "language": "en", "length": 188, "provenance": "stackexchange_0000F.jsonl.gz:891032", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623850" }
821d7fce4ff5b4f17ffb3702038b3e6e193583bf
Stackoverflow Stackexchange Q: React and CSS animations When making a state change, React will run a reconciliation algorithm and may completely re-create parts of the DOM. If I have a CSS animation or transition being applied to a DOM node, how do React developers typically avoid interfering with the DOM during the animation (which might stop the animation)? Does this "just work", because developers know to only start the animation (e.g. by adding or removing a class) when a specific part of the component lifecycle has completed (e.g. onComponentDidUpdate) - i.e. after they can be sure no further major DOM subtree changes will occur? A: Usually this should "just work" with Reacts dom diffing. A more controlled approach would be to move whatever dom that is being animated into it's own component and using the shouldComponentUpdate method to control when you let React perform a re-render.
Q: React and CSS animations When making a state change, React will run a reconciliation algorithm and may completely re-create parts of the DOM. If I have a CSS animation or transition being applied to a DOM node, how do React developers typically avoid interfering with the DOM during the animation (which might stop the animation)? Does this "just work", because developers know to only start the animation (e.g. by adding or removing a class) when a specific part of the component lifecycle has completed (e.g. onComponentDidUpdate) - i.e. after they can be sure no further major DOM subtree changes will occur? A: Usually this should "just work" with Reacts dom diffing. A more controlled approach would be to move whatever dom that is being animated into it's own component and using the shouldComponentUpdate method to control when you let React perform a re-render.
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:891083", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44623998" }
c229a8ab0bb9307037dab9b5847cdb836d02aa68
Stackoverflow Stackexchange Q: Unable to find any matching test cases with xUnit While the tests worked fine on friday I now get this error: When I look at xUnit's github it's clear that this fails on xUnit code: The GetTestCases code does this: So, as I read it, and as I would expect, the test assembly is read for matches, which for some reason suddenly fails, while being just fine on friday. I've tried another solution, it's tests run just fine. What I've tried * *Clean / rebuild solution *Manually remove bin obj folders *Uninstall and install package xunit (version 2.2.0) *Shut down / restart Visual Studio *Reboot laptop None of this helps, nor did updating ReSharper. What's going on and what can fix this? Possibly ReSharper is interfering somehow? A: My problem was, that the Unit Test project created in VS2017 (v15.2) did not have some specific assemblies reference. After every failed run attempt I just went through Output:Tests window a check for any exception. Exceptions were complaining about missing assembly references: System.Runtime, System.Runtime.Extensions, System.Reflection. System.Linq Once I have added all the references(NuGets) all works as intended. I'm using VS2017, SpecFlow(2.2.0), xUnit(2.2.0), .NET 4.7, R#(2017.1.3)
Q: Unable to find any matching test cases with xUnit While the tests worked fine on friday I now get this error: When I look at xUnit's github it's clear that this fails on xUnit code: The GetTestCases code does this: So, as I read it, and as I would expect, the test assembly is read for matches, which for some reason suddenly fails, while being just fine on friday. I've tried another solution, it's tests run just fine. What I've tried * *Clean / rebuild solution *Manually remove bin obj folders *Uninstall and install package xunit (version 2.2.0) *Shut down / restart Visual Studio *Reboot laptop None of this helps, nor did updating ReSharper. What's going on and what can fix this? Possibly ReSharper is interfering somehow? A: My problem was, that the Unit Test project created in VS2017 (v15.2) did not have some specific assemblies reference. After every failed run attempt I just went through Output:Tests window a check for any exception. Exceptions were complaining about missing assembly references: System.Runtime, System.Runtime.Extensions, System.Reflection. System.Linq Once I have added all the references(NuGets) all works as intended. I'm using VS2017, SpecFlow(2.2.0), xUnit(2.2.0), .NET 4.7, R#(2017.1.3)
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:891087", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624004" }
07f26046c2de24553e409aca693012a9f5631b56
Stackoverflow Stackexchange Q: Failed to create IXPlaceholder for app bundle ID in xcode 9 I just installed Xcode. Version is 9.0 I registered myself (personal team) as a team. when i am run code then : Failed to create IXPlaceholder for app bundle ID com.xyz.abc Thank you! A: I had the same problem, because I unzip and install Xcode on another laptop and then copy application to my own laptop! Try download and install it again and avoid copy/paste.Just unzip it in your laptop.
Q: Failed to create IXPlaceholder for app bundle ID in xcode 9 I just installed Xcode. Version is 9.0 I registered myself (personal team) as a team. when i am run code then : Failed to create IXPlaceholder for app bundle ID com.xyz.abc Thank you! A: I had the same problem, because I unzip and install Xcode on another laptop and then copy application to my own laptop! Try download and install it again and avoid copy/paste.Just unzip it in your laptop.
stackoverflow
{ "language": "en", "length": 82, "provenance": "stackexchange_0000F.jsonl.gz:891104", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624062" }
e9da29f9c6c08a4c03b7b1857f8176d8bdc0adae
Stackoverflow Stackexchange Q: How To Find Nearest Point From User Location using geodjango? I am trying to find the nearest point to a location using geodjango. I tried using the following code: LocationInfo.objects.filter(coordinates__distance_lte=(user_location, D(km=2))) But It only works if the location is within the specified distance (D(km=2) in this case). I need to find the point nearest to the user without using any limit during query. A: Let's assume that your LocationInfo has it's geometry field named position: For Django version >= 1.9: You can use the Distance() function: from django.contrib.gis.db.models.functions import Distance LocationInfo.objects.annotate( distance=Distance('position', user_location) ).order_by('distance').first() Which will return the nearest object to the user_location For Django 1.6 <= version < 1.9: You can use the .distance() method: LocationInfo.objects.distance(user_location).order_by('distance').first() For Django version < 1.6: The .first() method does not exist so you have to get the first of the ordered queryset as follows: LocationInfo.objects.distance(user_location).order_by('distance')[:1].get()
Q: How To Find Nearest Point From User Location using geodjango? I am trying to find the nearest point to a location using geodjango. I tried using the following code: LocationInfo.objects.filter(coordinates__distance_lte=(user_location, D(km=2))) But It only works if the location is within the specified distance (D(km=2) in this case). I need to find the point nearest to the user without using any limit during query. A: Let's assume that your LocationInfo has it's geometry field named position: For Django version >= 1.9: You can use the Distance() function: from django.contrib.gis.db.models.functions import Distance LocationInfo.objects.annotate( distance=Distance('position', user_location) ).order_by('distance').first() Which will return the nearest object to the user_location For Django 1.6 <= version < 1.9: You can use the .distance() method: LocationInfo.objects.distance(user_location).order_by('distance').first() For Django version < 1.6: The .first() method does not exist so you have to get the first of the ordered queryset as follows: LocationInfo.objects.distance(user_location).order_by('distance')[:1].get() A: This will give you the nearest location info: LocationInfo.geo_objects.distance(user_location).order_by('distance')[0] where geo_objects is Model manager for LocationInfo from django.contrib.gis.db import models as gis_models class LocationInfo(models.Model): geo_objects = gis_models.GeoManager()
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:891121", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624110" }
813b1fac7331c233a0342b6a3aeae2fe5d162741
Stackoverflow Stackexchange Q: How to configure compressed logs in WildFly? Is it possible to configure compressed logs in WildFly 10? Was not able to find the proper configuration here: https://docs.jboss.org/author/display/WFLY10/Handlers A: Log handlers are not supposed to zip log files. I assume, that you want to use log rotation and then zip older log entries. First, define a rotated file handler - you can decide to rotate either based on time e.g. every midnight or based on size e.g. every 5MB. An example of time based, daily rolling file handler: <periodic-rotating-file-handler name="FILE" autoflush="true"> <formatter> <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/> </formatter> <file relative-to="jboss.server.log.dir" path="server.log"/> <suffix value=".yyyy-MM-dd"/> <append value="true"/> </periodic-rotating-file-handler> Now for the second part, compression. If you are on linux, the easiest way ho to do that is to setup a CRON job that would find all entries that you want to zip and compress them. For example you can setup your cron job to run this script: ls server.log.*|grep -v '\.zip$' |xargs -i zip -m {}.zip {}
Q: How to configure compressed logs in WildFly? Is it possible to configure compressed logs in WildFly 10? Was not able to find the proper configuration here: https://docs.jboss.org/author/display/WFLY10/Handlers A: Log handlers are not supposed to zip log files. I assume, that you want to use log rotation and then zip older log entries. First, define a rotated file handler - you can decide to rotate either based on time e.g. every midnight or based on size e.g. every 5MB. An example of time based, daily rolling file handler: <periodic-rotating-file-handler name="FILE" autoflush="true"> <formatter> <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/> </formatter> <file relative-to="jboss.server.log.dir" path="server.log"/> <suffix value=".yyyy-MM-dd"/> <append value="true"/> </periodic-rotating-file-handler> Now for the second part, compression. If you are on linux, the easiest way ho to do that is to setup a CRON job that would find all entries that you want to zip and compress them. For example you can setup your cron job to run this script: ls server.log.*|grep -v '\.zip$' |xargs -i zip -m {}.zip {} A: As per Wildfly 19, if you add .zip or .gz in the suffix, it'll automatically zip them when rotated.
stackoverflow
{ "language": "en", "length": 187, "provenance": "stackexchange_0000F.jsonl.gz:891147", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624187" }
175d9bc13ee4f8b239a25077710c53c13a25542a
Stackoverflow Stackexchange Q: Software caused connection abort. Error returned in reply:Connection invalid My Xcode 9 gives the message to which I don't know how to respond. I want to run the app to my simulator, and I am getting this weird message. Attaching the snapshot for the same. A: Swapping between 2 versions of Xcode (8.3.3 and 9 GM) gave me this problem in Xcode 9. Solved by Xcode->Preferences->Locations->Command Line Tools, set to Xcode 9. Needed to quit Xcode and the simulator, but it then worked.
Q: Software caused connection abort. Error returned in reply:Connection invalid My Xcode 9 gives the message to which I don't know how to respond. I want to run the app to my simulator, and I am getting this weird message. Attaching the snapshot for the same. A: Swapping between 2 versions of Xcode (8.3.3 and 9 GM) gave me this problem in Xcode 9. Solved by Xcode->Preferences->Locations->Command Line Tools, set to Xcode 9. Needed to quit Xcode and the simulator, but it then worked. A: * *If you are using two versions of Xcode, remove one or quit all Xcode and simulators. *Go to preferences and Set proper version for command line tools *click on Derived Data, go to Derived data and delete that folder or simply use rm -rf ~/Library/Developer/Xcode/DerivedData *Click on Simulator reset content settings and just quit XCode and simulator and open clear and build the Xcode and run it. A: I had the same issue: Try to: - kill simulator (force quit) if it won't work, restart mac - it is funny but for me it worked A: Restart Xcode & Simulator. delete the app from simulator make clean & try to deploy again. it works for me. A: It seems that there is error while Xcode is trying to connect with Simulator/Device in order to run app. So there are multiple solution to this issue : * *Clean project (shortcut : cmd + shift + k) / Clean Build project (shortcut : cmd + shift + alt + k) *Delete derived data content (Open Xcode preference using cmd + comma). Goto Location tab. In Derived Data section press on arrow symbol. *Quit Xcode and Simulator For me solution 3 worked! A: Same error. For me running xcode-select helped: sudo xcode-select -s /Applications/Xcode-beta.app/Contents/Developer/ A: This is because you have multiple versions of Xcode in your system. Just quit all the other versions of xcode and also the simulators. Restart the required version of Xcode and it should work. A: You need to select the latest version of the command line tools in the preference pane. * *Xcode -> Preferences *In the Locations tab change the Command Line Tool pop up to the latest version. *Restart Xcode and the Simulator A: I faced the same issue. Quit Xcode and Restart Mac. This worked for me.
stackoverflow
{ "language": "en", "length": 388, "provenance": "stackexchange_0000F.jsonl.gz:891152", "question_score": "26", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624199" }
17050ebb6b13c00429e72e6141f3f4316e36ec64
Stackoverflow Stackexchange Q: How to convert String into locale in java I need to convert a given string into locale. String has value "fr_US" and I need to convert it into locale (in java.util.locale). I found one method in "org.apache.commons.lang.LocaleUtils" that does the conversion but I am looking for a method that converts into "java.util.locale" String val = "fr_US"; locale l1 = LocaleUtils.toLocale(val); // this converts into org.apache.commons.lang.LocaleUtils A: You can do: String val = "fr_US"; String[] tab = val.split("_"); Locale locale = new Locale(tab[0], tab[1]); Or, if you hardcoded you val Locale locale = new Locale("fr", "US"); Also in Locale we have a method forLanguageTag but as parameter you have to pass BCP 47 language tag (with -, not _).
Q: How to convert String into locale in java I need to convert a given string into locale. String has value "fr_US" and I need to convert it into locale (in java.util.locale). I found one method in "org.apache.commons.lang.LocaleUtils" that does the conversion but I am looking for a method that converts into "java.util.locale" String val = "fr_US"; locale l1 = LocaleUtils.toLocale(val); // this converts into org.apache.commons.lang.LocaleUtils A: You can do: String val = "fr_US"; String[] tab = val.split("_"); Locale locale = new Locale(tab[0], tab[1]); Or, if you hardcoded you val Locale locale = new Locale("fr", "US"); Also in Locale we have a method forLanguageTag but as parameter you have to pass BCP 47 language tag (with -, not _). A: if you are using the apache tool so the right way is: Locale myLocale = LocaleUtils.toLocale("fr_US"); that is the same as Locale myLocale = new Locale("fr", "US");
stackoverflow
{ "language": "en", "length": 147, "provenance": "stackexchange_0000F.jsonl.gz:891162", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624237" }
8a61c1db5199c05c76edbeb045c050cf95d47ac8
Stackoverflow Stackexchange Q: Laravel sync manytomany error I am attaching user_id, product_id with an extra field. Every thing is working fine until the extra field should be updated. When the field will be filled for second time instead of updating it will add another one to database. and it's obvious because I used attach instead of sync. But when I use sync I get an error. this is my code: $price = $request->input('price'); $product = Product::find($id); $product->users()->attach(Auth::id(), ['price' => $price]); and this is the error I get when I use sync: Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatRecordsList() must be of the type array, integer given A: The first parameter of the sync() method should be an array. So correct syntax is: $product->users()->sync([Auth::id() => ['price' => $price]]); https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships
Q: Laravel sync manytomany error I am attaching user_id, product_id with an extra field. Every thing is working fine until the extra field should be updated. When the field will be filled for second time instead of updating it will add another one to database. and it's obvious because I used attach instead of sync. But when I use sync I get an error. this is my code: $price = $request->input('price'); $product = Product::find($id); $product->users()->attach(Auth::id(), ['price' => $price]); and this is the error I get when I use sync: Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatRecordsList() must be of the type array, integer given A: The first parameter of the sync() method should be an array. So correct syntax is: $product->users()->sync([Auth::id() => ['price' => $price]]); https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships A: Sync method accepts an array of IDs to place on the pivot table also the sync method will delete the models from table if model does not exist in array and insert new items to the pivot table. So you need to do $product->users()->sync([Auth::id() => ['price' => $price]]); A: The sync method accepts an array of IDs to place on the intermediate table.Any IDs that are not in the given array will be removed from the intermediate table.So you should pass an array as a first parameter to sync() function as $product->users()->sync([Auth::id() => ['price' => $price]]);
stackoverflow
{ "language": "en", "length": 221, "provenance": "stackexchange_0000F.jsonl.gz:891166", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624252" }
8d71d826529314a97431eef8781e7955706d9b1a
Stackoverflow Stackexchange Q: Get only last row values from listview in asp.net I want to get only last row of listview. Is it possible? My listview binds with database. Every time it can returns different rows. I just want to get last row. Since I don't know how to do it. I have not tried anything A: var lastItem = ListView1.Items.LastOrDefault();
Q: Get only last row values from listview in asp.net I want to get only last row of listview. Is it possible? My listview binds with database. Every time it can returns different rows. I just want to get last row. Since I don't know how to do it. I have not tried anything A: var lastItem = ListView1.Items.LastOrDefault(); A: You can try Linq (the only trick is OfType or Cast): var result = myListView.Items .OfType<Object>() //TODO: out your type here .LastOrDefault(); // last row or null (if myListView is empty) Or direct var result = myListView.Items.Count > 0 // do we have any rows? ? myListView.Items[myListView.Items.Count - 1] // if yes, get the last one : null; // null on empty list view
stackoverflow
{ "language": "en", "length": 124, "provenance": "stackexchange_0000F.jsonl.gz:891178", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624278" }
9c4d6f9369421f59d38f113fd232c8789b3ee51d
Stackoverflow Stackexchange Q: Difference between systemd software watchdog and "normal" process monitoring I've tried out 2 systemd unit configurations: progA.service [Service] Type=simple ExecStart=/opt/progA WatchdogSec=10s progB.service [Service] Type=simple ExecStart=/opt/progB Restart=always RestartSec=10 The effect in 2 cases is similar: whenever the program killed/crashes/exits, it is restarted after 10s. To my understanding, using watchdog has advantage only if a specific thread/loop inside the program need to be monitored. Am I missing something? A: Yes, the watchdog will detect "liveness" above and beyond the Restart directive, which only detects "deadness". In order to avoid being killed by the watchdog, your service must actively call sd_notify. Imagine if something bad happens that doesn't quite kill your service, like a deadlock. The process would not be killed with a Restart directive, but it would fail to send the sd_notify and would be restarted by the watchdog (as long as the checkups are being sent on the same thread that is deadlocked).
Q: Difference between systemd software watchdog and "normal" process monitoring I've tried out 2 systemd unit configurations: progA.service [Service] Type=simple ExecStart=/opt/progA WatchdogSec=10s progB.service [Service] Type=simple ExecStart=/opt/progB Restart=always RestartSec=10 The effect in 2 cases is similar: whenever the program killed/crashes/exits, it is restarted after 10s. To my understanding, using watchdog has advantage only if a specific thread/loop inside the program need to be monitored. Am I missing something? A: Yes, the watchdog will detect "liveness" above and beyond the Restart directive, which only detects "deadness". In order to avoid being killed by the watchdog, your service must actively call sd_notify. Imagine if something bad happens that doesn't quite kill your service, like a deadlock. The process would not be killed with a Restart directive, but it would fail to send the sd_notify and would be restarted by the watchdog (as long as the checkups are being sent on the same thread that is deadlocked).
stackoverflow
{ "language": "en", "length": 153, "provenance": "stackexchange_0000F.jsonl.gz:891190", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624319" }
b4e13b54e2aa79984c6765c08e7e3cd69a7a2889
Stackoverflow Stackexchange Q: Angular NGRX - naming the store/app-instance for Redux-Devtools I am having trouble with Redux-Devtools plugin (for multiple browsers). So many websites use the Redux pattern that my own application often gets unselected. Does anyone know how how to name the store, so the plugin doesnt show 14/ngrx-store-somehash but the name of my app as the selected instance? A: As you can see here it has been added the parameter to configure store name with configuration option and it can be used like this: StoreDevtoolsModule.instrument({ maxAge: 5, name: "Yout custom store name here" }), Today in production version (4.1.1) it is not yet available but you can download the git version if you want to use it.
Q: Angular NGRX - naming the store/app-instance for Redux-Devtools I am having trouble with Redux-Devtools plugin (for multiple browsers). So many websites use the Redux pattern that my own application often gets unselected. Does anyone know how how to name the store, so the plugin doesnt show 14/ngrx-store-somehash but the name of my app as the selected instance? A: As you can see here it has been added the parameter to configure store name with configuration option and it can be used like this: StoreDevtoolsModule.instrument({ maxAge: 5, name: "Yout custom store name here" }), Today in production version (4.1.1) it is not yet available but you can download the git version if you want to use it.
stackoverflow
{ "language": "en", "length": 117, "provenance": "stackexchange_0000F.jsonl.gz:891197", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624341" }
d11f7d9bb141e56e139aa3b0040089e90ed557c7
Stackoverflow Stackexchange Q: Storing/retrieving json data to mysql using jdbctemplate I want to store/retrieve json object into mysql json column using jdbcTemplate. Here is my existing code, @RequestMapping(value="/create/template", method = RequestMethod.POST, consumes = "application/json", produces = "text/html") public String TemplateCreation(@RequestBody TemplateBojaClass dataFromUser){ TemplateBojaClass objCreation = dataFromUser; ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File("D:\\objCreation.getTemplateName()+".json"), objCreation); } But I want to store the json data to table column instead of storing in folder file. I know that mysql 5.7 have JSON dataType So now I have created table like below, CREATE TABLE `createTemplate` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `templateData` json DEFAULT NULL, PRIMARY KEY (`id`) ); I want to store the json input into that templateData column like below, @RequestMapping(value="/create/template", method = RequestMethod.POST, consumes = "application/json", produces = "text/html") public String TemplateCreation(@RequestBody TemplateBojaClass dataFromUser){ TemplateBojaClass objCreation = dataFromUser; ObjectMapper mapper = new ObjectMapper(); String sql="insert into template_creation(templateData) values(?);"; jdbcTemplate.update(sql, new Object[]{**How to pass the json parameter here?**}); } I could not found the solution from google. Somebody help me to achieve this?
Q: Storing/retrieving json data to mysql using jdbctemplate I want to store/retrieve json object into mysql json column using jdbcTemplate. Here is my existing code, @RequestMapping(value="/create/template", method = RequestMethod.POST, consumes = "application/json", produces = "text/html") public String TemplateCreation(@RequestBody TemplateBojaClass dataFromUser){ TemplateBojaClass objCreation = dataFromUser; ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File("D:\\objCreation.getTemplateName()+".json"), objCreation); } But I want to store the json data to table column instead of storing in folder file. I know that mysql 5.7 have JSON dataType So now I have created table like below, CREATE TABLE `createTemplate` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `templateData` json DEFAULT NULL, PRIMARY KEY (`id`) ); I want to store the json input into that templateData column like below, @RequestMapping(value="/create/template", method = RequestMethod.POST, consumes = "application/json", produces = "text/html") public String TemplateCreation(@RequestBody TemplateBojaClass dataFromUser){ TemplateBojaClass objCreation = dataFromUser; ObjectMapper mapper = new ObjectMapper(); String sql="insert into template_creation(templateData) values(?);"; jdbcTemplate.update(sql, new Object[]{**How to pass the json parameter here?**}); } I could not found the solution from google. Somebody help me to achieve this?
stackoverflow
{ "language": "en", "length": 170, "provenance": "stackexchange_0000F.jsonl.gz:891206", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624366" }
10c4d95f19549a7cfd2462925492d30b00709ea4
Stackoverflow Stackexchange Q: How to find the closest value in PHP How to determine the RESULTS field in table users, base on USER SCORE field with the provisions of the value closest to SCORE BRAND field. This is table Brand <table> <tr> <th>BRAND NAME</th> <th>SCORE BRAND</th> </tr>"; $sql = mysql_query("SELECT * FROM brand"); while($m=mysql_fetch_array($sql)){ echo "<tr> <td>$m[brand_name]</td> <td>$m[score]</td><tr>"; } </table> This is table users <table> <tr> <th>USER NAME</th> <th>SCORE USER</th> <th>RESULT</th> </tr>"; $sql2 = mysql_query("SELECT * FROM users"); while($u=mysql_fetch_array($sql2)){ echo "<tr> <td>$u[username]</td> <td>$u[score]</td> <td> ??? </td> <tr>"; } </table> A: You can use subquery in selection to find proper brand for every selected user like this: SELECT u.*, ( SELECT b.id FROM brand AS b ORDER BY ABS(b.score - u.score) ASC, b.score DESC -- selects brands ordered by their difference from user's score LIMIT 1 -- get just the first brand (with score closest to user's) ) FROM user AS u
Q: How to find the closest value in PHP How to determine the RESULTS field in table users, base on USER SCORE field with the provisions of the value closest to SCORE BRAND field. This is table Brand <table> <tr> <th>BRAND NAME</th> <th>SCORE BRAND</th> </tr>"; $sql = mysql_query("SELECT * FROM brand"); while($m=mysql_fetch_array($sql)){ echo "<tr> <td>$m[brand_name]</td> <td>$m[score]</td><tr>"; } </table> This is table users <table> <tr> <th>USER NAME</th> <th>SCORE USER</th> <th>RESULT</th> </tr>"; $sql2 = mysql_query("SELECT * FROM users"); while($u=mysql_fetch_array($sql2)){ echo "<tr> <td>$u[username]</td> <td>$u[score]</td> <td> ??? </td> <tr>"; } </table> A: You can use subquery in selection to find proper brand for every selected user like this: SELECT u.*, ( SELECT b.id FROM brand AS b ORDER BY ABS(b.score - u.score) ASC, b.score DESC -- selects brands ordered by their difference from user's score LIMIT 1 -- get just the first brand (with score closest to user's) ) FROM user AS u A: select * from table order by abs(value - $myvalue) limit 1 A: You should have some pre-defined threshold to match around (so that score 1 would not match with score 1000). SELECT .. WHERE score_brand >= score_user - :epsilon AND score_brand <= score_user + :epsilon A: Finally I got some pretty solution: SELECT u.*, b.nama_lengkap as result FROM `users` AS u JOIN `brands` AS b WHERE (b.score - u.score) > 0 AND (b.score - u.score) < 10 ORDER BY u.id; b.nama_lengkap -> brand name I have just joined two tables and did some arithmetic operation to get the appropriate row. EDIT SELECT v.id, v.username, v.score, b.nama_lengkap AS result FROM (SELECT users.id, users.score, users.username, min(brands.score) nextSc FROM users LEFT JOIN brands ON users.score <= brands.score GROUP BY users.id, users.score) AS v LEFT JOIN brands b ON v.nextSc = b.score ORDER BY v.id, v.score; This is the complete dynamic query for any multiplicated values. It will get you closure score of brands for users. You can find LIVE DEMO HERE
stackoverflow
{ "language": "en", "length": 318, "provenance": "stackexchange_0000F.jsonl.gz:891213", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624382" }
bd93470d8d76c9561fb778f44f026fe9be2ee2b9
Stackoverflow Stackexchange Q: Does the np.nan in numpy array occupy memory? I have a huge file of csv which can not be loaded into memory. Transforming it to libsvm format may save some memory. There are many nan in csv file. If I read lines and store them as np.array, with np.nan as NULL, will the array still occupy too much memory ? Does the np.nan in array also occupy memory ? A: When working with floating point representations of numbers, non-numeric values (NaN and inf) are also represented by a specific binary pattern occupying the same number of bits as any numeric floating point value. Therefore, NaNs occupy the same amount of memory as any other number in the array.
Q: Does the np.nan in numpy array occupy memory? I have a huge file of csv which can not be loaded into memory. Transforming it to libsvm format may save some memory. There are many nan in csv file. If I read lines and store them as np.array, with np.nan as NULL, will the array still occupy too much memory ? Does the np.nan in array also occupy memory ? A: When working with floating point representations of numbers, non-numeric values (NaN and inf) are also represented by a specific binary pattern occupying the same number of bits as any numeric floating point value. Therefore, NaNs occupy the same amount of memory as any other number in the array. A: As far as I know yes, nan and zero values occupy the same memory as any other value, however, you can address your problem in other ways: Have you tried using a sparse vector? they are intended for vectors with a lot of 0 values and memory consumption is optimized SVM Module Scipy Sparse matrices Scipy There you have some info about SVM and sparse matrices, if you have further questions just ask. Edited to provide an answer as well as a solution A: According to the getsizeof() command from the sys module it does. A simple and fast example : import sys import numpy as np x = np.array([1,2,3]) y = np.array([1,np.nan,3]) x_size = sys.getsizeof(x) y_size = sys.getsizeof(y) print(x_size) print(y_size) print(y_size == x_size) This should print out 120 120 True so my conclusion was it uses as much memory as a normal entry. Instead you could use sparse matrices (Scipy.sparse) which do not save zero / Null at all and therefore are more memory efficient. But Scipy strongly discourages from using Numpy methods directly https://docs.scipy.org/doc/scipy/reference/sparse.html since Numpy might not interpret them correctly.
stackoverflow
{ "language": "en", "length": 303, "provenance": "stackexchange_0000F.jsonl.gz:891220", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624404" }
a1b5fe881d33abb43d43f609c47db4fdd909c753
Stackoverflow Stackexchange Q: Kotlin - Add items to ExpandableListView I am trying to dynamically populate my expandable list view inside of Android Studio using Kotlin. But as of now, I wasn't able to find any up to date function to do so, all functions I found seem to be outdated. This is my skeleton code: private val shows = listOf("First", "Breaking Bad", "Game of Thrones", "Bob and Martin...") private val expandableListView: ExpandableListView by bind(R.id.theListView) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Add items to expandable list view here } Thanks in advance A: For me it worked fine. In your activity where you define your listdata do this: private ArrayList<HeaderInfo> SectionList = new ArrayList<>(); ... //create the adapter by passing your ArrayList data listAdapter = new ExpandableListAdapter(MyListActivity.this, SectionList); //attach the adapter to the list expandableListView.setAdapter(listAdapter); This is the constructor in my expandable list adapter public class ExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private ArrayList<HeaderInfo> SectionList; public ExpandableListAdapter(Context context, ArrayList<HeaderInfo> SectionList) { this.context = context; this.SectionList = SectionList; } ...
Q: Kotlin - Add items to ExpandableListView I am trying to dynamically populate my expandable list view inside of Android Studio using Kotlin. But as of now, I wasn't able to find any up to date function to do so, all functions I found seem to be outdated. This is my skeleton code: private val shows = listOf("First", "Breaking Bad", "Game of Thrones", "Bob and Martin...") private val expandableListView: ExpandableListView by bind(R.id.theListView) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Add items to expandable list view here } Thanks in advance A: For me it worked fine. In your activity where you define your listdata do this: private ArrayList<HeaderInfo> SectionList = new ArrayList<>(); ... //create the adapter by passing your ArrayList data listAdapter = new ExpandableListAdapter(MyListActivity.this, SectionList); //attach the adapter to the list expandableListView.setAdapter(listAdapter); This is the constructor in my expandable list adapter public class ExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private ArrayList<HeaderInfo> SectionList; public ExpandableListAdapter(Context context, ArrayList<HeaderInfo> SectionList) { this.context = context; this.SectionList = SectionList; } ...
stackoverflow
{ "language": "en", "length": 168, "provenance": "stackexchange_0000F.jsonl.gz:891225", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624412" }
87e28b20342437c7583aeada624495a8487b0ebc
Stackoverflow Stackexchange Q: How to use ImageMagick with XQuartz I am trying to create animated visualization in R and people say needs to install ImageMagick. However, it seems that current Mac no longer support x11, while ImageMagick just needs X11 server on Mac. Install ImageMagick I have also tried brew install imagemagick --with-x11, doesn't work and only returned so many errors. Apples says need to use XQuartz to replace x11. I have XQuartz, but when I turned on it, typed the same commands here, still give me the same error display: delegate library support not built-in '' (X11) @ error/display.c/DisplayImageCommand/1891. So, my questions is, how to install and use ImageMagick with Mac XQuartz? A: I created a Homebrew ImageMagick X11 formula that can be used like this: brew uninstall imagemagick # without X11 support brew install --cask xquartz brew install tlk/imagemagick-x11/imagemagick Note that homebrew-core used to support formula options such as --with-x11 in order to enable a configure option of the same name. This is no longer the case as the Homebrew maintainer(s) decided to remove formula options from homebrew-core formulas.
Q: How to use ImageMagick with XQuartz I am trying to create animated visualization in R and people say needs to install ImageMagick. However, it seems that current Mac no longer support x11, while ImageMagick just needs X11 server on Mac. Install ImageMagick I have also tried brew install imagemagick --with-x11, doesn't work and only returned so many errors. Apples says need to use XQuartz to replace x11. I have XQuartz, but when I turned on it, typed the same commands here, still give me the same error display: delegate library support not built-in '' (X11) @ error/display.c/DisplayImageCommand/1891. So, my questions is, how to install and use ImageMagick with Mac XQuartz? A: I created a Homebrew ImageMagick X11 formula that can be used like this: brew uninstall imagemagick # without X11 support brew install --cask xquartz brew install tlk/imagemagick-x11/imagemagick Note that homebrew-core used to support formula options such as --with-x11 in order to enable a configure option of the same name. This is no longer the case as the Homebrew maintainer(s) decided to remove formula options from homebrew-core formulas. A: Updated Answer Note that things have changed a bit since I wrote this answer, Homebrew no longer supports installation options such as --with-x11. One possibility, pointed out in the comments by @MattWhite was to install ImageMagick interactively: brew install imagemagick -i; ./configure --disable-osx-universal-binary --prefix=/usr/local/Cellar/imagemagick/7.0.8-66 --disable-silent-rules --with-x11 make install exit Another option that occurred to me was that, rather than installing all of XQuartz, you could just add your own delegate that uses macOS's built-in Preview app and tell ImageMagick to use that, i.e. delegate to it. This means you can do things like: magick SomeImage.png -crop 100x100+10+10 display: For this to work, you need to find your delegates.xml file. I used this: magick -list delegate | awk '/^Path/ {print $2}' and mine is at: /opt/homebrew/Cellar/imagemagick/7.1.0-16/etc/ImageMagick-7/delegates.xml Then I edited that file and added a line very close to the end, but just above the last line like this: <delegate decode="miff" encode="display" spawn="True" command="magick %i %u.png ; /usr/bin/open -a Preview %u.png"/> That converts any file formats that ImageMagick knows into a PNG which the Preview app understands and should be able to represent most images, even those with 16-bit depth and transparency. Original Answer In general, to use ImageMagick with X11, you will probably be most likely to succeed if you follow the following steps: Step 1 - Install or update Xcode command line tools It is important that your developer tools are up-to-date, especially if you have updated your macOS version since setting them up originally. You can do this with: xcode-select --install Step 2 - Ensure ImageMagick is correctly installed The easiest way to do this is first to ensure that old versions of ImageMagick are removed and cleaned up and that you then install (or re-install) with the latest version: brew update # update homebrew itself brew rm imagemagick # remove old IM versions brew install imagemagick --with-x11 # install latest IM version including X11 support Step 3 - Check If you have been trying for ages to install ImageMagick, you may have left some old versions lying around. It is important that you use the homebrew-installed version in /usr/local/bin, so check you are running the version you expect with the following: which convert # should report "/usr/local/bin/convert" which magick # should report "/usr/local/bin/magick" identify -version # should report same version as next command brew info imagemagick Step 4 - Start X11 Start X11, it is probably easiest to fire up xclock, which not only starts X11, but also checks everything X11 is running and your X11 environment is configured correctly: xclock & Step 5 - Run ImageMagick X11 Now you can test your ImageMagick configuration, without needing any test images as follows - since the wizard: image is built-in: display wizard:
stackoverflow
{ "language": "en", "length": 633, "provenance": "stackexchange_0000F.jsonl.gz:891246", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624479" }
43836b69b9ac02a0aac20cb138daa3bda7f477e7
Stackoverflow Stackexchange Q: Rather x <= 1 or x < 2? Say we have x which is an integer. is there any reason to prefer x <= 1 or x < 2? I mean if one is maybe faster or more readable. This question is language independant, meaning if the answer is different for two different languages, please let me know. A: Usually when I loop over a zero-based collection, I use i < col.Length, as it is more readable than i <= col.Length - 1. If I am iterating from 1 to x, I use for (int i = 1; i <= x ...), as it is more readable than < x + 1. Both of theese instructions have the same time requirement (at least on x86 architecture), so yes, it is only about readability.
Q: Rather x <= 1 or x < 2? Say we have x which is an integer. is there any reason to prefer x <= 1 or x < 2? I mean if one is maybe faster or more readable. This question is language independant, meaning if the answer is different for two different languages, please let me know. A: Usually when I loop over a zero-based collection, I use i < col.Length, as it is more readable than i <= col.Length - 1. If I am iterating from 1 to x, I use for (int i = 1; i <= x ...), as it is more readable than < x + 1. Both of theese instructions have the same time requirement (at least on x86 architecture), so yes, it is only about readability. A: I would say that it depends on the requirements of your software, was it specified that x needs to be one or less or was it specified that x needs to be less than two? If you ever changed x to be of a number type that allows decimal points, which way would work best then? This happens more often than you think and can introduce some interesting bugs. A: In general there is no evidence what types the literals 1 and 2 have. In most languages they will be the same, but in theory they could be different and then the results of two comparisons could be different as well. Also, integers are not infinite in most languages, so the behavior could be different on boundaries. In plain C, if the comparisons are x <= -0x80000000 and x < -0x7fffffff (note that -0x80000000 < -0x7fffffff) and x has type int, the results depend on the value of x: -0x80000000 : 1 1 -0x7fffffff .. -1 : 0 0 0 .. 0x7fffffff: 1 0 In other words, for all non-negative x, the results will be different. Similarly, with comparisons x <= 0x7fffffff and x < 0x80000000 (the relation between constants 0x7fffffff < 0x80000000 still holds), we get: -0x80000000 .. -1 : 1 0 0 .. 0x7fffffff: 1 1 Now the results are different for all negative values of x. Clearly, there are some typing rules and type conversions involved (they are described in the C language standard), but the point is that the two comparisons are not replaceable on boundary cases.
stackoverflow
{ "language": "en", "length": 396, "provenance": "stackexchange_0000F.jsonl.gz:891265", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624544" }
1955414bb7fd76c795579c60336fb638cf622fdc
Stackoverflow Stackexchange Q: Oozie workflow warning - "The application does not define formal parameters in its XML definition" What is the meaning of the org.apache.oozie.util.ParameterVerifier warning "The application does not define formal parameters in its XML definition" ? A: This is happening due to your workflow.xml or coordinator.xml not containing a child node for "parameters". The Oozie code for this check can be found here. You can find an example (second code section) here. Note: It appears that this is a benign warning ... unless these parameters are required for something else.
Q: Oozie workflow warning - "The application does not define formal parameters in its XML definition" What is the meaning of the org.apache.oozie.util.ParameterVerifier warning "The application does not define formal parameters in its XML definition" ? A: This is happening due to your workflow.xml or coordinator.xml not containing a child node for "parameters". The Oozie code for this check can be found here. You can find an example (second code section) here. Note: It appears that this is a benign warning ... unless these parameters are required for something else.
stackoverflow
{ "language": "en", "length": 90, "provenance": "stackexchange_0000F.jsonl.gz:891269", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624554" }
cd419f0dfa03d844b506caeac9003d8d925a34c0
Stackoverflow Stackexchange Q: Material UI Stepper with alternative label placement I want to create a material-ui stepper element which looks like this: They call it stepper element with alternative label placement. I am using material-ui library which implements Google's Material Design. Right now all examples from that library show in-line label placing and I don't see any property which would make it possible to use alternative label placement. But I believe it was implemented at some point of time because there was discussion about it. Is there a way to set alternative label placement for stepper right now? A: According to their docs Labels can be placed below the step icon by setting the alternativeLabel prop on the Stepper component.
Q: Material UI Stepper with alternative label placement I want to create a material-ui stepper element which looks like this: They call it stepper element with alternative label placement. I am using material-ui library which implements Google's Material Design. Right now all examples from that library show in-line label placing and I don't see any property which would make it possible to use alternative label placement. But I believe it was implemented at some point of time because there was discussion about it. Is there a way to set alternative label placement for stepper right now? A: According to their docs Labels can be placed below the step icon by setting the alternativeLabel prop on the Stepper component.
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:891286", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624614" }
50d93b99d1d345f28c4ba318e718d9c0a3c335db
Stackoverflow Stackexchange Q: Google Cloud Trace 192.168.1.1 In the Trace page of Google Cloud Console I can see address 192.168.1.1 which takes a lot of time to execute. What is this address? From where? Is it from internal cloud's infrastructure? Or is it mine local address (if it possible)? A: After talk with Google Cloud Support appears that 192.168.1.1 is exactly machine IP address on which Google Cloud Function is launched. But the interesting thing is that this address only appears if console.* things are in the code. So, for example I'm using console.log to log something with google cloud logging. And on the screen shot there are several calls of this address. In the top we can see long living calls, this calls are with kept console.log connection. And, for example last call lasts only 3ms and immediately closed. This console.log has been called right in the end of the request. Hope it might help someone.
Q: Google Cloud Trace 192.168.1.1 In the Trace page of Google Cloud Console I can see address 192.168.1.1 which takes a lot of time to execute. What is this address? From where? Is it from internal cloud's infrastructure? Or is it mine local address (if it possible)? A: After talk with Google Cloud Support appears that 192.168.1.1 is exactly machine IP address on which Google Cloud Function is launched. But the interesting thing is that this address only appears if console.* things are in the code. So, for example I'm using console.log to log something with google cloud logging. And on the screen shot there are several calls of this address. In the top we can see long living calls, this calls are with kept console.log connection. And, for example last call lasts only 3ms and immediately closed. This console.log has been called right in the end of the request. Hope it might help someone.
stackoverflow
{ "language": "en", "length": 155, "provenance": "stackexchange_0000F.jsonl.gz:891288", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624621" }
ec4a89376929c463f4b2c83066f152b547e62d3d
Stackoverflow Stackexchange Q: Dynamic Swagger generation We want to dynamically generate swagger documentation for our CRUD restful API. We have an API which allows consumers to create an entity e.g. User. Now we want to generate REST API definition for the created entity dynamically as the entity created can be any object e.g User, Organization, Institution. We have functionality in place to generate meta data for the given entity which will basically describe the entity created (properties, their validations etc.) . Is there an API by which we can write the swagger definition by using the meta data as an input? It will allow us to have Swagger definition for each of the entity we create dynamically. We are using Spring Framework.
Q: Dynamic Swagger generation We want to dynamically generate swagger documentation for our CRUD restful API. We have an API which allows consumers to create an entity e.g. User. Now we want to generate REST API definition for the created entity dynamically as the entity created can be any object e.g User, Organization, Institution. We have functionality in place to generate meta data for the given entity which will basically describe the entity created (properties, their validations etc.) . Is there an API by which we can write the swagger definition by using the meta data as an input? It will allow us to have Swagger definition for each of the entity we create dynamically. We are using Spring Framework.
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:891291", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624626" }
5c6a929622b3747cc41d2a52efebc4337f818bad
Stackoverflow Stackexchange Q: TensorFlow: “Attempting to use uninitialized value” in variable initialization Here's my code. import tensorflow as tf a=tf.Variable(tf.constant([0,1,2],dtype=tf.int32)) b=tf.Variable(tf.constant([1,1,1],dtype=tf.int32)) recall=tf.metrics.recall(b,a) init=tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) rec=sess.run(recall) print(rec) I tried to test tf.metrics.precision and got the following error message. FailedPreconditionError (see above for traceback): Attempting to use uninitialized value recall/true_positives/count [[Node: recall/true_positives/count/read = Identity[T=DT_FLOAT, _class=["loc:@recall/true_positives/count"], _device="/job:localhost/replica:0/task:0/gpu:0"](recall/true_positives/count)]] [[Node: recall/value/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_73_recall/value", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]] A: You also need to initialise the local variables hidden in the tf.metrics.recallmethod. For example, this piece of code would work: init_g = tf.global_variables_initializer() init_l = tf.local_variables_initializer() with tf.Session() as sess: sess.run(init_g) sess.run(init_l)
Q: TensorFlow: “Attempting to use uninitialized value” in variable initialization Here's my code. import tensorflow as tf a=tf.Variable(tf.constant([0,1,2],dtype=tf.int32)) b=tf.Variable(tf.constant([1,1,1],dtype=tf.int32)) recall=tf.metrics.recall(b,a) init=tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) rec=sess.run(recall) print(rec) I tried to test tf.metrics.precision and got the following error message. FailedPreconditionError (see above for traceback): Attempting to use uninitialized value recall/true_positives/count [[Node: recall/true_positives/count/read = Identity[T=DT_FLOAT, _class=["loc:@recall/true_positives/count"], _device="/job:localhost/replica:0/task:0/gpu:0"](recall/true_positives/count)]] [[Node: recall/value/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_73_recall/value", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]] A: You also need to initialise the local variables hidden in the tf.metrics.recallmethod. For example, this piece of code would work: init_g = tf.global_variables_initializer() init_l = tf.local_variables_initializer() with tf.Session() as sess: sess.run(init_g) sess.run(init_l)
stackoverflow
{ "language": "en", "length": 99, "provenance": "stackexchange_0000F.jsonl.gz:891299", "question_score": "20", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624648" }
725b369bb23a0397c520c8bb4dd3b8387b84c057
Stackoverflow Stackexchange Q: detecting multi color document with OpenCV4Android I am new to OpenCv with Android.I am trying to make an application which auto detects documents using OpenCv - 2.4.13 . In my app, there is a functionality of detection documents (like a Scanbot app) and then prospect it to document. So, far I am able to detect documents with single colour or documents which are clearly distinguishable from background. But the problem arises when the document is of multi-color. To clearly understand the problem , I have attached an image: As you can see, the blue line is a detection line and it is not detecting full document. What i did so far is as below : original image -> cvtColor -> GaussianBlur filter -> dilate it to sharpen edges -> applied watershed image segmentation algorithm -> canny edge detection with dynamic otsu's threshold -> then find largest contours -> draw contours After some research, I came to know that the problem rely on canny edge detection. Below is the result I get after canny edge detection: Is there any way to achieve this? Any help will be highly appreciated !! Thanks in advance
Q: detecting multi color document with OpenCV4Android I am new to OpenCv with Android.I am trying to make an application which auto detects documents using OpenCv - 2.4.13 . In my app, there is a functionality of detection documents (like a Scanbot app) and then prospect it to document. So, far I am able to detect documents with single colour or documents which are clearly distinguishable from background. But the problem arises when the document is of multi-color. To clearly understand the problem , I have attached an image: As you can see, the blue line is a detection line and it is not detecting full document. What i did so far is as below : original image -> cvtColor -> GaussianBlur filter -> dilate it to sharpen edges -> applied watershed image segmentation algorithm -> canny edge detection with dynamic otsu's threshold -> then find largest contours -> draw contours After some research, I came to know that the problem rely on canny edge detection. Below is the result I get after canny edge detection: Is there any way to achieve this? Any help will be highly appreciated !! Thanks in advance
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:891330", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624760" }
b47018f5d4fd761e0e37cebfe1904c6f9b557d82
Stackoverflow Stackexchange Q: Is `int` always signed? I always thought that in C, int stands for signed int ; but I have heard that this behavior is platform specific and in some platforms, int is unsigned by default. Is it true? What says the standard, and has it evolved over time? A: int, signed, and signed int are all the same type. The exact form of int is implementation specific; the range must be at least -32767 to +32767. There is no upper limit on the range. Note also that the complement scheme can differ too: 2's complement is common these days although 1's complement and signed magnitude are also allowed.
Q: Is `int` always signed? I always thought that in C, int stands for signed int ; but I have heard that this behavior is platform specific and in some platforms, int is unsigned by default. Is it true? What says the standard, and has it evolved over time? A: int, signed, and signed int are all the same type. The exact form of int is implementation specific; the range must be at least -32767 to +32767. There is no upper limit on the range. Note also that the complement scheme can differ too: 2's complement is common these days although 1's complement and signed magnitude are also allowed. A: According to this Wikipedia article, int is a signed integral data type which is at least 16 bits in size. A: You are quite right. As per C11 (the latest c standard), chapter §6.7.2 * *int, signed, or signed int is categorized as same type (type specifiers, to be exact). So, int is the same as signed int. Also, re-iterating the same, from chapter §6.2.5/P4 There are five standard signed integer types, designated as signed char, short int, int, long int, and long long int. (These and other types may be designated in several additional ways, as described in 6.7.2.) [....] So, for any conforming environment, int stands for signed int and vice versa.
stackoverflow
{ "language": "en", "length": 224, "provenance": "stackexchange_0000F.jsonl.gz:891354", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624857" }
e933479bc47c0000230cc0d3bddefeb8c5dbba65
Stackoverflow Stackexchange Q: Spring Security OAuth with JWK Example Does someone have a Spring Security OAuth 2 resource server (SP) example with JWT and asymmetric keys which is using JWK with a JWKS endpoint? Thanks a lot. Essey A: Spring Security OAuth 2 resource server can be configured to use JWK. If you are using Spring Boot, you only need to use the property security.oauth2.resource.jwk.key-set-uri to configure the JWKS endpoint. That is the only special difference with the plenty of samples you might find online.
Q: Spring Security OAuth with JWK Example Does someone have a Spring Security OAuth 2 resource server (SP) example with JWT and asymmetric keys which is using JWK with a JWKS endpoint? Thanks a lot. Essey A: Spring Security OAuth 2 resource server can be configured to use JWK. If you are using Spring Boot, you only need to use the property security.oauth2.resource.jwk.key-set-uri to configure the JWKS endpoint. That is the only special difference with the plenty of samples you might find online.
stackoverflow
{ "language": "en", "length": 83, "provenance": "stackexchange_0000F.jsonl.gz:891355", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624861" }
da403322c5e62e12afc7c98b886ef52e10c1ba93
Stackoverflow Stackexchange Q: Fetching data with Redux What are the advantages of fetching data with Redux as described here compared to just using the regular pattern with class Posts extends Component { state = { posts: [] }; componentDidMount() { fetch(url).then(res => this.setState({ posts: res.json().posts }); } render() { return ... } } Is it to make asynchronous fetching easier? Does it make it easier to persist the data in the store, so I can retrieve it when I reopen the app without having to fetch again? A: It is actually not a question about why to fetch data from async actions, it seems you need to understand what advantages Redux library as a whole brings. Read the article from Redux library author, whether you actually need Redux or not, or what advantages it brings: https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367
Q: Fetching data with Redux What are the advantages of fetching data with Redux as described here compared to just using the regular pattern with class Posts extends Component { state = { posts: [] }; componentDidMount() { fetch(url).then(res => this.setState({ posts: res.json().posts }); } render() { return ... } } Is it to make asynchronous fetching easier? Does it make it easier to persist the data in the store, so I can retrieve it when I reopen the app without having to fetch again? A: It is actually not a question about why to fetch data from async actions, it seems you need to understand what advantages Redux library as a whole brings. Read the article from Redux library author, whether you actually need Redux or not, or what advantages it brings: https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367 A: There is not necessarily an advantage to fetching data with Redux, but more of an advantage of knowing what is going on when using Redux to fetch data. Almost always its going to be the exact same flow. * *We are going to render a component on the screen. Such as your Posts or PostList component which needs to get a list of posts from the json api in order to show itself correctly. As a result I will define a componentDidMount() method on a class. That is why I created PostList to be a class based component, to ensure I had access to lifecycle methods. *Inside the componentDidMount() lifecycle method we are going to place an action creator. So anytime our component shows up on the screen the action creator will be automatically called. *The action creator will have some code inside that will use axios or fetch, but in my case I prefer axios, to make the API request over to the json api. *After the request is made, the api will respond with some amount of data. Once we get back the data, *Our action creator will do what it always should do which is to return an action and the action object will have a fetch data on the payload property. We are going to return the action from an action creator and the dispatch method will dispatch that action and send it off to all the different reducers inside our app. We will have some specially configured reducer that will be watching for an action of type whatever we gave it. The reducer will see the action, pull off the data from the payload property. *The reducer will run and produce a new state object and it will be sent off to the react side of the application. This will cause the react side of our application to be re-rendered with the json api data we got back. We can use the mapStateToProps() to get that json api data, lets say its a list of posts. We get it out of the global state object and into our component. Some notes around each step. Placing an action creator into a componentDidMount() lifecycle method is a common practice. We want to ensure components themselves are responsible for data they need by calling an action creator usually from within a lifecycle method. There are some other places where you can call an action creator to fetch data but that involves other libraries not mentioned here. The most common place will be the componentDidMount() lifecycle method. Regarding the action creators, we generally will ensure that action creators are responsible for making our API request. In some case you might put together some external class or service that is going to do the actual request for us, but in general its the action creator that will do the initial fetching of the api data. Enter stage left is Redux-Thunk. Last thing, when you fetch data and get it into a component you always make use of the mapStateToProps function to get data from the redux store and into the component.
stackoverflow
{ "language": "en", "length": 656, "provenance": "stackexchange_0000F.jsonl.gz:891361", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44624874" }
8db3ca425c05663989e605e358fb84ac2056e469
Stackoverflow Stackexchange Q: How to draw a dynamic line or curve per frame in SceneKit I have a Metal-backed SceneKit project where I'd like to draw a curve that is modified on the CPU every frame. This seems like it should be a simple task; one that I've done in OpenGL many times. Something like: array_of_points[0].x = 25 array_of_points[0].y = 35 upload_array_to_gpu() render_frame() It seems that modifying the SCNGeometrySource of an SCNNode is not possible. Recreating and setting the node.geometry works but the position lags / jitters compared to other nodes in the scene. Recreating the entire node each frame also lags. One possible avenue might be a geometry shader modifier, but I'd still have to somehow pass in my cpu-computed curve positions. Another option is to use metal APIs directly. Though this approach seems like it will require lots more code, and I couldn't find too much info about mixing SceneKit with Metal. I also tried setting the preferredRenderingAPI to OpenGL, but it doesn't change the renderingAPI.
Q: How to draw a dynamic line or curve per frame in SceneKit I have a Metal-backed SceneKit project where I'd like to draw a curve that is modified on the CPU every frame. This seems like it should be a simple task; one that I've done in OpenGL many times. Something like: array_of_points[0].x = 25 array_of_points[0].y = 35 upload_array_to_gpu() render_frame() It seems that modifying the SCNGeometrySource of an SCNNode is not possible. Recreating and setting the node.geometry works but the position lags / jitters compared to other nodes in the scene. Recreating the entire node each frame also lags. One possible avenue might be a geometry shader modifier, but I'd still have to somehow pass in my cpu-computed curve positions. Another option is to use metal APIs directly. Though this approach seems like it will require lots more code, and I couldn't find too much info about mixing SceneKit with Metal. I also tried setting the preferredRenderingAPI to OpenGL, but it doesn't change the renderingAPI.
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:891409", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625041" }
60ffa66dfa5d5f26f8c9b9149356b1a42c76c251
Stackoverflow Stackexchange Q: How to set cache control in aws s3 object while uploading in java? I tried the following options, but none of them will work * *metadata.setCacheControl("max-age=604800, must-revalidate"); *metadata.addUserMetadata("x-amz-meta-Cache-Control", "max-age=31536000, must-revalidate"); *metadata.setHeader("x-amz-meta-Cache-Control", "max-age=31536000, must-revalidate"); *metadata.addUserMetadata("Cache-Control", "max-age=31536000, must-revalidate"); Kindly help me to resolve this... A: First one is the correct approach, what i did wrong is, passed metadata via PutObjectRequest instead of TransferManager upload method. Need to pass metadata in TransferManager upload method. metadata.setCacheControl("max-age=604800, must-revalidate"); Not Correct: ObjectMetadata metadata = new ObjectMetadata(); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, PREFIX + folderName + DELIMITER, null, metadata); correct : ObjectMetadata metadata = new ObjectMetadata(); metadata.setCacheControl("max-age=31536000, must-revalidate"); Upload upload = transferManager.upload(bucketName, PREFIX + folderName + DELIMITER + fileName, fileStream, metadata); Now its working fine.
Q: How to set cache control in aws s3 object while uploading in java? I tried the following options, but none of them will work * *metadata.setCacheControl("max-age=604800, must-revalidate"); *metadata.addUserMetadata("x-amz-meta-Cache-Control", "max-age=31536000, must-revalidate"); *metadata.setHeader("x-amz-meta-Cache-Control", "max-age=31536000, must-revalidate"); *metadata.addUserMetadata("Cache-Control", "max-age=31536000, must-revalidate"); Kindly help me to resolve this... A: First one is the correct approach, what i did wrong is, passed metadata via PutObjectRequest instead of TransferManager upload method. Need to pass metadata in TransferManager upload method. metadata.setCacheControl("max-age=604800, must-revalidate"); Not Correct: ObjectMetadata metadata = new ObjectMetadata(); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, PREFIX + folderName + DELIMITER, null, metadata); correct : ObjectMetadata metadata = new ObjectMetadata(); metadata.setCacheControl("max-age=31536000, must-revalidate"); Upload upload = transferManager.upload(bucketName, PREFIX + folderName + DELIMITER + fileName, fileStream, metadata); Now its working fine.
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:891419", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625086" }
7976324fc771062a890980e6cdd73ba34d2fd16a
Stackoverflow Stackexchange Q: Duplicate resources on “ionic cordova build android” command. Firebase plugin I'm building a fresh new application for android with the following plugins and commands. Cordova plugin add cordova-plugin-fcm, ionic cordova build android. This is the error displayed: Parsing json file: /home/faichi/palav-ui/platforms/android/google-services.json :generateDebugResources :mergeDebugResources [string/google_app_id] /home/faichi/palav-ui/platforms/android/res/values/strings.xml [string/google_app_id] /home/faichi/palav-ui/platforms/android/build/generated/res/google-services/debug/values/values.xml: Error: Duplicate resources :mergeDebugResources FAILED BUILD FAILED Total time: 1.683 secs FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':mergeDebugResources'. > [string/google_app_id] /home/faichi/palav-ui/platforms/android/res/values/strings.xml [string/google_app_id] /home/faichi/palav-ui/platforms/android/build/generated/res/google-services/debug/values/values.xml: Error: Duplicate resources * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Error: /home/faichi/palav-ui/platforms/android/gradlew: Command failed with exit code 1 Error output: FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':mergeDebugResources'. > [string/google_app_id] /home/faichi/palav-ui/platforms/android/res/values/strings.xml [string/google_app_id] /home/faichi/palav-ui/platforms/android/build/generated/res/google-services/debug/values/values.xml: Error: Duplicate resources I've tried to delete the duplicate values on android\res\values\strings.xml but on each build its coming back and display the same error. Is this is currect way to build a cordova based application with fire bash push notification service ?
Q: Duplicate resources on “ionic cordova build android” command. Firebase plugin I'm building a fresh new application for android with the following plugins and commands. Cordova plugin add cordova-plugin-fcm, ionic cordova build android. This is the error displayed: Parsing json file: /home/faichi/palav-ui/platforms/android/google-services.json :generateDebugResources :mergeDebugResources [string/google_app_id] /home/faichi/palav-ui/platforms/android/res/values/strings.xml [string/google_app_id] /home/faichi/palav-ui/platforms/android/build/generated/res/google-services/debug/values/values.xml: Error: Duplicate resources :mergeDebugResources FAILED BUILD FAILED Total time: 1.683 secs FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':mergeDebugResources'. > [string/google_app_id] /home/faichi/palav-ui/platforms/android/res/values/strings.xml [string/google_app_id] /home/faichi/palav-ui/platforms/android/build/generated/res/google-services/debug/values/values.xml: Error: Duplicate resources * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Error: /home/faichi/palav-ui/platforms/android/gradlew: Command failed with exit code 1 Error output: FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':mergeDebugResources'. > [string/google_app_id] /home/faichi/palav-ui/platforms/android/res/values/strings.xml [string/google_app_id] /home/faichi/palav-ui/platforms/android/build/generated/res/google-services/debug/values/values.xml: Error: Duplicate resources I've tried to delete the duplicate values on android\res\values\strings.xml but on each build its coming back and display the same error. Is this is currect way to build a cordova based application with fire bash push notification service ?
stackoverflow
{ "language": "en", "length": 176, "provenance": "stackexchange_0000F.jsonl.gz:891421", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625093" }
35fe826f913d8273c90913ea0c6688747a548045
Stackoverflow Stackexchange Q: Sharing across view in Laravel 5.4 I have a project where users are assgned to a client and I wannt to share that info across views. In AppServiceProvider I added use View; use Auth; and then amended boot to if ( Auth::check() ) { $cid = Auth::user()->client_id; $company = \App\Clients::first($cid); view::share('company',$company); } but if I dd($company) I get Undefined variable: company A: This is because of the Auth is not working in AppServiceProvider So your If condition return false if you share data with all the views then your code like this without check Auth. then It will work. $company = 'Some value'; view::share('company',$company); dd($company); // for print output. Solution - For Alternate option you have to make Helper class.
Q: Sharing across view in Laravel 5.4 I have a project where users are assgned to a client and I wannt to share that info across views. In AppServiceProvider I added use View; use Auth; and then amended boot to if ( Auth::check() ) { $cid = Auth::user()->client_id; $company = \App\Clients::first($cid); view::share('company',$company); } but if I dd($company) I get Undefined variable: company A: This is because of the Auth is not working in AppServiceProvider So your If condition return false if you share data with all the views then your code like this without check Auth. then It will work. $company = 'Some value'; view::share('company',$company); dd($company); // for print output. Solution - For Alternate option you have to make Helper class. A: At the time the providers boot is run, the Auth guard has not been booted, so Auth::check() returns false, and Auth::user() returns null. You could do the View::share in a middleware, or perhaps in the constructor of a controller (the base controller to share it across the whole application, or some particular controller if you need it in some subset of routes).
stackoverflow
{ "language": "en", "length": 184, "provenance": "stackexchange_0000F.jsonl.gz:891428", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625119" }
51d78e64d09d6c8367e4cf9b40098373dcbca8a4
Stackoverflow Stackexchange Q: aws s3 sync with metadata possible? I want to regularily backup an S3 bucket (total size ~20GB, ~200k files) to a local filesystem. aws s3 sync s3://... ./data looks to be good for this task but AFAIK does not copy metadata to the filesystem, which is bad because the files in the backup store important metadata (mainly, if the file is gzip compressed or not). Can aws s3 or any similar tool copy metadata to the local file system (for example to xattr or a separate "metadata database")?
Q: aws s3 sync with metadata possible? I want to regularily backup an S3 bucket (total size ~20GB, ~200k files) to a local filesystem. aws s3 sync s3://... ./data looks to be good for this task but AFAIK does not copy metadata to the filesystem, which is bad because the files in the backup store important metadata (mainly, if the file is gzip compressed or not). Can aws s3 or any similar tool copy metadata to the local file system (for example to xattr or a separate "metadata database")?
stackoverflow
{ "language": "en", "length": 89, "provenance": "stackexchange_0000F.jsonl.gz:891438", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625145" }
c8178a98854cd0b1c4d1d9b5aa15aa6d84104cfe
Stackoverflow Stackexchange Q: How to create Named colors in Interface Builder? How do I setup & use custom named colors in Interface Builder? A: In Xcode9 you can add "New Color Set" to .xcassets files, where you can set rgba values or use IB's color picker. Then you can use that newly defined color from Interface Builder's color picker, it appears under the Named Colors section. Or you can use it from code like UIColor(named:"customColorName"). As for now, Xcode9 beta 1 does not support using string literal color names as UIColor (like it works with UIImages), but I hope it will work in a later release. Unfortunatelly it's only available for iOS11 and later.
Q: How to create Named colors in Interface Builder? How do I setup & use custom named colors in Interface Builder? A: In Xcode9 you can add "New Color Set" to .xcassets files, where you can set rgba values or use IB's color picker. Then you can use that newly defined color from Interface Builder's color picker, it appears under the Named Colors section. Or you can use it from code like UIColor(named:"customColorName"). As for now, Xcode9 beta 1 does not support using string literal color names as UIColor (like it works with UIImages), but I hope it will work in a later release. Unfortunatelly it's only available for iOS11 and later.
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:891465", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625223" }
21f861dd1ecfbca7377ff131ed9f29b1ca369cde
Stackoverflow Stackexchange Q: Python/Pandas - How to group by two columns and count rows with value from third column between two numbers I need to group my data frame by two columns and after that count the occurrences of values from third column, which are between 1 and 20. Data frame: col1 col2 value a b 1 a b 3 a b 22 a c 0 a c 3 a c 19 Result: col1 col2 counter a b 2 a c 2 My code: counter = data_frame.groupby(['column1', 'column2'])[((data_frame['value'] >= 1) & (data_frame['value'] < 20))].sum() Any ideas? A: You need filter first by boolean indexing or query and then groupby with aggregating size: df = data_frame[(data_frame['value'] >= 1) & (data_frame['value'] < 20)] df = df.groupby(['col1', 'col2']).size().reset_index(name='counter') print (df) col1 col2 counter 0 a b 2 1 a c 2 Or: df = data_frame.query('value >= 1 & value < 20') df = df.groupby(['col1', 'col2']).size().reset_index(name='counter') print (df) col1 col2 counter 0 a b 2 1 a c 2 What is the difference between size and count in pandas?
Q: Python/Pandas - How to group by two columns and count rows with value from third column between two numbers I need to group my data frame by two columns and after that count the occurrences of values from third column, which are between 1 and 20. Data frame: col1 col2 value a b 1 a b 3 a b 22 a c 0 a c 3 a c 19 Result: col1 col2 counter a b 2 a c 2 My code: counter = data_frame.groupby(['column1', 'column2'])[((data_frame['value'] >= 1) & (data_frame['value'] < 20))].sum() Any ideas? A: You need filter first by boolean indexing or query and then groupby with aggregating size: df = data_frame[(data_frame['value'] >= 1) & (data_frame['value'] < 20)] df = df.groupby(['col1', 'col2']).size().reset_index(name='counter') print (df) col1 col2 counter 0 a b 2 1 a c 2 Or: df = data_frame.query('value >= 1 & value < 20') df = df.groupby(['col1', 'col2']).size().reset_index(name='counter') print (df) col1 col2 counter 0 a b 2 1 a c 2 What is the difference between size and count in pandas? A: You need to filter those value first, then you can use the groupby and the count functions like this : df[(df.value<=20) & (df.value >= 1)].groupby(['col1','col2']).count().reset_index() output : col1 col2 value 0 a b 2 1 a c 2 100 loops, best of 3: 2.5 ms per loop
stackoverflow
{ "language": "en", "length": 221, "provenance": "stackexchange_0000F.jsonl.gz:891476", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625267" }
f9b5c1fdccdc6ee31b1a975bdc75d58a9806c7fa
Stackoverflow Stackexchange Q: IntelliJ IDEA - Asterisk after author's name in git log In our git log we sometimes see an asterisk after the user name in the Author column. The same user is listed without the asterisk in other commits. What does the asterisk stand for? I'm using IntelliJ IDEA 15.0.6. A: Every change in GIT (and in the most of modern VCS's) has an author and a committer. The Log shows an author because we respect authorship even if the author of changes doesn't have access to the repo or isn't able to commit code by himself. Asterisk on the author's name in the Log means that this commit was created by the described person, but was applied by someone else. Here is an illustration of how it looks: There are some common cases when this happens: * *you cherrypicked someone else's commit *you rebased branch with someone else's commits *you applied .patch file mailed to you by someone else *you merged the pull-request via GitHub UI - GitHub does it with its own user but leaves authorship to you.
Q: IntelliJ IDEA - Asterisk after author's name in git log In our git log we sometimes see an asterisk after the user name in the Author column. The same user is listed without the asterisk in other commits. What does the asterisk stand for? I'm using IntelliJ IDEA 15.0.6. A: Every change in GIT (and in the most of modern VCS's) has an author and a committer. The Log shows an author because we respect authorship even if the author of changes doesn't have access to the repo or isn't able to commit code by himself. Asterisk on the author's name in the Log means that this commit was created by the described person, but was applied by someone else. Here is an illustration of how it looks: There are some common cases when this happens: * *you cherrypicked someone else's commit *you rebased branch with someone else's commits *you applied .patch file mailed to you by someone else *you merged the pull-request via GitHub UI - GitHub does it with its own user but leaves authorship to you. A: That (the asterisk) is usually when another user has rebased the commits of the original author. You can confirm this in the message window on the lower right. It will show you the original author along with "committed by" with the name of the user who did the rebase. A: It indicates that commit is the most recent commit to modify the file. Annotations for lines modified in the current revision are marked with a bold type and an asterisk. https://www.jetbrains.com/help/idea/investigate-changes.html#annotate_blame A: As described in the source provided by @CrazyCoder the asterisk indicates that the branch was created by a different user. A: I think it signifies a commit issue. I see it in my company's codebase in what I believe is a missed merge. I see it with a Git log --graph command as well as in Intellij. This isn't suppose to happen, but it appears that there are two remote branches, BA and BB, both from the master. * *Developer Alice checks out remote branch BA. *Developer Bob checks out remote branch BB and merges in changes in the master branch. *Alice updates, commits, and pushes her local BA to the remote BA. *Alice makes a pull request to get her change in the master branch. *Meanwhile, Bob has committed and pushed his changes to BB. *Merge master Meg performs the pull. So BB, which Bob committed after Meg merged Alice's change to BA, does not contain the changes. In other words, BB is based on the pre-BA changes. Git is smart enough to see the problem and alert you with this obscure, seemingly undocumented feature. I'm a n00b when it comes to Git, so I may be wrong. Look for commit issues with the asterisked commit. A: The Asterisk in Intellij blame lines marked by asterisk in Intellij blame means that those lines are commit of the last / most recent commit in the code. here is the link with more details. Click [here]https://www.jetbrains.com/help/idea/investigate-changes.html#annotate_blame:~:text=Annotations%20for%20lines%20modified%20in%20the%20current%20revision%20are%20marked%20with%20a%20bold%20type%20and%20an%20asterisk.
stackoverflow
{ "language": "en", "length": 508, "provenance": "stackexchange_0000F.jsonl.gz:891477", "question_score": "63", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625270" }
da3ccb6563a7b8c6399acc62fe21cf899e43578e
Stackoverflow Stackexchange Q: Move code from Mercurial to Bitbucket Currently, I have Mercurial as my version control in Kiln server. I want to migrate my code to Bitbucket server with Git. I have tried the import option available in Bitbucket but I can only import as a Mercurial repository. Is there any possible way to achieve this? A: Except the fast-export tool, there is an easy way to migrate Hg to git: Initial a local git repo mkdir git cd git git init Clone hg repo cd .. hg clone <URL for hg_repo> cd <hg_repo> hg bookmarks hg hg push ../git Get changes from hg repo in local git repo cd ../git git checkout hg Create an empty git repo on bitbucket, and push local git repo to it git remote add origin <URL for bitbucket repo> git push -u origin hg
Q: Move code from Mercurial to Bitbucket Currently, I have Mercurial as my version control in Kiln server. I want to migrate my code to Bitbucket server with Git. I have tried the import option available in Bitbucket but I can only import as a Mercurial repository. Is there any possible way to achieve this? A: Except the fast-export tool, there is an easy way to migrate Hg to git: Initial a local git repo mkdir git cd git git init Clone hg repo cd .. hg clone <URL for hg_repo> cd <hg_repo> hg bookmarks hg hg push ../git Get changes from hg repo in local git repo cd ../git git checkout hg Create an empty git repo on bitbucket, and push local git repo to it git remote add origin <URL for bitbucket repo> git push -u origin hg A: You probably need to do the Mercurial -> Git conversion on your own machine with a tool like fast-export. You then create a new repo on Bitbucket and follow the instructions to push your project to it. You shouldn't hit any major roadblocks. This answer will give you further information on how to do it. A: I have a very positive experience with git-remote-hg.
stackoverflow
{ "language": "en", "length": 205, "provenance": "stackexchange_0000F.jsonl.gz:891483", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625288" }
fb3caf1d9901a975717fec5fa4403aebb390cb96
Stackoverflow Stackexchange Q: Get all documents from an index - elasticsearch How can I get all documents from an index in elasticsearch without determining the size in the query like GET http://localhost:8090/my_index/_search?size=1000&scroll=1m&pretty=true'-d '{"size": 0,"query":{"query_string":{ "match_all" : {}}}} Thanks A: According to the ES scan query documentation, size parameter is not just the number of results: The size parameter allows you to configure the maximum number of hits to be returned with each batch of results. Each call to the scroll API returns the next batch of results until there are no more results left to return, ie the hits array is empty. To retrieve all the results you need to do subsequent calls to the API in the manner described in the aforementioned documentation, or to use some ready made implementation, like there is in python. Here is an example script to dump resulting jsons on stdout: import elasticsearch from elasticsearch.helpers import scan import json es = elasticsearch.Elasticsearch('https://localhost:8090') es_response = scan( es, index='my_index', doc_type='my_doc_type', query={"query": { "match_all" : {}}} ) for item in es_response: print(json.dumps(item))
Q: Get all documents from an index - elasticsearch How can I get all documents from an index in elasticsearch without determining the size in the query like GET http://localhost:8090/my_index/_search?size=1000&scroll=1m&pretty=true'-d '{"size": 0,"query":{"query_string":{ "match_all" : {}}}} Thanks A: According to the ES scan query documentation, size parameter is not just the number of results: The size parameter allows you to configure the maximum number of hits to be returned with each batch of results. Each call to the scroll API returns the next batch of results until there are no more results left to return, ie the hits array is empty. To retrieve all the results you need to do subsequent calls to the API in the manner described in the aforementioned documentation, or to use some ready made implementation, like there is in python. Here is an example script to dump resulting jsons on stdout: import elasticsearch from elasticsearch.helpers import scan import json es = elasticsearch.Elasticsearch('https://localhost:8090') es_response = scan( es, index='my_index', doc_type='my_doc_type', query={"query": { "match_all" : {}}} ) for item in es_response: print(json.dumps(item)) A: As per the latest documentation, you will have to use the search_after parameter to retrieve records more than 10,000 from an index. take a look here https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#search-after
stackoverflow
{ "language": "en", "length": 201, "provenance": "stackexchange_0000F.jsonl.gz:891487", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625303" }
38e8440a4fed1794e9fcaffb4881e497d29a02b7
Stackoverflow Stackexchange Q: Angular test keyup does not working I have a simple component with input. I want to test some functionality on keyup, but when I run the test with Chrome, I don't see any output on the input. it('should be...', function () { const input = fixture.debugElement.query(By.css('input')); input.triggerEventHandler('keydown', { keyCode: 67 }); input.triggerEventHandler('keyup', { keyCode: 67 }); fixture.detectChanges(); }); What I am missing?
Q: Angular test keyup does not working I have a simple component with input. I want to test some functionality on keyup, but when I run the test with Chrome, I don't see any output on the input. it('should be...', function () { const input = fixture.debugElement.query(By.css('input')); input.triggerEventHandler('keydown', { keyCode: 67 }); input.triggerEventHandler('keyup', { keyCode: 67 }); fixture.detectChanges(); }); What I am missing?
stackoverflow
{ "language": "en", "length": 63, "provenance": "stackexchange_0000F.jsonl.gz:891488", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625306" }
8483e7b717c071c8075ad0272513b0827be81666
Stackoverflow Stackexchange Q: How to add a pivot table filter field using EPPlus and C# I'm creating an Excel file using the EPPlus library and C#. In this Excel file there is a sheet with pivot table to which I'd like to add a filter field like in this manually created Excel sheet (Country): How can I do this using EPPlus? A: I did not see your code, but you can do something like this. var ws = excelPackage.Workbook.Worksheets["index of your worksheet"]; var pivotTable = ws.PivotTables[0]; //assuming that you only have 1 var pivotField = pivotTable.Fields["Country"]; pivotTable.PageFields.Add(pivotField); // should add field into desired place Hope it´s a little bit helpful. Don´t forget to save your excel file at the end.
Q: How to add a pivot table filter field using EPPlus and C# I'm creating an Excel file using the EPPlus library and C#. In this Excel file there is a sheet with pivot table to which I'd like to add a filter field like in this manually created Excel sheet (Country): How can I do this using EPPlus? A: I did not see your code, but you can do something like this. var ws = excelPackage.Workbook.Worksheets["index of your worksheet"]; var pivotTable = ws.PivotTables[0]; //assuming that you only have 1 var pivotField = pivotTable.Fields["Country"]; pivotTable.PageFields.Add(pivotField); // should add field into desired place Hope it´s a little bit helpful. Don´t forget to save your excel file at the end.
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:891492", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625321" }
53bf9b4d9a67bfde0c6c88c33c36874ab1fafd20
Stackoverflow Stackexchange Q: searching query to mysql in angularjs using ng-keyup but $http only after 3 seconds I want to make online search in angularjs, using ng-keyup function. But I suppose that it is wrong to make query to BD on each keyup. So how can I set timer that will make $http service work only if in last 3 second there were no keyups? <input type="text" ng-keyup="search(param.values, param.url)"> JS: app.controller('searchCtrl', function($scope,$rootScope,$http){ $scope.search = function( values , type) { var data={}; data.values=values; data.type=type; console.log(data); $http.post("search.php", data).then(function success (response) { console.log(response.data); $rootScope.search_result=response.data; },function error (response){ console.log(response.data); } ); }; }); A: You could use ng-model-options to debounce your input value which will tell angular to update ng-model to update after a particular amount of time. Then switch to ng-change event would make more sense instead of ng-keyup. In short, we use debounce to delay our API call. <input type="text" ng-model="value" ng-change="search(param.values, param.url)" ng-model-options="{ debounce: 3000 }"
Q: searching query to mysql in angularjs using ng-keyup but $http only after 3 seconds I want to make online search in angularjs, using ng-keyup function. But I suppose that it is wrong to make query to BD on each keyup. So how can I set timer that will make $http service work only if in last 3 second there were no keyups? <input type="text" ng-keyup="search(param.values, param.url)"> JS: app.controller('searchCtrl', function($scope,$rootScope,$http){ $scope.search = function( values , type) { var data={}; data.values=values; data.type=type; console.log(data); $http.post("search.php", data).then(function success (response) { console.log(response.data); $rootScope.search_result=response.data; },function error (response){ console.log(response.data); } ); }; }); A: You could use ng-model-options to debounce your input value which will tell angular to update ng-model to update after a particular amount of time. Then switch to ng-change event would make more sense instead of ng-keyup. In short, we use debounce to delay our API call. <input type="text" ng-model="value" ng-change="search(param.values, param.url)" ng-model-options="{ debounce: 3000 }" A: Waiting for a few seconds in a search module is not very ergonomic / user friendly. What we usually do is cancel the previous request each time a new character is entered by the user. You can do this by passing a promise to the timeout property of you $http request. $http.get(request, {timeout: promise}).then... You initialise the promise at the start of your search function: abort = $q.defer(); This way, each time the function is called, you can check if there's a promise and resolve it (cancel it) before making a new request. if(abort) { abort.resolve(); } Check out the working plunker. (and open the console to see requests being cancelled as you type.)
stackoverflow
{ "language": "en", "length": 268, "provenance": "stackexchange_0000F.jsonl.gz:891502", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625348" }
2ac7800a40c38c81f8c91cc564e6a9b24aa324d5
Stackoverflow Stackexchange Q: Why is bower not using my bower.json resolutions? I have a project I need to use angularjs 1.2 with. I have a bower.json file with the following: { "name": "myproject", "dependencies": { "angular": "1.2.32" }, "resolutions": { "angular": "1.2.32" } } When I install angular it asks me which version I want, although it should not if I understood correctly. And when I try to install another project like angular-route it asks again and even installs the wrong one: bower install angular-route bower angular-route#* cached https://github.com/angular/bower-angular-route.git#1.6.4 bower angular-route#* validate 1.6.4 against https://github.com/angular/bower-angular-route.git#* bower angular#1.6.4 cached https://github.com/angular/bower-angular.git#1.6.4 bower angular#1.6.4 validate 1.6.4 against https://github.com/angular/bower-angular.git#1.6.4 Unable to find a suitable version for angular, please choose one by typing one of the numbers below: 1) angular#1.2.32 which resolved to 1.2.32 and is required by angamcharts2 2) angular#1.6.4 which resolved to 1.6.4 and is required by angular-route#1.6.4 Prefix the choice with ! to persist it to bower.json ? Answer !1 bower angular resolution Saved angular#1.2.32 as resolution bower angular-route#^1.6.4 install angular-route#1.6.4 angular-route#1.6.4 bower_components/angular-route └── angular#1.2.32 I know there is angular-route 1.2.32 but I don't want to install all my packages by hand with the correct version. Why is the "resolutions" not working?
Q: Why is bower not using my bower.json resolutions? I have a project I need to use angularjs 1.2 with. I have a bower.json file with the following: { "name": "myproject", "dependencies": { "angular": "1.2.32" }, "resolutions": { "angular": "1.2.32" } } When I install angular it asks me which version I want, although it should not if I understood correctly. And when I try to install another project like angular-route it asks again and even installs the wrong one: bower install angular-route bower angular-route#* cached https://github.com/angular/bower-angular-route.git#1.6.4 bower angular-route#* validate 1.6.4 against https://github.com/angular/bower-angular-route.git#* bower angular#1.6.4 cached https://github.com/angular/bower-angular.git#1.6.4 bower angular#1.6.4 validate 1.6.4 against https://github.com/angular/bower-angular.git#1.6.4 Unable to find a suitable version for angular, please choose one by typing one of the numbers below: 1) angular#1.2.32 which resolved to 1.2.32 and is required by angamcharts2 2) angular#1.6.4 which resolved to 1.6.4 and is required by angular-route#1.6.4 Prefix the choice with ! to persist it to bower.json ? Answer !1 bower angular resolution Saved angular#1.2.32 as resolution bower angular-route#^1.6.4 install angular-route#1.6.4 angular-route#1.6.4 bower_components/angular-route └── angular#1.2.32 I know there is angular-route 1.2.32 but I don't want to install all my packages by hand with the correct version. Why is the "resolutions" not working?
stackoverflow
{ "language": "en", "length": 198, "provenance": "stackexchange_0000F.jsonl.gz:891505", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625357" }
dbe076510ef12cfe175b474599389886dd755ff2
Stackoverflow Stackexchange Q: Getting meeting invites & events for the specific day for the logged in user using microsoft Graph API in UWP I am working on a UWP app that's getting data from Microsoft Graph API. I need to get the list of all the meetings scheduled for the day for the logged in user. I am authenticating the user from Azure AD and I am setting up few meetings/events according to my timezone. I want to only fetch data for the current user based on his geography time and geography for the same day. Example: Currently in India, If I set up a meeting at 7 PM IST, the same shall get converted to his current time zone and show. I am using this API string _graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me/events?$select=subject,body,bodyPreview,organizer,attendees,start,end,location" (https://graph.microsoft.com/v1.0/me/events?$select=subject,body,bodyPreview,organizer,attendees,start,end,location') ; but I want to limit his meetings based on his login time -meetings that are passed, shouldn't be displayed. Can anyone look into this ? A: You want to use a calendar view here. That way you can specify a start and end time and get back all events between the two.
Q: Getting meeting invites & events for the specific day for the logged in user using microsoft Graph API in UWP I am working on a UWP app that's getting data from Microsoft Graph API. I need to get the list of all the meetings scheduled for the day for the logged in user. I am authenticating the user from Azure AD and I am setting up few meetings/events according to my timezone. I want to only fetch data for the current user based on his geography time and geography for the same day. Example: Currently in India, If I set up a meeting at 7 PM IST, the same shall get converted to his current time zone and show. I am using this API string _graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me/events?$select=subject,body,bodyPreview,organizer,attendees,start,end,location" (https://graph.microsoft.com/v1.0/me/events?$select=subject,body,bodyPreview,organizer,attendees,start,end,location') ; but I want to limit his meetings based on his login time -meetings that are passed, shouldn't be displayed. Can anyone look into this ? A: You want to use a calendar view here. That way you can specify a start and end time and get back all events between the two.
stackoverflow
{ "language": "en", "length": 183, "provenance": "stackexchange_0000F.jsonl.gz:891506", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625359" }
6e93a41a193cd95e49236562feb270756475090b
Stackoverflow Stackexchange Q: Remove White space around image - CSS I'm trying to get image from odoo database to show the image into div background, but my image has white space around it, so i need to remove this white space to apply div background image, Mycode : <div t-attf-style="text-align:center;background:url('/web/image/event.event.ticket/#{doc.event_ticket_id.id}/image_medium') no-repeat; font-size:#{doc.event_ticket_id.font_size}px;width:50%;height:900px;float:left;background-size:500px 900px;display:table;"> <span style="vertical-align:middle;text-align:center;display:table-cell;" t-esc="doc.name"></span> </div> How to remove white space around images using CSS ? A: Maybe try one of these code's: img{vertical-align:bottom} or img { vertical-align: top; } or html, body { margin: 0; padding: 0; } Hope it helped.
Q: Remove White space around image - CSS I'm trying to get image from odoo database to show the image into div background, but my image has white space around it, so i need to remove this white space to apply div background image, Mycode : <div t-attf-style="text-align:center;background:url('/web/image/event.event.ticket/#{doc.event_ticket_id.id}/image_medium') no-repeat; font-size:#{doc.event_ticket_id.font_size}px;width:50%;height:900px;float:left;background-size:500px 900px;display:table;"> <span style="vertical-align:middle;text-align:center;display:table-cell;" t-esc="doc.name"></span> </div> How to remove white space around images using CSS ? A: Maybe try one of these code's: img{vertical-align:bottom} or img { vertical-align: top; } or html, body { margin: 0; padding: 0; } Hope it helped. A: You can try something like this .main{ text-align:center; background:url('https://i.stack.imgur.com/hQPzy.png') no-repeat; font-size:12px; width:50%; height:900px; float:left; background-size:500px 900px; display:table; background-position:-50px -35px; } <div class="main"> <span style="vertical-align:middle;text-align:center;display:table-cell;"> Content</span> </div> But you have to know size of white space of images. Then you can (-) the position. A: I have tried something. Please check it this works fine for you. Here I have tried to set background position and background size. Rest everything can vary like div's width and height. .back{ background: url('https://i.stack.imgur.com/hQPzy.png'); height: 200px; width: 200px; background-size: 130% 150%; border: 1px solid black; background-position: 42% 15%; } <div class="back"></div>
stackoverflow
{ "language": "en", "length": 188, "provenance": "stackexchange_0000F.jsonl.gz:891508", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625371" }
73e9806183b4b183fb867dc405966c828e0bd2b8
Stackoverflow Stackexchange Q: How to use reveal_type in mypy I have read that I can reveal the type of variables by using a function called reveal_type, but I can't find how to use it or from where to import it. A: I found out in the end how to use it: You should just put and use the reveal_type in the code, and run it with the mypy program. Then, it will log a message that look like this: Revealed type is 'builtins.str*' From the mypy documentation: reveal_type is only understood by mypy and doesn’t exist in Python, if you try to run your program. You’ll have to remove any reveal_type calls before you can run your code. reveal_type is always available and you don’t need to import it. For more reading: here.
Q: How to use reveal_type in mypy I have read that I can reveal the type of variables by using a function called reveal_type, but I can't find how to use it or from where to import it. A: I found out in the end how to use it: You should just put and use the reveal_type in the code, and run it with the mypy program. Then, it will log a message that look like this: Revealed type is 'builtins.str*' From the mypy documentation: reveal_type is only understood by mypy and doesn’t exist in Python, if you try to run your program. You’ll have to remove any reveal_type calls before you can run your code. reveal_type is always available and you don’t need to import it. For more reading: here.
stackoverflow
{ "language": "en", "length": 131, "provenance": "stackexchange_0000F.jsonl.gz:891519", "question_score": "66", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625422" }
ba5ddb6419b778f412c595e028b24715aa044a9d
Stackoverflow Stackexchange Q: SQL Server group by but select 'top' date I have a table in SQL server like so (Note the ID field is not unique): ----------------------------------- | ID | IsAdamBrown | DateComplete | | 1 | TRUE | 2017-01-01 | | 1 | TRUE | 2017-01-03 | ----------------------------------- I'd like to select one row for all the unique IDs in the table and the most recent 'DateComplete' for that ID. My desired output in this case would be: ----------------------------------- | ID | IsAdamBrown | DateComplete | | 1 | TRUE | 2017-01-03 | ----------------------------------- I've tried: SELECT DISTINCT DateComplete, ID, IsAdamBrown FROM thisTable WHERE IsAdamBrown IS NOT NULL GROUP BY DateComplete, ID, IsAdamBrown ORDER BY DateComplete DESC Unfortunately I still get the two date rows back. In MySQL I would group by just the first two rows and the ORDER BY would make sure the DateComplete was the most recent. SQL servers requirement that the SELECT fields match the GROUP BY makes this impossible. How can I get a single row back for each ID with the most recent DateComplete? A: SELECT id, isadambrown, Max(datecomplete) AS DateComplete FROM thistable GROUP BY id, isadambrown ORDER BY Max(datecomplete) DESC
Q: SQL Server group by but select 'top' date I have a table in SQL server like so (Note the ID field is not unique): ----------------------------------- | ID | IsAdamBrown | DateComplete | | 1 | TRUE | 2017-01-01 | | 1 | TRUE | 2017-01-03 | ----------------------------------- I'd like to select one row for all the unique IDs in the table and the most recent 'DateComplete' for that ID. My desired output in this case would be: ----------------------------------- | ID | IsAdamBrown | DateComplete | | 1 | TRUE | 2017-01-03 | ----------------------------------- I've tried: SELECT DISTINCT DateComplete, ID, IsAdamBrown FROM thisTable WHERE IsAdamBrown IS NOT NULL GROUP BY DateComplete, ID, IsAdamBrown ORDER BY DateComplete DESC Unfortunately I still get the two date rows back. In MySQL I would group by just the first two rows and the ORDER BY would make sure the DateComplete was the most recent. SQL servers requirement that the SELECT fields match the GROUP BY makes this impossible. How can I get a single row back for each ID with the most recent DateComplete? A: SELECT id, isadambrown, Max(datecomplete) AS DateComplete FROM thistable GROUP BY id, isadambrown ORDER BY Max(datecomplete) DESC A: You can get by GROUP BY with MAX() of DateComplete SELECT ID, IsAdamBrown, MAX(DateComplete) AS DateComplete FROM thisTable WHERE IsAdamBrown IS NOT NULL GROUP BY ID, IsAdamBrown ORDER BY MAX(DateComplete) DESC A: You can using LIMIT SELECT ID, IsAdamBrown, DateComplete FROM thisTable WHERE IsAdamBrown IS NOT NULL GROUP BY ID, IsAdamBrown ORDER BY DateComplete LIMIT 1 A: You can use this. I hope it will work for you. SELECT ID, IsAdamBrown, DateComplete FROM thisTable a WHERE DateComplete IN ( SELECT MAX(DateComplete) FROM thisTable b WHERE a.ID = b.ID GROUP BY b.ID ) ORDER BY DateComplete DESC A: You can use ROW_NUMBER() for grouping according to ID and a subquery to get the only first record with recent iscomplete. This will first sort your data according to id and recent iscomplete and then the first result for all the unique IDs SELECT X.ID, X.IsAdamBrown, X.DateComplete FROM ( SELECT ID, IsAdamBrown, DateComplete,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY DateComplete DESC) RN FROM thisTable WHERE IsAdamBrown IS NOT NULL ) X WHERE X.RN=1
stackoverflow
{ "language": "en", "length": 367, "provenance": "stackexchange_0000F.jsonl.gz:891547", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625516" }
7ff47796f182e824c1cbea50ae1cee27c50b6f29
Stackoverflow Stackexchange Q: iOS, UIGraphics How to change only alpha channel when you drawing round rect to create brush with glow effect I ma working on app that has brush tool. I need create brush like in Instagram. Currently I am using Shadow to create such glow effect. But I can't set such shadow effect. let startPoint = convertToOutput(firstPoint), endPoint = convertToOutput(secondPoint) UIGraphicsBeginImageContextWithOptions(self.outputCanvasSize, false, 1.0) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.setStrokeColor(color.cgColor) context?.setShadow(offset: CGSize(width:0, height: 0), blur: 20, color: color.cgColor) context?.setLineJoin(.round) context?.setLineCap(.round) context?.setLineWidth(brush.radius * 2) context?.move(to: startPoint) context?.addLine(to: endPoint) context?.drawPath(using: .stroke) glowOverlayCanvas.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() But effect isn't so good. So I what draw such brush using next algorithm: * *Draw colored smooth fill circles with 1px step, rad 20 px. *Then draw white fill circles foreground, without smooth, rad 5 px. I have a problem with blend mode, because if I use .normal, smooth effect disappear - alpha channel accumulate (few circles crossing) How to implement the following blend mode Rrgb = Srgb Ra = MAX(Da, Sa)
Q: iOS, UIGraphics How to change only alpha channel when you drawing round rect to create brush with glow effect I ma working on app that has brush tool. I need create brush like in Instagram. Currently I am using Shadow to create such glow effect. But I can't set such shadow effect. let startPoint = convertToOutput(firstPoint), endPoint = convertToOutput(secondPoint) UIGraphicsBeginImageContextWithOptions(self.outputCanvasSize, false, 1.0) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.setStrokeColor(color.cgColor) context?.setShadow(offset: CGSize(width:0, height: 0), blur: 20, color: color.cgColor) context?.setLineJoin(.round) context?.setLineCap(.round) context?.setLineWidth(brush.radius * 2) context?.move(to: startPoint) context?.addLine(to: endPoint) context?.drawPath(using: .stroke) glowOverlayCanvas.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() But effect isn't so good. So I what draw such brush using next algorithm: * *Draw colored smooth fill circles with 1px step, rad 20 px. *Then draw white fill circles foreground, without smooth, rad 5 px. I have a problem with blend mode, because if I use .normal, smooth effect disappear - alpha channel accumulate (few circles crossing) How to implement the following blend mode Rrgb = Srgb Ra = MAX(Da, Sa)
stackoverflow
{ "language": "en", "length": 165, "provenance": "stackexchange_0000F.jsonl.gz:891555", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625538" }
bb7afccae3de5d0a8791109830c01950fec57f1e
Stackoverflow Stackexchange Q: Testing a React component with Enzyme. Typescript can't find instance methods I want to test a React class component. Let's say I have a method in my class that computes something based on the current state and props. import Component from './Component' const wrapper = enzyme.shallow(<Component {...props} />); it('does something', () => { expect(wrapper.instance().someInstanceMethod(input)).toBe(true); }); Typescript says Property 'someInstanceMethod' is not defined on type Component<any, any>. How can I tell Typscript how my class is looking and what methods it has? Is there a good example for this? A: You can set the component type in the call to shallow. This is a little bit of boilerplate, but it makes things typesafe. The good thing is that the wrapper is typesafe, not just the instance you pull out. import Component from './Component' // Wrapper will know the type of the component. const wrapper = enzyme.shallow<Component>(<Component {...props} />); it('does something', () => { expect(wrapper.instance().someInstanceMethod(input)).toBe(true); // You can also get the state from the wrapper. expect(wrapper.state().someComponentState).toBeTruthy(); });
Q: Testing a React component with Enzyme. Typescript can't find instance methods I want to test a React class component. Let's say I have a method in my class that computes something based on the current state and props. import Component from './Component' const wrapper = enzyme.shallow(<Component {...props} />); it('does something', () => { expect(wrapper.instance().someInstanceMethod(input)).toBe(true); }); Typescript says Property 'someInstanceMethod' is not defined on type Component<any, any>. How can I tell Typscript how my class is looking and what methods it has? Is there a good example for this? A: You can set the component type in the call to shallow. This is a little bit of boilerplate, but it makes things typesafe. The good thing is that the wrapper is typesafe, not just the instance you pull out. import Component from './Component' // Wrapper will know the type of the component. const wrapper = enzyme.shallow<Component>(<Component {...props} />); it('does something', () => { expect(wrapper.instance().someInstanceMethod(input)).toBe(true); // You can also get the state from the wrapper. expect(wrapper.state().someComponentState).toBeTruthy(); }); A: One possible solution (thanks to the comment from marzelin) is to explicitly declare the type of the instance() method. There might be more elegant ways to do this. import Component from './Component' const wrapper = enzyme.shallow(<Component {...props} />); const instance = wrapper.instance() as Component; // explicitly declare type it('does something', () => { expect(instance.someInstanceMethod(input)).toBe(true); // no TS error }); A: Thanks to @marzelin and @Chris! Other possible solution import Component from './Component' const wrapper = enzyme.shallow(<Component {...props} />); const instance = wrapper.instance() as any; // explicitly declare type it('does something', () => { expect(instance.someInstanceMethod(input)).toBe(true); // no TS error }); This comes in handy where someInstanceMethod receives event as parameter, explicitly declare type as component requires you to pass whole event object which is not something a developer want for writing test cases.
stackoverflow
{ "language": "en", "length": 299, "provenance": "stackexchange_0000F.jsonl.gz:891566", "question_score": "24", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625581" }
4142bcb421ea5ecdf0216f2213995d9724e3955e
Stackoverflow Stackexchange Q: Generics and Comparator I am working on generics and found that the following code is giving compile time error at comparing method. Multiple markers at this line - Cannot infer type argument(s) for comparing(Function) - The type A does not define m1(Object) that is applicable here class A<T> { String m1() { return null; } } class B { void test() { Comparator<A<String>> target = Comparator.comparing(A::m1).thenComparing(A::m1); } } Can some one help me understand this behavior; and how can I fix the problem? A: If you specify the exact generic types at the comparing method, the code compiles. Comparator<A<String>> target = Comparator.<A<String>, String>comparing(A::m1).thenComparing(A::m1);
Q: Generics and Comparator I am working on generics and found that the following code is giving compile time error at comparing method. Multiple markers at this line - Cannot infer type argument(s) for comparing(Function) - The type A does not define m1(Object) that is applicable here class A<T> { String m1() { return null; } } class B { void test() { Comparator<A<String>> target = Comparator.comparing(A::m1).thenComparing(A::m1); } } Can some one help me understand this behavior; and how can I fix the problem? A: If you specify the exact generic types at the comparing method, the code compiles. Comparator<A<String>> target = Comparator.<A<String>, String>comparing(A::m1).thenComparing(A::m1); A: You should specify type parameter for class A. Comparator<A<String>> target = Comparator.comparing(A<String>::m1).thenComparing(A<String>::m1); A: Interesting question. Haven't gone into JLS but I guess type inference does not work in case of chained method call. (You can see it works for a simple Comparator<A<String>> target = Comparator.comparing(A<String>::m1); ) One quick fix, which is similar to another answer, is help Java do the type inference: Comparator<A<String>> target = Comparator.comparing(A<String>::m1) .thenComparing(A::m1); Please note doing it at the first method already do the trick. (Looking forward to see if someone can dig out JLS to see if such inference is supposed to be valid :P ) A: you can nested as Comparator<A<String>> target1 = Comparator.comparing(A::m1); Comparator<A<String>> target2 = target1.thenComparing(A::m1); myVarList.sort(target2); A: Comparator<A<String>> target = Comparator.comparing(A::m1).thenComparing(A::m1); thenComparing() expects a Comparator object as parameter...
stackoverflow
{ "language": "en", "length": 232, "provenance": "stackexchange_0000F.jsonl.gz:891591", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625657" }
32b62b31c27d5510dba64c82427380a775130612
Stackoverflow Stackexchange Q: Using media breakpoints in Bootstrap 4 / SASS - _breakpoints.scss does not know $grid-breakpoints I am trying to use media queries in Bootstrap 4. On their website they do this: @include media-breakpoint-up(xs) { ... } @include media-breakpoint-up(sm) { ... } @include media-breakpoint-up(md) { ... } @include media-breakpoint-up(lg) { ... } @include media-breakpoint-up(xl) { ... } // Example usage: @include media-breakpoint-up(sm) { .some-class { display: block; } } So I grabbed the Bootstrap SCSS, and copied the _breakpoints.scss and included this in my project. I import it, and then try to use a media query: @import "partials/breakpoints"; @include media-breakpoint-up(sm) { .mycontainer { background-color: black; } } However, I get the following error when i compile SASS: Change detected to: main.scss error pages/_geschichte.scss (Line 54: Undefined variable: "$grid-breakpoints".) Am I doing this the wrong way or will I need to include more files? I then tried to fix that by also including _grid.scss, but then for this, something else is required again, so I got unsure whether this is indeed the right way and thought I'd better ask. A: Did you include the bootstrap variables.scss ? Seems like the variables are missing
Q: Using media breakpoints in Bootstrap 4 / SASS - _breakpoints.scss does not know $grid-breakpoints I am trying to use media queries in Bootstrap 4. On their website they do this: @include media-breakpoint-up(xs) { ... } @include media-breakpoint-up(sm) { ... } @include media-breakpoint-up(md) { ... } @include media-breakpoint-up(lg) { ... } @include media-breakpoint-up(xl) { ... } // Example usage: @include media-breakpoint-up(sm) { .some-class { display: block; } } So I grabbed the Bootstrap SCSS, and copied the _breakpoints.scss and included this in my project. I import it, and then try to use a media query: @import "partials/breakpoints"; @include media-breakpoint-up(sm) { .mycontainer { background-color: black; } } However, I get the following error when i compile SASS: Change detected to: main.scss error pages/_geschichte.scss (Line 54: Undefined variable: "$grid-breakpoints".) Am I doing this the wrong way or will I need to include more files? I then tried to fix that by also including _grid.scss, but then for this, something else is required again, so I got unsure whether this is indeed the right way and thought I'd better ask. A: Did you include the bootstrap variables.scss ? Seems like the variables are missing
stackoverflow
{ "language": "en", "length": 191, "provenance": "stackexchange_0000F.jsonl.gz:891595", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625668" }
2dbe8c9bb3f0f6b30850ed84c5e3f3a74b649971
Stackoverflow Stackexchange Q: Disable zoom on web-view react-native? How to disable zoom on react-native web-view,is there a property like hasZoom={false}(just an example) that can be included in the below web-view tag that can disable zooming. It has to be working on both android and ios. <WebView ref={WEBVIEW_REF} source={{uri:Environment.LOGIN_URL}} ignoreSslError={true} onNavigationStateChange={this._onNavigationStateChange.bind(this)} onLoad={this.onLoad.bind(this)} onError={this.onError.bind(this)} ></WebView> A: Little hacky stuff but it works const INJECTEDJAVASCRIPT = 'const meta = document.createElement(\'meta\'); meta.setAttribute(\'content\', \'width=device-width, initial-scale=1, maximum-scale=0.99, user-scalable=0\'); meta.setAttribute(\'name\', \'viewport\'); document.getElementsByTagName(\'head\')[0].appendChild(meta); ' <WebView injectedJavaScript={INJECTEDJAVASCRIPT} scrollEnabled ref={(webView) => { this.webView = webView }} originWhitelist={['*']} source={{ uri: url }} onNavigationStateChange={(navState) => { this.setState({ backButtonEnabled: navState.canGoBack, }) }} /> Note initial-scale=1, maximum-scale=0.99, user-scalable=0
Q: Disable zoom on web-view react-native? How to disable zoom on react-native web-view,is there a property like hasZoom={false}(just an example) that can be included in the below web-view tag that can disable zooming. It has to be working on both android and ios. <WebView ref={WEBVIEW_REF} source={{uri:Environment.LOGIN_URL}} ignoreSslError={true} onNavigationStateChange={this._onNavigationStateChange.bind(this)} onLoad={this.onLoad.bind(this)} onError={this.onError.bind(this)} ></WebView> A: Little hacky stuff but it works const INJECTEDJAVASCRIPT = 'const meta = document.createElement(\'meta\'); meta.setAttribute(\'content\', \'width=device-width, initial-scale=1, maximum-scale=0.99, user-scalable=0\'); meta.setAttribute(\'name\', \'viewport\'); document.getElementsByTagName(\'head\')[0].appendChild(meta); ' <WebView injectedJavaScript={INJECTEDJAVASCRIPT} scrollEnabled ref={(webView) => { this.webView = webView }} originWhitelist={['*']} source={{ uri: url }} onNavigationStateChange={(navState) => { this.setState({ backButtonEnabled: navState.canGoBack, }) }} /> Note initial-scale=1, maximum-scale=0.99, user-scalable=0 A: Thought this might help others, I solved this by adding the following in the html <head> section: <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0"> A: I was also find me with this problem and I resolved using setBuiltInZoomControls={false} like prop in WebView example <WebView /*all prop to use*/ setBuiltInZoomControls={false} /> I hope that to be help A: For those who want a clear idea: const INJECTEDJAVASCRIPT = `const meta = document.createElement('meta'); meta.setAttribute('content', 'width=device-width, initial-scale=0.5, maximum-scale=0.5, user-scalable=0'); meta.setAttribute('name', 'viewport'); document.getElementsByTagName('head')[0].appendChild(meta); ` <WebView source={{ html: params.content.rendered }} scalesPageToFit={isAndroid() ? false : true} injectedJavaScript={INJECTEDJAVASCRIPT} scrollEnabled /> A: I was able to disable zooming, text selection and other pointer events by wrapping WebView in a View and setting a few props: <View pointerEvents="none"> <WebView source={{ uri: webviewUrl }} scrollEnabled={false} /> </View> A: Try scalesPageToFit={false} more info in here A: If you are using WKWebView - scalesPageToFit prop does not work. You can check this issue here that will lead you to this one Now to accomplish what you want you should use the injectedJavascript prop. But there is something else as described here Be sure to set an onMessage handler, even if it's a no-op, or the code will not be run. This took me some time to discover. So in the end you have something like this: const INJECTED_JAVASCRIPT = `(function() { const meta = document.createElement('meta'); meta.setAttribute('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'); meta.setAttribute('name', 'viewport'); document.getElementsByTagName('head')[0].appendChild(meta); })();`; <WebView source={{ uri }} scrollEnabled={false} injectedJavaScript={INJECTED_JAVASCRIPT} onMessage={() => {}} /> A: For anyone in the future, I solved this by adding the following css : *:not(input) { user-select: none; } The above basically disable text selection on all elements, which during my testing disallowed zooming on webpage. FYI: I haven't dived deep into details, just stating its effects.
stackoverflow
{ "language": "en", "length": 390, "provenance": "stackexchange_0000F.jsonl.gz:891599", "question_score": "40", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625680" }
8e17b94fdb7bff65c6f9d828126b72c3fdedb44c
Stackoverflow Stackexchange Q: How can I configure an Azure Function triggered by Service Bus with a custom INameResolver? I want to be able to control the name of the Service Bus Queue or Subscription that my Azure Function reads from at run-time. With WebJobs (which Azure Functions are based on) you could do this by implementing and configuring a custom INameResolver, see: How to have a configuration based queue name for web job processing? However, with Azure functions I have no access to JobHostConfiguration to wire up this custom resolver. Can I still use an INameResolver, and if so how? A: Right now you cannot use a custom INameResolver as there is no mechanism for injecting your own services like this into the host. It's being tracked here: https://github.com/Azure/azure-webjobs-sdk-script/issues/1579
Q: How can I configure an Azure Function triggered by Service Bus with a custom INameResolver? I want to be able to control the name of the Service Bus Queue or Subscription that my Azure Function reads from at run-time. With WebJobs (which Azure Functions are based on) you could do this by implementing and configuring a custom INameResolver, see: How to have a configuration based queue name for web job processing? However, with Azure functions I have no access to JobHostConfiguration to wire up this custom resolver. Can I still use an INameResolver, and if so how? A: Right now you cannot use a custom INameResolver as there is no mechanism for injecting your own services like this into the host. It's being tracked here: https://github.com/Azure/azure-webjobs-sdk-script/issues/1579
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:891633", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625782" }
58601d1fcbe941997f69389298d0e6546c448c90
Stackoverflow Stackexchange Q: How to use tzutc() What am I missing, how do I get this function to work? import dateutil.parser import datetime my_date = datetime.datetime(2000, 1, 1, 0, 0, 0, 000000, tzinfo=tzutc()) print(my_date) Gives me the error: NameError: name 'tzutc' is not defined A: You did not import it: from dateutil.tz import tzutc
Q: How to use tzutc() What am I missing, how do I get this function to work? import dateutil.parser import datetime my_date = datetime.datetime(2000, 1, 1, 0, 0, 0, 000000, tzinfo=tzutc()) print(my_date) Gives me the error: NameError: name 'tzutc' is not defined A: You did not import it: from dateutil.tz import tzutc
stackoverflow
{ "language": "en", "length": 52, "provenance": "stackexchange_0000F.jsonl.gz:891639", "question_score": "39", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625803" }
0f8e460195b5ab0b8b2545c5390ddb929c07b6ca
Stackoverflow Stackexchange Q: laravel 5.2: Command "optimize" is not defined I am working on laravel 5.2. When I run composer install and composer update command, it show error: [InvalidArgumentException] Command "optimize" is not defined. Please let me know how to solved this problem. A: "scripts": { "post-root-package-install": [ "php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ], "post-create-project-cmd": [ "php artisan key:generate", "php artisan jwt:secret -f" ], "post-install-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postInstall", "php artisan optimize" ], "post-update-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postUpdate", "php artisan optimize" ] }, remove php artisan optimize from post-install-cmd array and also from post-update-cmd than it will look like this. "scripts": { "post-root-package-install": [ "php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ], "post-create-project-cmd": [ "php artisan key:generate", "php artisan jwt:secret -f" ], "post-install-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postInstall", ], "post-update-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postUpdate", ] }, working perfectly fine without any warning.
Q: laravel 5.2: Command "optimize" is not defined I am working on laravel 5.2. When I run composer install and composer update command, it show error: [InvalidArgumentException] Command "optimize" is not defined. Please let me know how to solved this problem. A: "scripts": { "post-root-package-install": [ "php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ], "post-create-project-cmd": [ "php artisan key:generate", "php artisan jwt:secret -f" ], "post-install-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postInstall", "php artisan optimize" ], "post-update-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postUpdate", "php artisan optimize" ] }, remove php artisan optimize from post-install-cmd array and also from post-update-cmd than it will look like this. "scripts": { "post-root-package-install": [ "php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ], "post-create-project-cmd": [ "php artisan key:generate", "php artisan jwt:secret -f" ], "post-install-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postInstall", ], "post-update-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postUpdate", ] }, working perfectly fine without any warning. A: https://laravel.com/docs/5.6/upgrade says: The previously deprecated optimize Artisan command has been removed. With recent improvements to PHP itself including the OPcache, the optimize command no longer provides any relevant performance benefit. Therefore, you may remove php artisan optimize from the scripts within your composer.json file. A: This artisan command is deprecated. Simply remove it from your composer.json file. A: Please note the after install or upgrade laravel following commands will be executed through composer.json file. Since 5.2 onwards optimize command has been depreciated. Please remove it. A: To add of other accepted answer posted : I face this error while migrating project from laravel5.2 to laravel5.6 Made following change in the composer.json * *Ensure "post-create-project-cmd" of "Scripts" doesn't have "Illuminate\Foundation\ComposerScripts::postInstall", "php artisan optimize" line *Ensure "post-update-cmd" of "Scripts" doesn't have "Illuminate\Foundation\ComposerScripts::postUpdate", "php artisan optimize" line ** Still project didn't run** Log file shows "Please provide a valid cache path" error. Run following command from project root and it worked. mkdir -p storage/framework/{sessions,views,cache}
stackoverflow
{ "language": "en", "length": 293, "provenance": "stackexchange_0000F.jsonl.gz:891679", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625918" }
79f724111ae463028404ddb00548239ba5aca932
Stackoverflow Stackexchange Q: Using flask session to store dict As a follow-up on an earlier question, I wonder how to use flask.g and flask.session to transfer a dictionary from one function to another. If I understand g correctly, it only temporarily stores info until a new request. Since the function I want to transfer the dict object to, starts with a new request (it loads a new flask template), I guess I cannot use g. So, this leaves me to wonder whether I can use flask.session for this. If I try to save my dict as follows: session.dict, and then try to use this dict in a new function, it returns an "AttributeError: 'FileSystemSession' object has no attribute 'dict'. Any idea whether the saving of a dict in a flask session is at all possible? And if so, what am I doing wrong? A: Session in flask is a dictionary. So if you need to save anything in session you can do this: from flask import session ... def foo(...): session['my_dict'] = my_dict def bar(...): my_dict = session['my_dict'] Note that you need to check whether the my_dict is present in session before trying to use it.
Q: Using flask session to store dict As a follow-up on an earlier question, I wonder how to use flask.g and flask.session to transfer a dictionary from one function to another. If I understand g correctly, it only temporarily stores info until a new request. Since the function I want to transfer the dict object to, starts with a new request (it loads a new flask template), I guess I cannot use g. So, this leaves me to wonder whether I can use flask.session for this. If I try to save my dict as follows: session.dict, and then try to use this dict in a new function, it returns an "AttributeError: 'FileSystemSession' object has no attribute 'dict'. Any idea whether the saving of a dict in a flask session is at all possible? And if so, what am I doing wrong? A: Session in flask is a dictionary. So if you need to save anything in session you can do this: from flask import session ... def foo(...): session['my_dict'] = my_dict def bar(...): my_dict = session['my_dict'] Note that you need to check whether the my_dict is present in session before trying to use it.
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:891681", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625926" }
78d13ca99d30cbdca3314fbbd608271a71dd72c6
Stackoverflow Stackexchange Q: Representation of org.joda.LocalTime in Swagger We are using Swagger (1.5.15) to visualize our rest api. To represent time we use org.joda.LocalTime (can not use java8 time for legacy reasons). The api works as expected with time formatted as "HH:MM:SS", however, swagger shows this as "LocalTime": { "type": "object", "properties": { "chronology": { "$ref": "#/definitions/Chronology" }, "millisOfDay": { "type": "integer", "format": "int32" }, "hourOfDay": { "type": "integer", "format": "int32" }, ... Which (if I'm not gravely mistaken) means that the problem is not in the Swagger-UI. We have tried different versions of Swagger together with @ApiModelProperty(dataType = "org.joda.time.LocalTime", example = "10:11:12") without luck. Any help would be greatly appreciated. A: I have not resolved the original issue of using joda LocalTime in swagger. However, since the date & time api in java is now (finally) updated as of java 8, the problem was resolved for us when we moved to these instead of using joda time.
Q: Representation of org.joda.LocalTime in Swagger We are using Swagger (1.5.15) to visualize our rest api. To represent time we use org.joda.LocalTime (can not use java8 time for legacy reasons). The api works as expected with time formatted as "HH:MM:SS", however, swagger shows this as "LocalTime": { "type": "object", "properties": { "chronology": { "$ref": "#/definitions/Chronology" }, "millisOfDay": { "type": "integer", "format": "int32" }, "hourOfDay": { "type": "integer", "format": "int32" }, ... Which (if I'm not gravely mistaken) means that the problem is not in the Swagger-UI. We have tried different versions of Swagger together with @ApiModelProperty(dataType = "org.joda.time.LocalTime", example = "10:11:12") without luck. Any help would be greatly appreciated. A: I have not resolved the original issue of using joda LocalTime in swagger. However, since the date & time api in java is now (finally) updated as of java 8, the problem was resolved for us when we moved to these instead of using joda time.
stackoverflow
{ "language": "en", "length": 156, "provenance": "stackexchange_0000F.jsonl.gz:891688", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625938" }
606e43ed4339696f1c9b0a2204cf406148934724
Stackoverflow Stackexchange Q: Is possible to listen on Redux @@INIT action in middleware In Redux, there is initial action @@INIT. Is possible to dispatch another action (in middleware) when this action occurred? If not, what is best alternative to push action after store is ready? A: According to https://github.com/reactjs/redux/issues/186 @@INIT * *internal action *name of that action may differ in dev mode, so if you use it - it might broke app functionality or automatic reloading *to sum-up, this action should not be touched in app codebase How to push initial Redux actions then? Without library: const store = createStore(...); store.dispatch(...) In middleware like Redux Saga: function * initialSaga() { yield put({ ... }) } export default function * root() { yield fork(initialSaga); }
Q: Is possible to listen on Redux @@INIT action in middleware In Redux, there is initial action @@INIT. Is possible to dispatch another action (in middleware) when this action occurred? If not, what is best alternative to push action after store is ready? A: According to https://github.com/reactjs/redux/issues/186 @@INIT * *internal action *name of that action may differ in dev mode, so if you use it - it might broke app functionality or automatic reloading *to sum-up, this action should not be touched in app codebase How to push initial Redux actions then? Without library: const store = createStore(...); store.dispatch(...) In middleware like Redux Saga: function * initialSaga() { yield put({ ... }) } export default function * root() { yield fork(initialSaga); }
stackoverflow
{ "language": "en", "length": 122, "provenance": "stackexchange_0000F.jsonl.gz:891689", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625944" }
09e02a6f05999b70b4732aff5873d67365bbb8a0
Stackoverflow Stackexchange Q: Tensorflow 1.2 Android Demo and Hexagon (Qualcomm 835) Will Tensorflow 1.2 Android Demo utilize Hexagon (Qualcomm 835) or not? More general question: does Tensorflow 1.2 for Android (from jcenter) include specific code for supporting Hexagon? PS Previously it was not supported according TensorFlow HVX Acceleration support
Q: Tensorflow 1.2 Android Demo and Hexagon (Qualcomm 835) Will Tensorflow 1.2 Android Demo utilize Hexagon (Qualcomm 835) or not? More general question: does Tensorflow 1.2 for Android (from jcenter) include specific code for supporting Hexagon? PS Previously it was not supported according TensorFlow HVX Acceleration support
stackoverflow
{ "language": "en", "length": 47, "provenance": "stackexchange_0000F.jsonl.gz:891693", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44625952" }
3ed0ea784fac86fdf06d3760340c8606259adbb9
Stackoverflow Stackexchange Q: How to get PublicKey of a csproj file for use in `InternalsVisibleTo`? I have a signed assembly where I'd like to use InternalsVisibleTo: [assembly: InternalsVisibleTo("My.Project.Name", PublicKey=002400000...")] Where I also have a My.Project.Name.csproj in another directory that has My.Project.Name as the AssemblyName. I need to get the PublicKey for this assembly. How do I do that using the command line tools? Various references indicate I call sn -Tp path-to-assembly but I don't have a path yet. I need the PublicKey first since I can't compile until the internals are visible to this assembly. I also use a <AssemblyOriginatorKeyFile> in both projects, which I presume is for the signing, but I'm not clear on if, or how, this relates to the PublicKey I need. Note: I'm doing this on Mac using the Mono CLI toolkit.
Q: How to get PublicKey of a csproj file for use in `InternalsVisibleTo`? I have a signed assembly where I'd like to use InternalsVisibleTo: [assembly: InternalsVisibleTo("My.Project.Name", PublicKey=002400000...")] Where I also have a My.Project.Name.csproj in another directory that has My.Project.Name as the AssemblyName. I need to get the PublicKey for this assembly. How do I do that using the command line tools? Various references indicate I call sn -Tp path-to-assembly but I don't have a path yet. I need the PublicKey first since I can't compile until the internals are visible to this assembly. I also use a <AssemblyOriginatorKeyFile> in both projects, which I presume is for the signing, but I'm not clear on if, or how, this relates to the PublicKey I need. Note: I'm doing this on Mac using the Mono CLI toolkit.
stackoverflow
{ "language": "en", "length": 134, "provenance": "stackexchange_0000F.jsonl.gz:891753", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626195" }
71bc0a46661531280963c7d3f5f621435997ae90
Stackoverflow Stackexchange Q: Why "unsigned int64_t" gives an error in C? Why the following program gives an error? #include <stdio.h> int main() { unsigned int64_t i = 12; printf("%lld\n", i); return 0; } Error: In function 'main': 5:19: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'i' unsigned int64_t i = 12; ^ 5:19: error: 'i' undeclared (first use in this function) 5:19: note: each undeclared identifier is reported only once for each function it appears in But, If I remove the unsigned keyword, it's working fine. So, Why unsigned int64_t i gives an error? A: int64_t is not some builtin type. Try adding #include <stdint.h> to define such types; then use uint64_t which means what you appear to intend. Hth
Q: Why "unsigned int64_t" gives an error in C? Why the following program gives an error? #include <stdio.h> int main() { unsigned int64_t i = 12; printf("%lld\n", i); return 0; } Error: In function 'main': 5:19: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'i' unsigned int64_t i = 12; ^ 5:19: error: 'i' undeclared (first use in this function) 5:19: note: each undeclared identifier is reported only once for each function it appears in But, If I remove the unsigned keyword, it's working fine. So, Why unsigned int64_t i gives an error? A: int64_t is not some builtin type. Try adding #include <stdint.h> to define such types; then use uint64_t which means what you appear to intend. Hth A: int64_t is a typedef name. N1570 §7.20.1.1 p1: The typedef name intN_t designates a signed integer type with width N, no padding bits, and a two’s complement representation. Thus, int8_t denotes such a signed integer type with a width of exactly 8 bits. Standard lists what combinations are legal in §6.7.2 p2: * *char *signed char *unsigned char *short, signed short, short int, or signed short int *unsigned short, or unsigned short int *int, signed, or signed int *unsigned, or unsigned int *long, signed long, long int, or signed long int *unsigned long, or unsigned long int *long long, signed long long, long long int, or signed long long int *unsigned long long, or unsigned long long int ... * *typedef name Types that are not relevant to the question have been removed from the list. Note how you cannot mix typedef name with unsigned. To use unsigned 64-bit type, you need to: * *Use uint64_t (note the leading u) without unsigned specifier. uint64_t i = 12; *Include stdint.h (or inttypes.h) where uint64_t is defined. *To print uint64_t you need to include inttypes.h and use PRIu64: printf("%" PRIu64 "\n", i); You can also or cast to unsigned long long which is 64-bits or more. However it's preferable to avoid casting when it's not strictly necessary, so the you should prefer PRIu64 method. printf("%llu\n", (unsigned long long)i); A: You cannot apply the unsigned modifier on the type int64_t. It only works on char, short, int, long, and long long. You probably want to use uint64_t which is the unsigned counterpart of int64_t. Also note that int64_t et al. are defined in the header stdint.h, which you should include if you want to use these types. A: typedef of int64_t is something like: typedef signed long long int int64_t; So, unsigned int64_t i; becomes something like: unsigned signed long long int i; Which is obviously a compiler error. So, use int64_t instead of unsigned int64_t. Also, add #include <stdint.h> header file in your program.
stackoverflow
{ "language": "en", "length": 453, "provenance": "stackexchange_0000F.jsonl.gz:891765", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626223" }
bd1db272b2c6c0be4a8b235a99632efc90534375
Stackoverflow Stackexchange Q: Cannot find module 'ansi-regex' | npm not getting uninstalled or updated I am unable to uninstall or update npm. I tried running rn -rf node-modules, rimraf node-modules, and even manually deleting the npm folder from the system. I even removed the environment variable. Unfortunately, nothing is working. I uninstalled nodejs and completely removed ALL the folders and temp files. Post system restart, I did a fresh installation of nodejs and when I again tried to install npm, I get this error: throw err; ^ Error: Cannot find module 'ansi-regex' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object.<anonymous> (C:\Users\Admin\AppData\Roaming\npm\node_modules\npm\n ode_modules\strip-ansi\index.js:2:38) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) Basically, whatever method I tried, I get the same error. Please help! node version: v6.11.0 OS: Windows 8 I have also tried installing 'ansi-regex' using npm install ansi-regex
Q: Cannot find module 'ansi-regex' | npm not getting uninstalled or updated I am unable to uninstall or update npm. I tried running rn -rf node-modules, rimraf node-modules, and even manually deleting the npm folder from the system. I even removed the environment variable. Unfortunately, nothing is working. I uninstalled nodejs and completely removed ALL the folders and temp files. Post system restart, I did a fresh installation of nodejs and when I again tried to install npm, I get this error: throw err; ^ Error: Cannot find module 'ansi-regex' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object.<anonymous> (C:\Users\Admin\AppData\Roaming\npm\node_modules\npm\n ode_modules\strip-ansi\index.js:2:38) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) Basically, whatever method I tried, I get the same error. Please help! node version: v6.11.0 OS: Windows 8 I have also tried installing 'ansi-regex' using npm install ansi-regex
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:891770", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626232" }
fd7ea18be73a6d4e89e25de51c8f8869865355c2
Stackoverflow Stackexchange Q: How to deploy AWS elasticsearch using serverless.yml I need to use AWS elasticsearch service but also want to automate it. We have serverless configuration. How can we create an AWS elasticsearch service using serverless.yml? A: to add to Jens' answer, you might want the output you can add this to your serverless.yml config Outputs: DomainArn: Value: !GetAtt ElasticsearchDomain.DomainArn DomainEndpoint: Value: !GetAtt ElasticsearchDomain.DomainEndpoint SecurityGroupId: Value: !Ref mySecurityGroup SubnetId: Value: !Ref subnet
Q: How to deploy AWS elasticsearch using serverless.yml I need to use AWS elasticsearch service but also want to automate it. We have serverless configuration. How can we create an AWS elasticsearch service using serverless.yml? A: to add to Jens' answer, you might want the output you can add this to your serverless.yml config Outputs: DomainArn: Value: !GetAtt ElasticsearchDomain.DomainArn DomainEndpoint: Value: !GetAtt ElasticsearchDomain.DomainEndpoint SecurityGroupId: Value: !Ref mySecurityGroup SubnetId: Value: !Ref subnet A: You can add CloudFormation resources to the "resources" section. For ElasticSearch this would look something like this. service: aws-nodejs provider: name: aws runtime: nodejs6.10 functions: hello: handler: handler.hello environment: elasticURL: Fn::GetAtt: [ ElasticSearchInstance , DomainEndpoint ] resources: Resources: ElasticSearchInstance: Type: AWS::Elasticsearch::Domain Properties: EBSOptions: EBSEnabled: true VolumeType: gp2 VolumeSize: 10 ElasticsearchClusterConfig: InstanceType: t2.small.elasticsearch InstanceCount: 1 DedicatedMasterEnabled: false ZoneAwarenessEnabled: false ElasticsearchVersion: 5.3
stackoverflow
{ "language": "en", "length": 132, "provenance": "stackexchange_0000F.jsonl.gz:891794", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626308" }
91e0fea54e19aa72f6d5b1fcd7f0e04823b9d8ed
Stackoverflow Stackexchange Q: Cancel search in vscode If i try search something in vs code it works fine but even after it has found the result i am looking for it continues to search, which is not ideal because i think it is searching everything in the node-modules folder, which depending on my search term, with freeze vs code completely. I know i could probably just regex the node-modules folder out of the search, but its so simple as it is , it always finds the results quickly but then just hangs. Don't know if i have maybe overlooked something in the editor but is there a simple stop on searching? A: Just press esc to stop the search Here's the default keybinding for that: { "key": "escape", "command": "search.action.cancel", "when": "listFocus && searchViewletVisible" }
Q: Cancel search in vscode If i try search something in vs code it works fine but even after it has found the result i am looking for it continues to search, which is not ideal because i think it is searching everything in the node-modules folder, which depending on my search term, with freeze vs code completely. I know i could probably just regex the node-modules folder out of the search, but its so simple as it is , it always finds the results quickly but then just hangs. Don't know if i have maybe overlooked something in the editor but is there a simple stop on searching? A: Just press esc to stop the search Here's the default keybinding for that: { "key": "escape", "command": "search.action.cancel", "when": "listFocus && searchViewletVisible" }
stackoverflow
{ "language": "en", "length": 133, "provenance": "stackexchange_0000F.jsonl.gz:891840", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626478" }
371cb4ba8dfdc0a4d616ff5c7a963c1e6ab5eddc
Stackoverflow Stackexchange Q: Chunks of async_generator I can get chunks of an iterator doing as follow: def get_chunks_it(l, n): """ Chunks an iterator `l` in size `n` Args: l (Iterator[Any]): an iterator n (int): size of Returns: Generator[Any] """ iterator = iter(l) for first in iterator: yield itertools.chain([first], itertools.islice(iterator, n - 1)) Now let's say I have an asynchronous generator (python 3.6): async def generator(): for i in range(0, 10): yield i await asyncio.sleep(1) How could I get chunks (let's say of size 3 that would yield [0, 1, 2], [3, 4, 5], [6, 7, 8], [9]) of the resulting async_generator so that I could write: async for chunk in get_chunk_it_async(generator(), 3): print(chunk) A: You can use aiostream.stream.chunks: from aiostream import stream async def main(): async for x in stream.chunks(generator(), 3): print(x) Output: [0, 1, 2] [3, 4, 5] [6, 7, 8] [9] See the project page and the documentation for further information. Disclaimer: I am the project maintainer.
Q: Chunks of async_generator I can get chunks of an iterator doing as follow: def get_chunks_it(l, n): """ Chunks an iterator `l` in size `n` Args: l (Iterator[Any]): an iterator n (int): size of Returns: Generator[Any] """ iterator = iter(l) for first in iterator: yield itertools.chain([first], itertools.islice(iterator, n - 1)) Now let's say I have an asynchronous generator (python 3.6): async def generator(): for i in range(0, 10): yield i await asyncio.sleep(1) How could I get chunks (let's say of size 3 that would yield [0, 1, 2], [3, 4, 5], [6, 7, 8], [9]) of the resulting async_generator so that I could write: async for chunk in get_chunk_it_async(generator(), 3): print(chunk) A: You can use aiostream.stream.chunks: from aiostream import stream async def main(): async for x in stream.chunks(generator(), 3): print(x) Output: [0, 1, 2] [3, 4, 5] [6, 7, 8] [9] See the project page and the documentation for further information. Disclaimer: I am the project maintainer. A: This is slightly complicated by the lack of an aiter() function in Python 3.6 (it'll be added in 3.7 once returning an awaitable from __aiter__ is properly deprecated). There are no async versions of itertools objects yet either. Define your own: try: aiter except NameError: # not yet a built-in, define our own shim for now from inspect import iscoroutinefunction as _isasync def aiter(ob, _isasync=_isasync): obtype = type(ob) # magic methods are looked up on the type if not hasattr(obtype, '__aiter__'): raise TypeError(f'{obtype.__name__!r} object is not async iterable') async_iter = obtype.__aiter__(ob) if _isasync(async_iter): # PEP 492 allowed for __aiter__ to be a coroutine, but 525 reverses this again raise TypeError(f'{obtype.__name__!r} object is not async iterable') return async_iter del _isasync Next, you need to define async islice and chain objects: class achain(): """Chain over multiple async iterators""" def __init__(self, *async_iterables): self._source = iter(async_iterables) self._active = None def __aiter__(self): return self async def __anext__(self): if self._source is None: # we are all done, nothing more to produce raise StopAsyncIteration if self._active is None: # get next async iterable to loop over ait = next(self._source, None) if ait is None: # we are all done, nothing more to produce self._source = None raise StopAsyncIteration self._active = aiter(ait) try: return await type(ait).__anext__(ait) except StopAsyncIteration: # exhausted, recurse self._active = None return await self.__anext__() class aslice(): """Slice an async iterator""" def __init__(self, ait, start, stop=None, step=1): if stop is None: start, stop = 0, start self._ait = ait self._next, self._stop, self._step = start, stop, step self._cnt = 0 def __aiter__(self): return self async def __anext__(self): ait, stop = self._ait, self._stop if ait is None: raise StopAsyncIteration anext = type(ait).__anext__ while self._cnt < self._next: try: await anext(ait) except StopAsyncIteration: self._ait = None raise self._cnt += 1 if stop is not None and self._cnt >= stop: self._ait = None raise StopAsyncIteration try: item = await anext(ait) except StopAsyncIteration: self._ait = None raise self._cnt += 1 self._next += self._step return item With those in place, simply add async in the right places: async def get_chunks_it(l, n): """ Chunks an async iterator `l` in size `n` Args: l (Iterator[Any]): an iterator n (int): size of Returns: Generator[Any] """ iterator = aiter(l) async for first in iterator: async def afirst(): yield first yield achain(afirst, aslice(iterator, n - 1))
stackoverflow
{ "language": "en", "length": 536, "provenance": "stackexchange_0000F.jsonl.gz:891850", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626518" }
5fdfc4b9f602e3690b299491a12315161232cf85
Stackoverflow Stackexchange Q: Laravel append URI in route Hi I want to append the uri in laravel route function. e.g we have /search?type=listing //how do i can achieve this with route('search',['type'=>'listing']) Once the we are on the search. I want to have all the variable appended to search like type=listing&query=blah blah A: If I get you right, you want to save all query parameters. Use Request::query() to get it and then merge with your new parameters. route('search', array_merge(\Request::query(), ['type' => 'listing'])));
Q: Laravel append URI in route Hi I want to append the uri in laravel route function. e.g we have /search?type=listing //how do i can achieve this with route('search',['type'=>'listing']) Once the we are on the search. I want to have all the variable appended to search like type=listing&query=blah blah A: If I get you right, you want to save all query parameters. Use Request::query() to get it and then merge with your new parameters. route('search', array_merge(\Request::query(), ['type' => 'listing']))); A: If you have a named route and want to generate url with query params then: route('route_name', ['param1' => 'value', 'param2' => 'value']); In your case you can do this with route('search',['type'=>'listing','subject' => ['blah'],[....]])
stackoverflow
{ "language": "en", "length": 113, "provenance": "stackexchange_0000F.jsonl.gz:891878", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626622" }
41f9febf64d73aeede1afdc769b7e72994f61fac
Stackoverflow Stackexchange Q: Laravel valet always asks password After reinstalling macOS, I started setup my dev environment based on Laracasts "Setup a mac dev machine from scratch". At the previous time when I installed php/valet/composer etc, everything was fine, but now the terminal (in every new session) always asks password when I type valet. I added the composer path to .zshrc export PATH=$HOME/bin:/usr/local/bin:$HOME/.composer/vendor/bin:$PATH A: In order to get this going you can run the following command: $ valet trust This will let you enter the password once, and remember it. Using the trust command, you indicate that the current machine can be trusted for development, and Valet will stop asking for the password.
Q: Laravel valet always asks password After reinstalling macOS, I started setup my dev environment based on Laracasts "Setup a mac dev machine from scratch". At the previous time when I installed php/valet/composer etc, everything was fine, but now the terminal (in every new session) always asks password when I type valet. I added the composer path to .zshrc export PATH=$HOME/bin:/usr/local/bin:$HOME/.composer/vendor/bin:$PATH A: In order to get this going you can run the following command: $ valet trust This will let you enter the password once, and remember it. Using the trust command, you indicate that the current machine can be trusted for development, and Valet will stop asking for the password. A: Your macOS native apache might be running, try stopping it sudo apachectl stop A: running sudo valet start fixed it for me.
stackoverflow
{ "language": "en", "length": 134, "provenance": "stackexchange_0000F.jsonl.gz:891929", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626760" }
0e42b6f60dd4f16566dd509be885e60fa57062c7
Stackoverflow Stackexchange Q: Get Decoder for Deep Autoencoder I'm following the tutorial for deep autoencoders in keras here. For the simple autoencoder in the beginning there is a decoder defined like this: # retrieve the last layer of the autoencoder model decoder_layer = autoencoder.layers[-1] # create the decoder model decoder = Model(encoded_input, decoder_layer(encoded_input)) This doesn't work anymore if you have more than one decoder layer. How to do similar if I have three decoder layers? encoded = Dense(128, activation='relu')(input_img) encoded = Dense(64, activation='relu')(encoded) encoded = Dense(32, activation='relu')(encoded) decoded = Dense(64, activation='relu')(encoded) decoded = Dense(128, activation='relu')(decoded) decoded = Dense(784, activation='sigmoid')(decoded) autoencoder = Model(input_img, decoded) encoder = Model(input_img, encoded) For encoder it does work easily, but how to get a model of the last three layers? A: Try (following this answer): # retrieve the last layer of the autoencoder model decoder_layer1 = autoencoder.layers[-3] decoder_layer2 = autoencoder.layers[-2] decoder_layer3 = autoencoder.layers[-1] # create the decoder model decoder = Model(input=encoded_input, output=decoder_layer3(decoder_layer2(decoder_layer1(encoded_input))))
Q: Get Decoder for Deep Autoencoder I'm following the tutorial for deep autoencoders in keras here. For the simple autoencoder in the beginning there is a decoder defined like this: # retrieve the last layer of the autoencoder model decoder_layer = autoencoder.layers[-1] # create the decoder model decoder = Model(encoded_input, decoder_layer(encoded_input)) This doesn't work anymore if you have more than one decoder layer. How to do similar if I have three decoder layers? encoded = Dense(128, activation='relu')(input_img) encoded = Dense(64, activation='relu')(encoded) encoded = Dense(32, activation='relu')(encoded) decoded = Dense(64, activation='relu')(encoded) decoded = Dense(128, activation='relu')(decoded) decoded = Dense(784, activation='sigmoid')(decoded) autoencoder = Model(input_img, decoded) encoder = Model(input_img, encoded) For encoder it does work easily, but how to get a model of the last three layers? A: Try (following this answer): # retrieve the last layer of the autoencoder model decoder_layer1 = autoencoder.layers[-3] decoder_layer2 = autoencoder.layers[-2] decoder_layer3 = autoencoder.layers[-1] # create the decoder model decoder = Model(input=encoded_input, output=decoder_layer3(decoder_layer2(decoder_layer1(encoded_input))))
stackoverflow
{ "language": "en", "length": 154, "provenance": "stackexchange_0000F.jsonl.gz:891931", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626765" }
69a925b44e66d5e8326156a0f8a57175e770ae75
Stackoverflow Stackexchange Q: PyCharm python console - ipython magic output I have started recently to use PyCharm for some python development under Win10. I am still struggling to find the best configuration with consoles. I have ipython enabled in the built-in PyCharm console, but it does not always work like a normal ipython. The most annoying feature is that the output of the pinfo/? magic does not display properly: In[1]: a=123 In[2]: ?a {'text/plain': "Type: int\nString form: 123\nDocstring: \nint(x=0)[...] In a normal ipython console I get, as expected, In [1]: a=123 In [2]: a? Type: int String form: 123 Docstring: int(x=0) -> integer [...] Is there a way to change this behavior? Or a way to hook up PyCharm to an external console running in e.g. ConEmu? I am using PyCharm 2017.1.4, python 3.5.3, PyCharm invokes there ipython 5.3.0.
Q: PyCharm python console - ipython magic output I have started recently to use PyCharm for some python development under Win10. I am still struggling to find the best configuration with consoles. I have ipython enabled in the built-in PyCharm console, but it does not always work like a normal ipython. The most annoying feature is that the output of the pinfo/? magic does not display properly: In[1]: a=123 In[2]: ?a {'text/plain': "Type: int\nString form: 123\nDocstring: \nint(x=0)[...] In a normal ipython console I get, as expected, In [1]: a=123 In [2]: a? Type: int String form: 123 Docstring: int(x=0) -> integer [...] Is there a way to change this behavior? Or a way to hook up PyCharm to an external console running in e.g. ConEmu? I am using PyCharm 2017.1.4, python 3.5.3, PyCharm invokes there ipython 5.3.0.
stackoverflow
{ "language": "en", "length": 137, "provenance": "stackexchange_0000F.jsonl.gz:891938", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626782" }
71103dc4d7ab4985779d5a6908f95610915483b0
Stackoverflow Stackexchange Q: Open app upon receiving push-notification I'm developing a WebRTC app with React Native. I've got Firebase working, and I can receive notifications on my Android/iOS devices whilst in the background or foreground. Is there any way of when I receive a push-notification to automatically open the app for me, without requiring the user input? Thanks in advance. A: If you are going for the scenario of an incoming call, it's not the same for both platforms. For Android, you can start an activity responding to a push notification, but iOS doesn't allow that. You can either send a regular push notification the user might miss, or use CallKit and integrate it with your stuffs. Unfortunately I don't know good libraries for React Native that can help you with that yet, so it might have to be done natively and bridged to your RN code. Edit: Android example - In your native code handling a notification, you can use context.startActivity(launchIntent); to launch your app with an incoming call screen.
Q: Open app upon receiving push-notification I'm developing a WebRTC app with React Native. I've got Firebase working, and I can receive notifications on my Android/iOS devices whilst in the background or foreground. Is there any way of when I receive a push-notification to automatically open the app for me, without requiring the user input? Thanks in advance. A: If you are going for the scenario of an incoming call, it's not the same for both platforms. For Android, you can start an activity responding to a push notification, but iOS doesn't allow that. You can either send a regular push notification the user might miss, or use CallKit and integrate it with your stuffs. Unfortunately I don't know good libraries for React Native that can help you with that yet, so it might have to be done natively and bridged to your RN code. Edit: Android example - In your native code handling a notification, you can use context.startActivity(launchIntent); to launch your app with an incoming call screen. A: Sorry to deviate a little from the code perspective. But if you are looking forward for external triggers, I would recommend MacroDroid as a potential solution. There are numerous triggers including Notification reads, SMS etc., Macrodroid is available in Play store with trial version limited to five macros per user. Logical validations, loops and much more features to explore.
stackoverflow
{ "language": "en", "length": 229, "provenance": "stackexchange_0000F.jsonl.gz:891945", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626809" }
070a61d95ec771188d379982500ee9f05f045ea9
Stackoverflow Stackexchange Q: What does (void) sizeof (0[array]) mean? I come across the following code, which returns the size of a C style array. template <typename Type, int N> int GetArraySize(Type (&array)[N]) { (void) sizeof (0[array]); return N; } The templated part seems to have been already explained in this question. But still, I don't understand what is the utility of the sizeof line. Any ideas? Some suggest that it is to avoid unused variable warning, but a simpler #pragmacould have been used, right? Moreover, will this piece of code be effective in any situation? Aren't there any restrictions? A: I think the purpose of the line is to silent unused variable warning. The simpler would be to omit parameter name template <typename Type, int N> int GetArraySize(Type (&)[N]) { return N; }
Q: What does (void) sizeof (0[array]) mean? I come across the following code, which returns the size of a C style array. template <typename Type, int N> int GetArraySize(Type (&array)[N]) { (void) sizeof (0[array]); return N; } The templated part seems to have been already explained in this question. But still, I don't understand what is the utility of the sizeof line. Any ideas? Some suggest that it is to avoid unused variable warning, but a simpler #pragmacould have been used, right? Moreover, will this piece of code be effective in any situation? Aren't there any restrictions? A: I think the purpose of the line is to silent unused variable warning. The simpler would be to omit parameter name template <typename Type, int N> int GetArraySize(Type (&)[N]) { return N; }
stackoverflow
{ "language": "en", "length": 131, "provenance": "stackexchange_0000F.jsonl.gz:891947", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44626815" }