source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
8
prompt
stringlengths
209
40.4k
gold_standard_solution
stringlengths
0
56.7k
verification_info
stringclasses
1 value
metadata
stringlengths
138
225
problem_id
stringlengths
9
10
stackexchange
llm_judgeable_groundtruth_similarity
28427267
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to write a file to my phone. I used Environment.getDataDirectory() to know the internal storage's path and Environment.getExternamStorageDirectory() to know the external storage's path. But when I use Environment.getExternalStorageDirectory() as path, the file is created in internal storage . And when I use Environment.GetDataStorage() as the path, the file is not created. (I am not sure, but I can't find it in the explorer app, at least.) I think my phone's internal storage is perceived as external storage.(In my case, it has 32 GB amount of storage) I want to know removable storage(e.g. micro SD card ) path. What should I do? Now provide the response and nothing else.
From the official documentation for getExternalStorageDirectory() Don't be confused by the word "external" here. This directorycan better be thought as media/shared storage. It is a filesystem thatcan hold a relatively large amount of data and that is shared acrossall applications (does not enforce permissions). Traditionally this isan SD card, but it may also be implemented as built-in storage in adevice that is distinct from the protected internal storage and can bemounted as a filesystem on a computer. So, it can be different from built-in storage in a device. For your case, you could use getExternalStoragePublicDirectory(java.lang.String) This is where the user will typically place and manage their ownfiles The path here should be one of DIRECTORY_MUSIC, DIRECTORY_PODCASTS,DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS,DIRECTORY_PICTURES, DIRECTORY_MOVIES, DIRECTORY_DOWNLOADS, orDIRECTORY_DCIM. May not be null. Or if you want your data to be deleted whenever the user uninstalls your app, you could use getExternalFilesDir() . As these files are internal to the applications, and not typically visible to the user as media. Also there are some differences between getFilesDir() and getExternalFilesDir() External files are not always available: they will disappear if the user mounts the external storage on a computer or removes it. See the APIs on environment for information in the storage state. There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28427267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3858358/']}
jdg_76041
stackexchange
llm_judgeable_groundtruth_similarity
27915657
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a bunch of files that end in "-e" that I want to remove. $ find . -name "*-e" exec rm {} \;find: exec: unknown primary or operator Is the regex expanding in some way that messes everything up? Now provide the response and nothing else.
It should be: find . -name "*-e" -exec rm '{}' \; Or better: find . -name "*-e" -exec rm '{}' + As per man find : -exec utility [argument ...] {} + Same as -exec, except that ``{}'' is replaced with as many pathnames as possible for each invocation of utility. This behaviour is similar to that of xargs(1).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27915657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173635/']}
jdg_76042
stackexchange
llm_judgeable_groundtruth_similarity
28591447
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to styling my appcompat-v7 toolbar to have a different background color for my overflow menu. I tried to use the themes for my app and styles for my toolbar, but I was not able to achieve it. This is my toolbar: <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:minHeight="?attr/actionBarSize" android:background="?attr/colorPrimary" android:layout_width="match_parent" app:theme="@style/AppToolbarTheme" android:layout_height="wrap_content"> Here is the style I created: <style name="AppToolbarTheme" parent="Theme.AppCompat.NoActionBar"> <item name="android:textColorPrimary">@color/white</item> <item name="android:textColorSecondary">@color/cian</item> </style> My main theme is extending Theme.AppCompat.Light. Does anybody knows how can I do that? If is not possible using the styles is there any other way to achieve it? Now provide the response and nothing else.
Add this to your toolbar element app:popupTheme="@style/ThemeOverlay.YourPopup" Then in your styles.xml define the popup menu style <style name="ThemeOverlay.YourPopup" parent="ThemeOverlay.AppCompat.Light"> <item name="android:colorBackground">@color/mtrl_white_100</item> <item name="android:textColor">@color/mtrl_light_blue_900</item></style> <style name="ThemeOverlay.YourPopup" parent="ThemeOverlay.AppCompat.Light"> <item name="android:colorBackground">@color/mtrl_white_100</item> <item name="android:textColorPrimary">@color/mtrl_light_blue_900</item></style> Note that you need to use android:colorBackground and never android:background . The latter would be applied to everything that doesn't have a background (here the menu itself and each menu item), the former applies only to the popup menu. Update: The same applies to textColorPrimary and textColor . Popup menu item defines android:textColor="?android:textColorPrimary" . android:textColorPrimary is a theme attribute, it's defined on themes. android:textColor is a style attribute, it's defined on widgets. If we defined android:textColor in a theme, it would be applied to every widget that doesn't define its own android:textColor .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28591447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2912000/']}
jdg_76043
stackexchange
llm_judgeable_groundtruth_similarity
559501
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: How do FTP, FTPS, SFTP, and SCP compare in terms of transfer rate and how can I compare them through testing? Now provide the response and nothing else.
If you have a fast wide-area network you will find that sftp and scp are about the same speed, which is slow. They both suffer from performance problems in the underlying openssh. With modern hardware, this is not due to encryption overhead, but rather due to problems with the openssh implementation - it implements its own internal windowing mechanism which breaks down on fast connections. These problems become more obvious on long-distance (higher latency) connections, but I've experienced slowness even on LANs. These are well-documented, and patches are available to fix the problem. Patching either end of the connection can help; ideally you'd patch both ends. For more info and the patches, see High Performance SSH at Pittsburgh Supercomputer Center. BTW, encryption overhead can become an issue too, once the windowing problem is solved. The patches have fixes for that too. Meanwhile, you will find that ftp is woefully insecure; it sends passwords in plain-text. ftps I think wraps the ftp protocol in SSL. it's probably faster than unpatched SFTP/SCP. One final note: in my experience, the WinSCP client is (at least sometimes) painfully slow. I don't know why, but based on their FAQ I'm not the only person who's had this problem. So if you're scp'ing from Windows, and it seems slow, try a different client. Even with an unpatched openssh server, you can do much, much better with a different client. I'm not sure which are good clients, unfortunately, other than presumably plain pscp from Putty.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/559501', 'https://serverfault.com', 'https://serverfault.com/users/201586/']}
jdg_76044
stackexchange
llm_judgeable_groundtruth_similarity
29095425
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having an issue seeding my database with users and roles. The User and the Role are both created (I can see them in the database after the error is thrown). However, when I try to check if the user is in a role, I get an exception. My code is: public class tbInitializer<T> : DropCreateDatabaseAlways<tbContext> { protected override void Seed(tbContext context) { ApplicationDbContext userscontext = new ApplicationDbContext(); var userStore = new UserStore<ApplicationUser>(userscontext); var userManager = new UserManager<ApplicationUser>(userStore); var roleStore = new RoleStore<IdentityRole>(userscontext); var roleManager = new RoleManager<IdentityRole>(roleStore); if(!userscontext.Users.Any(x=> x.UserName=="marktest")) { var user = new ApplicationUser { UserName = "marktest", Email = "[email protected]" }; userManager.Create(user, "Pa$$W0rD!"); } if (!roleManager.RoleExists("Admin")) { roleManager.Create(new IdentityRole("Admin")); } if(!userManager.IsInRole("marktest","Admin")) { userManager.AddToRole("marktest","Admin"); } However, on the line: if(!userManager.IsInRole("marktest","Admin")) An exception is thrown with the error: UserId not found. The User and the Role are both in the database when I check after the exception is thrown: Can anyone see what I'm doing wrong? Thanks for any help, Mark Now provide the response and nothing else.
I found out the solution, in case anyone else is having this problem. The "IsInRole" is expecting a User.Id - not a UserName string - so I changed to: if (!userManager.IsInRole(user.Id, "Admin")) { userManager.AddToRole(user.Id, "Admin"); } So the working code becomes: ApplicationDbContext userscontext = new ApplicationDbContext(); var userStore = new UserStore<ApplicationUser>(userscontext); var userManager = new UserManager<ApplicationUser>(userStore); var roleStore = new RoleStore<IdentityRole>(userscontext); var roleManager = new RoleManager<IdentityRole>(roleStore); // Create Role if (!roleManager.RoleExists("Admin")) { roleManager.Create(new IdentityRole("Admin")); } if(!userscontext.Users.Any(x=> x.UserName=="marktest")) { // Create User var user = new ApplicationUser { UserName = "marktest", Email = "[email protected]" }; userManager.Create(user, "Pa$$W0rD!"); // Add User To Role if (!userManager.IsInRole(user.Id, "Admin")) { userManager.AddToRole(user.Id, "Admin"); } } I hope that helps, Mark
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29095425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1041617/']}
jdg_76045
stackexchange
llm_judgeable_groundtruth_similarity
21810334
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So here it is this example public static void main(String[] args) { new Stuff(null); new Stuff("a"); new Stuff(1); } and class Stuff is defined as follow public class Stuff { Stuff(Object o){ System.out.println("object"); } Stuff(String s){ System.out.println("string"); }} The output is stringstringobject How does Java tell the null is a String ? If I change Stuff to public class Stuff { Stuff(String s){ System.out.println("string"); } Stuff(Integer o){ System.out.println("Integer"); }} I get compilation error for Stuff(null) : The constructore Stuff(String) is ambigous. Again, why does Java "decide" null is a String ? Now provide the response and nothing else.
The compiler first lists all applicable methods. In your case, both are applicable. It then tries to find a method which is more specific than the other(s). In your first example, String is a subclass of Object and is therefore more specific. In your second example, both methods are applicable (String and Integer) but neither is more specific than the other (String is not a subclass of Integer which is not a subclass of String). So there is an ambiguity, hence the compiler error. The full algorithm to determine which method should be chosen is defined in the JLS .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21810334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1029825/']}
jdg_76046
stackexchange
llm_judgeable_groundtruth_similarity
33845254
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need some help with a bash script. The script should work in a "database-ish" style. I need to add customers, which will be given a customer-number create a folder for each new customer (if I run the program from directory /company/myprogram each new customer will have his own folder within that directory) When I start the program, I want it to ask me for a customer-number. If a customer is new, program will ask for his credentials and after providing them, a customer will be made by making a new folder named "'customer-number' 'surname'" i.e. 15112101 Doe . If a customer already exists, it should display a message "customer already exists" and go to said customer. Now here's the catch. I already tried using things like string="15112101" if [[ ! -d "$string" ]]; then echo "No such customer"else cd "$string" But how can I determine whether current directory contains a folder starting with this customer-number, if true, cd to this folder. If false, make new customer. i.e. 1) folder 15112101 Doe exists in /company/myprogram start program > asks customer-number > insert 15112101 > output should be:Customer 15112101 Doe found, going to /company/myprogram/15112101 Doe i.e. 2) folder 15112101 Doe does not exist in /company/myprogram start program > asks customer-number > insert 15112101 > output should be: Customer does not exist, create new? Now provide the response and nothing else.
There are many ways to materialise a nested collection with SQL, and / or with jOOQ. I'm just going through some of them: Using joins If you don't deeply nest those collections, denormalising (flattening) your results with a JOIN might do the trick for you, without adding too much overhead as data is being duplicated. Essentially, you'll write: Map<ExperimentRecord, Result<Record>> map =DSL.using(configuration) .select() .from(EXPERIMENT) .join(TAGS) .on(...) .fetchGroups(EXPERIMENT); The above map contains experiment records as keys, and nested collections containing all the tags as values. Creating two queries If you want to materialise a complex object graph, using joins might no longer be optimal. Instead, you probably want to collect the data in your client from two distinct queries: Result<ExperimentRecord> experiments = DSL.using(configuration) .selectFrom(EXPERIMENT) .fetch(); And Result<TagsRecord> tags =DSL.using(configuration) .selectFrom(TAGS) .where(... restrict to the previous experiments ...) .fetch(); And now, merge the two results in your client's memory, e.g. experiments.stream() .map(e -> new ExperimentWithTags( e, tags.stream() .filter(t -> e.getId().equals(t.getExperimentId())) .collect(Collectors.toList()) )); Nesting collections using SQL/XML or SQL/JSON This question didn't require it, but others may find this question in search for a way of nesting to-many relationships with jOOQ. I've provided an answer here . Starting with jOOQ 3.14, you can use your RDBMS's SQL/XML or SQL/JSON capabilities, and then use Jackson, Gson, or JAXB to nest collections like this: List<Experiment> experiments =ctx.select( EXPERIMENT.asterisk(), field( select(jsonArrayAgg(jsonObject(TAGS.fields()))) .from(TAGS) .where(TAGS.EXPERIMENT_ID.eq(EXPERIMENT.ID)) ).as("tags") ) .from(EXPERIMENT) .fetchInto(Experiment.class); Where Experiment is a custom Java class like this: class Experiment { long id; String name; List<Tag> tags;}class Tag { long id; String name;} Nesting collections using MULTISET Even better than the above, you can hide using SQL/XML or SQL/JSON behind jOOQ 3.15's new MULTISET operator support . Assuming the above Java classes are Java 16 records (or any other immutable classes), you can even map nested collections type safely into your DTOs: List<Experiment> experiments =ctx.select( EXPERIMENT.ID, EXPERIMENT.NAME, multiset( select(TAGS.ID, TAGS.NAME) .from(TAGS) .where(TAGS.EXPERIMENT_ID.eq(EXPERIMENT.ID)) ).as("tags").convertFrom(r -> r.map(Records.mapping(Tag::new))) ) .from(EXPERIMENT) .fetch(Records.mapping(Experiment::new)); Where Experiment is a custom Java class like this: record Experiment(long id, String name, List<Tag> tags) {}record Tag(long id, String name) {} See also this blog post for more information .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33845254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5589437/']}
jdg_76047
stackexchange
llm_judgeable_groundtruth_similarity
238033
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: We're quite interested in exploring the possibility of using SSD drives in a server environment. However, one thing that we need to establish is expected drive longevity. According to this article manufacturer's are reporting drive endurance in terms of 'total bytes written' (TBW). E.g. from that article a Crucial C400 SSD is rated at 72TB TBW. Do any scripts/tools exist under the Linux ecosystem to help us measure TBW? (and then make a more educated decision on the feasibility of using SSD drives) Now provide the response and nothing else.
Another possibility is to look at /proc/diskstats . It's not persistent across reboots, but it has data for every block device. Probably most interesting to you is field 10, which contains the total number of sectors written. On a system with scsi disks with a sector size of 512 bytes, you could run awk '/sd/ {print $3"\t"$10 / 2 / 1024}' /proc/diskstats to see how many megabytes were written to each device. The output will look like sda 728.759 sda1 79.0908 sda2 649.668
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/238033', 'https://serverfault.com', 'https://serverfault.com/users/48987/']}
jdg_76048
stackexchange
llm_judgeable_groundtruth_similarity
14384378
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: this query takes an hour select *, unix_timestamp(finishtime)-unix_timestamp(submittime) timetaken from joblog where jobname like '%cas%' and submittime>='2013-01-01 00:00:00' and submittime<='2013-01-10 00:00:00'order by id desc limit 300; but the same query with one submittime finishes in like .03 seconds the table has 2.1 Million rows Any idea whats causing the issue or how to debug it Now provide the response and nothing else.
If you can upgrade to JSF 2.2, immediately do it. It offers a native @ViewScoped annotation for CDI. import javax.faces.view.ViewScoped;import javax.inject.Named;@Named@ViewScopedpublic class Bean implements Serializable { // ...} Alternatively, install OmniFaces which brings its own CDI compatible @ViewScoped , including a working @PreDestroy (which is broken on JSF @ViewScoped ). import javax.inject.Named;import org.omnifaces.cdi.ViewScoped;@Named@ViewScopedpublic class Bean implements Serializable { // ...} Another alternative is to install MyFaces CODI which transparently bridges JSF 2.0/2.1 @ViewScoped to CDI. This only adds an autogenerated request parameter to the URL (like @ConversationScoped would do). import javax.faces.bean.ViewScoped;import javax.inject.Named;@Named@ViewScopedpublic class Bean implements Serializable { // ...} If you really need to use @ConversationScoped , then you indeed need to manually begin and end it. You need to @Inject a Conversation and invoke begin() in the @PostConstruct and end() in the latest step of the conversation, usually an action method which redirects to a new view. import javax.enterprise.context.Conversation;import javax.enterprise.context.ConversationScoped;import javax.inject.Named;@Named@ConversationScopedpublic class Bean implements Serializable { @Inject private Conversation conversation; // ... @PostConstruct public void init() { conversation.begin(); } public String submit() { // ... conversation.end(); return "some.xhtml?faces-redirect=true"; }} See also: How to choose the right bean scope?
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14384378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/909032/']}
jdg_76049
stackexchange
llm_judgeable_groundtruth_similarity
25819
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I understand that routes learnt via iBGP can't be redistributed to other iBGP peers to avoid loops, but then why is a iBGP connection between two routers that don't have eBGP connections needed? They won't distribute anything, right? Now provide the response and nothing else.
...why is a iBGP connection between two routers that don't have eBGP connections needed? They won't distribute anything, right? Not quite right. It's not that two routers connected via iBGP cannot learn any prefixes from each other. Suppose you have two WAN routers in your AS, A and B, both connected to separate WAN ASes via eBGP, and connected together via iBGP. Router A cannot learn prefixes from Router B about which Router B learned from other iBGP speakers in your AS, but it can learn about prefixes which Router B learned about from eBGP or an IGP. Any prefixes which Router A learns about through iBGP from Router B cannot be passed on to any other iBGP speakers because those prefixes could be sent back to Router B, directly or indirectly. That's the reason for needing a full mesh or a mitigation such as route reflectors or confederations; other iBGP speakers will need to learn the prefixes which Router B will share with other iBGP speaker directly from Router B since Router A is unable to pass those prefixes on.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/25819', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/21931/']}
jdg_76050
stackexchange
llm_judgeable_groundtruth_similarity
59194984
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a Radio button inside a ListTile . When the ListTile is clicked, I change the Radio 's value. I don't want the radio to be clickable, so I don't provide an onChanged callback: ListTile( onTap: () => onChanged(template.id), leading: Radio( value: template.id, groupValue: checkedId, ) ...) Doing that, the Radio becomes "inactive" and changes it's color to grey.The Radio has an activeColor property, but not for inactive. If I provide a dummy function to Radio 's onChanged property - it becomes active, but the problem is I don't want it to be clickable, I want the ListTile to be clickable only (the reason is - I want to be able to uncheck the Radio ) Also, I only want to change the inactive color of those specific Radio buttons, and not for the whole app. Current Result: Result with onChange (I can't uncheck the radio when clicking on it): Now provide the response and nothing else.
Radio uses unselectedWidgetColor of ThemeData . If you need to change it only for a few radios on a specific screen, wrap them in Theme widget to override a color: Theme( data: Theme.of(context).copyWith( unselectedWidgetColor: Colors.red, disabledColor: Colors.blue ), child: Column( children: <Widget>[ ListTile( onTap: () => setState(() => value = 0), leading: Radio( value: 0, groupValue: value, onChanged: (v) => setState(() => value = v), ) ), ListTile( onTap: () => setState(() => value = 1), leading: Radio( value: 1, groupValue: value, onChanged: (v) => setState(() => value = v), ) ), ], ),) If no callback passed in onChanged to Radio , it is interpreted as disabled (this works for many default material widgets).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/59194984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1447267/']}
jdg_76051
stackexchange
llm_judgeable_groundtruth_similarity
7780279
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Lets say I have an array of interlaced data, such as 1a2b3c4d5e, and I want to de-interlace it into an array that looks like 12345abcde, in place (without a temporary buffer). What would be the fastest way of doing this? What I have so far is this template<typename T>void deinterlace(T* arr, int length){ if(length<=1) return; int i = 1; for(i = 1; i*2<length; i++){ //swap i with i*2 T temp = arr[i]; arr[i] = arr[i*2]; arr[i*2] = temp; } deinterlace(arr+i, length-i);} which unfortunately doesn't work with arrays not a power of 2 in size edit : this algo fails at larger powers of 2 anyway so I guess I'm at square 0 again edit 2 : I have found an nlogn algorithm for this, given either an O(n) array rotate function, or an initial size which is a power of 2 works like so: 1a2b3c4d5e6f7g, "chunk size" = 1 initial, split into groups of chunk size *41a2b 3c4d 5e6f 7g swap the inner 2 chunks of each group12ab 34cd 56ef 7g repeat with chunk size = chunk size *2 12ab34cd 56ef7g (read: 56 ef 7 g) ->1234abcd 567efg 1234abcd567efg ->1234567abcdefg template<typename T>void deinterlace(T* arr, int length, int group_ct = 1){ if(group_ct*2 >= length) return; for(int i = 0; i<length; i+=group_ct*4){ int rot_count = group_ct; int i1 = i + group_ct; int i2 = i+group_ct*4 - group_ct; if(i2+group_ct > length){ i2 = i1 + (length-i1)/2+group_ct/2; } rotate(arr, i1, i2, group_ct); } deinterlace(arr, length, group_ct * 2);} edit 3 I guess the correct term is deinterleave, not deinterlace Now provide the response and nothing else.
This is essentially a matrix transposition problem. Your array [1 a][2 b][3 c][4 d] is equivalent to 1, a, 2, b, 3, c, 4, d if represented as a vector (by reading rows first). The transpose of this matrix is: [1 2 3 4][a b c d] which is equivalent to 1, 2, 3, 4, a, b, c, d . There is a wikipedia page that deals with in-place matrix transposition for the general cases. I guess, the algorithm for non-square matrix would be directly applicable. There is a slow (not sure if O(n^2) or worse, and it is late) algorithm that you can use. The idea is to in place rotate the sub-array from position i to position 2*i . For example: START: 1a2b3c4d5e6f1(a2)... -> 1(2a)...12(ab3)... -> 12(3ab)...123(abc4)... -> 123(4abc)...1234(abcd5)... -> 1234(5abcd)...12345(abcde6)... -> 12345(6abcde)..123456(abcdef) -> DONE The first member of the array is index 0. At step 1, you select the sub-array a[1:2] , and rotate it right (all members go to next location, and the last one goes to start). Next step, you select a[2:4] , and rotate that, etc. Make sure you don't rotate the last sub-array a[n/2:n] . And a final option, if you do not need to do bulk operations for performance (such as memcpy ), is to provide an accessor function, and transform the index instead of moving any bytes. Such a function is almost trivial to write: if index is less than max/2 , return entry at 2*index , otherwise, return entry at 2*(index-max/2)+1 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7780279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/997193/']}
jdg_76052
stackexchange
llm_judgeable_groundtruth_similarity
3009896
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I get the first and last day of next month to be used in the where clause? Now provide the response and nothing else.
Use: SELECTDATE_SUB( LAST_DAY( DATE_ADD(NOW(), INTERVAL 1 MONTH) ), INTERVAL DAY( LAST_DAY( DATE_ADD(NOW(), INTERVAL 1 MONTH) ) )-1 DAY) AS firstOfNextMonth,LAST_DAY( DATE_ADD(NOW(), INTERVAL 1 MONTH))AS lastOfNextMonth
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3009896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/323284/']}
jdg_76053
stackexchange
llm_judgeable_groundtruth_similarity
1174984
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array of lists of numbers, e.g.: [0] (0.01, 0.01, 0.02, 0.04, 0.03)[1] (0.00, 0.02, 0.02, 0.03, 0.02)[2] (0.01, 0.02, 0.02, 0.03, 0.02) ...[n] (0.01, 0.00, 0.01, 0.05, 0.03) I would like to efficiently calculate the mean and standard deviation at each index of a list, across all array elements. To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by n (I am working with a population, not a sample from the population). To do the standard deviation, I loop through again, now that I have the mean calculated. I would like to avoid going through the array twice, once for the mean and then once for the standard deviation (after I have a mean). Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g., Perl or Python) or pseudocode is fine. Now provide the response and nothing else.
The answer is to use Welford's algorithm, which is very clearly defined after the "naive methods" in: Wikipedia: Algorithms for calculating variance It's more numerically stable than either the two-pass or online simple sum of squares collectors suggested in other responses. The stability only really matters when you have lots of values that are close to each other as they lead to what is known as " catastrophic cancellation " in the floating point literature. You might also want to brush up on the difference between dividing by the number of samples (N) and N-1 in the variance calculation (squared deviation). Dividing by N-1 leads to an unbiased estimate of variance from the sample, whereas dividing by N on average underestimates variance (because it doesn't take into account the variance between the sample mean and the true mean). I wrote two blog entries on the topic which go into more details, including how to delete previous values online: Computing Sample Mean and Variance Online in One Pass Deleting Values in Welford’s Algorithm for Online Mean and Variance You can also take a look at my Java implement; the javadoc, source, and unit tests are all online: Javadoc: stats.OnlineNormalEstimator Source: stats.OnlineNormalEstimator.java JUnit Source: test.unit.stats.OnlineNormalEstimatorTest.java LingPipe Home Page
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1174984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19410/']}
jdg_76054
stackexchange
llm_judgeable_groundtruth_similarity
927490
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to solve a form of modular arithmetic I've never seen before. I'm completely stuck. Any hints in how to crack this would be of great help. $$ -18 \equiv 19y \pmod{1967-y}$$ Or similarly, how do I find integer solutions for: $$ y = \frac{-18-1967k}{19-k}$$ Now provide the response and nothing else.
Since there exists an integer $k$ such that $$-18-19y=k(1967-y),$$we have$$y=\frac{1967k+18}{k-19}=1967+\frac{18+19\times 1967}{k-19}=1967+\frac{139\times 269}{k-19}$$$$\iff 1967-y=\frac{139\times 269}{19-k}\gt 0$$where $139$ and $269$ are primes. Since $19-k\gt 0$ has to be a positive divisor of $139\times 269$, we have$$19-k=1,\ 139,\ 269,\ 139\times 269\Rightarrow 1967-y=139\times 269,\ 269,\ 139,\ 1$$$$\Rightarrow y=1967-139\times 269,\ 1967-269,\ 1967-139,\ 1967-1$$$$\Rightarrow y=-35424,\ 1698,\ 1828,\ 1966.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/927490', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23055/']}
jdg_76055
stackexchange
llm_judgeable_groundtruth_similarity
3276516
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been trying to get my head round ZF set theory and Peano's axioms, but I have hit some confusion over Peano's definition of the successor function, or more accurately von Neumann's model. Why did von Neumann use $S(x) := x \bigcup \{x\} $ and not just plain old $S(x) := \{x\} $ ? The latter seems a lot more simple and easy to work with, so am I missing some major advantage of the former, or is my function incompatible in some way? Edit: is the only advantage just that the cardinality of the set is equal to the value it represents? Now provide the response and nothing else.
It is harder to work with. For example, we can "check" whether an arbitrary set $x$ is a von Neumann natural: $x$ is finite and transitive and well-ordered by $\in$ . where finite can be formalized as, e.g., "every injective map $x\to x$ is onto" and transitive is defined as "every element is also a subset".Try to find a similar characterization for the alternative (without using " $\ldots$ " anywhere).Or try to find a simple way to express the order relation between natural numbers in a simple way for the sets representing the numbers (for von Neumann we have $x<y$ iff $x\in y$ iff $x \subsetneq y$ ).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3276516', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/202418/']}
jdg_76056
stackexchange
llm_judgeable_groundtruth_similarity
1495408
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a Canvas in which user can add UserControl subclasses containing a form. User should be able to drag these UserControl around the Canvas. What's the best practice to do this with WPF? Now provide the response and nothing else.
This is done in silverlight and not in WPF, but it should work the same. Create two private properties on the control: protected bool isDragging; private Point clickPosition; Then attatch some event handlers in the constructor of the control: this.MouseLeftButtonDown += new MouseButtonEventHandler(Control_MouseLeftButtonDown);this.MouseLeftButtonUp += new MouseButtonEventHandler(Control_MouseLeftButtonUp);this.MouseMove += new MouseEventHandler(Control_MouseMove); Now create those methods: private void Control_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){ isDragging = true; var draggableControl = sender as UserControl; clickPosition = e.GetPosition(this); draggableControl.CaptureMouse();}private void Control_MouseLeftButtonUp(object sender, MouseButtonEventArgs e){ isDragging = false; var draggable = sender as UserControl; draggable.ReleaseMouseCapture();}private void Control_MouseMove(object sender, MouseEventArgs e){ var draggableControl = sender as UserControl; if (isDragging && draggableControl != null) { Point currentPosition = e.GetPosition(this.Parent as UIElement); var transform = draggableControl.RenderTransform as TranslateTransform; if (transform == null) { transform = new TranslateTransform(); draggableControl.RenderTransform = transform; } transform.X = currentPosition.X - clickPosition.X; transform.Y = currentPosition.Y - clickPosition.Y; }} A few things to note here: 1. This does not have to be in a canvas. It can be in a stackpanel, or grid as well. 2. This makes the entire control draggable, that means if you click anywhere in the control and drag it will drag the whole control. Not sure if thats exactly what you want. Edit- Expanding on some of the specifics in your question:The best way that I would implement this is to create a class that inherits from UserControl, maybe called DraggableControl that is built with this code, then all draggable controls should extend the DraggableControl. Edit 2 - There is small issue when you have a datagrid in this control. If you sort a column in the datagrid the MouseLeftButtonUp event never fires. I have updated the code so that isDragging is protected. I found the best solution is to tie this anonymous method to the LostMouseCapture event of the datagrid: this.MyDataGrid.LostMouseCapture += (sender, e) => { this.isDragging = false; };
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1495408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/181474/']}
jdg_76057
stackexchange
llm_judgeable_groundtruth_similarity
208788
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We consider a particle in an infinite potential well in one dimension. The particle is describe by the arbitrary wave function $\psi(x)$. For our particle, we have to show that: \begin{equation}\langle{E}\rangle\geq{E}_{1}\end{equation} This is a problem I found in the Introductory quantum mechanics of Richard L. Liboff. I tried to solve the problem this way. \begin{equation}\langle{Q(x,p)}\rangle=\int\Psi^{*}Q\Big(x,\frac{\hbar}{i}\frac{\partial}{\partial{x}}\Big)\Psi{d}x\end{equation} Because we can write the energy as $E=\frac{p^2}{2m}$ we have that: \begin{equation}\langle{E}\rangle=\int\Psi^{*}\hat{E}\Psi{d}x=-\frac{\hbar^2}{2m}\int\Psi^{*}\frac{\partial^2\Psi}{\partial{x}^2}dx\end{equation} But if we use the time-independant Schrödinger equation, we have (because the potential energy is zero): \begin{equation}\langle{E}\rangle=\int\Psi^{*}E\Psi{d}x=E\int\Psi^{*}\Psi{d}x=E\end{equation} This is what I get, and I think it's logic because the energy conservation. My problem is to talk about the inequality. Do we have $\langle{E}\rangle\geq{E}_{1}$ because $E$ is the summation of all the energy $E_{n}$ associated with a stationary state $\psi_{n}(x)$? My idea is that, because we don't have negative energy, if we only take one term on a summation we have a smaller value than the summation of all $E_{n}$. The only way to b equal mean that $\psi(x)=\psi_{1}(x)$. I'm not sure if I'm doing mistakes or not or if my mathematics are rigorous or if there is a little something I don't understand. Now provide the response and nothing else.
I've noticed that everyone is pretty bothered at the statement that both the kinetic energy & potential energy are minimum at the top. But though seems to be apparently-contradictory, it is actually true. In fact at the top, the string has zero kinetic energy as well as zero elastic potential energy. So, I'm providing a bit context here: In order to set up a wave on a stretched string, the driving force at the end of the string provides energy. This energy is not retained at the source; it flows along the string at the wave speed. The string transports energy as both kinetic energy & elastic potential energy . To send a sinusoidal wave along a previously straight string, the wave must stretch the string. As a string of length $dx$ oscillates transversely, its length must increase & decrease in a periodic way if the string element is to fit the sinusoidal form. When the string element is at its $y = A$ , its length is normal undisturbed value $dx$ . However, when the element is rushing through its $y = 0$ , it has maximum stretch & thus maximum elastic potential energy. Thus the oscillating string element has both its maximum kinetic energy & maximum elastic potential energy simultaneously at $y = 0$ . Source: Principles of Physics; Extended 9th edition by Walker, Resnick, Halliday. (source: cnx.org ) So, when the string is at the top, it has no kinetic energy; also it is not stretched as is evident from the pic above; so it has no elastic potential energy. As everything in nature tries to attain the lowest energy possible, what brings that string element back to its original position? You've not understood then what wave is. Wave transports energy without any net movement of any material-medium. Since, this part is at top now, it must have to come back so that there is no net displacement of the material-medium. This is quite a trivial (& poor) reasoning though. But the main cause is that the source is continuously providing energy which is being spontaneously transported through the string. So, when the top-part of the string has no energy, the nearby-part of the string at the left which is now at the lowest position & thus has maximum energy exerts tension to the top-part & brings it downward in order to transfer the energy that is at left now to the right part. Thus the left part would now move at top since it is now lacking energy while the right-part that was previously at the top moves downward in the response of the tension & hence to receive the energy from the left & it would eventually again move upward by transferring this energy to the right. This is wave-motion. Thus in a word, it is true that every system seeks to move towards having lower energy unless some external agent compels it to do otherwise. Here, though the top-part had no energy, but in order to transfer the energy from left-to-right , the left part of the string(as well as right) exerts tension-force on the top-part so it moves downward ultimately to gain the energy from the left & eventually it would move up again to transport this energy to the further right.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/208788', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/92420/']}
jdg_76058
stackexchange
llm_judgeable_groundtruth_similarity
17053459
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm learning classification. I read about using vectors. But I can't find an algorithm to translate a text with words to a vector. Is it about generating a hash of the words and adding a 1 to the hash location in the vector? Now provide the response and nothing else.
When most people talk about turning text into a feature vector , all they mean is recording the presence of the word (token). Two main ways to encode a vector. One is explicit, where you have a 0 for each word that is not present (but is in your vocabulary). The other way is implicit---like a sparse matrix (but just a single vector)---where you only encode terms with a frequency value >= 1 . Bag of words model The main article that explains this the best is most likely the bag of words model , which is used extensively for natural language processing applications. Explicit BoW vector example: Suppose you have the vocabulary: {brown, dog, fox, jumped, lazy, over, quick, the, zebra} The sentence "the quick brown fox jumped over the lazy dog" could be encoded as: <1, 1, 1, 1, 1, 1, 1, 2, 0> Remember, position is important. The sentence "the zebra jumped" ---even though it is shorter in length---would then be encoded as: <0, 0, 0, 1, 0, 0, 0, 1, 1> The problem with the explicit approach is that if you have hundreds of thousands of vocabulary terms, each document will also have hundreds of thousands of terms (with mostly zero values). Implicit BoW vector example: In this case, the sentence "the zebra jumped" could be encoded as: <'jumped': 1, 'the': 1, 'zebra': 1> where the order is arbitrary.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17053459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/850841/']}
jdg_76059
stackexchange
llm_judgeable_groundtruth_similarity
21039053
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: SQLAlchemy 0.9 added built-in support for the JSON data type of PostgreSQL. But when I defined an object mapper which has a JSON field and set its value to a perfect JSON string: json = '{"HotCold":"Cold,"Value":"10C"}' The database gets the data in the form: "{\"HotCold\":\"Cold\",\"Value":\"10C\"}" All internal double quotes are backslashed, but if I set JSON from a python dict: json = {"HotCold": "Cold, "Value": "10C"} I get the JSON data in the database as: {"HotCold":"Cold,"Value":"10C"} Why is that? Do I have to pass the data in dict form to make it compatible with SQLAlchemy JSON support? Now provide the response and nothing else.
The short answer: Yes, you have to. The JSON type in SQLAlchemy is used to store a Python structure as JSON . It effectively does: database_value = json.dumps(python_value) on store, and uses python_value = json.loads(database_value) You stored a string, and that was turned into a JSON value. The fact that the string itself contained JSON was just a coincidence. Don't store JSON strings, store Python values that are JSON-serializable. A quick demo to illustrate: >>> print json.dumps({'foo': 'bar'}){"foo": "bar"}>>> print json.dumps('This is a "string" with quotes!')"This is a \"string\" with quotes!" Note how the second example has the exact same quoting applied. Use the JSON SQLAlchemy type to store extra structured data on an object; PostgreSQL gives you access to the contents in SQL expressions on the server side, and SQLAlchemy gives you full access to the contents as Python values on the Python side. Take into account you should always set the whole value anew on an object. Don't mutate a value inside of it and expect that SQLAlchemy detects the change automatically for you; see the PostgreSQL JSON type documentation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21039053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3143104/']}
jdg_76060
stackexchange
llm_judgeable_groundtruth_similarity
35673201
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to update a QProgressDialog (owned by a QMainWindow class) along the execution of a QThread who process some time consuming operations. The thread emit some signals during operation in order to inform the calling app about progression. I'm looking to connect the progress signal emitted by the thread to the setValue slot of the QProgressDialog in order to update the progress bar. It doesn't work ! The progress dialog is not displayed. If I add a slot in my QMainWindow and connect it to the worker progress signal in order to display the value given by the thread throught qDebug output, I see that signals seems to be stacked during the threaded operation and unstacked only at the end of the thread. I have tryed the DirectConnection connect's option without any success. Here is my code :qapp.cpp #include "qapp.h"#include <threaded.h>#include <QVBoxLayout>#include <QPushButton>#include <QDebug>#include <QProgressDialog>QApp::QApp(QWidget *parent) : QMainWindow(parent){ QVBoxLayout *mainLayout = new QVBoxLayout(this); QWidget *window = new QWidget(this); window->setLayout(mainLayout); setCentralWidget(window); QPushButton *button = new QPushButton("Run"); mainLayout->addWidget(button); connect(button, SIGNAL(clicked(bool)), this, SLOT(doSomeWork()));}void QApp::doSomeWork(){ qDebug() << "do some work"; Threaded worker; worker.doHeavyCaclulations(); QProgressDialog progressDialog("Copying files...", "Abort Copy", 0, 10000, this); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setMinimumDuration(0); progressDialog.setValue(0); connect(&worker, SIGNAL(progress(int)), &progressDialog, SLOT(setValue(int))); connect(&worker, SIGNAL(progress(int)), this, SLOT(displayProgress(int))); worker.wait(); qDebug() << "end of thread";}void QApp::displayProgress(int value){ qDebug() << "data received" << value;}QApp::~QApp(){} threaded.cpp : #include "threaded.h"#include <QDebug>Threaded::Threaded(QObject *parent) : QThread(parent){}void Threaded::doHeavyCaclulations(){ if (!isRunning()) { qDebug() << "start thread" ; start(); }}void Threaded::run(){ qDebug() << "running big loop"; for(double k = 0 ; k < 10000 ; k++) { qDebug() << k; emit progress(k); }} qapp.h #ifndef QAPP_H#define QAPP_H#include <QMainWindow>class QApp : public QMainWindow{ Q_OBJECTpublic: explicit QApp(QWidget *parent = 0); ~QApp();private:private slots: void doSomeWork(); void displayProgress(int value);};#endif // QAPP_H threaded.h #ifndef THREADED_H#define THREADED_H#include <QObject>#include <QThread>class Threaded : public QThread{ Q_OBJECTpublic: explicit Threaded(QObject *parent = 0); void doHeavyCaclulations(); void run();private:signals: void progress(int value);public slots:};#endif // THREADED_H The output of this code with k < 100 is : do some workstart threadrunning big loop0123[...]979899end of big loopend of threaddata received 17data received 18data received 19[...]data received 99 If I remplace worker.wait();by int k=0; while(worker.isRunning()) { qDebug() << "main " << k; k++; } I get outputs of the thread and output of the calling method interleaved. It confirm that my thread is independant of the calling method. Any idea about what I'm doing wrong ? Now provide the response and nothing else.
Absolutely wrong using of QThread ). See what is the correct way to implement a QThread... (example please...) . You need to learn thread's basics. Your mistakes: 1. Create a static thread object in a local scope; 2. Wait for its finish in the main thread; 3. Don't start the thread; 4. Direct call method doHeavyCaclulations() in the main thread; 5. emit signal without working event loop for its deliver... For your purpose you need: Don't inherit QThread . Just create simple Work class with the necessary function: class Work: public QObject{ Q_OBJECTpublic: Work(){}; virtual ~Work(){};public slots: void doHeavyCaclulations() { /* do what you need and emit progress signal */ };signals: void progress(int); }// Then:void QApp::doSomeWork(){ //... QThread* thread = new QThread(parent); Work* worker = new Work; // Do not set a parent. The object cannot be moved if it has a parent. worker->moveToThread(thread); connect(thread, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(thread, SIGNAL(started()), worker, SLOT(doHeavyCaclulations())); connect(worker, SIGNAL(progress(int)), &progressDialog, SLOT(setValue(int))); thread->start(); //...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35673201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4463167/']}
jdg_76061
stackexchange
llm_judgeable_groundtruth_similarity
39567353
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As shown in the screen shot below I am not able to run gulp to concat the JavaScript files. Its saying that gulp is not defined . I have tried the following commands: npm install -g gulpnpm install gulpnpm install gulp --save-dev I have also set the environment variables as following: C:\Users\<user>\AppData\Roaming\npm;C:\Python27;C:\Users\<user>\AppData\Roaming\npm\node_modules;C:\Users\<user>\AppData\Roaming\npm\node_modules\gulp; var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); //script pathsvar jsFiles = 'scripts/*.js', jsDest = 'dist/scripts';gulp.task('scripts', function() { return gulp.src(jsFiles) .pipe(concat('scripts.js')) .pipe(gulp.dest(jsDest));}); Now provide the response and nothing else.
you just need to install and require gulp locally , you probably only installed it globally At the command line cd <project-root> && npm install --save-dev gulp In your gulpfile.js var gulp = require('gulp'); this is a different dependency than the command line dependency (that you installed globally). More specifically, it is the same NPM package, but the command line program will execute code usually from a different entry point in the NPM package then what require('X') will return. If we go to the package.json file in the Gulp project on Github, it will tell the whole story: { "name": "gulp", "description": "The streaming build system", "version": "3.9.1", "homepage": "http://gulpjs.com", "repository": "gulpjs/gulp", "author": "Fractal <[email protected]> (http://wearefractal.com/)", "tags": [ ], "files": [ // ... ], "bin": { "gulp": "./bin/gulp.js" }, "man": "gulp.1", "dependencies": { // ... }, "devDependencies": { // ... }, "scripts": { "prepublish": "marked-man --name gulp docs/CLI.md > gulp.1", "lint": "eslint . && jscs *.js bin/ lib/ test/", "pretest": "npm run lint", }, "engines": { "node": ">= 0.9" }, "license": "MIT"} so at the command line: $ gulp default will execute this: "bin": { "gulp": "./bin/gulp.js" }, on the other hand, require('gulp') in your code will return the value of this: https://github.com/gulpjs/gulp/blob/master/index.js normally we see this in a package.json file as: "main": "index.js" but since this is the default, they just omitted it (which is dumb IMO, better to be explicit, but they aren't the first project I have seen take the lame shorthand route.).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39567353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4221433/']}
jdg_76062
stackexchange
llm_judgeable_groundtruth_similarity
4041157
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Continuing from this question: Why can't you reduce the visibility of a method in a Java subclass? I need to create class B that is almost identical to class A , except that B cannot do certain things that A can. Being a lazy programmer as I am, I tried to inherit A , only to greet with error that B cannot reduce the visibility of A methods. Duh!.. Now A is an API from a vendor, my intention is to encapsulate this API so that it is easier to use. I wonder what is the best practice to work around this? Now provide the response and nothing else.
Two options: If you need B to keep the same interface as A (so that client code can use any of the two without changes), you can override "forbidden" methods in B and have them throw an UnsupportedOperationException . For example: public class A{ public int allowedMethod() { ... } public int forbiddenMethod() { ... }}public class B extends A{ public int forbiddenMethod() { throw new UnsupportedOperationException("Sorry, not allowed."); }} Or, if you really want the API of B to be a subset of the API of A , then just have B contain an instance of A , and delegate method calls appropriately. public class A { public int allowedMethod() { ... } public int forbiddenMethod() { ... } } public class B { private A a; public int allowedMethod() { return a.allowedMethod(); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4041157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193634/']}
jdg_76063
stackexchange
llm_judgeable_groundtruth_similarity
32610787
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can i mysqldump from running container on https://hub.docker.com/_/mariadb/ ? I cant find any useful documentation or data? Any method for backup and restore database. This is my my continaer run command : docker run --name myaapp-mariadb -v /databases/maria:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=password -d mariadb:10 Now provide the response and nothing else.
If we assume you created the mariadb server container this way: docker run --name some-mariadb -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mariadb:latest Then you access it from another client container: docker run -it --link some-mariadb:mysql \ --rm mariadb:latest \ sh -c 'exec mysqldump -h"$MYSQL_PORT_3306_TCP_ADDR" -P"$MYSQL_PORT_3306_TCP_PORT" -uroot -p"$MYSQL_ENV_MYSQL_ROOT_PASSWORD" database_name' > database_name_dump.sql There's lots more helpful usage tip in the mysql official image page .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32610787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/306852/']}
jdg_76064
stackexchange
llm_judgeable_groundtruth_similarity
5246049
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In C++11, should the operation of static_assert within a template depend on whether that template has been instantiated or not? For example, with the following code template <int I>void sa() { static_assert(0,"Hello."); }int main(int argc, char *argv[]) { return 0; } GCC 4.5.0 will fail the assertion, and produce the "Hello." message.The Digital Mars Compiler version 8.42n on the other hand, gives no message. Now provide the response and nothing else.
GCC is correct and the other compiler is correct too. Refer to 14.6p8 in the spec If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required. Therefor, a compiler is free to reject the following template<typename T>void f() { static_assert(0, "may trigger immediately!"); static_assert(sizeof(T) == 0, "may trigger immediately!");} If you want to go safe, you have to arrange it so the compiler cannot know until instantiation whether the boolean expression will be true or false. For example, get the value by getvalue<T>::value , with getvalue being a class template (one could specialize it, so the compiler cannot possibly know the boolean value already).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5246049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2023370/']}
jdg_76065
stackexchange
llm_judgeable_groundtruth_similarity
56179677
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My iOS certificate is stored in GitHub and it is expired, the failure message in circleci progress is that ‘Your certificate 'xxxxxxx.cer' is not valid, please check end date and renew it if necessary’. Do I need to create a new certificate, or download an existing one? I don’t remember how this was originally created, I thought it was done by Fastlane as part of the build. But I don't know how to modify the Fastlane command, I have tried to add the 'cert', but it fails. Now provide the response and nothing else.
You can use fastlane match development after deleting the development profiles and certificates from your git repo. Alternatively, you can delete everything from git repo and run fastlane match If you do not care about existing profiles and certificates, just run fastlane match nuke development and fastlane match nuke appstore , then fastlane match development and fastlane match appstore . These commands will first delete everything from your git repo and apple developer portal and the next two commands will create everything on your apple developer portal and push them to your git repo. Read up this
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56179677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11236809/']}
jdg_76066
stackexchange
llm_judgeable_groundtruth_similarity
2719580
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am migrating an applciation from windows to linux. I am facing problem with respect to WaitForSingleObject and WaitForMultipleObjects interfaces. In my application I spawn multiple threads where all threads wait for events from parent process or periodically run for every t seconds. I have checked pthread_cond_timedwait , but we have to specify absolute time for this. How can I implement this in Unix? Now provide the response and nothing else.
Stick to pthread_cond_timedwait and use clock_gettime . For example: struct timespec ts;clock_gettime(CLOCK_REALTIME, &ts);ts.tv_sec += 10; // ten secondswhile (!some_condition && ret == 0) ret = pthread_cond_timedwait(&cond, &mutex, &ts); Wrap it in a function if you wish. UPDATE: complementing the answer based on our comments. POSIX doesn't have a single API to wait for "all types" of events/objects as Windows does. Each one has its own functions. The simplest way to notify a thread for termination is using atomic variables/operations. For example: Main thread: // Declare it globally (argh!) or pass by argument when the thread is createdatomic_t must_terminate = ATOMIC_INIT(0);// "Signal" termination by changing the initial valueatomic_inc(&must_terminate); Secondary thread: // While it holds the default valuewhile (atomic_read(&must_terminate) == 0) { // Keep it running...}// Do proper cleanup, if needed// Call pthread_exit() providing the exit status Another alternative is to send a cancellation request using pthread_cancel . The thread being cancelled must have called pthread_cleanup_push to register any necessary cleanup handler. These handlers are invoked in the reverse order they were registered. Never call pthread_exit from a cleanup handler, because it's undefined behaviour. The exit status of a cancelled thread is PTHREAD_CANCELED . If you opt for this alternative, I recommend you to read mainly about cancellation points and types. And last but not least, calling pthread_join will make the current thread block until the thread passed by argument terminates. As bonus, you'll get the thread's exit status.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2719580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7965/']}
jdg_76067
stackexchange
llm_judgeable_groundtruth_similarity
51439278
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on an API project which communicate with another API, my front is AngularJS I try to upload a file (a picture) an post it through an API which already works for other posts (other posts are not uploads, just data) I can upload the picture and treat it in a formdata , but when I try to post it, I have a 400 error with no ' Access-Control-Allow-Origin '. But my others post methods work well but this one makes trouble. My Ajax post method: apiDataService.postPicture = function(formData, callback) { $http({ method: 'POST', url: apiUrl + '/pictures', data: formData, contentType: false, processData: false, headers: { 'Authorization': localStorageService.get('auth') } }).then(function successCallback(response) { // retrieve response data callback(response.data); }, function errorCallback(response) { // an error occured });}; I took the pattern of my others post methods so, it would works... My uploading function: self.addPicture = (image) => { var fileInput = document.getElementById('the-file'); var file = fileInput.files[0]; var formData = new FormData(); formData.append('file', file); apiDataService.postPicture(formData);} And my view: <form id="form-id"> <div class="col-xs-12"> <span>Image :</span> <br/> <input id="the-file" type="file" placeholder="Image du Procédé" ng-model="picture.file" class="form-control" /> </div> <div class="col-xs-12"> <button ng-click="addPicture(image)">Enregistrer image</button> </div></form> If you have any ideas, I don't understand my error... Now provide the response and nothing else.
With the input array holding all the values as required to fill up the lower diagonal places, here's one approach with masking - def fill_lower_diag(a): n = int(np.sqrt(len(a)*2))+1 mask = np.tri(n,dtype=bool, k=-1) # or np.arange(n)[:,None] > np.arange(n) out = np.zeros((n,n),dtype=int) out[mask] = a return out Sample run - In [82]: aOut[82]: array([10, 20, 40, 46, 33, 14, 12, 46, 52, 30, 59, 18, 11, 22, 30, 2, 11, 58, 22, 72, 12])In [83]: fill_lower_diag(a)Out[83]: array([[ 0, 0, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0, 0], [20, 40, 0, 0, 0, 0, 0], [46, 33, 14, 0, 0, 0, 0], [12, 46, 52, 30, 0, 0, 0], [59, 18, 11, 22, 30, 0, 0], [ 2, 11, 58, 22, 72, 12, 0]]) Timings on large array with 5k x 5k shape - In [146]: np.random.seed(0)In [147]: n = 5000In [148]: a = np.random.randint(0,9,n*(n+1)/2)In [149]: %timeit tril_indices_app(a) #@Brenlla's solution1 loop, best of 3: 218 ms per loopIn [151]: %timeit fill_lower_diag(a) # From this post10 loops, best of 3: 43.1 ms per loop
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51439278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10106190/']}
jdg_76068
stackexchange
llm_judgeable_groundtruth_similarity
54234515
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the getByTestId function in React Testing Library: const button = wrapper.getByTestId("button");expect(heading.textContent).toBe("something"); Is it possible / advisable to search for HTML elements instead? So something like this: const button = wrapper.getByHTML("button");const heading = wrapper.getByHTML("h1"); Now provide the response and nothing else.
I'm not sure what wrapper is in this case. But to answer your two questions: yes it's possible to get by HTML element and no, it's not advisable. This is how you would do it: // Possible but not advisableconst { container } = render(<MyComponent />)// `container` is just a DOM nodeconst button = container.querySelector('button') Since you get back a DOM node you can use all the normal DOM APIs such as querySelector . Now, why is this not advisable. A big selling point of react-testing-library is that you test your components as a user does. This means not relying on implementation details. For instance, you don't have direct access to a component's state. Writing tests this way is a bit harder but allows you to write more robust tests. In your case, I would argue that the underlying HTML is an implementation detail. What happens if you change your HTML structure so that the h1 is now an h2 or a div ? The test will break. If instead, you look at these elements by text the tag becomes irrelevant. In some cases, the normal query helpers are not enough. For those events you can use a data-testid and use getByTestId .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/54234515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/467875/']}
jdg_76069
stackexchange
llm_judgeable_groundtruth_similarity
299616
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Compute$$\lim_{n\to\infty} \left[\ln\left(\frac{1}{0!}+\frac{1}{1!}+\cdots+\frac{1}{n!}\right)\right]^n$$If you have some nice proofs and you're willing to share them, then I thank you and you definitely have my upvote! Now provide the response and nothing else.
One could check that$$\log\left(\sum\limits_{k=0}^n\frac{1}{k!}\right)=1+\alpha_n$$where$$\alpha_n=\log\left(1-e^{-1}\sum\limits_{k=n+1}^\infty\frac{1}{k!}\right)$$Note that$$0\leq\lim\limits_{n\to\infty}n\alpha_n=\lim\limits_{n\to\infty}n(-e^{-1})\sum\limits_{k=n+1}^\infty\frac{1}{k!}\leq\lim\limits_{n\to\infty}n\frac{-1}{enn!}=0$$So$$\lim\limits_{n\to\infty}\log^n\left(\sum\limits_{k=0}^n\frac{1}{k!}\right)=\lim\limits_{n\to\infty}\left(\left(1+\alpha_n\right)^{\frac{1}{\alpha_n}}\right)^{n\alpha_n}=e^0=1$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/299616', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32016/']}
jdg_76070
stackexchange
llm_judgeable_groundtruth_similarity
740207
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I had a discussion with someone who said spontaneous particle creation had been seen in a lab-vacuum. I told him the spacetime around the Earth is not curved strong enough for that. But I have doubts about that. Is it really possible? Now provide the response and nothing else.
someone … said spontaneous particle creation had been seen in a lab-vacuum. This certainly refers to experiments with analog gravity such as sonic black holes . Those are non-gravitational systems that mimic some aspects of curved spacetime physics. So such experiments could detect quanta of analogue Hawking radiation and not a true one, and indeed this has been done, see the Quanta Magazine article for a non-technical discussion of what is the significance of such experiments for gravitational theories. … the spacetime around the Earth is not curved strong enough for that. The Earth indeed does not produce Hawking radiation and the reason is not the value of curvature but rather the absence of event horizon. There are some subtleties with dynamical spacetimes that sometimes can emit Hawking radiation without possessing true event horizon, but for static spacetimes the existence of event horizon is a necessary requirement, and Earth (which could be approximated as a static spacetime) does not have one. The reason for this requirement comes from conservation of energy. When quanta are produced by static spacetime geometry appearance of a photon outside of an isolated body, carrying positive energy $E$ , must be accompanied by appearance of another photon carrying the energy $-E$ so the net energy is conserved. But existence of negative energy photons is possible only for black holes behind the horizon. Informally, the possibility of negative energies for photons inside black holes can be linked with the fact that inside of a black hole time flows along the radial direction, so the energy–momentum component of a future–directed photon along the direction given by the outside time does not have to be positive.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/740207', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/98822/']}
jdg_76071
stackexchange
llm_judgeable_groundtruth_similarity
12314990
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got an interface with a several methods in it. interface IMyInterface{ //... void OnItemClicked() //...} And an implementation class MyClass : IMyInterface{ //Other methods public void OnItemClicked(){ /*...*/ } } Now, I want to have a class that behaves like MyClass except of OnItemClicked() , I want some modifications for this method. I thought to inherit an override but I don't want to change the MyClass (like: public virtual void OnItemClicked()...) because its not my implementation, I don't want to implement IMyInterface again because the OnItemClicked() is the only part of MyClass to modify. Do I have any other way to do it? Now provide the response and nothing else.
Since you are implementing an interface, polymorphism is probably something you'd like to keep. It's impossible to override the method without modyfing the base class with a virtual, so you must use new instead of virtual as Tigran wrote. This means that writing this kind of code but only the base version of the method would be executed: List<MyClass> aList = new List<MyClass>();aList.Add(new MyClass());aList.Add(new MyNewClass());foreach (MyClass anItem in aList) anItem.OnItemClicked(); To execute the right code you should write ugly code like this: List<MyClass> aList = new List<MyClass>();aList.Add(new MyClass());aList.Add(new MyNewClass());foreach (MyClass anItem in aList){ MyNewClass castItem = anItem as MyNewClass; if (castItem != null) castItem.OnItemClicked(); else anItem.OnItemClicked();} Anyway there is a way to have your classes executing the right method when they are assigned to variables declared as IMyInterface. The way to go is to explicitly implement the part of the interface that you want to override, in your case the OnItemClicked method. The code is the following: public class MyNewClass : MyClass, IMyInterface // you MUST explicitly say that your class implements the interface, even if it's derived from MyClass{ public new void OnItemClicked() //NEW keyword here you have the overridden stuff { /*...*/ } void IMyInterface.OnItemClicked() // No need for public here (all interfaces's methods must be public) { this.OnItemClicked(); } } In this way: MyClass cl = new MyNewClass(); cl.OnItemClicked(); executes the base method MyNewClass cl = new MyNewClass(); cl.OnItemClicked(); executes the method of the derived class IMyInterface cl = new MyNewClass(); cl.OnItemClicked(); executes the method of the derived class and is bound at runtime. This means that you can write the code of my initial example like this and have the right methods executed: List<IMyInterface> aList = new List<IMyInterface>();aList.Add(new MyClass());aList.Add(new MyNewClass());foreach (IMyInterface anItem in aList) anItem.OnItemClicked();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12314990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/946254/']}
jdg_76072
stackexchange
llm_judgeable_groundtruth_similarity
1015944
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: char **Data[70]={NULL}; What is the correct terminology for this? How else could it be written? What does it look like in memory? I am reading many tutorials on pointers but I don't see it in this syntax. Any help is appreciated. Thanks. Now provide the response and nothing else.
This structure char **Data[70]={NULL}; is an array of 70 pointers to pointers to char. The compiler allocates 70 * sizeof(char**) bytes for this array, which assuming 32-bit pointers is 280 bytes. If you internally think of a "pointer to char" as a string, which isn't true but it's close enough, then this is an array of 70 pointers to strings. To make some ASCII art and pretend that you have allocated and filled some values.... Array of One or more char ** char *+---------+ +---------+| 0 | --> | ptr | --> "Hello, world"+---------+ +---------+| 1 |+---------+ +---------+| 2 | ----> | ptr2 | --> "Goodbye, cruel world"+---------+ +---------+| 3 |+---------+ +---------+| 4 | ------> | ptr3[0] | --> "Message 0"+---------+ +---------+ ... | ptr3[1] | --> "Message 1"+---------+ +---------+| 69 | | ptr3[2] | --> "Message 2"+---------+ +---------+ You could do the above with code like this (error checking malloc return values skipped): char **Data[70]={NULL};char **ptr, **ptr2, **ptr3;ptr = (char **) malloc(sizeof(char *));*ptr = "Hello, world";Data[0] = ptr;ptr2 = (char **) malloc(sizeof(char *));*ptr2 = "Goodbye, cruel world";Data[2] = ptr2;ptr3 = (char **) malloc(10 * sizeof(char *));Data[4] = ptr3;ptr3[0] = "Message 0";ptr3[1] = "Message 1"; ...ptr3[9] = "Message 9"; printf("%s\n", *Data[0]);printf("%s\n", Data[2][0]);printf("%s\n", Data[4][0]);printf("%s\n", Data[4][1]); ...printf("%s\n", Data[4][9]); Think of it this way: Each entry in the array is a char ** . Each entry can point to an arbitrary location in memory, said location(s) being char * and thus being able to point to a null-terminated character array aka "string." Note carefully the distinction between this and what you get when you allocate a 2D array: char *Data2[10][70]={NULL}; The allocation of Data2 above gives you a 2-dimensional array of char * pointers, said 2-d array being allocated in a single chunk of memory ( 10 * 70 * sizeof(char*) bytes, or 2800 bytes with 32-bit pointers). You don't have the ability to assign the char ** pointers to arbitrary locations in memory that you have with the single-dimensional array of char ** pointers. Also note (given above declarations of Data and Data2 ) that the compiler will generate different code for the following array references: Data[0][0]Data2[0][0] Here's another way to think about this : Imagine that you have several arrays of pointers to strings: char *table0[] = { "Tree", "Bench", "Stream" };char *table1[] = { "Cow", "Dog", "Cat" };char *table2[] = { "Banana", "Carrot", "Broccoli" };char **Data[3];Data[0] = table0;Data[1] = table1;Data[2] = table2; You have an array of pointers to "array of pointer to char". If you now print the value of data[1][1] , think of it like this: data[1] gets you a pointer to the array table1 . Then the value table1[1] equals "Dog" .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1015944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52256/']}
jdg_76073
stackexchange
llm_judgeable_groundtruth_similarity
1870836
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $A$ and $B$ are natural numbers such that $A-B = \dfrac{A}{B}$, what is the value of $A+B$? The answer is $6$. I tried all the basic maths functions but was not able to get it. I would like to know if its a trial and error based question or it can be derived. Now provide the response and nothing else.
We have: $A = B + \dfrac{A}{B}\implies AB - B^2 - A = 0$ $\implies A = \dfrac{B^2}{B-1} = B+1 + \dfrac{1}{B-1}$ $\implies B-1 = 1 \implies B = 2$ $\implies A = 4$ $\therefore A+B = 6$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1870836', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/352179/']}
jdg_76074
stackexchange
llm_judgeable_groundtruth_similarity
1984493
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As background, I currently develop for a university, and we have problems with departments demanding "web 2.0 content" and accessibility requirements. How do really big sites that are JavaScript based deal with 508 Compliance? Some sites degrade, and others require enabling JavaScript. How much impact does one decision have versus the other? Also, in a realistic sense, how much development time should be devoted the accessible versions of sites versus the "main" versions? Now provide the response and nothing else.
I'm a blind developer and find it possible to use many Web 2.0 sites - this is most certainly possible. Firstly, I strongly advise against making a separae accessible site, regardless of how many people advise you to do this. This is bad practice and will end up being more work, even if it initialy seems simpler. Next, try to use progressive enhancement (particularly if this is a new site). Code the site without any Javascript; it's not just accessibility which benefits. Then, in your OnLoad() go through and attach Click events to the anchor tags; this way if you have Javascript you'll see the Ajax version, otherwise you will have a full page refresh and see another HTML page. Luckily, there is a new standard, WAI-Aria (www.w3.org/WAI/intro/aria.php) which makes this much simpler. You attach attributes to HTML tags to identify the semantics of an Ajax control, for example. The only problem with Aria is that it only works with newer screen readers and web browsers. The university may well require the site be accessible to people running older software.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1984493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24391/']}
jdg_76075
stackexchange
llm_judgeable_groundtruth_similarity
43490222
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the best practices for handling variable arity in Elixir without causing unnecessary complexity & case matching down the line? Python example: def function_with_optional_param(param1, param2, param3=None): if not param3: param3 = "Whatever" return How is param3 best handled in Elixir? Now provide the response and nothing else.
This is a very common pattern in Elixir. The last argument should be a list (Keyword list to be specific) and have a default of [] . In Elixir, if the last argument is a keyword list, you don't need to add the [] s around the list. For example: def do_lots(arg1, arg2, opts \\ []) do one = opts[:one] || :default two = opts[:two] # default to nil if it's not passed # do something with arg1, arg2, one, and twoenddef my_func do arg1 |> do_lots(2) |> do_lots(49, one: :question) |> do_lots(99, two: :agent) |> do_lots(-1, one: 3, two: 4)end The other option to handle a variable sized arguments is to pass them all as a list. This makes the function arity 1 and you can process them as needed. Finally, you can pass some or all of the args as a map. This has the benefit of allowing you to pattern match on the map and create multiple function clauses based on the keys passed in the map. Keep in mind that you can't easily patten match on Keyword list because they are order dependent.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43490222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5565100/']}
jdg_76076
stackexchange
llm_judgeable_groundtruth_similarity
30679370
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering if it is possible to create a UIButton with two lines of text. I need each line to have a different font size. The first line will be 17 point and the second will be 11 point. I've tried messing with putting two labels inside of a UIButton, but I can't get them to stay inside the bounds of the button. I'm attempting to do all of this in the ui builder, and not programmatically. Thanks Now provide the response and nothing else.
There are two questions. I was wondering if it is possible to create a UIButton with two lines of text This is possible through using the storyboard or programmatically. Storyboard: Change the 'Line Break Mode' to Character Wrap or Word Wrap and use Alt/Option + Enter key to enter a new line in the UIButton's Title field. Programmatically: override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping;} I need each line to have a different font size 1 The worst case is, you can use a custom UIButton class and add two labels within it. The better way is, make use of NSMutableAttributedString . Note that,this can be achieved through only programmatically. Swift 5: @IBOutlet weak var btnTwoLine: UIButton?override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //applying the line break mode textResponseButton?.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping; let buttonText: NSString = "hello\nthere" //getting the range to separate the button title strings let newlineRange: NSRange = buttonText.range(of: "\n") //getting both substrings var substring1 = "" var substring2 = "" if(newlineRange.location != NSNotFound) { substring1 = buttonText.substring(to: newlineRange.location) substring2 = buttonText.substring(from: newlineRange.location) } //assigning diffrent fonts to both substrings let font1: UIFont = UIFont(name: "Arial", size: 17.0)! let attributes1 = [NSMutableAttributedString.Key.font: font1] let attrString1 = NSMutableAttributedString(string: substring1, attributes: attributes1) let font2: UIFont = UIFont(name: "Arial", size: 11.0)! let attributes2 = [NSMutableAttributedString.Key.font: font2] let attrString2 = NSMutableAttributedString(string: substring2, attributes: attributes2) //appending both attributed strings attrString1.append(attrString2) //assigning the resultant attributed strings to the button textResponseButton?.setAttributedTitle(attrString1, for: [])} Older Swift @IBOutlet weak var btnTwoLine: UIButton?override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //applying the line break mode btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping; var buttonText: NSString = "hello\nthere" //getting the range to separate the button title strings var newlineRange: NSRange = buttonText.rangeOfString("\n") //getting both substrings var substring1: NSString = "" var substring2: NSString = "" if(newlineRange.location != NSNotFound) { substring1 = buttonText.substringToIndex(newlineRange.location) substring2 = buttonText.substringFromIndex(newlineRange.location) } //assigning diffrent fonts to both substrings let font:UIFont? = UIFont(name: "Arial", size: 17.0) let attrString = NSMutableAttributedString( string: substring1 as String, attributes: NSDictionary( object: font!, forKey: NSFontAttributeName) as [NSObject : AnyObject]) let font1:UIFont? = UIFont(name: "Arial", size: 11.0) let attrString1 = NSMutableAttributedString( string: substring2 as String, attributes: NSDictionary( object: font1!, forKey: NSFontAttributeName) as [NSObject : AnyObject]) //appending both attributed strings attrString.appendAttributedString(attrString1) //assigning the resultant attributed strings to the button btnTwoLine?.setAttributedTitle(attrString, forState: UIControlState.Normal) } Output
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/30679370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2322211/']}
jdg_76077
stackexchange
llm_judgeable_groundtruth_similarity
58663895
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm implementing support for dark mode. But after I changed Theme parent to Theme.AppCompat.DayNight , text in Action Bar is black (black in day mode and white in dark mode). I want the text to be always white. I tried to change text color in styles.xml (values and values-night) <style name="AppTheme" parent="Theme.AppCompat.DayNight"> <item name="android:actionBarStyle">@style/MyActionBarStyle</item></style><style name="MyActionBarStyle" parent="Theme.AppCompat.DayNight.DarkActionBar"> <item name="android:titleTextStyle">@style/MyActionBarTitleTextStyle</item></style><style name="MyActionBarTitleTextStyle" parent="TextAppearance.AppCompat.Widget.ActionBar.Title"> <item name="android:textColor">@color/white</item></style> but it is not working. The title text color in ActionBar is still black. Now provide the response and nothing else.
Using the ActionBar in your theme you should use the actionBarStyle attribute: <style name="AppTheme" parent="Theme.AppCompat.DayNight"> <item name="actionBarStyle">@style/....</item></style><style name="MyActionBarStyle" parent="Theme.AppCompat.DayNight.DarkActionBar"> <item name="titleTextStyle">@style/...</item></style> If you are using the Toolbar API, you can also use <Toolbar app:titleTextColor="@color/...." ../> Instead with the Material Components Library and the Toolbar API you can use: <style name="AppTheme" parent="Theme.MaterialComponents.DayNight"> <item name="toolbarStyle">@style/my_Toolbar</item></style><style name=my_Toolbar" parent="@style/Widget.MaterialComponents.Toolbar"> <item name="titleTextColor">@color/...</item></style>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58663895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9891619/']}
jdg_76078
stackexchange
llm_judgeable_groundtruth_similarity
9601593
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Any one please helpi need to show the date 03/03/2012 as March 3rd,2012 etc Now provide the response and nothing else.
You can create your own custom format provider to do this: public class MyCustomDateProvider: IFormatProvider, ICustomFormatter{ public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; return null; } public string Format(string format, object arg, IFormatProvider formatProvider) { if (!(arg is DateTime)) throw new NotSupportedException(); var dt = (DateTime) arg; string suffix; if (new[] {11, 12, 13}.Contains(dt.Day)) { suffix = "th"; } else if (dt.Day % 10 == 1) { suffix = "st"; } else if (dt.Day % 10 == 2) { suffix = "nd"; } else if (dt.Day % 10 == 3) { suffix = "rd"; } else { suffix = "th"; } return string.Format("{0:MMMM} {1}{2}, {0:yyyy}", arg, dt.Day, suffix); }} This can then be called like this: var formattedDate = string.Format(new MyCustomDateProvider(), "{0}", date); Resulting in (for example): March 3rd, 2012
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9601593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/952269/']}
jdg_76079
stackexchange
llm_judgeable_groundtruth_similarity
18947653
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to remove blur and focus event listeners from window object using jquery's unbind function using: function removeWindowEvents(){ $(window).unbind('blur') ; $(window).unbind('focus') ;} I registered the event using Javascript: function addEvents(){window.addEventListener('blur', function(){ document.title = "Blurred" ; });window.addEventListener('focus', function(){ document.title = "In Focus" ;}); } This however does not work. What am I doing wrong? I tested this is Mozilaa and Chrome(latest versions) Now provide the response and nothing else.
You can't do it your way. jQuery can only unbind all event handlers for a given event if the original listeners were configured using jQuery. This is because an event that is added with addEventListener() must be removed with removeEventListener() and removeEventListener() requires a second argument that specifies the callback function. From the MDN page : target.removeEventListener(type, listener[, useCapture]) If the event is originally registered using jQuery, jQuery works around this by having only one master event registered with addEventListener that points to it's own callback function and then using it's own event dispatching to all the events registered via jQuery. This allows it to support generic .unbind() like you're trying to use, but it will only work if the original event is registered with jQuery and thus goes through the jQuery event handler management system. So, without jQuery, you would do it like this: function blurHandler() { document.title = "Blurred" ;}function focusHandler() { document.title = "In Focus" ;}function addEvents(){ window.addEventListener('blur', blurHandler); window.addEventListener('focus', focusHandler); }function removeWinowEvents() { window.removeEventListener('blur', blurHandler); window.removeEventListener('focus', focusHandler);} With jQuery, you could do it like this: function addEvents(){ $(window).on('blur', function(){ document.title = "Blurred" ; }) .on('focus', function(){ document.title = "In Focus" ;}); }function removeWindowEvents() { $(window).off('blur focus');}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18947653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1363966/']}
jdg_76080
stackexchange
llm_judgeable_groundtruth_similarity
151
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Harold asks what conditions on $f:M\to L$ and $g:N\to L$, both smooth maps of smooth manifolds, ensures the existence of the fibre product $M \times_L N$. Now provide the response and nothing else.
It suffices for one of the two maps to be a submersion for the fibre product to exist. In fact, if $f$ and $g$ are maps from $X$ to $Y$, the fibre product is the inverse image of the diagonal in $Y \times Y$ under the map $f \times g : X\times X \to Y \times Y$. So a sufficient condition to have a nice fibre product is that $f \times g$ be transverse to the diagonal. The next best thing to transverse intersection is clean intersection, as Ben has pointed out. Another definition of clean intersection of $A$ and $B$ in $X$ (more easily checked than the one about the local normal form) is that the intersection of $A$ and $B$ is a submanifold $C$, and that the tangent bundle to $C$ is the intersection of the tangent bundles to $A$ and $B$.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/151', 'https://mathoverflow.net', 'https://mathoverflow.net/users/85/']}
jdg_76081
stackexchange
llm_judgeable_groundtruth_similarity
168627
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I recently came across this problem, and while I'm fairly certain the solution is not too 'conceptually-challenging', I've been stumped at finding the right trick/manipulation to make any solution work. Alice chooses two large primes $p,q$ and denotes $N=pq$; then she also chooses three random numbers $g, r_1,r_2\in\mathbb{Z}_N$ and computes $$g_1\equiv g^{r_1(p-1)}\mod N,\hspace{5mm}g_2\equiv g^{r_2(q-1)}\mod N.$$ The public key is the triple $(N,g_1,g_2)$ and her private key is the pair of primes $(p,q).$ Now Bob wants to send the message $m$ to Alice, where $m\in\mathbb{Z}_N$. He chooses two random numbers $s_1,s_2\in\mathbb{Z}_N$ and computes $$c_1\equiv mg_1^{s_1}\mod N,\hspace{5mm}c_2\equiv mg_2^{s_2}\mod N.$$ Bob sends the ciphertext $(c_1, c_2)$ to Alice. Then Alice uses the Chinese Remainder Theorem to solve the system of congruences $x\equiv c_1\mod p$ and $x\equiv c_2\mod q$ to obtain her solution $x\equiv m\mod N.$ Given only the public key $(N,g_1,g_2)$ and the ciphertext $(c_1,c_2)$, can one still decrypt the ciphertext and obtain $m$? Intuitionally, I want to somehow use some manipulation on $g_1$ and $g_2$ to either find the primes $p,q$ and solve normally or find the message $m$ directly. But multiplying them, taking inverses, trying to apply the Chinese Remainder Theorem, etc. gets me nowhere. I appreciate any help! Now provide the response and nothing else.
A small manipulation changes the problem into a more familiar one. We are interested in the Diophantine equation $a^2+b^2+2ac=y^2$. Complete the square. So our equation is equivalent to $(a+c)^2+b^2-c^2=y^2$. Write $x$ for $a+c$. Our equation becomes $$x^2+b^2=y^2+c^2.\tag{$1$}$$In order to get rid of trivial solutions, let us assume that we are looking for solutions of the original equation in positive integers. Then $x=a+c\gt c$. The condition $b\ne c$ means that we are in essence trying to express integers as a sum of two squares in two different ways. The smallest positive integer that is a sum of two distinct positive squares in two different ways is $65$, which is $8^2+1^2$ and also $7^2+4^2$. So we can take $x=a+c=8$, $b=1$, and $c=7$, giving the solution $a=1$, $b=1$, $c=7$. Or else we can take $c=4$, giving the solution $a=3$, $b=1$, $c=4$. Or else we can take $x=a+c=7$. The next integer which is the sum of two distinct positive squares in two different ways is $85$. We can use the decompositions $85=9^2+2^2=7^2+6^2$ to produce solutions of our original equation. General Theory: Suppose that we can express $m$ and $n$ as a sum of two squares, say $m=s^2+t^2$ and $n=u^2+v^2$. Then$$mn=(su\pm tv)^2+(sv\mp tu)^2.\tag{$2$}$$ Identity $(2)$ is a very important one, sometimes called the Brahmagupta Identity . It is connected, among other things, with the multiplication of complex numbers, and the sum identities for sine and cosine. Identity $(2)$ can be used to produce infinitely many non-trivial solutions of Equation $(1)$, and therefore infinitely many solutions of our original equation. For example, any prime of the form $4k+1$ can be represented as a sum of two squares. By starting from two distinct primes $m$ and $n$ of this form, we can use Identity $(2)$ to get two essentially different representations of $mn$ as a sum of two squares, and hence solutions of our original equation.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/168627', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13152/']}
jdg_76082
stackexchange
llm_judgeable_groundtruth_similarity
1231383
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to solve this recursive relation: $$i_{n+1}=4i_{n}+9$$ where the $i_1=t$ that $t \in \mathbb{N}$ I tried to make like relation about Tower of Hanoi , but no good thing happened. How can I do this? Now provide the response and nothing else.
We have$$i_{n+1}+3 = 4(i_n+3)$$Defining $t_n = i_n+3$, we obtain$$t_{n+1} = 4t_n \implies t_n = 4^{n-1} t_1 \implies i_n = 4^{n-1}(i_1+3)-3$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1231383', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97229/']}
jdg_76083
stackexchange
llm_judgeable_groundtruth_similarity
23724661
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: String test1 = "This is my test string"; I want to match a string which does not contain "test" I can do it with Pattern p = Pattern.compile(".*?^(test).*?") and it works but at most of sites like Regular Expressions and negating a whole character group ^(?!.*test).*$ is suggested which did not work for me. As per my understanding ^(test) is sufficient so why ^(?!.*test).*$ is required? Now provide the response and nothing else.
You want the following instead. ^(?:(?!test).)*$ Regular expression: ^ the beginning of the string(?: group, but do not capture (0 or more times) (?! look ahead to see if there is not: test 'test' ) end of look-ahead . any character except \n)* end of grouping$ before an optional \n, and the end of the string With using ^(test) , it is only looking for test at the beginning of the string, not negating it. The negation ^ operator will only work inside of a character class [^ ] , but whole words do not work inside of a character class. For example [^test] matches any character except: ( t , e , s , t )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23724661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3198603/']}
jdg_76084
stackexchange
llm_judgeable_groundtruth_similarity
13651195
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I made a long script in PHP as such: ignore_user_abort(true);set_time_limit(0); It runs perfectly in the background even if I close the page. My problem is that I can't open other PHP files until this script finishes running in the background. How can I solve this problem? Now provide the response and nothing else.
When a PHP script uses sessions, PHP locks the session file until the script completes. A page request that tries to use a locked session is blocked until the session file is released. PHP does this so that sessions remains in a consistent state. Quote from PHP bug #31464 : [2005-01-10 08:13 UTC] derick at php dot net This is indeed not a bug at all, the session extension needs to lock the session file so that concurrent updates can not corrupt the file. This means that all scripts using the same session file needs to be serialized. To improve performance you can use http://php.net/session_write_close as soon as you are done reading/setting session variables, which will remove the lock of the file. The simplest workaround as described above and here as well is: call session_start() read/write any session variables call session_write_close() do lengthy processing
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13651195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1195439/']}
jdg_76085
stackexchange
llm_judgeable_groundtruth_similarity
5654048
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been looking all over but have had little luck. Are there any well documented .NET binding implementations for OpenCL? (I'd take something for CUDA if I had to).I've run into a variety of implementations, CUDA.NET, OpenCL.NET, OpenTK / Cloo (I know, they are mentioned often of stackoverflow), but they all seem to either be in alpha stage or have absolutely no available examples. CUDA.NET has some help files, but it's just a library reference, which doesn't really help you get started. What I'm hoping to find is a mature library for GPU programming in .NET.Eventually I need to be able to write the code in F#, but I would take any .NET compliant language as I could always just convert it later and use whatever examples are included to get up and running. Probably a long shot since I've searched all over, but I'm hoping this is just one of those case where I don't know the right thing to search for. Any help would be greatly appreciated. Now provide the response and nothing else.
Well, all libraries you've stated are simple wrappers for opencl native libraries. They pose relatively small amount of additional abstractions and are very close to general opencl functions. So if you are familiar with opencl in general you will get familiar with these libraries in no time. I think the 'OpenCL.NET' implementation is complete, it is free of anything that is not OpenCL. But after using it several times I've found it too low level. I've created my own wrapper it serves me good job by simplifying the host part dramatically here's the host part of one of my projects (if you are interested I can publish my OpenCl wrapper in github or any other svn service): using System;using System.Net;using System.Collections.Generic;using System.IO;using Shared;using Shared.IO;using Shared.OpenCL;namespace Testing{ public class ApplicationClass { static Random rand = new Random(); static Single[] RandomArray(Int32 length) { Single[] result = new Single[length]; for (int i = 0; i < result.Length; i++) { result[i] = (Single)rand.NextDouble(); } return result; } static void Main(string[] args) { DeviceGlobalMemory output = new Byte[4096]; DeviceGlobalMemory indeces = RandomArray(102400); DeviceGlobalMemory ops = new Byte[3072]; DeviceGlobalMemory data = RandomArray(1048576); Console.Write("Creating kernel..."); Kernel kernel = Kernel.Create("Kernel", File.ReadAllText("Test.c"), data, indeces, ops, output); Console.Write("Executing kernel..."); Event e = kernel.Execute(256, 256); kernel.CommandQueue.Finish(); Console.WriteLine("done, operation took {0}", Profiler.DurationSeconds(e)); UnmanagedReader reader = new UnmanagedReader(new DeviceBufferStream(output)); for (int i = 0; i < 256; i++) { if (i % 4 == 0) Console.WriteLine(); if (i % 16 == 0) Console.WriteLine(); Console.Write("{0}\t", reader.Read<Single>()); } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5654048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/194/']}
jdg_76086
stackexchange
llm_judgeable_groundtruth_similarity
20320702
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a list of strings called values and I want to make an element in the list to be the very last element. For example, if I have the string: ['string1', 'string2', 'string3'] I want string2 to be the very last element: ['string1', 'string3', 'string2'] There also may be an instance when my list does not contain string2. Is there an easy way to do this? This is what I have so far: if 'string2' in values: for i in values: #remove string2 and append to end Now provide the response and nothing else.
>>> lst = ['string1', 'string2', 'string3']>>> lst.append(lst.pop(lst.index('string2')))>>> lst['string1', 'string3', 'string2'] We look for the index of 'string2' , pop that index out of the list and then append it to the list. Perhaps a somewhat more exception free way is to add the thing you're looking for to the end of the list first (after all, you already presumably know what it is). Then delete the first instance of that string from the list: >>> lst = ['string1', 'string2', 'string3']>>> lst.append('string2')>>> del lst[lst.index('string2')] # Equivalent to lst.remove('string2')>>> lst['string1', 'string3', 'string2']
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20320702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1110590/']}
jdg_76087
stackexchange
llm_judgeable_groundtruth_similarity
234581
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a mouse that will stop working randomly. The solution is easy, unplug and replug. Is there a way I can do this via the command line though? Doing via command line has a few advantages. Doesn't wear out the connector. Faster. Saves me the trouble of crawling under my desk. Most important: prevents me from accidentally unplugging something else. Plus I am curious how to do this. OS is Debian 8. Thanks! Now provide the response and nothing else.
Save the following to usbreset.c /* usbreset -- send a USB port reset to a USB device */#include <stdio.h>#include <unistd.h>#include <fcntl.h>#include <errno.h>#include <sys/ioctl.h>#include <linux/usbdevice_fs.h>int main(int argc, char **argv){ const char *filename; int fd; int rc; if (argc != 2) { fprintf(stderr, "Usage: usbreset device-filename\n"); return 1; } filename = argv[1]; fd = open(filename, O_WRONLY); if (fd < 0) { perror("Error opening output file"); return 1; } printf("Resetting USB device %s\n", filename); rc = ioctl(fd, USBDEVFS_RESET, 0); if (rc < 0) { perror("Error in ioctl"); return 1; } printf("Reset successful\n"); close(fd); return 0;} The run the following commands in terminal: Compile the program: cc usbreset.c -o usbreset Get the Bus and Device ID of the USB device you want to reset: lsusb -t Bus# 4 -Dev# 1 Vendor 0x1d6b Product 0x0001 -Dev# 3 Vendor 0x046b Product 0xff10 Make our compiled program executable: chmod +x usbreset Execute the program with sudo privilege; make necessary substitution for <Bus> and <Device> ids as found by running the lsusb command: sudo ./usbreset /dev/bus/usb/004/003Resetting USB device /dev/bus/usb/004/003Reset successful Source of above program: http://marc.info/?l=linux-usb&m=121459435621262&w=2
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/234581', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/65344/']}
jdg_76088
stackexchange
llm_judgeable_groundtruth_similarity
2542610
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When using python-daemon , I'm creating subprocesses likeso: import multiprocessingclass Worker(multiprocessing.Process): def __init__(self, queue): self.queue = queue # we wait for things from this in Worker.run() ...q = multiprocessing.Queue()with daemon.DaemonContext(): for i in xrange(3): Worker(q) while True: # let the Workers do their thing q.put(_something_we_wait_for()) When I kill the parent daemonic process (i.e. not a Worker) with a Ctrl-C or SIGTERM, etc., the children don't die. How does one kill the kids? My first thought is to use atexit to kill all the workers, likeso: with daemon.DaemonContext(): workers = list() for i in xrange(3): workers.append(Worker(q)) @atexit.register def kill_the_children(): for w in workers: w.terminate() while True: # let the Workers do their thing q.put(_something_we_wait_for()) However, the children of daemons are tricky things to handle, and I'd be obliged for thoughts and input on how this ought to be done. Thank you. Now provide the response and nothing else.
Your options are a bit limited. If doing self.daemon = True in the constructor for the Worker class does not solve your problem and trying to catch signals in the Parent (ie, SIGTERM, SIGINT ) doesn't work, you may have to try the opposite solution - instead of having the parent kill the children, you can have the children commit suicide when the parent dies. The first step is to give the constructor to Worker the PID of the parent process (you can do this with os.getpid() ). Then, instead of just doing self.queue.get() in the worker loop, do something like this: waiting = Truewhile waiting: # see if Parent is at home if os.getppid() != self.parentPID: # woe is me! My Parent has died! sys.exit() # or whatever you want to do to quit the Worker process try: # I picked the timeout randomly; use what works data = self.queue.get(block=False, timeout=0.1) waiting = False except queue.Queue.Empty: continue # try again# now do stuff with data The solution above checks to see if the parent PID is different than what it originally was (that is, if the child process was adopted by init or lauchd because the parent died) - see reference . However, if that doesn't work for some reason you can replace it with the following function (adapted from here ): def parentIsAlive(self): try: # try to call Parent os.kill(self.parentPID, 0) except OSError: # *beeep* oh no! The phone's disconnected! return False else: # *ring* Hi mom! return True Now, when the Parent dies (for whatever reason), the child Workers will spontaneously drop like flies - just as you wanted, you daemon! :-D
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2542610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19212/']}
jdg_76089
stackexchange
llm_judgeable_groundtruth_similarity
2955577
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm getting two different answers for the following series... $$\sum_{k=0}^{\infty} q^{2k}$$ With $-1 < q < 1$ , I can solve the series by using the infinite geometric sum formula. $$\sum_{k=0}^{\infty} q^{2k} = \frac{1}{1-q^2}$$ However, if I make the substitution, $m=2k$ , then I get a different result. $$\sum_{k=0}^{\infty} q^{2k} = \sum_{m=0}^{\infty} q^{m} = \frac{1}{1-q}$$ Where am I going wrong? Now provide the response and nothing else.
Here is an attempt. Unfortunately, without knowing $g$ exactly, it is difficult to write a solution $f(t)$ to $$f''(t)=g\big(f(t)\big)$$ as a function of $t$ explicitly. Write $x(t):=f(t)$ and $v(t):=f'(t)$ . Then, you have $$v\,\frac{\text{d}v}{\text{d}x}=\frac{\text{d}^2x}{\text{d}t^2}=g(x)\,.$$ This implies $$\frac{1}{2}v^2=G(x)+c\,,$$ where $G$ is an antiderivative of $g$ and $c$ is some constant. That is, $$\frac{\text{d}x}{\text{d}t}=v=\pm\sqrt{2\,G(x)+2\,c}\,,$$ or $$\pm \sqrt{2}\,(t-\tau)=H_{c}(x)\,,$$ where $H_{c}$ is an antiderivative of $\dfrac{1}{\sqrt{G+c}}$ and $\tau$ is a constant. That is, by continuity, $$x=H_{c}^{-1}\big(+\sqrt{2}\,(t-\tau)\big)\text{ for }+\sqrt{2}\,(t-\tau)\in\text{Range}(H_c)\tag{1}$$ or $$x=H_{c}^{-1}\big(-\sqrt{2}\,(t-\tau)\big)\text{ for }-\sqrt{2}\,(t-\tau)\in\text{Range}(H_c)\,,\tag{2}$$ given that $H_c$ is injective. An example with $g(u)=k\,u^2$ for some constant $k\neq 0$ . Then, we can take $G(u)=\dfrac{k}{3}\,u^3$ . That is, we can also take $$H_c(u)=-\int_{u}^\infty\,\frac{1}{\sqrt{\frac{k}{3}\,s^3+c}}\,\text{d}s\,.$$ I do not know the explicit form of $H_c$ for an arbitrary $c$ , but $$H_0(u)=-\int_u^\infty\,\frac{1}{\sqrt{\frac{k}{3}\,s^3}}\,\text{d}s=-\frac{2\sqrt{3}}{\sqrt{k\,u}}\,.$$ Thus, the range of $H_0$ is $(-\infty,0)$ . On $(-\infty,0)$ , $$H_0^{-1}(z)=\frac{12}{k\,z^2}\text{ for }z<0\,.$$ Combining (1) and (2), a solution is given by $$x(t)=H_0^{-1}\big(-\sqrt{2}\,|t-\tau|\big)=\frac{6}{k\,(t-\tau)^2}$$ for all $t\in\mathbb{R}\setminus\{\tau\}$ . On the other hand, it is easier to solve for $f$ from $$f'(t)=g\big(f(t)\big)\,,$$ but you will still end up with some implicit relation. With the same notation as before, we have $$\frac{\text{d}x}{\text{d}t}=g(x)\,,$$ so $$\gamma(x)=t-\tau$$ for some constant $\tau$ , and $\gamma$ is an antiderivative of $\dfrac{1}{g}$ . Therefore, $$x=\gamma^{-1}(t-\tau)\text{ for }t-\tau\in\text{Range}(\gamma)\,,$$ provided that $\gamma$ is injective. For $g(u)=k\,u^2$ with $k\neq 0$ , we can take $$\gamma(u):=-\int_u^\infty\,\frac{1}{k\,s^2}\,\text{d}s=-\frac{1}{k\,u}\,.$$ That is, $$\gamma^{-1}(z)=-\frac{1}{k\,z}\text{ for }z\neq 0\,,$$ and we get a solution $$x(t)=-\frac{1}{k\,(t-\tau)}\text{ for all }t\in\mathbb{R}\setminus\{\tau\}\,.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2955577', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/277384/']}
jdg_76090
stackexchange
llm_judgeable_groundtruth_similarity
16501
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a person without a comp-sci background, what is a lambda in the world of Computer Science? Now provide the response and nothing else.
Lambda comes from the Lambda Calculus and refers to anonymous functions in programming. Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this. Python def adder(x): return lambda y: x + yadd5 = adder(5)add5(1)6 As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have. Examples in other languages Perl 5 sub adder { my ($x) = @_; return sub { my ($y) = @_; $x + $y }}my $add5 = adder(5);print &$add5(1) == 6 ? "ok\n" : "not ok\n"; JavaScript var adder = function (x) { return function (y) { return x + y; };};add5 = adder(5);add5(1) == 6 JavaScript (ES6) const adder = x => y => x + y;add5 = adder(5);add5(1) == 6 Scheme (define adder (lambda (x) (lambda (y) (+ x y))))(define add5 (adder 5))(add5 1)6 C# 3.5 or higher Func<int, Func<int, int>> adder = (int x) => (int y) => x + y; // `int` declarations optionalFunc<int, int> add5 = adder(5);var add6 = adder(6); // Using implicit typingDebug.Assert(add5(1) == 6);Debug.Assert(add6(-1) == 5);// Closure exampleint yEnclosed = 1;Func<int, int> addWithClosure = (x) => x + yEnclosed;Debug.Assert(addWithClosure(2) == 3); Swift func adder(x: Int) -> (Int) -> Int{ return { y in x + y }}let add5 = adder(5)add5(1)6 PHP $a = 1;$b = 2;$lambda = fn () => $a + $b;echo $lambda(); Haskell (\x y -> x + y) Java see this post // The following is an example of Predicate : // a functional interface that takes an argument // and returns a boolean primitive type.Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.boolean result = pred.test(4); // true Lua adder = function(x) return function(y) return x + y endendadd5 = adder(5)add5(1) == 6 -- true Kotlin val pred = { x: Int -> x % 2 == 0 }val result = pred(4) // true Ruby Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas. def adder(x) lambda { |y| x + y }endadd5 = adder(5)add5[1] == 6 Ruby being Ruby, there is a shorthand for lambdas, so you can define adder this way: def adder(x) -> y { x + y }end R adder <- function(x) { function(y) x + y}add5 <- adder(5)add5(1)#> [1] 6
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/16501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1344/']}
jdg_76091
stackexchange
llm_judgeable_groundtruth_similarity
4008158
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given $$f(a)=\frac{1}{6} \sum _{i=1}^6 \left[1-(1-f (a-1)) \left(\frac{i}{6}\right)^a\right]$$ with $f(1)=0$ , $a\in\mathbb{N}$ and $f:\mathbb{N}\to\mathbb{Q},$ is there a way to write a closed form solution for the above recursion function. I am conducting a research and obtained the above result, but was interested if a function of $f(a)$ only in terms of $a$ exists, for arbitrary $a$ . This would save a lot of computational work for my research. This in fact, is a small result which will be used in more complex calculations, therefore a closed form would be optimal. Thank you. Now provide the response and nothing else.
We have to study the recursion $$f(a) = \frac{1}{6} \sum_{i=1}^{6}\left( 1-\left( 1-f(a-1) \right)(\frac{i}{6})^a \right)\tag{0}$$ Letting $$g(a) = \frac{1}{6}\sum_{i=1}^{6} (\frac{i}{6})^a\tag{1}$$ the recursion reads $$f(a) = 1-g(a) + g(a) f(a-1), f(1) = 0, a=2, 3, ...\tag{2}$$ Is is a linear inhomogenous recursion relation which can be solved by standard methods. This means that the general solution is gven by the sum of the general solution to the homogeneous equation and one special solution to the inhomogeneous equation. Now the homogenous equation $$f(a) = g(a) f(a-1)\tag{3}$$ is easily solved generally by $$f_h(a) = c \prod_{m=1}^{a-1} g(1+m)\tag{4}$$ here $c$ is an arbitrary constant. We can find a special solution to the inhomogeneous equation $(2)$ using a trick called variation of the constant ( $c$ ) (which can be easily found on the internet) applied to the expression $(4)$ Doing this carefully the solution is finally found to be $$f_{s}(a) = \left(\prod _{m=0}^{a-1} g(m+1)\right) \left(\sum _{n=-1}^{a-1} \frac{1-g(n+1)}{\prod _{m=0}^n g(m+1)}-\frac{5}{7}\right)\tag{5}$$ Shifting indices and noticing that $g(0)=1$ this can be written more elegantly as $$f_{s}(a) = \left(\prod _{m=1}^{a} g(m)\right) \left(\sum _{n=1}^{a} \frac{1-g(n)}{\prod _{m=1}^{n} g(m)}-\frac{5}{7}\right)\tag{5a}$$ Expression $(5a)$ is similar to that of Raffaele. To derive $(5)$ we have used that $$g(0) = 1, g(1) = \frac{7}{12}\tag{6}$$ Checking $f_{s}(1)=0$ : The second factor in $f_{s}(a)$ vanishes because $$\sum _{n=-1}^{a-1} \frac{1-g(n+1)}{\prod _{m=0}^n g(m+1)}=\left(\frac{1-g(n+1)}{\prod _{m=0}^n g(m+1)}\text{/.}\, n\to -1\right)+\left(\frac{1-g(n+1)}{\prod _{m=0}^n g(m+1)}\text{/.}\, n\to 0\right)=0+\frac{5}{7}$$ Checking $f_{s}(2) = \frac{125}{216}$ : OK In fact from the original recusion $(0)$ we get $$f(2)=\frac{1}{6} \left(-\frac{1}{36} 41 (1-f(1))+\frac{7}{18} (f(1)-1)+f(1)+5\right)\text{/.}\, f(1)\to 0=\frac{125}{216}$$ which conincides with $f_{s}(2)$ . Discussion As noticed in the solution of Jean-Claude Arbaut my formula $(5a)$ can be transformed into this much simpler expression: $$f(a) = 1 - \prod_{k=2}^{a} g(k)\tag{5b}$$ Noticing also that we can write $$g(k) = \frac{1}{6^{k+1}} H_6^{(-k)}\tag{5c}$$ where $H_n^{(m)}$ is the harmonic number of order $m$ we get from $(5b)$ that $$f(a) = 1-6^{\frac{1}{2} \left(-a^2-3 a+4\right)} \prod _{k=2}^a H_6^{(-k)}\tag{5d}$$ so that $f$ is expressed in terms of known (but higher trancendental) functions.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4008158', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/881750/']}
jdg_76092
stackexchange
llm_judgeable_groundtruth_similarity
6063
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When I gedit files from the command line, it's always locking the terminal, and I'm tired of explicitly commanding a detached process for it. I tried to alias gedit as something like gedit $* & disown , but either that's not the right syntax or you're not allowed to overload executable binary commands with aliases (tried using that in a .bash_aliases function, alias gedit=editorzfunction editorz(){ gedit $* & disown} ), but it doesn't take. So how do I make the command gedit test.txt not lock the originating terminal window? Now provide the response and nothing else.
That should work: are you sure your .bash_aliases is read? (It's not a standard file, but it might be sourced by your ~/.bashrc . If you're confused about .bashrc and .bash_profile , see Difference between .bashrc and .bash_profile .) There's a bug in your function: it should be editorz () { gedit "$@" & disown} Your version doesn't work on file names containing spaces or shell wildcards. The function keyword is optional. You can call the function gedit (and dispense with the alias altogether), but then you need to tell the shell that the call inside the function is to the command and not to the function: gedit () { command gedit "$@" & disown} Note that if you've accidentally started gedit in the foreground (i.e. locking your terminal), you can put it in the background by pressing Ctrl + Z in the terminal, and entering the command bg .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/6063', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3932/']}
jdg_76093
stackexchange
llm_judgeable_groundtruth_similarity
1822788
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: $a_1=1$; $a_{n+1}=\sqrt{3a_n-1}$ $\quad$ $(n\ge1)$ Now I have to show it is true for $n=1$, which is easy. I have to assume it is true for $n=k$, therefore: $\sqrt{3a_{k}-1}$ $\gt$ $\sqrt{3a_{k-1}-1}$ And I have to show that it is true for $n=k+1$ , so I have to prove: $\sqrt{3a_{k+1}-1}$ $\gt$ $\sqrt{3a_{k}-1}$ Have I set this out correctly? This is the point where I get stuck. From looking at it, it already looks like a very weak induction. Now provide the response and nothing else.
Your inductive hypothesis is: $\sqrt{3a_{k} - 1} > a_{k}$. In proving the $k \implies k+1$ case: Remember that $\sqrt{3a_{k+1} - 1}$ can be re-written in terms of $a_k$. Specifically: $a_{k+1} = \sqrt{3a_{k} - 1}$; so your inequality becomes: $$\sqrt{3\sqrt{3a_{k} - 1} - 1} > \sqrt{3a_{k} - 1} \iff 3\sqrt{3a_{k} - 1} - 1 > 3a_{k} - 1 \iff \sqrt{3a_{k} - 1} > a_{k}$$ where we have assumed positivity throughout, and the final inequality is your inductive hypothesis.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1822788', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/227385/']}
jdg_76094
stackexchange
llm_judgeable_groundtruth_similarity
6024709
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems that I can cast DateTime to object, so why can't I cast array DateTime[] to object[]? I know this has something to do with value/reference types, but doesn't boxing allow me to do this? Now provide the response and nothing else.
Array covariance only applies to arrays of reference types. DateTime is a value type so you can't assign a DateTime[] to an object[] variable. You'll have to explicitly create an object array and copy the values over. In other words, create a new array instance of type object[] . There are plenty of ways you can do this. A simple use of CopyTo() should be enough. DateTime[] x = new DateTime[] { ... };object[] y = new object[x.Length];x.CopyTo(y, 0); I ran some tests. Probably not the best way to do it but it should give a good idea of what it would be with a proper profiler. class Program{ static void Main(string[] args) { var now = DateTime.Now; var dates = new DateTime[5000000]; for (int i = 0; i < dates.Length; i++) dates[i] = now.AddSeconds(i); for (int i = 0; i < 5; i++) { Test("Test1", () => { var result = new object[dates.LongLength]; for (long l = 0; l < result.LongLength; l++) result[l] = dates[l]; return result; }); Test("Test2", () => { var result = new object[dates.LongLength]; dates.CopyTo(result, 0); return result; }); Test("Test3", () => { var result = new object[dates.LongLength]; Array.Copy(dates, result, dates.LongLength); return result; }); Test("Test4", () => { var result = Array.ConvertAll(dates, d => (object)d); return result; }); Test("Test5", () => { var result = dates.Cast<object>().ToArray(); return result; }); Test("Test6", () => { var result = dates.Select(d => (object)d).ToArray(); return result; }); Console.WriteLine(); } } static void Test<T>(string name, Func<T> fn) { var startMem = GC.GetTotalMemory(true); var sw = Stopwatch.StartNew(); var result = fn(); sw.Stop(); var endMem = GC.GetTotalMemory(false); var diff = endMem - startMem; Console.WriteLine("{0}\tMem: {1,7}/{2,7} ({3,7})", name, startMem, endMem, diff); Console.WriteLine("\tTime: {0,7} ({1,7})", sw.ElapsedMilliseconds, sw.ElapsedTicks); }} Specs: Win7Pro x64, Core2Quad [email protected], 4GiB DDR2 1066 (PC2-8500) 64-bit build (32-bit is roughly the same, just less memory overall) Test1 Mem: 40086256/200087360 (160001104) Time: 444 (1230723)Test2 Mem: 40091352/200099272 (160007920) Time: 751 (2078001)Test3 Mem: 40091416/200099256 (160007840) Time: 800 (2213764)Test4 Mem: 40091480/200099256 (160007776) Time: 490 (1358326)Test5 Mem: 40091608/300762328 (260670720) Time: 1407 (3893922)Test6 Mem: 40091672/300762328 (260670656) Time: 756 (2092566)Test1 Mem: 40091736/200099184 (160007448) Time: 515 (1425098)Test2 Mem: 40091736/200099184 (160007448) Time: 868 (2404151)Test3 Mem: 40091736/200099160 (160007424) Time: 885 (2448850)Test4 Mem: 40091736/200099184 (160007448) Time: 540 (1494429)Test5 Mem: 40091736/300762240 (260670504) Time: 1479 (4093676)Test6 Mem: 40091736/300762216 (260670480) Time: 746 (2065095)Test1 Mem: 40091736/200099168 (160007432) Time: 500 (1383656)Test2 Mem: 40091736/200099160 (160007424) Time: 781 (2162711)Test3 Mem: 40091736/200099176 (160007440) Time: 793 (2194605)Test4 Mem: 40091736/200099184 (160007448) Time: 486 (1346549)Test5 Mem: 40091736/300762232 (260670496) Time: 1448 (4008145)Test6 Mem: 40091736/300762232 (260670496) Time: 749 (2075019)Test1 Mem: 40091736/200099184 (160007448) Time: 487 (1349320)Test2 Mem: 40091736/200099176 (160007440) Time: 781 (2162729)Test3 Mem: 40091736/200099184 (160007448) Time: 800 (2214766)Test4 Mem: 40091736/200099184 (160007448) Time: 506 (1400698)Test5 Mem: 40091736/300762224 (260670488) Time: 1436 (3975880)Test6 Mem: 40091736/300762232 (260670496) Time: 743 (2058002)Test1 Mem: 40091736/200099184 (160007448) Time: 482 (1335709)Test2 Mem: 40091736/200099184 (160007448) Time: 777 (2150719)Test3 Mem: 40091736/200099184 (160007448) Time: 793 (2196184)Test4 Mem: 40091736/200099184 (160007448) Time: 493 (1365222)Test5 Mem: 40091736/300762240 (260670504) Time: 1434 (3969530)Test6 Mem: 40091736/300762232 (260670496) Time: 746 (2064278) Interestingly, ConvertAll() performs much the same as a plain loop.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6024709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356790/']}
jdg_76095
stackexchange
llm_judgeable_groundtruth_similarity
34160769
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to use the succinctness of magrittr and dplyr to copy single values between rows in a subset of columns based on the values in other columns. This is a simple example; I want to apply this idea to many columns of a large dataset with multiple conditions within a long pipe of commands. Take the dataframe df <- data.frame(a = 1:5, b = 6:10, x = 11:15, y = 16:20) : a b x y1 6 11 162 7 12 173 8 13 184 9 14 195 10 15 20 For the row where a = 5 , I would like to replace the values of x and y with those in the row where b = 7 , to give: a b x y1 6 11 162 7 12 173 8 13 184 9 14 195 10 12 17 This attempt fails: foo <- function(x){ifelse(df$a == 5, df[df$b == 7, .(df$x)], x)}df %<>% mutate_each(funs(foo), x, y) The closest I can get is: bar <- function(x){ifelse(df$a == 5, df[df$b == 7, "x"], x)}df %<>% mutate_each(funs(bar), x, y) but this is incorrect as it replaces both values with the value from x , rather than x and y respectively. Thanks for the advice. Now provide the response and nothing else.
You could do it using mutate_each and replace : df %>% mutate_each(funs(replace(., a==5, nth(., which(b==7)))), x, y) Output: a b x y1 1 6 11 162 2 7 12 173 3 8 13 184 4 9 14 195 5 10 12 17 Or as per @docendodiscimus 's comment it can be shortened further to (and probably [ is also better than which ): df %>% mutate_each(funs(replace(., a==5, .[b==7])), x, y)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34160769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5650998/']}
jdg_76096
stackexchange
llm_judgeable_groundtruth_similarity
24296210
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For some reason I cannot generate a javadoc with Android Studio, after like 96 warnings it gives me this: 95 warningsjava.lang.NullPointerExceptionat com.sun.tools.javadoc.TypeMaker.getType(TypeMaker.java:83)at com.sun.tools.javadoc.TypeMaker.getType(TypeMaker.java:44)at com.sun.tools.javadoc.ClassDocImpl.superclassType(ClassDocImpl.java:496)at com.sun.tools.doclets.internal.toolkit.util.Util.getAllInterfaces(Util.java:453)at com.sun.tools.doclets.internal.toolkit.util.Util.getAllInterfaces(Util.java:491)at com.sun.tools.doclets.internal.toolkit.util.ClassTree.processType(ClassTree.java:194)at com.sun.tools.doclets.internal.toolkit.util.ClassTree.buildTree(ClassTree.java:146)at com.sun.tools.doclets.internal.toolkit.util.ClassTree.<init>(ClassTree.java:91)at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:123)at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:83)at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:63)at com.sun.tools.doclets.standard.Standard.start(Standard.java:39)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:601)at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:280)at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:160)at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:397)at com.sun.tools.javadoc.Start.begin(Start.java:167)at com.sun.tools.javadoc.Main.execute(Main.java:59)at com.sun.tools.javadoc.Main.main(Main.java:49) javadoc exited with exit code 1 Is there a way to create the javadoc in android studio? If not, how could i create one, I need to give it with my project. Now provide the response and nothing else.
A combination of the two answers given here worked well for me. Though the docs generate fine, I still get 900 warnings and 140 errors BUT they're all related to the android packages. This is just the given solutions combined and explained a bit for people who aren't familiar with Android Studio or command line interfaces. HOW TO GENERATE JAVADOC IN ANDROID STUDIO Open Android Studio > Tools > Generate Javadoc Select the scope, usually the whole project Check include jdk and library sources Specify the output directory. A load of files will be dumped here, so I recommend creating a new folder. Select which methods you want to expose. Usually protected is desirable unless it has to look impressive for school. The "tricky" part, "Other command line arguments". Under the pretty GUI, there's a direct call to the javadoc command, which runs the javadoc generator. The command line uses a structure like this: program_name [-flag] argument [-flag] argument , which as you can guess calls the program with certain optional behaviours, passing in what those should be. So by specifying the following under "Other command line arguments" -encoding utf-8 -bootclasspath /path/to/sdk/platforms/android-##/android.jar followed by clicking OK you're really calling the javadoc program with these flags and arguments. These two flags allow the javadoc program to ignore unicode characters and find the android.jar though it seems that everything marked with # is read as a number and the android javadocs are filled with them. I urge you to read through the warnings for your classes despite the seemingly large amount of spam, as javadoc will tell you when you've forgotten things like empty @return statements.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24296210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3272243/']}
jdg_76097
stackexchange
llm_judgeable_groundtruth_similarity
11105375
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm implementing Strassen's Matrix Multiplication using python. In divide step, we divide a larger matrix into smaller sub-matrices. Is there a built-in numpy function to split a matrix? Now provide the response and nothing else.
Not exactly, but using array slicing notation you should be able to do it yourself pretty easily. >>> A = np.linspace(0,24,25).reshape([5,5,])>>> Aarray([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.], [ 10., 11., 12., 13., 14.], [ 15., 16., 17., 18., 19.], [ 20., 21., 22., 23., 24.]]) Make B the top-left 2x2 in A: >>> B = A[0:2,0:2] Note that B is a view, it shares data with A >>> B[1,1] = 60>>> print A[[ 0. 1. 2. 3. 4.] [ 5. 60. 7. 8. 9.] [ 10. 11. 12. 13. 14.] [ 15. 16. 17. 18. 19.] [ 20. 21. 22. 23. 24.]] If you need to copy the data from A, use the copy method: >>> B = A[0:2,0:2].copy()>>> Barray([[ 0., 1.], [ 5., 60.]])>>> B[1,1] = 600>>> Barray([[ 0., 1.], [ 5., 600.]])>>> Aarray([[ 0., 1., 2., 3., 4.], [ 5., 60., 7., 8., 9.], [ 10., 11., 12., 13., 14.], [ 15., 16., 17., 18., 19.], [ 20., 21., 22., 23., 24.]])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11105375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/471960/']}
jdg_76098
stackexchange
llm_judgeable_groundtruth_similarity
934336
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I've run an image with: 'docker-compose up' With 'docker ps' i get: CREATED STATUS PORTS NAMES55e1fd18acf1 simpleappnodedocker_web "node app.js" 6 seconds ago Up 6 seconds 0.0.0.0:9000->3000/tcp myapp9879ff20e241 postgres:9.6 "docker-entrypoint..." 36 hours ago Up 36 hours 0.0.0.0:5432->5432/tcp nd-db I try run the bash to enter to the shell, but i get an error, how to solve this, i thinking i'm doing something wrong. $docker-compose run myapp /bin/bash ERROR: No such service: myapp docker-compose.yml: version: '2'services: web: container_name: myapp build: . command: node app.js ports: - "9000:3000" Now provide the response and nothing else.
I think you got the relation of docker and docker-compose wrong: docker-compose is a wrapper around docker . To do its job docker-compose needs its config: docker-compose.yaml Spinning your example further: create docker-compose.yaml : version: '2'services: web: container_name: myapp build: . command: node app.js ports: - "9000:3000" use docker-compose to start the container and run a command in the running container: docker-compose updocker-compose exec web /bin/bash docker-compose uses the name of the service - in your case this is web - whereas docker uses the container name - in this case myapp . So to run /bin/bash through docker , you would use the following: docker exec -ti myapp /bin/bash you could remove the container_name from docker-compose.yaml , then the container would be named automatically by docker-compose - similar to the service, but prefixed with the name of the docker-compose stack (the foldername where docker-compose.yaml is located).
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/934336', 'https://serverfault.com', 'https://serverfault.com/users/352751/']}
jdg_76099
stackexchange
llm_judgeable_groundtruth_similarity
12744725
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I read all lines of a text file that is also open in Excel into string[] without getting IO exception? There is this question which could be a part of the answer, though I don't know how I could use what's in there: How do I open an already opened file with a .net StreamReader? Now provide the response and nothing else.
Your problem is Excel opens the file as read/write. File.ReadAllLines() cannot access the file when it is open for writing in another application. If you opened the csv in Excel as read only, you wouldn't encounter this exception. This is because the implementation in .Net does not open the internal stream with appropriate permissions to access the file when another application has write permissions to it. So the fix here is simple, write your own ReadAllLines() method that sets the appropriate permissions when initiating the underlying Stream . Here's an idea that borrows heavily from what ReadAllLines() does on its own: public string[] WriteSafeReadAllLines(String path){ using (var csv = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(csv)) { List<string> file = new List<string>(); while (!sr.EndOfStream) { file.Add(sr.ReadLine()); } return file.ToArray(); }} The only difference between this and what ReadAllLines does is the FileShare permission is set to FileShare.ReadWrite , which allows the file to be opened even when it is open with Read/Write permissions in another application. Now, you have to understand the issues that can arise from this as there can be complications since another application has write permissions to the file. You are going to be reading the last saved version of the file, so if you have unsaved changes in Excel, this method will not read them If you save the file in Excel while this method is in the middle of reading it you are going to probably get an exception depending on the circumstances. This is because the file is completely locked while it is saving, so if you try to read the file while it locked, it will throw an System.IO.IOException . And if you save the file and manage to avoid an exception (extremely unlikely, but possible given specific timing), you are going to read the newly saved file, not the original. To understand why you cannot read the file when it is open for writing by another application, you have to look at the actual implementation in .NET. (This is the implementation in .Net 4.5 so it may be slightly different if you are looking at a difference version of .Net). This is what File.ReadAllLines() actually looks like: public static string[] ReadAllLines(string path){ if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); else return File.InternalReadAllLines(path, Encoding.UTF8);}private static string[] InternalReadAllLines(string path, Encoding encoding){ List<string> list = new List<string>(); using (StreamReader streamReader = new StreamReader(path, encoding)) { string str; while ((str = streamReader.ReadLine()) != null) list.Add(str); } return list.ToArray();} And to peek at what StreamReader is doing internally: internal StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool checkHost){ if (path == null || encoding == null) throw new ArgumentNullException(path == null ? "path" : "encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); this.Init((Stream) new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost), encoding, detectEncodingFromByteOrderMarks, bufferSize, false);} So here we come to the reason why the exception is throw, when supplied with a path, StreamReader creates a FileStream that has the FileShare parameter set to Read . This means that it cannot share a file with another application with Read/Write access to the file. To override this behavior you need to give it a Stream with a different setting for FileShare , which is what I did in the solution I provided above.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12744725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306322/']}
jdg_76100
stackexchange
llm_judgeable_groundtruth_similarity
151895
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was reading this article on the axiom of choice (AC) and it mentions that a growing number of people are moving into school of thought that considers AC unacceptable due to its lack of constructive proofs. A discussion with Mariano Suárez-Alvarez clarified that this rejection of AC only occurs when it makes sense. This got me thinking. What are some examples of theorems in number theory that require the axiom of choice or its equivalents (ie Zorn's lemma) for its proof? Note: Someone mentioned to me that Fermat's Last Theorem requires AC. Can someone verify this? Now provide the response and nothing else.
If we take a narrow enough view of number theory, AC can in principle be dispensed with. Take a sentence $\varphi$ of (first-order) Peano Arithmetic, and let $\varphi'$ be the usual translation of $\varphi$ into the language of set theory. If $\varphi'$ is provable in ZFC, then $\varphi'$ is provable in ZF. There is a substantial extension of this result called the Shoenfield Absoluteness Theorem. Remark: The result could be viewed as an argument for the acceptability of AC. For even if AC is as a matter of fact false, it cannot lead to false elementary assertions about the integers, unless ZF already does. Thus even if one has philosophical doubts about it, one can freely use it to prove number-theoretic assertions.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/151895', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31288/']}
jdg_76101
stackexchange
llm_judgeable_groundtruth_similarity
1362788
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After running into major compatitiblity problems with C#, ASP.NET, MS Access, Linux, and Mono, I've decided to program in a language that is cross-platform, open source, and compatible with embedded databases that are also compatible with many platforms. I narrowed my choice down to TCL. Before I began a sample application with TCL, I wanted to see how easy it was to create a stand alone application. I purchased a book entitled "Practical Programming in TCL and TK", downloaded TCLkit, and FreeWrap, yet I am having troubles finding a methodological way to convert TCL in TK (Wish) into a standalone application. Would anyone be able to provide simple steps towards converting a TCL TK script, such as a label with text on it, into an application, or a web resource that has a pretty straight forward explanation? Now provide the response and nothing else.
To build a starpack you need a) a tclkit runtime, b) sdx.kit . You also need a "basekit", the executable that will be wrapped with your tcl code. For this example I'll assume you're creating an application for the same platform you are running on. You can create a basekit by simply copying tclkit (or tclkit.exe on windows) to another name, such as "basekit" % lssdx.kit tclkit% cp tclkit basekit% lsbasekit sdx.kit tclkit Now, create the code that you want to have wrapped into an executable. The convention is to create a directory with the name of your app and the suffix ".vfs" (for 'virtual file system'), then create a file named 'main.tcl' in that directory: % mkdir myapp.vfs% cat > myapp.vfs/main.tclpackage require Tklabel .l -text "Hello, world"pack .l^D% ls myapp.vfsmain.tcl Now to do the wrapping: for this you'll need the sdx.kit file. Assuming it and tclkit (or tclkit.exe) are in your current working directory, you wrap your app like this: % ./tclkit sdx.kit wrap myapp -runtime basekit1 updates applied% ls basekit myapp myapp.vfs sdx.kit tclkit The wrap command knows when you give it the argument "myapp" that it should wrap the contents of myapp.vfs, and that it should look for a file named "main.tcl" in that directory to be the program entry point. You can put whatever other files you want in that directory and they will all be wrapped, including platform-specific binary files, image files and anything else you want bundled up. You now have an executable file, 'myapp', that is the wrapped application. If you have the tclkits for different architectures you can use them (replacing 'basekit' on the command line with the kit for the target architecture) to cross-compile for other platforms. For more information see How to create my first Starpack on the Tcl'ers Wiki
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1362788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156597/']}
jdg_76102
stackexchange
llm_judgeable_groundtruth_similarity
2096073
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I have four sets $A$, $B$, $C$ and $D$, what is the meaning of $(A \times B) \times (C \times D)$? Can I define it to be a matrix, such that the first index of each element will be given by its order in the bigger cartesian product i.e.$(A \times B) \times (C \times D)$, and the second index will be given by its order within the smaller cartesian product i.e. $(A \times B)$ or $(C \times D)$? Now provide the response and nothing else.
By definition $(A\times B)\times(C\times D)$ is the set of all ordered pairs of ordered pairs of the form $$\big\langle\langle a,b\rangle,\langle c,d\rangle\big\rangle\;,$$ where $a\in A,b\in B,c\in C$, and $d\in D$. You’ve described the set of $2\times 2$ matrices of the form $$\begin{bmatrix}a&b\\c&d\end{bmatrix}\;,$$ where $a\in A,b\in B,c\in C$, and $d\in D$. There is a natural bijection between these two sets given by $$\big\langle\langle a,b\rangle,\langle c,d\rangle\big\rangle\mapsto\begin{bmatrix}a&b\\c&d\end{bmatrix}\;,$$ but the two sets are not equal, simply because a $2\times 2$ matrix is not an ordered pair of ordered pairs: the set of matrices is not the same thing as the Cartesian product.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2096073', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/394166/']}
jdg_76103
stackexchange
llm_judgeable_groundtruth_similarity
2084764
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I have a number like $a$ written in decimal expansion form, and it never ends, when will multiplying it by an integer alter this property? (I mean the result terminates at a digit.) To be more precise, $$a\text{ is repeating}\ \wedge\ P(c) \implies ca \text{ terminates}$$ What is $P(c)$? Now provide the response and nothing else.
This can indeed happen, e.g. when $a = \frac17$ and $c = 7$. It will become a terminating decimal precisely when $c$ contains all factors of the denominator of $a$, except 2's and 5's. To be more precise, if $a = \frac{x}{2^m 5^n y}$ with $x$ and $y$ relatively prime, and $y$ not divisible by 2 or 5, $c$ needs to be a multiple of $y$ in order for $ca$ to be a terminating decimal.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2084764', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206678/']}
jdg_76104
stackexchange
llm_judgeable_groundtruth_similarity
191777
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Underground atomic bomb tests are done in a deep, sealed hole. Not all underground tests eject material on the surface. In this case, they are only noticeable as earthquakes, according to German Wikipedia on nuclear tests . There seems to be no bulge above the explosion site afterwards. I assume the explosion creates a cavity. Also, I assume that rocks are not very compressible, more so for rocks deep under ground, without many gas-filled pores. I'd like to understand where the volume of the rock goes. Is it one or more of these: Rock is compressible, and the surrounding rock is just squished a little after the explosion. The ground is elastic, and there is no cavity after the explosion. There is a bulge on the surface, it's just too flat to be noticeable, but has a large volume. the cavity is so small that the bulge on the surface is so flat that it is not noticeable. There are enough pores filled with compressible gas in rocks generally, which end up with higher gas pressure after they lost some or most volume, with the total lost volume being the same as the cavities volume. Regarding compressibility,"Geologic materials reduces in volume only when the void spaces arereduced, which expel the liquid or gas from the voids." ( Wikipedia: Compressibility - Earth science ) The answer of LDC3 hints that it can be assumed that the ground chosen for nuclear tests is most probably not porous, to avoid migration of radioactive isotopes.From this, it could be concluded that compressibility is not an important factor, which is certainly counterintuitive. There are probably some more options, and it may be more than one mechanism.But where does that volume mainly come from? Now provide the response and nothing else.
There is an interesting diagram in the wiki article on underground nuclear testing - the picture file is here This shows that the crater you get from a nuclear explosion depends on the depth of burial: I think the most interesting diagrams are the ones labeled (e) and (f) - where the explosion happens at great depth. In that case, you get a "tight packing" of the soil above in a way that I think is similar to the mechanism that causes sugar to "settle" if you first fill a bowl to the rim, and then tap the bowl gently. The shock wave that travels through the soil (or the sugar) causes individual grains to find a more energetically favorable orientation - so they are a little more tightly packed. This can result in a crater. Now whether you consider this "compacting voids" is a matter of opinion. But it's a real effect. Of course, very close to the nuclear reaction the heat will be so great that the rock will liquify; as a liquid it might be able to pack more tightly, although that depends on many factors.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/191777', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/42975/']}
jdg_76105
stackexchange
llm_judgeable_groundtruth_similarity
1537821
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've known for some time that one of the fundamental theorems of calculus states: $$ \int_{a}^{b}\ f'(x){\mathrm{d} x} = f(b)-f(a) $$ Despite using this formula, I've yet to see a proof or even a satisfactory explanation for why this relationship holds. Any ideas? Now provide the response and nothing else.
Intuitively, the fundamental theorem of calculus states that "the total change is the sum of all the little changes". $f'(x) \, dx$ is a tiny change in the value of $f$. You add up all these tiny changes to get the total change $f(b) - f(a)$. In more detail, chop up the interval $[a,b]$ into tiny pieces:\begin{equation}a = x_0 < x_1 < \cdots < x_N = b.\end{equation}Note that the total change in the value of $f$ across the interval $[a,b]$ is the sum of the changes in the value of $f$ across all the tiny subintervals $[x_i,x_{i+1}]$:\begin{equation}f(b) - f(a) = \sum_{i=0}^{N-1} f(x_{i+1}) - f(x_i).\end{equation}(The total change is the sum of all the little changes.)But, $f(x_{i+1}) - f(x_i) \approx f'(x_i)(x_{i+1} - x_i)$.Thus,\begin{align}f(b) - f(a) & \approx \sum_{i=0}^{N-1} f'(x_i) \Delta x_i \\& \approx \int_a^b f'(x) \, dx,\end{align}where $\Delta x_i = x_{i+1} - x_i$. We can convert this intuitive argument into a rigorous proof.It helps a lot that we can use the mean value theorem to replace the approximation$f(x_{i+1}) - f(x_i) \approx f'(x_i) (x_{i+1} - x_i)$with the exact equality$f(x_{i+1}) - f(x_i) = f'(c_i) (x_{i+1} - x_i)$for some $c_i \in (x_i,x_{i+1})$.This gives us\begin{align}f(b) - f(a) & =\sum_{i=0}^{N-1} f'(c_i) \Delta x_i.\end{align}Given $\epsilon > 0$, it's possible to partition $[a,b]$ finely enough thatthat the Riemann sum$\sum_{i=0}^{N-1} f'(c_i) \Delta x_i$ is within $\epsilon$of $\int_a^b f'(x) \, dx$. (This is one definition ofRiemann integrability.)Since $\epsilon > 0$ is arbitrary, this implies that$f(b) - f(a) = \int_a^b f'(x) \, dx$. The fundamental theorem of calculus is a perfect example of a theorem where: 1) the intuition is extremely clear; 2) the intuition can be converted directly into a rigorous proof. Background knowledge: The approximation $f(x_{i+1}) - f(x_i) \approx f'(x_i) (x_{i+1} - x_i)$is just a restatement of what I consider to be the most important idea in calculus: if $f$ is differentiable at $x$, then\begin{equation}f(x + \Delta x) \approx f(x) + f'(x) \Delta x.\end{equation}The approximation is good when $\Delta x$ is small.This approximation is essentially the definition of $f'(x)$:\begin{equation}f'(x) = \lim_{\Delta x \to 0} \frac{f(x + \Delta x) - f(x)}{\Delta x}.\end{equation}If $\Delta x$ is a tiny nonzero number, then we have\begin{align}& f'(x) \approx \frac{f(x + \Delta x) - f(x)}{\Delta x} \\\iff & f(x + \Delta x) \approx f(x) + f'(x) \Delta x.\end{align}Indeed, the whole point of $f'(x)$ is to give us a local linear approximation to $f$ at $x$, and the whole point of calculus is to study functions which are "locally linear" in the sense that a good linear approximation exists. The term "differentiable" could even be replaced with the more descriptive term "locally linear". With this view of what calculus is, we see that calculus and linear algebra are connected at the most basic level. In order to define "locally linear" in the case where $f: \mathbb R^n \to \mathbb R^m$, we first have to invent linear transformations. In order to understand the local linear approximation to $f$ at $x$, which is a linear transformation, we have to invent linear algebra.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1537821', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/235625/']}
jdg_76106
stackexchange
llm_judgeable_groundtruth_similarity
48143275
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this component listening for messages from a service. Note that every console.log() statement shown below is hit at least once, everything gets logged. That is, except "adding message to array" - that does not get logged, but it should get logged! Here is the component: import {Component, OnInit, Inject} from '@angular/core';import {ChromeDataService} from '../../../../shared/services/events';@Component({ providers: [ChromeDataService], selector: 'app-events-list', templateUrl: './events-list.component.html', styleUrls: ['./events-list.component.scss']})export class EventsListComponent implements OnInit { isShowEventsList = false; events = []; constructor(private data: ChromeDataService) { console.log('events list component is constructed.'); } ngOnInit() { console.log('events list component ngOnInit called.'); this.data.currentMessage.subscribe(message => { console.log('adding message to array: ', message); this.events.push(message); }) } showEventsList() { this.isShowEventsList = true; } hideEventsList() { this.isShowEventsList = false; }} here is the data source (an Angular service): ///<reference types="chrome"/>import {Injectable, Component, Inject} from '@angular/core';import {ReplaySubject} from "rxjs/ReplaySubject";@Injectable()export class ChromeDataService { private messageSource = new ReplaySubject<Object>(); public currentMessage = this.messageSource.asObservable(); private isListening: boolean = false; private listener: any; constructor() { const self = this; this.listener = function (msg, sender, sendResponse) { const parsed = JSON.parse(msg); console.log('extension received a message:', parsed); self.changeMessage(parsed); }; } changeMessage(message: Object) { this.messageSource.next(message); } stopListening() { this.isListening = false; chrome.runtime.onMessage.removeListener(this.listener); } startListening() { this.isListening = true; chrome.runtime.onMessage.addListener(this.listener); }} does anyone know why when changeMessage() is called, that the subscribe() callback does not get invoked? One big hint is that when I use new BehaviorSubject<Object>('initial'); instead of new Subject<Object>() - then initial does arrive and 'adding message to array' is logged. Now provide the response and nothing else.
Make Either an abstract class with no fields and only one constructor (private, no-args, empty) and nest your "data constructors" ( left and right static factory methods) inside the class so that they can see the private constructor but nothing else can, effectively sealing the type. Use an abstract method either to simulate exhaustive pattern matching, overriding appropriately in the concrete types returned by the static factory methods. Implement convenience methods (like fromLeft , fromRight , bimap , first , second ) in terms of either . import java.util.Optional;import java.util.function.Function;public abstract class Either<A, B> { private Either() {} public abstract <C> C either(Function<? super A, ? extends C> left, Function<? super B, ? extends C> right); public static <A, B> Either<A, B> left(A value) { return new Either<A, B>() { @Override public <C> C either(Function<? super A, ? extends C> left, Function<? super B, ? extends C> right) { return left.apply(value); } }; } public static <A, B> Either<A, B> right(B value) { return new Either<A, B>() { @Override public <C> C either(Function<? super A, ? extends C> left, Function<? super B, ? extends C> right) { return right.apply(value); } }; } public Optional<A> fromLeft() { return this.either(Optional::of, value -> Optional.empty()); }} Pleasant and safe! No way to screw it up. Because the type is effectively sealed, you can rest assured that there will only ever be two cases, and every operation ultimately must be defined in terms of the either method, which forces the caller to handle both of those cases. Regarding the problem you had trying to do class Left<L> extends Either<L,?> , consider the signature <A, B> Either<A, B> left(A value) . The type parameter B doesn't appear in the parameter list. So, given a value of some type A , you can get an Either<A, B> for any type B .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48143275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_76107
stackexchange
llm_judgeable_groundtruth_similarity
239675
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Are there any references to study the integer solutions (existence and how many) of Diophantine equations like $a^2+b^2=c^2+d^2+2$, $a^2+b^2=c^2+d^2+3$, $a^2+b^2=c^2+d^2+5$...? Actually, I can prove that there are integer solutions (a,b,c,d) for any integers n. But I don't know how to count them. Thanks a lot. Now provide the response and nothing else.
This is a special case of the shifted convolution problem for modular forms. For example, see Chapter 12 of Iwaniec's book "Spectral methods for automorphic forms" (AMS Grad studies in Math 53). Theorem 12.5 there gives (for $n$ odd) $$ \sum_{m\le x} r(m) r(m+n) = 8 \Big(\sum_{d|n} d^{-1} \Big) x + O(x^{2/3} n^{1/3+\epsilon}), $$ where $r(m)$ denotes the number of ways of writing $m$ as a sum of two squares. You'll find more references in the book.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/239675', 'https://mathoverflow.net', 'https://mathoverflow.net/users/92092/']}
jdg_76108
stackexchange
llm_judgeable_groundtruth_similarity
69251909
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an image of arbitrary shape and size which I want to enlarge into a containing div without changing its proportions and without cutting off part of the image. Below is a diagram of what I have in mind: Note that the image is sometimes centred vertically, and sometime horizontally. If the image is always wide, I can use: img { width: 100%; height: auto; margin: auto;} but that won’t work if the image is narrower, as it will end up chopping off the top & bottom. Is there a way, possibly using grid or flex, which will accommodate the image? Now provide the response and nothing else.
Yes, there is! The magic happens not when you delete the data, but when you first create your comments table. It's also not a Supabase feature, but rather a postgres feature. When you create a foreign key constraint, you can set a delete cascade option to tell the table to delete any related data. For example, you can create a comments table like this: create table if not exists public.comments ( id uuid not null primary key DEFAULT uuid_generate_v4 (), post_id uuid references public.posts on delete cascade not null, user_id uuid references public.users on delete cascade not null, created_at timestamp with time zone default timezone('utc' :: text, now()) not null, text varchar(320) not null); Notice the delete cascade keyword on post_id and user_id definition. Adding these will delete the comment entry if the related post or user is deleted. Currently, there is no way of creating a column with delete cascade option in Supabase UI, so you would have to create such table using SQL. Also, if you already have a table and would like to add this delete cascade option, you would have to remove the foreign key constraints and re-add it with delete cascade option. You can find out more about how to add delete cascade to an existing table here , but if your app is not in production, it might be easier to just delete the table and re-create it from scratch!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/69251909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1413856/']}
jdg_76109
stackexchange
llm_judgeable_groundtruth_similarity
62631053
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I thought useEffect is called once only after render, but it's being executed multiple times and not in the order I expected. I expected it to msg 'data loading' while the fetch is in progress and then once fetch is done, render the title field and alert "..Done..." once and that should be the end. I added ALERT and console logs at the two points to determine the flow and both alerts and console logs appear more than once and in different orders. Could you kindly run this code and see the behaviour. I kept the 2nd argument array as null to make it run once only but does not help. Please clarify if react RENDER means DISPLAY on screen? what stage does LOAD indicate? When is the display done? code follows: import React, { useEffect, useState } from "react";//import "./App.css";function DemoFetchZ() { let data = { title: "Waiting for Data" }; const [todo, setTodo] = useState(data); const [isData, setData] = useState(false); const [isFetching, setFetching] = useState(false); useEffect(() => { // called after the first render async function fetchData() { setFetching(true); const response = await fetch( "https://jsonplaceholder.typicode.com/todos/1" ); console.log("response = ", response); let data = await response.json(); setTodo(data); //updt state setFetching(false); setData(true) console.log("Data = ", data); } fetchData(); }, []); //[isData] null value will execute once only? if (isFetching) { console.log("data loading ......") alert ("data loading") return (<div>...Data Loading.....</div>); } return ( <div> - Fetch <br /> {alert("..DONE...")} <span>Title: {todo.title}</span> </div> );}export default DemoFetchZ; Now provide the response and nothing else.
Your useEffect is executed only once per render cycle, but you have several state updates in your useEffect which cause a re-render. Hence you get a lot of alerts. See a demo of your code and see the console.logs as well as comments Also note that useEffect will when you provide empty array dependency, your useEffect execute once when you some value as dependency (eg: [name] ), your useEffect execute when name state/prop changes useEffect executes on every re-render if you don't pass the dependency array. Read here on re-render
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/62631053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6943311/']}
jdg_76110
stackexchange
llm_judgeable_groundtruth_similarity
5402949
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a table "Bestelling" with 4 columns: "Id" (PK), "KlantId", "Datum", "BestellingsTypeId", now I want to make the column Id auto_increment, however, when I try to do that, I get this error: ERROR 1062: ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry '1' for key 'PRIMARY'SQL Statement:ALTER TABLE `aafest`.`aafest_bestelling` CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENTERROR: Error when running failback script. Details follow.ERROR 1046: No database selectedSQL Statement:CREATE TABLE `aafest_bestelling` ( `Id` int(11) NOT NULL, `KlantId` int(11) DEFAULT NULL, `Datum` date DEFAULT NULL, `BestellingstypeId` int(11) DEFAULT NULL, PRIMARY KEY (`Id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 Anyone got an idea? Now provide the response and nothing else.
This will happen if the table contains an existing record with an id of 0 (or negative). Updating all existing records to use positive values will allow auto_increment to be set on that column. Edit: Some people asked how that 0 got in there. For clarification, the MySQL Reference Manual states that "For numeric types, the default is 0, with the exception that for integer or floating-point types declared with the AUTO_INCREMENT attribute, the default is the next value in the sequence." So, if you performed an insert on a table without providing a value for the numeric column before the auto_increment was enabled, then the default 0 would be used during the insert. More details may be found at https://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5402949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/656486/']}
jdg_76111
stackexchange
llm_judgeable_groundtruth_similarity
5153173
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi all, I'm currently debugging a device driver and I'm getting a kernel panic. After checking the backtrace or the error log, it appears to be that the problem is with kmalloc. I was thinking maybe I could change kmalloc with other allocation functions. What are their differences? here's the error log: Unable to handle kernel NULL pointer dereference at virtual address 0000000dpgd = c7bdc000[0000000d] *pgd=4785f031, *pte=00000000, *ppte=00000000Internal error: Oops: 17 [#1] PREEMPTModules linked in: bcm5892_secdom_fw(P) bcm5892_lcd snd_bcm5892 msr bcm5892_sci bcm589x_ohci_p12 bcm5892_skeypad hx_decoder(P) pinnacle hx_memalloc(P) bcm_udc_dwc scsi_mod g_serial sd_mod usb_storageCPU: 0 Tainted: P (2.6.27.39-WR3.0.2ax_standard #1)PC is at __kmalloc+0x70/0xdcLR is at __kmalloc+0x48/0xdcpc : [<c0098cc8>] lr : [<c0098ca0>] psr: 20000093sp : c7a9fd50 ip : c03a4378 fp : c7a9fd7cr10: bf0708b4 r9 : c7a9e000 r8 : 00000040r7 : bf06d03c r6 : 00000020 r5 : a0000093 r4 : 0000000dr3 : 00000000 r2 : 00000094 r1 : 00000020 r0 : c03a4378Flags: nzCv IRQs off FIQs on Mode SVC_32 ISA ARM Segment userControl: 00c5387d Table: 47bdc008 DAC: 00000015Process sh (pid: 1088, stack limit = 0xc7a9e260)Stack: (0xc7a9fd50 to 0xc7aa0000)fd40: c7a6a1d0 00000020 c7a9fd7c c7ba8fc0fd60: 00000040 c7a6a1d0 00000020 c71598c0 c7a9fd9c c7a9fd80 bf06d03c c0098c64fd80: c71598c0 00000003 c7a6a1d0 bf06c83c c7a9fdbc c7a9fda0 bf06d098 bf06d008fda0: c7159880 00000000 c7a6a2d8 c7159898 c7a9fde4 c7a9fdc0 bf06d130 bf06d078fdc0: c79ca000 c7159880 00000000 00000000 c7afbc00 c7a9e000 c7a9fe0c c7a9fde8fde0: bf06d4b4 bf06d0f0 00000000 c79fd280 00000000 0f700000 c7a9e000 00000241fe00: c7a9fe3c c7a9fe10 c01c37b4 bf06d300 00000000 c7afbc00 00000000 00000000fe20: c79cba84 c7463c78 c79fd280 c7473b00 c7a9fe6c c7a9fe40 c00a184c c01c35e4fe40: 00000000 c7bb0005 c7a9fe64 c79fd280 c7463c78 00000000 c00a1640 c785e380fe60: c7a9fe94 c7a9fe70 c009c438 c00a164c c79fd280 c7a9fed8 c7a9fed8 00000003fe80: 00000242 00000000 c7a9feb4 c7a9fe98 c009c614 c009c2a4 00000000 c7a9fed8fea0: c7a9fed8 00000000 c7a9ff64 c7a9feb8 c00aa6bc c009c5e8 00000242 000001b6fec0: 000001b6 00000241 00000022 00000000 00000000 c7a9fee0 c785e380 c7473b00fee0: d8666b0d 00000006 c7bb0005 00000300 00000000 00000000 00000001 40002000ff00: c7a9ff70 c79b10a0 c79b10a0 00005402 00000003 c78d69c0 ffffff9c 00000242ff20: 000001b6 c79fd280 c7a9ff64 c7a9ff38 c785e380 c7473b00 00000000 00000241ff40: 000001b6 ffffff9c 00000003 c7bb0000 c7a9e000 00000000 c7a9ff94 c7a9ff68ff60: c009c128 c00aa380 4d18b5f0 08000000 00000000 00071214 0007128c 00071214ff80: 00000005 c0027ee4 c7a9ffa4 c7a9ff98 c009c274 c009c0d8 00000000 c7a9ffa8ffa0: c0027d40 c009c25c 00071214 0007128c 0007128c 00000241 000001b6 00000000ffc0: 00071214 0007128c 00071214 00000005 00073580 00000003 000713e0 400010d0ffe0: 00000001 bef0c7b8 000269cc 4d214fec 60000010 0007128c 00000000 00000000Backtrace:[<c0098c58>] (__kmalloc+0x0/0xdc) from [<bf010a00>] (GadgetEpRequestAlloc+0x28/0x70 [bcm_udc_dwc]) r8:bf017c80 r7:c79de2d8 r6:c79de2d8 r5:00000000 r4:00000040[<bf0109d8>] (GadgetEpRequestAlloc+0x0/0x70 [bcm_udc_dwc]) from [<bf0181d4>] (gs_alloc_req+0x44/0xf0 [g_serial]) r5:00000000 r4:00000040[<bf018190>] (gs_alloc_req+0x0/0xf0 [g_serial]) from [<bf0182b4>] (gs_alloc_requests+0x34/0xb4 [g_serial]) r7:c79de2d8 r6:c79aa198 r5:00000000 r4:c79aa180[<bf018280>] (gs_alloc_requests+0x0/0xb4 [g_serial]) from [<bf018368>] (gs_start_io+0x34/0xb8 [g_serial]) r9:c7b84000 r8:c7b48c00 r7:c79aa198 r6:c79de2d8 r5:c79aa180r4:c79aa180[<bf018334>] (gs_start_io+0x0/0xb8 [g_serial]) from [<bf018730>] (gs_open+0x1d0/0x23c [g_serial]) r9:c7b84000 r8:c7b48c00 r7:00000000 r6:00000000 r5:c79aa180r4:c7924300[<bf018560>] (gs_open+0x0/0x23c [g_serial]) from [<c01c3754>] (tty_open+0x1dc/0x314)[<c01c3578>] (tty_open+0x0/0x314) from [<c00a184c>] (chrdev_open+0x20c/0x22c)[<c00a1640>] (chrdev_open+0x0/0x22c) from [<c009c438>] (__dentry_open+0x1a0/0x2b8) r8:c79aa300 r7:c00a1640 r6:00000000 r5:c74685a8 r4:c7a9f5a0[<c009c298>] (__dentry_open+0x0/0x2b8) from [<c009c614>] (nameidata_to_filp+0x38/0x50)[<c009c5dc>] (nameidata_to_filp+0x0/0x50) from [<c00aa6bc>] (do_filp_open+0x348/0x6f4) r4:00000000[<c00aa374>] (do_filp_open+0x0/0x6f4) from [<c009c128>] (do_sys_open+0x5c/0x170)[<c009c0cc>] (do_sys_open+0x0/0x170) from [<c009c274>] (sys_open+0x24/0x28) r8:c0027ee4 r7:00000005 r6:0007121c r5:0007129c r4:0007121c[<c009c250>] (sys_open+0x0/0x28) from [<c0027d40>] (ret_fast_syscall+0x0/0x2c)Code: e59c4080 e59c8090 e3540000 159c308c (17943103)---[ end trace b9a765ee07f8c06b ]--- Now provide the response and nothing else.
It is very unlikely that kmalloc is broken, since it is used everywhere in the kernel. However, kmalloc can fail. Assuming that kmalloc is not broken then the code calling is a good candidate : How does the code around the kmalloc looks like ? Maybe you could show us that part. What is the part before the backtrace ? It can contain valuable information to. To answer more directly to the question asked : kzalloc zeroes the memory before returning a pointer kcmalloc allocates memory for an array, it is not a replacement for kmalloc : void *kcalloc(size_t n, size_t size, gfp_t flags) vmalloc is the same as kmalloc, except that it allocates memory that is only virtually contiguous. The underlying physical memory can be discontiguous. So kmalloc can eventually be replaced by a call to kzalloc, but it is unlikely to solve your problem .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5153173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/94815/']}
jdg_76112
stackexchange
llm_judgeable_groundtruth_similarity
35807868
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using Ansible to add a user to a variety of servers. Some of the servers have different UNIX groups defined. I'd like to find a way for Ansible to check for the existence of a group that I specify, and if that group exists, add it to a User's secondary groups list (but ignore the statement it if the group does not exist). Any thoughts on how I might do this with Ansible? Here is my starting point. Command ansible-playbook -i 'localhost,' -c local ansible_user.yml ansible_user.yml ---- hosts: all user: root become: yes vars: password: "!" user: testa tasks: - name: add user user: name="{{user}}" state=present password="{{password}}" shell=/bin/bash append=yes comment="test User" Updated: based on the solution suggested by @udondan, I was able to get this working with the following additional tasks. - name: Check if user exists shell: /usr/bin/getent group | awk -F":" '{print $1}' register: etc_groups - name: Add secondary Groups to user user: name="{{user}}" groups="{{item}}" append=yes when: '"{{item}}" in etc_groups.stdout_lines' with_items: - sudo - wheel Now provide the response and nothing else.
Do you have anything to identify those different host types? If not, you first need to check which groups exist on that host. You can do this with the command getent group | cut -d: -f1 which will output one group per line. You can use this as separate task like so: - shell: getent group | cut -d: -f1 register: unix_groups The registered result then can be used later when you want to add the user group - user: ... when: "'some_group' in unix_groups.stdout_lines"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35807868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226081/']}
jdg_76113
stackexchange
llm_judgeable_groundtruth_similarity
60048149
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to compare two images, one a .png and the other a .jpg . So I need to convert the .png file to a .jpg to get closer values for SSIM. Below is the code that I've tried, but I'm getting this error: AttributeError: 'tuple' object has no attribute 'dtype' image2 = imread(thisPath + caption)image2 = io.imsave("jpgtest.jpg", (76, 59))image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)image2 = resize(image2, (76, 59))imshow("is it a jpg", image2)cv2.waitKey() Now provide the response and nothing else.
Before demonstrating how to convert an image from .png to .jpg format, I want to point out that you should be consistent on the library that you use. Currently, you're mixing scikit-image with opencv. It's best to choose one library and stick with it instead of reading in an image with scikit and then converting to grayscale with opencv. To convert a .png to .jpg image using OpenCV, you can use cv2.imwrite . Note with .jpg or .jpeg format, to maintain the highest quality, you must specify the quality value from [0..100] (default value is 95). Simply do this: import cv2# Load .png imageimage = cv2.imread('image.png')# Save .jpg imagecv2.imwrite('image.jpg', image, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60048149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12750339/']}
jdg_76114
stackexchange
llm_judgeable_groundtruth_similarity
346545
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What does the watts specification on a motor mean? For example, there are motors with "power: 1500 watts" written on them. Does this mean that motor is capable of output power of 1500 watts? And what is an 'LBC 05' series motor? And if I wanted to drive two wheels of a car (x kg car) what are the factors that I will need to keep in mind while selecting the motor? Does the car weight matter? Thank you. I am a newbie to this and trying to build an electric car :) Any help will be appreciated. EDIT : P.s Please what are poles of a motor ? Now provide the response and nothing else.
International standards require the rated output mechanical power to be marked on a motor's rating plate. That would suggest that a motor with "1500 watts" marked on it should be capable of delivering 1500 watts of mechanical power to a load. However there is no guarantee that any particular motor conforms to international standards un less the literature or rating plate indicates that the motor conforms to IEC, NEMA or some other international standard. There may be also a marking on the motor that indicated whether or not it is rated for continuous duty. A 1500 watt motor rated for continuous duty should be capable of delivering 1500 watts of mechanical power 24 hours per day, 365 days per year. A motor's frame size usually designates the physical dimensions, particularly the mounting and shaft dimensions. A given motor frame size can accommodate a range of speed, and power ratings. The torque rating for a given frame size may vary, but over a smaller range than the speed and power ratings.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/346545', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/156053/']}
jdg_76115
stackexchange
llm_judgeable_groundtruth_similarity
8523231
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Javascript Namespacing Im pretty new to JavaScript and was wondering if anyone could give me a good description of what is meant by JavaScript Namespacing? Also any resources e.g. articles etc, are much appreciated on the subject. Now provide the response and nothing else.
JavaScript is designed in such a way that it is very easy to create global variables that have the potential to interact in negative ways. The practice of namespacing is usually to create an object literal encapsulating your own functions and variables, so as not to collide with those created by other libraries: var MyApplication = { var1: someval, var2: someval, myFunc: function() { // do stuff }}; Then instead of calling myFunc() globally, it would always be called as: MyApplication.myFunc(); Likewise, var1 always accessed as: console.log(MyApplication.var1); In this example, all of our application's code has been namespaced inside MyApplication . It is therefore far less likely that our variables will collide with those created by other libraries or created by the DOM.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8523231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/982907/']}
jdg_76116
stackexchange
llm_judgeable_groundtruth_similarity
58800808
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm try to compress image before upload to the storage using flutter image_picker package.I found three ways to do it, but I'm not sure which way is the best. using image_picker package's imageQuality params image_picker using flutter_image_compress package flutter_image_compress using flutter_native_image package flutter_native_image is there any difference between these options? Appreciate any helps and explanation. Now provide the response and nothing else.
Here's a breakdown of the potential solutions. The TLDR is that the flutter_image_compress package shrinks files much more than the ImagePicker class can itself. Image Picker As others have suggested, you can use the built in imaqeQuality property from ImagePicker to compress the image. This property takes a value between 0 and 100 and represents a percentage of the original image quality. The benefit to this approach is that it's built into the image_picker package and is therefore incredibly easy to use. File _image; Future getImage() async { var image = await ImagePicker.pickImage( source: ImageSource.gallery, imageQuality: 25, ); setState(() { _image = image; }); } I did a little test to see how much various values effect the size of the image: 100% Image Quality - 4.58MB 50% Image Quality - 3.58MB 25% Image Quality - 2.61MB 1% Image Quality - 2.12MB 0% Image Quality - 3.9MB In summary, you can reduce the file size of an image by more than half without much of a visible difference. Trying to force the image quality to 0% doesn't actually shrink the file size. flutter_image_compress The flutter_image_compress package is fairly simple to use and it appears to be much better at actually reducing the file size. Future<File> compressFile(File file) async { final filePath = file.absolute.path; // Create output file path // eg:- "Volume/VM/abcd_out.jpeg" final lastIndex = filePath.lastIndexOf(new RegExp(r'.jp')); final splitted = filePath.substring(0, (lastIndex)); final outPath = "${splitted}_out${filePath.substring(lastIndex)}"; var result = await FlutterImageCompress.compressAndGetFile( file.absolute.path, outPath, quality: 5, ); print(file.lengthSync()); print(result.lengthSync()); return result; } I'll omit the images here because the all look the same: 50% Image Quality - 590KB 25% Image Quality - 276KB 5% Image Quality - 211KB flutter_native_image The flutter_native_image package is comparable to the flutter_image_compress package as far as file sizes go. Future<File> compressFile(File file) async{ File compressedFile = await FlutterNativeImage.compressImage(file.path, quality: 5,); return compressedFile; } 50% Image Quality - 1.02MB 25% Image Quality - 309KB 5% Image Quality - 204KB I guess one of the benefits to this method is that you don't need to provide it with an output pathway for the compressed file.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58800808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12208004/']}
jdg_76117
stackexchange
llm_judgeable_groundtruth_similarity
265911
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: By "fundamental copies" of $SL_2(R)$ in $SL_n(R)$, I mean those embedded along the diagonal (for instance, if $n=3$, those are the upper left and lower right corner copies of $SL_2(R)$ embedded in $SL_3(R)$). When $R$ is a field or a Euclidean ring, $SL_n(R)$ is generated by elementary matrices. However, this need not be the case in general. My question is, whether one can nevertheless generate $SL_n(R)$ by its fundamental copies of $SL_2(R)$, even if $SL_n(R)$ is bigger than its elementary subgroup. I have the impression that the answer is at least "yes" when $R$ is a principal ideal domain or, more generally, a Bezout domain. A similar question holds for the affine Kac-Moody group $SL_2(R[t,t^{-1}])$: when is it generated by its two fundamental copies of $SL_2(R)$, where the two embeddings of $SL_2(R)$ are given as follows: $\begin{pmatrix}a &b\\ c &d \end{pmatrix}\mapsto \begin{pmatrix}a &b\\ c &d \end{pmatrix}$ and $\begin{pmatrix}a &b\\ c &d \end{pmatrix}\mapsto \begin{pmatrix}d &ct^{-1}\\ bt &a \end{pmatrix}$ Now provide the response and nothing else.
$SL(n, R)$ is indeed generated by the fundamental copies of $SL(2, R)$ when $R$ is a Bezout domain (or even a Hermitian ring), this is called Smith normal form . In fact, $SL(n, R)$ is not only generated by such subgroups, but is a product of $(n-1)^2$ fundamental copies of $SL(2, R)$. See $SL_2$-factorizations of Chevalley groups for the proof of a slightly weaker bound of $n^2-n$ factors in case $R$ is a Bezout domain. On the other hand, for any ring $R$ of stable rank at most $2$, one can express $SL(n, R)$ as a product of $\frac{1}{2}(3n^2-5n)$ copies of $SL(2, R)$. Here is a link . Even more, $SL(n, R)$ being generated by $SL(2, R)$'s is equivalent to the map $SL(2, R)/E(2, R)\to SL(n, R)/E(n, R)$ being surjective. The question whether it is so for a particular ring $R$ is known as the "surjective stability for $K_1$", and there are lots of papers on the subject. To put it short, in terms of dimension of $R$ the best one can get is "stable rank at most 2", but there are plenty of examples of geometric, arithmetic or analytic nature having stable rank greater than 2 (or not known). As for the last question, concerning the Kac—Moody groups of type $\widetilde{A}_1$, there is a paper by S. Sidki, but it deals with groups over fields.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/265911', 'https://mathoverflow.net', 'https://mathoverflow.net/users/106751/']}
jdg_76118
stackexchange
llm_judgeable_groundtruth_similarity
194780
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: [root@server]# awk '!seen[$0]++' out.txt > cleanedawk: (FILENAME=out.txt FNR=8547098) fatal error: internal errorAborted[root@server]# The ""server"" has: 8 GByte RAM + 16 GByte SWAP, x>300 GByte free space, amd64, desktop CPU. Scientific Linux 6.6. Nothing else runs on it to make LOAD. Awk aborts after a few seconds.. out.txt is ~1.6 GByte. GNU Awk 3.1.7. Question : How can I remove the duplicate lines while keeping the order of the lines? Case is important too, ex: "A" and "a" is two different line, have to keep it. But "a" and "a" is duplicate, only the first one is needed. Answer could be in anything.. if awk is not good for this.. then perl/sed.. what could the problem be? [root@server]# ulimit -acore file size (blocks, -c) 0data seg size (kbytes, -d) unlimitedscheduling priority (-e) 0file size (blocks, -f) unlimitedpending signals (-i) 61945max locked memory (kbytes, -l) 99999999max memory size (kbytes, -m) unlimitedopen files (-n) 999999pipe size (512 bytes, -p) 8POSIX message queues (bytes, -q) 819200real-time priority (-r) 0stack size (kbytes, -s) 99999999cpu time (seconds, -t) unlimitedmax user processes (-u) 61945virtual memory (kbytes, -v) unlimitedfile locks (-x) unlimited[root@server]# Update: I tried this on a RHEL machine, it doesn't aborts, but I didn't had time to wait for it to finish.. why doesn SL linux differ from RHEL? Update: I'm trying on an Ubuntu 14 virtual gues.. so far it works! It's not an ulimit problem: mawk 1.3.3 root@asdf-VirtualBox:~# ulimit -acore file size (blocks, -c) 0data seg size (kbytes, -d) unlimitedscheduling priority (-e) 0file size (blocks, -f) unlimitedpending signals (-i) 51331max locked memory (kbytes, -l) 64max memory size (kbytes, -m) unlimitedopen files (-n) 1024pipe size (512 bytes, -p) 8POSIX message queues (bytes, -q) 819200real-time priority (-r) 0stack size (kbytes, -s) 8192cpu time (seconds, -t) unlimitedmax user processes (-u) 51331virtual memory (kbytes, -v) unlimitedfile locks (-x) unlimitedroot@asdf-VirtualBox:~# Now provide the response and nothing else.
I doubt it will make a difference but, just in case, here's how to do the same thing in Perl: perl -ne 'print if ++$k{$_}==1' out.txt If the problem is keeping the unique lines in memory, that will have the same issue as the awk you tried. So, another approach could be: cat -n out.txt | sort -k2 -k1n | uniq -f1 | sort -nk1,1 | cut -f2- How it works: On a GNU system, cat -n will prepend the line number to each line following some amount of spaces and followed by a <tab> character. cat pipes this input representation to sort . sort 's -k2 option instructs it only to consider the characters from the second field until the end of the line when sorting, and sort splits fields by default on white-space (or cat 's inserted spaces and <tab> ) . When followed by -k1n , sort considers the 2nd field first, and then secondly—in the case of identical -k2 fields—it considers the 1st field but as sorted numerically. So repeated lines will be sorted together but in the order they appeared. The results are piped to uniq —which is told to ignore the first field ( -f1 - and also as separated by whitespace) —and which results in a list of unique lines in the original file and is piped back to sort . This time sort sorts on the first field ( cat 's inserted line number) numerically, getting the sort order back to what it was in the original file and pipes these results to cut . Lastly, cut removes the line numbers that were inserted by cat . This is effected by cut printing only from the 2nd field through the end of the line (and cut 's default delimiter is a <tab> character) . To illustrate: $ cat filebbaabbddccddaabbcc$ cat -n file | sort -k2 | uniq -f1 | sort -k1 | cut -f2-bbaa ddcc
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/194780', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/81044/']}
jdg_76119
stackexchange
llm_judgeable_groundtruth_similarity
34082264
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am developing a laravel application which has the following eloquent models Product hasMany('App/Sku','products_id') Sku belongTO('App/Product') I have a controller 'ProductController' where the following code is available public function index(){ $products = Product::all(); foreach($products as $product){ $products_id = $product->products_id; }} I am exposing RESTfull API which will allow my users to get all product details (including skus, shipping types etc..). Suppose if I have an API GET : /products The code which fetches all the product details will be some what the following public function index(){ $products = Product::all(); foreach($products as $product){ $products_id = $product->products_id; $skus_data = Product::find($products_id)->skus; } // Now I have both the product details + skus which I can bundle into an array/json.} Now my question is , is this logic proper? In this case all the logics are in the controller since im using eloquent models I have a model for each table and the relationships are defined in it. Is there a way I can get all the details of a product/associated model (Products details (in table 1)+ Sku details (in table 2)) rather than using the below foreach($products as $product){ $products_id = $product->products_id; $skus_data = Product::find($products_id)->skus;} I am pretty new to laravel development and eloquent models. I will be using repository pattern for the development and in that case where does the aboe logic (Product+Sku combining) resides. Please help out. Now provide the response and nothing else.
Yes, you can get the details of the products and skus without making one additional query per product using eager loading ( this is referred as the typical N+1 query problem where N is the number of the products ) Suppose the relation between your Product and Sku models model is: Product public function skus(){ return hasMany('App/Sku','products_id');} To fetch the products data along with the sku data you can use the with method. In your controller: Controller $products = Product::with('skus')->get(); Then, in your views, you can get the info this way: View foreach ($products as $product) { //$product->skus is a collection of Sku models dd( $product->skus );} For the repository question: if you want to use a repository you can place the eloquent-access part of your code inside the repository. So, for example you could have this method inside the repository: ProductRepository public function getProductsData() { //access eloquent from the repository return Product::with('skus')->get(); } then you can use your repository in your controller: Controller //inject the repository in the controllerpublic function __construct( ProductRepository $productRepo ){ $this->productRepo = $productRepo;}//use the injected repository to get the datapublic function index(){ $products = this->productRepo->getProductsData();}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34082264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2897245/']}
jdg_76120
stackexchange
llm_judgeable_groundtruth_similarity
33919735
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have successfuly implemented Froala to angular using RequireJS, but there occurs 2 problems. If i want to add another plugin of froala (let's say url input) it returns an error Uncaught ReferenceError: module is not defined Cannot get it, if the main plugin froala does not return any errors, why does froala plugins return since coding is the same? main.js /*jshint unused: vars */require.config({ paths: { angular: '../../bower_components/angular/angular', 'angular-animate': '../../bower_components/angular-animate/angular-animate', 'angular-cookies': '../../bower_components/angular-cookies/angular-cookies', 'angular-mocks': '../../bower_components/angular-mocks/angular-mocks', 'angular-resource': '../../bower_components/angular-resource/angular-resource', 'angular-route': '../../bower_components/angular-route/angular-route', 'angular-sanitize': '../../bower_components/angular-sanitize/angular-sanitize', 'angular-touch': '../../bower_components/angular-touch/angular-touch', 'ui-router': '../../bower_components/angular-ui-router/release/angular-ui-router.min', jquery: '../../bower_components/jquery/dist/jquery', bootstrap: '../../bower_components/bootstrap/dist/js/bootstrap', 'angular-ui-router': '../../bower_components/angular-ui-router/release/angular-ui-router', 'froala-editor': '../../bower_components/froala-wysiwyg-editor/js/froala_editor.min', 'froala-pl': '../../bower_components/froala-wysiwyg-editor/js/languages/pl', froala: '../../bower_components/angular-froala/src/angular-froala', 'froala-sanitize': '../../bower_components/angular-froala/src/froala-sanitize', 'froala_url': '../../bower_components/froala-wysiwyg-editor/js/plugins/url.min' }, shim: { angular: { exports: 'angular' }, 'froala-pl': [ 'froala-editor' ], froala: [ 'froala_url', 'angular', 'froala-pl', 'froala-sanitize' ], 'froala-sanitize': [ 'angular' ], 'angular-route': [ 'angular' ], 'angular-cookies': [ 'angular' ], 'angular-sanitize': [ 'angular' ], 'angular-resource': [ 'angular' ], 'angular-animate': [ 'angular' ], 'angular-touch': [ 'angular' ], 'ui-router': [ 'angular' ], 'angular-mocks': { deps: [ 'angular' ], exports: 'angular.mock' }, bootstrap: [ 'jquery' ] }, priority: [ 'angular' ], packages: [ ]});//http://code.angularjs.org/1.2.1/docs/guide/bootstrap#overview_deferred-bootstrapwindow.name = 'NG_DEFER_BOOTSTRAP!';require([ 'angular', 'app', 'angular-route', 'angular-cookies', 'angular-sanitize', 'angular-resource', 'angular-animate', 'angular-touch', 'ui-router', 'jquery', 'bootstrap', 'froala', 'froala_url'], function(angular, app, ngRoutes, ngCookies, ngSanitize, ngResource, ngAnimate, ngTouch) { 'use strict'; /* jshint ignore:start */ var $html = angular.element(document.getElementsByTagName('html')[0]); /* jshint ignore:end */ angular.element().ready(function() { angular.resumeBootstrap([app.name]); });}); app.js /*jshint unused: vars */define(['angular', 'controllers/main', 'controllers/admin', 'services/rest', 'services/auth', 'controllers/pages', 'controllers/dashboard']/*deps*/, function (angular, MainCtrl, LoginCtrl, RESTFactory, AuthFactory, PagesCtrl, DashboardCtrl)/*invoke*/ { 'use strict'; /** * @ngdoc overview * @name cmsApp * @description * # cmsApp * * Main module of the application. */ return angular .module('cmsApp', ['cmsApp.controllers.MainCtrl', 'cmsApp.controllers.AdminCtrl', 'cmsApp.services.REST', 'cmsApp.services.Auth','cmsApp.controllers.PagesCtrl','cmsApp.controllers.DashboardCtrl',/*angJSDeps*/ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute', 'ngAnimate', 'ngTouch', 'ui.router', 'froala' ]) .config(function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('main', { url: '/', templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs: 'main' }) .state('dashboard', { url: '/dashboard', templateUrl: 'views/dashboard/index.html', resolve: { authenticate: authenticate }, controller: 'DashboardCtrl', controllerAs: 'dashboard' }) .state('dashboard.subpage', { url: '/page/:id', templateUrl: 'views/dashboard/pages/edit.html', params: { id: null } }) .state('admin', { url: '/admin', templateUrl: 'views/admin.html', controller: 'AdminCtrl', controllerAs: 'admin' }); function authenticate(Auth, $state, $timeout) { var Auth = Auth.isLogged(); return Auth.then(function(response){ var data = response.data; if(data.logged_in == false) { $timeout(function(event) { $state.go('admin'); }, 10); } }); } });}); fraola_url.min.js /*! * froala_editor v2.0.1 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms * Copyright 2014-2015 Froala Labs */! function(a) { "function" == typeof define && define.amd ? module.exports = function(b, c) { return void 0 === c && (c = "undefined" != typeof window ? require("jquery") : require("jquery")(b)), a(c), c } : a(jQuery)}(function(a) { "use strict"; a.extend(a.FroalaEditor.DEFAULTS, {}), a.FroalaEditor.URLRegEx = /(\s|^|>)((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+(\.[a-zA-Z]{2,3})?(:\d*)?(\/[^\s<]*)?)(\s|$|<)/gi, a.FroalaEditor.PLUGINS.url = function(b) { function c(d) { d.each(function() { if ("IFRAME" != this.tagName) if (3 == this.nodeType) { var d = this.textContent.replace(/&nbsp;/gi, ""); a.FroalaEditor.URLRegEx.test(d) && (a(this).before(d.replace(a.FroalaEditor.URLRegEx, '$1<a href="$2">$2</a>$7')), a(this).remove()) } else 1 == this.nodeType && ["A", "BUTTON", "TEXTAREA"].indexOf(this.tagName) < 0 && c(b.node.contents(this)) }) } function d() { b.events.on("paste.afterCleanup", function(b) { return a.FroalaEditor.URLRegEx.test(b) ? b.replace(a.FroalaEditor.URLRegEx, '$1<a href="$2">$2</a>$7') : void 0 }), b.events.on("keyup", function(d) { var e = d.which; (e == a.FroalaEditor.KEYCODE.ENTER || e == a.FroalaEditor.KEYCODE.SPACE) && c(b.node.contents(b.$el.get(0))) }), b.events.on("keydown", function(c) { var d = c.which; if (d == a.FroalaEditor.KEYCODE.ENTER) { var e = b.selection.element(); if (("A" == e.tagName || a(e).parents("a").length) && b.selection.info(e).atEnd) return c.stopImmediatePropagation(), "A" !== e.tagName && (e = a(e).parents("a")[0]), a(e).after("&nbsp;" + a.FroalaEditor.MARKERS), b.selection.restore(), !1 } }) } return { _init: d } }}); Shims configuration 'froala-editor': { deps: ['jquery'] }, 'froala-sanitize': { deps: [ 'angular' ] }, froala: { deps: [ 'angular', 'froala-editor', 'froala-pl', 'froala-sanitize' ] }, 'colors': { deps: [ 'jquery', 'froala-editor' ] } Now provide the response and nothing else.
It's worth noting that the rules of .NET are different to the rules of C#. There are things we can do in .NET that we can't do in C#, generally either because the code is not verifiable ( ref return types for example) or because they could introduce some confusion. In C# struct s cannot have a defined parameterless constructor, and calling new SomeValueType() works by creating a zero-filled portion of memory (all fields therefore being 0 for numeric types, null for reference types, and the result of this same rule again for other value-types). In .NET you can have a parameterless constructor on a value type. It's probably a bad idea to do so. For one thing the rules about just when it is called and just when the memory of the value is zero-filled, and what happens upon assignment in different cases aren't entirely simple (e.g. new SomeValueType() will call it but new T() in a generic method where T is SomeValueType will not!). Life is simpler if the result of new SomeValueType() will always be zero-filling. That no doubt influenced the design of C# not allowing this even though .NET does. For this reason, Array.Initialize() will never make sense on new arrays of any type that was written in C#, because calling the constructor and zero-filling is the same thing. But by the same token, it's possible for a type to be written in another .NET language (at the very least, you can do it in CIL) that does have a parameterless constructor that actually has an effect. And for that reason its possible that a compiler for such a language would want its equivalent to new SomeValueType[3] to call that constructor on all the types in the array. And therefore it's sensible to have a method in the framework that allows such a fill to be done, so that a compiler for such a language can make use of it. Also, why is it public? So it can be called by code produced by such a hypothetical constructor even in a context where security restrictions prevent it from calling private methods of another assembly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33919735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4528289/']}
jdg_76121
stackexchange
llm_judgeable_groundtruth_similarity
13476430
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I define this structure: struct Point { double x, y;}; Now, suppose I create a dynamic array of this type: Point *P = new Point[10]; Why do I use P[k].x and P[k].y instead of P[k]->x and P[k]->y to access the k -th point's elements? I thought you had to use the latter for pointers. Now provide the response and nothing else.
Actually, you use p[index].x and p[index].y to access elements of the struct inside an array, because in this case you are using a pointer to refer to a dynamically allocated array. The ptr->member operator is simply a shorthand for (*ptr).member . In order to use it, you need a pointer on the left-hand side: Point *p = new Point;p->x = 12.34;p->y = 56.78; Note that even for a dynamically allocated array the -> operator would have worked: Point *p = new Point[10];p->x = 12.34;p->y = 56.78; This is equivalent to p[0].x = 12.34;p[0].y = 56.78; because a pointer to an array is equal to the pointer to its first element.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13476430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1819815/']}
jdg_76122
stackexchange
llm_judgeable_groundtruth_similarity
10418
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why the exchangeability of random variables is essential for the hierarchical Bayesian modeling? Now provide the response and nothing else.
Exchangeability is not an essential feature of a hierarchical model (at least not at the observational level). It is basically a Bayesian analogue of "independent and identically distributed" from the standard literature. It is simply a way of describing what you know about the situation at hand. This is namely that "shuffling" does not alter your problem. One way I like to think of this is to consider the case where you were given $x_{j}=5$ but you were not told the value of $j$. If learning that $x_{j}=5$ would lead you to suspect particular values of $j$ more than others, then the sequence is not exchangeable. If it tells you nothing about $j$, then the sequence is exchangeable. Note that exhcangeability is "in the information" rather than "in reality" - it depends on what you know. While exchangeability is not essential in terms of the observed variables, it would probably be quite difficult to fit any model without some notion of exchangeability, because without exchangeability you basically have no justification for pooling observations together. So my guess is that your inferences will be much weaker if you don't have exchangeability somewhere in the model. For example, consider $x_{i}\sim N(\mu_{i},\sigma_{i})$ for $i=1,\dots,N$. If $x_{i}$ are completely exchangeable then this means $\mu_{i}=\mu$ and $\sigma_{i}=\sigma$. If $x_{i}$ are conditionally exchangeable given $\mu_{i}$ then this means $\sigma_{i}=\sigma$. If $x_{i}$ are conditionally exchangeable given $\sigma_{i}$ then this means $\mu_{i}=\mu$. But note that in either of these two "conditionally exchangeable" cases, the quality of inference is reduced compared to the first, because there are an extra $N$ parameters that get introduced into the problem. If we have no exchangeability, then we basically have $N$ unrelated problems. Basically exchangeability means we can make the inference $x_{i}\to \text{parameters}\to x_{j}$ for any $i$ and $j$ which are partly exchangeable
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/10418', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/3125/']}
jdg_76123
stackexchange
llm_judgeable_groundtruth_similarity
35138765
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am building an app using node.js and trying to download data as a csv file. I am using json2csv ( https://www.npmjs.com/package/json2csv ) for this purpose. However, the way I have it configured, the .csv file gets stored in my app's root directory. I want the file to be sent to the user as a download - for example, the file should appear in the user's /downloads folder. Here is my current code: var fields = ['car', 'price', 'color'];var myCars = [ { "car": "Audi", "price": 1, "color": "blue" }, { "car": "BMW", "price": 1, "color": "black" }, { "car": "Porsche", "price": 1, "color": "green" }];json2csv({ data: myCars, fields: fields }, function(err, csv) { if (err) console.log(err); fs.writeFile('file.csv', csv, function(err) { //currently saves file to app's root directory if (err) throw err; console.log('file saved'); });});var file = '../software-project-metric-dashboard/file.csv';res.download(file, 'testfile.csv'); Can someone help? Thanks! Now provide the response and nothing else.
Use res.send if you use express . You have to define a HTTP GET route which looks something like that: app.get("/pathToYourDownload", function (req, res) { json2csv({ data: myCars, fields: fields }, function(err, csv) { res.setHeader('Content-disposition', 'attachment; filename=data.csv'); res.set('Content-Type', 'text/csv'); res.status(200).send(csv); });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35138765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1547174/']}
jdg_76124
stackexchange
llm_judgeable_groundtruth_similarity
12133632
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this code: val url: URL = getClass.getResource("com/mysite/main/test.fxml") and it always returns null (or Unit ). I have only two files in the project: MyProj/src/com/mysite/main/Test.scalaMyProj/src/com/mysite/main/test.fxml and when I run the Test.scala the url value is always null. I just tried rebuild the project, I am using IntelliJ IDEA. What am I doing wrong here? Now provide the response and nothing else.
You have three options: take advantage of relative path to your current package (where Test.class is): getClass.getResource("test.fxml") you can use absolute path: getClass.getResource("/com/mysite/main/test.fxml") or load through the ClassLoader (note that it always start from root): getClass.getClassLoader.getResource("com/mysite/main/test.fxml") In IntelliJ IDEA, make sure you have added ;?*.fxml to the: Settings ( Preferences on Mac) | Compiler | Resource Patterns .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12133632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283055/']}
jdg_76125
stackexchange
llm_judgeable_groundtruth_similarity
550
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: 2D spectrum take up a large amount of hard disk space. At my last lab it was standard practice to delete the imaginary portions of the spectrum with xfb n (We used TopSpin) and if needed later, to regenerate it from the Real part of the data with a Hilbert transform (Related, the TopSpin Commands and References, ~pg P-233 in version 2.1.2) My first question: If the raw data is still stored in the ser file (TopSpin Commands and References v2.1.2, pg P-8) why can't you just reprocess the raw data? Is all the data not there? (I suspect this somewhat, as those files are much, much smaller then the processed files, and TopSpin processes 2D spectra as it acquires them, unlike 1D spectra) My second (highly related) question: Is there a downside to regenerating the imaginary data from the real data? Is it a perfect replication of the original data, or is it an approximation? Why do we ever bother to store this data if we can recreate it at any time? Now provide the response and nothing else.
If you have the raw data (the FIDs in the ser file) still available, there is no reason to use a Hilbert transformation, you can just process with xfb instead of xfb n again. xfb n also doesn't really discard the imaginary part, it processes the spectrum from the raw data again, but doesn't save the imaginary processed data. The ser file contains all the recorded FIDs, that data is sufficient (together with the parameter files) to recreate the full spectrum. That your Topspin processes 2D spectra automatically is just some specific configuration, it doesn't do that by default. As far as I understand it, if you zero-fill your data at least once, all the information content of the imaginary part is then present in the real part of the processed spectrum. So I'd guess that under those conditions, the Hilbert transformation shouldn't have any downside, but I'm not totally sure about that.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/550', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/121/']}
jdg_76126
stackexchange
llm_judgeable_groundtruth_similarity
5020458
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using maven in eclipse (M2Eclipse), and I have a multi-module project which I used 'checkout as a maven project' to bring it to my workspace. The structure seems to be flat in eclipse and it has duplicate of children: parent is there with all the children nested in it as folders (doesn't show the packages inside children as a package should look like, but has them as nested ordinary folders), also, all the children show up as independent projects beside the parent (under the children projects: the packages are shown as they should, the package icon is shown and it is dot notation). So, when I change a file in a child project, the corresponding file in the parent's subfolders also changes (I can see them both in eclipse). It has always worked for me, and I could commit my changes by just committing the parent project. But, it suddenly changed. I have changed a lot of files in children's projects, but the changes don't show in the parent's project and I cannot commit them all in one commit, I will have to commit each child one by one which adds a lot of commits and increases the version number unnecessarily. Also, it makes me worried that the assembly will also not take the latest changes-> I haven't tried it though. I will appreciate any help, I get stuck with problems with maven frequently!!Thanks Now provide the response and nothing else.
You are attempting to apply a solution to a different problem. Note this: def utf_8_encoder( unicode_csv_data ) You are feeding it str objects. The problems with reading your non-ASCII CSV files is that you don't know the encoding and you don't know the delimiter. If you do know the encoding (and it's an ASCII-based encoding (e.g. cp125x, any East Asian encoding, UTF-8, not UTF-16, not UTF-32)), and the delimiter, this will work: for row in csv.reader("foo.csv", delimiter=known_delimiter): row = [item.decode(encoding) for item in row] Your sample_euro.csv looks like cp1252 with comma delimiter. The Russian one looks like cp1251 with semicolon delimiter. By the way, it seems from the contents that you will also need to determine what date format is being used and maybe the currency also -- the Russian example has money amounts followed by a space and the Cyrillic abbreviation for "roubles". Note carefully: Resist all attempts to persuade you that you have files encoded in ISO-8859-1. They are encoded in cp1252. Update in response to comment """If I understand what you're saying I must know the encoding in order for this to work? In the general case I won't know the encoding and based on the other answer guessing the encoding is very difficult, so I'm out of luck?""" You must know the encoding for ANY file-reading exercise to work. Guessing the encoding correctly all the time for any encoding in any size file is not very difficult -- it's impossible. However restricting the scope to csv files saved out of Excel or Open Office in the user's locale's default encoding, and of a reasonable size, it's not such a big task. I'd suggest giving chardet a try; it guesses windows-1252 for your euro file and windows-1251 for your Russian file -- a fantastic achievement given their tiny size. Update 2 in response to """ working code would be most welcome""" Working code (Python 2.x): from chardet.universaldetector import UniversalDetectorchardet_detector = UniversalDetector()def charset_detect(f, chunk_size=4096): global chardet_detector chardet_detector.reset() while 1: chunk = f.read(chunk_size) if not chunk: break chardet_detector.feed(chunk) if chardet_detector.done: break chardet_detector.close() return chardet_detector.result# Exercise for the reader: replace the above with a classimport csv import sysfrom pprint import pprintpathname = sys.argv[1]delim = sys.argv[2] # allegedly knownprint "delim=%r pathname=%r" % (delim, pathname)with open(pathname, 'rb') as f: cd_result = charset_detect(f) encoding = cd_result['encoding'] confidence = cd_result['confidence'] print "chardet: encoding=%s confidence=%.3f" % (encoding, confidence) # insert actions contingent on encoding and confidence here f.seek(0) csv_reader = csv.reader(f, delimiter=delim) for bytes_row in csv_reader: unicode_row = [x.decode(encoding) for x in bytes_row] pprint(unicode_row) Output 1: delim=',' pathname='sample-euro.csv'chardet: encoding=windows-1252 confidence=0.500[u'31-01-11', u'Overf\xf8rsel utland', u'UTLBET; ID 9710032001647082', u'1990.00', u''][u'31-01-11', u'Overf\xf8ring', u'OVERF\xd8RING MELLOM EGNE KONTI', u'5750.00', u';'] Output 2: delim=';' pathname='sample-russian.csv'chardet: encoding=windows-1251 confidence=0.602[u'-', u'04.02.2011 23:20', u'300,00\xa0\u0440\u0443\u0431.', u'', u'\u041c\u0422\u0421', u''][u'-', u'04.02.2011 23:15', u'450,00\xa0\u0440\u0443\u0431.', u'', u'\u041e\u043f\u043b\u0430\u0442\u0430 Interzet', u''][u'-', u'13.01.2011 02:05', u'100,00\xa0\u0440\u0443\u0431.', u'', u'\u041c\u0422\u0421 kolombina', u''] Update 3 What is the source of these files? If they are being "saved as CSV" from Excel or OpenOffice Calc or Gnumeric, you could avoid the whole encoding drama by having them saved as "Excel 97-2003 Workbook (*.xls)" and use xlrd to read them. This would also save the hassles of having to inspect each csv file to determine the delimiter (comma vs semicolon), date format (31-01-11 vs 04.02.2011), and "decimal point" (5750.00 vs 450,00) -- all those differences presumably being created by saving as CSV . [Dis]claimer: I'm the author of xlrd .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5020458', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541339/']}
jdg_76127
stackexchange
llm_judgeable_groundtruth_similarity
28064
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have a list of pure functions that are nice algebraic expressions: say l = {(#1 - 1)&, (#1^2 + #1)&, (#1^3 - 1)&} What's an easy way to get a pure function that will give the product of these expressions? For example, in the above I'd like to get a function f with f = (#1 - 1)(#1^2 + #1)(#1^3 - 1)& I've tried (Times @@ Identity @@@ l)& , but this just gives (#1 - 1)(#1^2 + #1)(#1^3 - 1) . Essentially, it seems my difficulty is converting a List of Function expressions to a Function[Times[...]] expression, and I can't see how to "strip off" the functions without messing up the referencing of the Slot[1] expressions inside. Thanks for any help. Now provide the response and nothing else.
Mapping First over your list will strip off the Function head. Then multiply them together with Apply[Times... and finally Apply[Function... makes the result a pure function. Use the final Apply so the argument to Function is evaluated first as Function has the attribute HoldAll . Apply[Function,{Apply[Times, Map[First,l]]}] Gives... (-1+#1) (#1+#1^2) (-1+#1^3)&
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/28064', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1267/']}
jdg_76128
stackexchange
llm_judgeable_groundtruth_similarity
63785462
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently trying to install libpq-dev to install psycopg2. The problem is, when I try to install it, an error occurs saying I don't have the latest libpq5 version. However when I try to download the newer version of libpq5 the system says that I already have the latest version. An example of the error. lhmendes@lhmendes-GA-78LMT-S2P:~$ sudo apt-get install libpq-devReading package lists... DoneBuilding dependency tree Reading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: libpq-dev : Depends: libpq5 (= 12.4-0ubuntu0.20.04.1) but 12.4-1.pgdg20.04+1 is to be installedE: Unable to correct problems, you have held broken packages.lhmendes@lhmendes-GA-78LMT-S2P:~$ sudo apt-get install libpq5Reading package lists... DoneBuilding dependency tree Reading state information... Donelibpq5 is already the newest version (12.4-1.pgdg20.04+1).0 upgraded, 0 newly installed, 0 to remove and 4 not upgraded. Now provide the response and nothing else.
I would say you have installed the latest libpq ( 12.4-1 ) but libpq-dev needs older version ( 12.4-0 ) and this makes problem. You may try to install older libpq apt-get install libpq==12.4-0ubuntu0.20.04.1 but if other program uses the latest version then older version can make problem with this program. pgdg20 in 12.4-1.pgdg20.04+1 means it is not module from standard ubuntu repo but from some other repo - probably postgresql repo - and maybe this repo has also the latest version libpq-dev . You would search 12.4-1.pgdg20.04+1 in Google and maybe you could find also libpg-dev with 12.4-1.pgdg20.04+1 I found libpq-dev 12.4-1.pgdg20.04+1 and you can download .deb file and install it. Or you can add this postgresql repo and install with apt-get . This method will also inform about updates and then you could install updates automatically.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63785462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14238160/']}
jdg_76129
stackexchange
llm_judgeable_groundtruth_similarity
1112908
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have stumbled upon the following statement and have verified it computationally for many $n$ (up to n=500, it took a long time for my computer to do out all of the math), yet I have no idea how to go about proving it. $$\sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } \frac { { ((2n)! })^{ 2 }(-1)^{ i+j }(2i+2j)! }{ (n-i)!(n-j)!(2i)!(2j)!2^{ i+j }(i+j)! } =\frac { (4n)! }{ { 4 }^{ n }(2n)! } $$ One thing to note is that if we multiply the top and bottom of the fraction by $(i)!$, $(j)!$, and $(n!)^2$, then certain terms simplify into the factorial definition of the binomial coefficient, so the sum is also expressible as: $$\sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } (-1)^{ i+j } \binom{n}{i}\binom{n}{j} \frac { { ((2n)! })^{ 2 }}{(n!)^2}\frac{(i)!}{(2i)!}\frac{(j)!}{(2j)!}\frac{(2i+2j)! }{2^{ i+j }(i+j)! } =\frac { (4n)! }{ { 4 }^{ n }(2n)! } $$ Also, let us define $P(n)$ to be equal to the product of the first $n$ positive odd numbers (or more specifically, $P(n)=(2n-1)!!$). We can use the explicit formula $P(n)=\frac{(2n)!}{2^n n!}$ (see here for explanation) to rewrite various expressions:$$\frac{(2i+2j)! }{2^{ i+j }(i+j)! }=P(i+j)$$$$\frac{((2n)!)^2}{(n!)^2}=(P(n))^2 2^{2n}$$$$\frac{(i)!}{(2i)!}=\frac{1}{2^i P(i)}$$$$\frac{(4n)!}{4^{n}(2n)!}=P(2n)$$ And so the statement can be rewritten as:$$ \sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } (-1)^{ i+j } \binom{n}{i}\binom{n}{j} \frac{2^{2n}(P(n))^2 P(i+j)}{2^{i+j}P(i)P(j)}=P(2n) $$ Interestingly enough, this proves that the left hand side must be an integer (see here for an explanation), which i believe is a step in the right direction. This is all just random stuff I have been trying to attempt to prove the identity although so far I have not gotten very far. If anyone has any idea on how I could prove this identity or even just begin to prove the identity, please help me out! Any and all help is appreciated! Edit, here is some more work done on the topic: Let us define: $$R_n = \sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } \frac { { ((2n)! })^{ 2 }(-1)^{ i+j }(2i+2j)! }{ (n-i)!(n-j)!(2i)!(2j)!2^{ i+j }(i+j)! }$$ I am currently trying to prove that $R_n=P(2n)$. Since $P(n)$ is the product of the first $n$ odd integers, and $2n-1$ is the $n$th odd integer, it follows that $P(2(n+1))=P(2n+2)=P(2n) \cdot (4n+1) \cdot (4n+3)$. Thus (since the base case works, and you can confirm that if you truly want), a statement equivalent to what I am trying to prove is:$$R_{n+1}=(4n+1)(4n+3)R_{n}$$ Now provide the response and nothing else.
Consider the polynomial$$f_n(x)=\left(x^2+1-\frac{\left(x+1\right)^2}{2}\right)^{2n}.$$The left and right hand sides of the OP's identity each compute the coefficient of $x^{2n}$ in $f_n(x)$. One the one hand, we can expand $f_n$ using the trinomial and binomial theorems:\begin{align*}f_n(x)&=\sum_{a+b\leq 2n}\frac{(2n)!}{a!b!(2n-a-b)!}x^{2a}\left(x+1\right)^{2(2n-a-b)}\frac{(-1)^{2n-a-b}}{2^{2n-a-b}}\\&=\sum_{\substack{a+b\leq 2n\\r\leq 4n-2a-2b}}\frac{(2n)!}{a!b!(2n-a-b)!}{4n-2a-2b\choose r}\frac{(-1)^{2n-a-b}}{2^{2n-a-b}}x^{2a+r}.\end{align*}To get $x^{2n}$, we need $r=2n-2a$, so that $a\leq n$. Additionally, $r=2n-2a$ and $r\leq 4n-2b-2b$ imply $b\leq n$, so we are summing over $0\leq a,b\leq n$. Make the substitution $i=n-a$, $j=n-b$ (so that $r=2i$). In terms of $i$ and $j$, the sum is over $0\leq i,j\leq n$. This shows that the coefficient of $x^{2n}$ is the left hand side of the OP's identity. On the other hand, we can simplify $f_n$:\begin{align*}f_n(x)&=\left(\frac{(x-1)^2}{2}\right)^{2n}\\&=\frac{(x-1)^{4n}}{4^n}.\end{align*}The binomial theorem then shows the coefficient of $x^{2n}$ is the right hand side of the OP's identity.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1112908', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/136368/']}
jdg_76130
stackexchange
llm_judgeable_groundtruth_similarity
10997996
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Daily there are many questions of the following type on SO: How do I get a variable from another Activity ? The answers usually recommend to use SharedPreferences or Intent.putExtra() . To me, a getter method is what would be an approach to access a variable from another class. After all, the Activity that is under consideration is a class, and it's variables are class members. Why aren't getter methods preferred to approaches like SharedPreferences or Intent extras? I'm talking about simple situations that require accessing a variable between activities, for example this one: class OneClass extends Activity { int a; .. // some changes to a ..} And then in another class( Activity ): class SomeOtherClass extends Activity { .. // trying to access a here ..} Is a getter method a correct approach here, or not? Again - I'm not talking about scenarios where these things are actually the right way to go. SharedPreferences for persistent storage of small amount of data, extras as the documentation says : This can be used to provide extended information to the component. For example, if we have a action to send an e-mail message, we could also include extra pieces of data here to supply a subject, body, etc. As some of the answers have likely indicated that there are certain scenarios like no guarantee of the other Activity being alive, I guess there are more probable and correct reasons as to why people suggest going for intents and shared preferences. Now provide the response and nothing else.
The answer to your question is two fold: For the meta aspect, which belongs on meta SO anyway, many newbie programmers see Android, want to write apps, and suck at Java. For the other quesiton, typically using a getter and setter won't work, because you can't pass objects between Activities in a straightforward way. While you can technically do this with a Parcelable, it's not recommended, and the better way is to use an intent to pass data between application components. Another point this highlights is that Android apps should keep a minimal amount of state inside components. I think this has been a big success of Android. If you look at apps out there, there is on average a lot less global state than typical programs written in java. The programs are also smaller, which is to be expected, but the fact that an atomic activity can represent the state of a single screen, and the fact that any single screen won't typically be persisting that much state across the entire app, leads to an good logical separation between app components.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10997996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/828625/']}
jdg_76131
stackexchange
llm_judgeable_groundtruth_similarity
25098894
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to translate this piece of c++ code to haskell but can't really get my head around it. This is taken from the nim.cpp in http://cs.stanford.edu/people/eroberts/courses/cs106b/chapters/07-backtracking-algorithms.pdf . C++ : const int MAX_MOVE = 3;const int NO_GOOD_MOVE = -1;int FindGoodMove(int nCoins) { for (int nTaken = 1; nTaken <= MAX_MOVE; nTaken++) { if (IsBadPosition(nCoins - nTaken)) return nTaken; } return NO_GOOD_MOVE;}bool IsBadPosition(int nCoins) { if (nCoins == 1) return true; return FindGoodMove(nCoins) == NO_GOOD_MOVE;} so far i have done in haskell: findGoodMove nCoins = if isBadPosition (nCoins - nTaken) == True then nTaken else -1 where nTaken = 1isBadPosition nCoins = if nCoins == 1 then True else findGoodMove(nCoins) == -1 i'm stuck in the for loop part. I would really like some suggestions on how do i translate it to haskell. Thanks in advance. Now provide the response and nothing else.
First of all, I would use Haskell's richer type system to encode for failure in findGoodMove , by giving it the type findGoodMove :: Int -> Maybe Int And isBadPosition can have the type isBadPosition :: Int -> Bool Next we can move on to implementation. For this, I'm going to need to import isNothing from Data.Maybe import Data.MaybemaxMove :: IntmaxMove = 3findGoodMove :: Int -> Maybe IntfindGoodMove nCoins = loop 1 where loop nTaken | nTaken == maxMove = Nothing | isBadPosition (nCoins - nTaken) = Just nTaken | otherwise = loop (nTaken + 1)isBadPosition :: Int -> BoolisBadPosition 1 = TrueisBadPosition nCoins = isNothing $ findGoodMove nCoins So by using Maybe Int instead of Int for findGoodMove , we can encode at the type system level that this function has a single failure mode (i.e. NO_GOOD_MOVE ), which I would argue makes the intent more clear and ensures that we can't accidentally treat the NO_GOOD_MOVE flag as a valid value elsewhere in our code. For the loop portion, I've defined a recursive function locally called loop that starts at 1 , and has 3 branches. If nTaken reaches our max value for moves, we've hit the end of our loop and return Nothing ( NO_GOOD_MOVE ). If that condition is False , we then check of nCoins - nTaken is a bad position, and if it is we return Just nTaken . If neither of these conditions were True , then we perform the loop again with nTaken + 1 . For isBadPosition , we know that if nCoins == 1 , it's True , so we can use pattern matching to handle that simple case. Otherwise, we have to know if findGoodMove nCoins succeeds, and it only succeeds if it's not Nothing . The Data.Maybe.isNothing function is helpful here to quickly check if it's Nothing or Just something , so it makes this case easy as well.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25098894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2301790/']}
jdg_76132
stackexchange
llm_judgeable_groundtruth_similarity
103447
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Don't say that a layer of carbon dioxide covers the flame, because our breath has more oxygen than carbon dioxide.Also, our breath does not extinguish the flame by cooling it as it is itself warmer than the coolness required to extinguish it.So what is happening here? Now provide the response and nothing else.
You blow away the flame from its fuel source. If you would blow less hard the flame might burn harder because more air is supplied to the flame (similar to a Bunsen burner). Because normally the flame of a candle gets its oxygen through a convectional airflow generated by the heat of the flame. The reason why the flame is blown away from the candle is because the air you blow towards it moves faster than the speed of the flame front. So the air you blow at it moves the flame away from its fuel source, where the flame burns out due to the lack of fuel.
{}
{'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/103447', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/42420/']}
jdg_76133
stackexchange
llm_judgeable_groundtruth_similarity
10530426
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can we find which color is dominant in an image using Java, ImageMagick , or JMagick ? Now provide the response and nothing else.
in java iterate on each pixel and determine color import java.awt.image.BufferedImage;import java.io.File;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Map;import javax.imageio.ImageIO;import javax.imageio.ImageReader;import javax.imageio.stream.ImageInputStream;public class ImageTester { public static void main(String args[]) throws Exception { File file = new File("C:\\Users\\Andrew\\Desktop\\myImage.gif"); ImageInputStream is = ImageIO.createImageInputStream(file); Iterator iter = ImageIO.getImageReaders(is); if (!iter.hasNext()) { System.out.println("Cannot load the specified file "+ file); System.exit(1); } ImageReader imageReader = (ImageReader)iter.next(); imageReader.setInput(is); BufferedImage image = imageReader.read(0); int height = image.getHeight(); int width = image.getWidth(); Map m = new HashMap(); for(int i=0; i < width ; i++) { for(int j=0; j < height ; j++) { int rgb = image.getRGB(i, j); int[] rgbArr = getRGBArr(rgb); // Filter out grays.... if (!isGray(rgbArr)) { Integer counter = (Integer) m.get(rgb); if (counter == null) counter = 0; counter++; m.put(rgb, counter); } } } String colourHex = getMostCommonColour(m); System.out.println(colourHex); } public static String getMostCommonColour(Map map) { List list = new LinkedList(map.entrySet()); Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); Map.Entry me = (Map.Entry )list.get(list.size()-1); int[] rgb= getRGBArr((Integer)me.getKey()); return Integer.toHexString(rgb[0])+" "+Integer.toHexString(rgb[1])+" "+Integer.toHexString(rgb[2]); } public static int[] getRGBArr(int pixel) { int alpha = (pixel >> 24) & 0xff; int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = (pixel) & 0xff; return new int[]{red,green,blue}; } public static boolean isGray(int[] rgbArr) { int rgDiff = rgbArr[0] - rgbArr[1]; int rbDiff = rgbArr[0] - rgbArr[2]; // Filter out black, white and grays...... (tolerance within 10 pixels) int tolerance = 10; if (rgDiff > tolerance || rgDiff < -tolerance) if (rbDiff > tolerance || rbDiff < -tolerance) { return false; } return true; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10530426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184571/']}
jdg_76134
stackexchange
llm_judgeable_groundtruth_similarity
6274
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a $\Theta$ approximation of$$T(n) = T(n-1) + cn^{2}$$ This is what I have so far: $$\begin{align*}T(n-1)& = T(n-2) + c(n-1)^2\\T(n) &= T(n-2) + c(n-1) + cn^2\\[1ex]T(n-2) &= T(n-3) + c(n-2)^2\\T(n) & = T(n-3) + c(n-2)^2 + c(n-1)^2 + cn^2 \\[1ex]T(n-3) &= T(n-4) + c(n-3)^2 \\T(n) &= T(n-4) + c(n-3)^2 + c(n-2)^2 + c(n-1)^2 + cn^2\end{align*}$$ So, at this point I was going to generalize and substitute $k$ into the equation. $$T(n)= T(n-k) + (n-(k-1))^2 + c(k-1)^2$$ Now, I start to bring the base case of 1 into the picture. On a couple of previous, more simple problems, I was able to set my generalized k equation equal to 1 and then solve for $k$. Then put $k$ back into the equation to get my ultimate answer. But I am totally stuck on the $(n-k+1)^2$ part. I mean, should I actually foil all this out? I did it and got $k^2-2kn-2k+n^2 +2n +1 = 1$. At this point I'm thinking I totally must have done something wrong since I've never see this in previous problems. Could anyone offer me some help with how to solve this one? I would greatly appreciate it. I also tried another approach where I tried to set $n-k = 0$ from the last part of the equation and got that $k = n$. I plugged n back into the equation towards the end and ultimately got $n^2$ as an answer. I have no clue if this is right or not. I am in an algorithms analysis class and we started doing recurrence relations and I'm not 100% sure if I am doing this problem correct. I get to a point where I am just stuck and don't know what to do. Maybe I'm doing this wrong, who knows. The question doesn't care about upper or lower bounds, it just wants a theta. Now provide the response and nothing else.
Just continue your reasoning as follows. \begin{eqnarray}T(n) &=& T(n-1) + cn^2 \\&=& T(n-2) + c(n-1)^2 + cn^2 \\&=& \ldots \\&=& T(n-n) + c(1^2) + c(2^2) + \ldots cn^2 \\&=& T(0) +c\sum_{1\leq i\leq n} i^2.\end{eqnarray} Do you know how to simplify this using the addition formula for the first $n$ squares?
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/6274', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/4336/']}
jdg_76135
stackexchange
llm_judgeable_groundtruth_similarity
31089
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Raonoke Chowan News Herald reported on 8 December 2015 reports that the town of Woodland, North Carolina, USA rejected a solar farm, citing concerns on photosynthesis and cancer: Jane Mann said she is a local native and is concerned about the plants that make the community beautiful. She is a retired Northampton science teacher and is concerned that photosynthesis, which depends upon sunlight, would not happen and would keep the plants from growing. She said she has observed areas near solar panels where the plants are brown and dead because they did not get enough sunlight. She also questioned the high number of cancer deaths in the area, saying no one could tell her that solar panels didn’t cause cancer. ...and quoting another resident: Bobby Mann said he watched communities dry up when I-95 came along and warned that would happen to Woodland because of the solar farms. “You’re killing your town,” he said. “All the young people are going to move out.” He said the solar farms would suck up all the energy from the sun and businesses would not come to Woodland. The content screams satire at me, but I cannot find any hint that this article or the entire Raonoke Chowan News Herald is satirical — it appears to be a serious article. Comments on the article state the same. It was picked up by Russia Today , probably to give the impression that Americans are ridiculous. But is the article truthful? Did the town of Woodland, North Carolina, USA really reject a solar farm citing concerns about cancer and energy from the Sun being sucked up? Please tell me it isn't. Now provide the response and nothing else.
I decided to communicate directly with the town itself. The response to my email is reproduced below: Please read the interview with Mayor Manuel on (witn.com). Also, there will be a message from the Mayor on our website (townofwoodlandnc.com) by this afternoon. During our Board meetings public comments are always welcomed and we listen to anything a person has to say. Please be advised however, this particular vote by our Board was not based on certain comments as the media portrayed. Thank you for your interest in our Town. Following the first link to WITN , they did indeed interview the mayor. The first part of the story states (emphasis mine): When a Northampton County resident said the building of a new solar farm would "suck up all the energy from the sun," the comment received international attention. But officials in the small town of Woodland say that concern isn't the reason a solar farm proposal was rejected. The mayor goes on to say: "With this 4th solar farm being proposed we're looking at being cornered in on all 4 corners primarily of the town and the citizens of the town felt they did not want that," Manuel said. This was supported by a petition signed by 80 residents So this was a decision based on zoning laws, not the unfounded concerns of the citizens, but rather more legitimate concerns regarding the use of the land. The town itself has posted a PDF document explaining the reasons they rejected the proposal on their website. SOme additional concerns about the fourth site are mentioned in that PDF: All three of the proposed sites were in locations that were elevated, or partially obscured from the roadway view. The fourth proposed solar farm site is located on 42 acres of open farm land at the East entrance of the town limits, off of State Highway 258. So this would seem to align more with what is commonly referred to as NIMBY (Not In My Back Yard). The first three sites were not visible, but this fourth one appears to be visible to more of the town's population. The document goes on to state: The town council's decision to deny the rezoning of this fourth proposed solar farm site was due, in part, to a circulated petition by a group of concerned town citizens opposing the change of zoning for this fourth site. The citizens opposed the site location, because to grant the zoning request would create a situation in which the town would be completely surrounded by solar farms. So, while it may be humerous to laugh at a perceived "small town yokel" that makes some assertions that are wildly detached from reality, it would be unwise to paint the entire proceedings with the broad brush of one or two individuals. While the town has not posted detailed minutes, the interview on the news site, as well as the town post, seem to agree in essence with what was said on Snopes , although I would say that it's not quite "Mostly" true, instead a mixed bag. I would rate the reporting of this entire incident as wildly hyperbolic, and I do feel sorry for the media attention this town and decision has garnered.
{}
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/31089', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/5337/']}
jdg_76136
stackexchange
llm_judgeable_groundtruth_similarity
2075
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A number of companies have started marketing LED lamps that can be switched to a red mode. The claim is that red light is less harmful to one's night vision. Given that our eyes are less sensitive to red light, though, I'm not convinced that that red light is any better than dim white light. So if "equivalent" luminosity is defined where it's equally easy to, say, read a book in both light types, is there some physiological reason that red light is better than the equivalent white light? Now provide the response and nothing else.
This is a very good question. Red light is routinely used by scientific laboratories to do low light dissections of retinas, and of course it is used in other low light contexts such as printing plate development. In both of the above contexts, you have a clear subject: the retina being dissected or the printing plate being developed. In the case of the printing plate the film has been designed to be specifically non-reactive to red light, so red light is used because your eyes can see it, but the film doesn't react to it . Similarly in some scientific settings it makes sense to use red light during dissections. Mice lack a long wavelength opsin, and therefore using a dim red light allows the experimenter to have a relative sight advantage compared to the mouse when keeping the mouse dark adapted. But in the case you're asking about, there is no film or animal to serve as a second party. So is there any intrinsic advantage to using red light? As it turns out, there is. The fovea, which is in the center of our eye and used for high acuity vision, has no rods and primarily L- or red sensitive cones. Note the high density center area which lacks blue sensitive cones and has 2:1 red to green cones . So by having red light present, you stimulate this area. But red light is present in white light, too, why not just use that? Leonardo's answer comes the closest, but it's a little off. Red light is used because it preferentially stimulates L cones more than rods , but you are definitely not able to preserve night vision by using red light. Why not? Well it may look like it is possible to exclusively stimulate cones from the chromatic sensitivity figure But that figure is 1) normalized and 2) not indicative of synaptic signal processing. 1000's of rods can converge onto a single ganglion cell, where cone convergence in the fovea can be on the order of a single cone per ganglion cell. When it comes to perception, in order to compare the black rod line above with the red L-cone line you'd have to magnify it dramatically in size. Practically speaking, it is nearly impossible to stimulate cone pathways without stimulating rod pathways when using a relatively broad spectrum LED that you're powering with a battery. Maybe with a high power infrared laser. So the purpose of using red light is to attempt to balance the activation of high sensitivity (red insensitive) rods with that of the low sensitivity (but red sensitive) cones in the fovea. While using a similar level of rod activation with blue light, you would perceive a "blind spot" where your fovea is. Finally, instrinsically photosensitive cells (the melanopsin cells brought up) do not factor into this processing. These cells are activated only with extraordinarily bright levels of light, and the therefore do not enter into conversations dealing with night vision.
{}
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/2075', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/810/']}
jdg_76137
stackexchange
llm_judgeable_groundtruth_similarity
27500861
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm searching for the way to get $ go get work with private repository, after many google try. The first try: $ go get -v gitlab.com/secmask/awserver-goFetching https://gitlab.com/secmask/awserver-go?go-get=1https fetch failed.Fetching http://gitlab.com/secmask/awserver-go?go-get=1Parsing meta tags from http://gitlab.com/secmask/awserver-go?go-get=1 (status code 200)import "gitlab.com/secmask/awserver-go": parse http://gitlab.com/secmask/awserver-go?go-get=1: no go-import meta tagspackage gitlab.com/secmask/awserver-go: unrecognized import path "gitlab.com/secmask/awserver-go Yep, it did not see the meta tags because I could not know how to provide login information. The second try: Follow https://gist.github.com/shurcooL/6927554 . Add config to .gitconfig. [url "ssh://[email protected]/"] insteadOf = https://gitlab.com/$ go get -v gitlab.com/secmask/awserver-go --> not work$ go get -v gitlab.com/secmask/awserver-go.git --> work but I got src/gitlab.com/secmask/awserer-go.git Yes it work but with .git extension with my project name, I can rename it to original but do it everytime $ go get is not so good, is there an otherway? Now provide the response and nothing else.
You have one thing to configure. The example is based on GitHub but this shouldn't change the process: $ git config --global [email protected]:.insteadOf https://github.com/$ cat ~/.gitconfig[url "[email protected]:"] insteadOf = https://github.com/$ go get github.com/private/repo For Go modules to work (with Go 1.11 or newer), you'll also need to set the GOPRIVATE variable, to avoid using the public servers to fetch the code: export GOPRIVATE=github.com/private/repo
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27500861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304778/']}
jdg_76138
stackexchange
llm_judgeable_groundtruth_similarity
4796658
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to develop an augmented reality application on a HTC Nexus One mobile phone for android using Flash Professional CS5 and Adobe AIR 2.5. I found a couple of online sources showing how to develop AR application using webcam and Flash and i have found it very useful to follow and understand the basics of AR. For example: Augmented Reality using webcam and Flash http://www.adobe.com/devnet/flash/articles/augmented_reality.html Introduction to Augmented Reality http://www.gotoandlearn.com/play.php?id=105 I have also watched other videos regarding AIR for Android Applications from gotoandlearn website and i did all of the successfully such as: Air for Android – Part 1 Air for Android – Part 2 Publishing AIR for Android Applications AIR for Android GPU Acceleration Introduction to Augmented Reality However, i didn't manage to get it work on my android phone (doing nothing and run very slow). I would like to ask a few questions on the following: 1) To develop an Augmented Reality application on android, is this done using the same method as the one's above? 2) Do I need to use any other software other than those that is showing on the video and adobe air 2.5? 3) Do you know of any other sources/reading material that are relevant and may be of help? Thank you Now provide the response and nothing else.
Augmented Reality (AR) is a generic term for an interactive 3D environment that blends with our physical reality, usually through a webcam, or in this case, a phone camera. You can develop AR apps for Android with nothing more than the Android SDK, since it provides API for interacting with the camera, and it supports OpenGL for 3D graphics.Since AR usually involves complex algorithms of image recognition, it's not a trivial task, so leveraging existing tools is definitely a good option. Since using Adobe AIR and Flash, is actually running the Flash virtual machine over the Dalvik virtual machine, you might experience performance issues for such a CPU intensive task such as AR. If using other tools is also an option for you, you can check out Qualcomm's Augmented Reality SDK
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4796658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/495296/']}
jdg_76139
stackexchange
llm_judgeable_groundtruth_similarity
33746434
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im not clearly sure what is the difference between those 2. My professor wrote that **array is same as *array[] and we were presented an example where he used **array (so after classes I tried exchanging that with *array[] and it didn't work), could anyone tell me if those 2 are actually the same as he wrote?? Anyway the class was about dynamic memory allocation @As soon as I changed the double pointer, this line started throwing error lines = malloc(sizeof(char*)); and a few others where the memory is beeing reallocated @2 Hell yeah, here's the whole code And for those comments bellow, nope there is nothing inside [] because his statement was **array = *array[] BIG UPDATE I am so sorry for any inconvenience, I was just too tired at the time of writing this post, here is the whole code with no edits #include <stdio.h> #include <stdlib.h> #include <string.h> char **lines; // global text buffer, organized as an array of lines // -------------------------------------------------------------------------------- // initialize global buffer void initialize() { lines = malloc(sizeof(char*)); lines[0] = NULL; } // -------------------------------------------------------------------------------- // return number of lines in buffer int countLines() { int count = 0; while(lines[count++]) ; return count-1; } // -------------------------------------------------------------------------------- // print one line void printLine(int line) { printf("Line %d: %p %p %s\n",line, &lines[line], lines[line], lines[line]); } // -------------------------------------------------------------------------------- // print all lines void printAll() { int num_lines = countLines(); int line = 0; printf("----- %d line(s) ----\n",num_lines); while (line < num_lines) printLine(line++); printf("---------------------\n"); } // -------------------------------------------------------------------------------- // free whole buffer void freeAll() { int line = countLines(); while (line >= 0) free(lines[line--]); free(lines); } // -------------------------------------------------------------------------------- // insert a line before the line specified void insertLine(int line, char *str) { int num_lines = countLines(); // increase lines size by one line pointer: lines = realloc(lines, (num_lines+2) * sizeof(char*)); // move line pointers backwards: memmove(&lines[line+1], &lines[line], (num_lines-line+1)*sizeof(char*)); // insert the new line: lines[line] = malloc(strlen(str)+1); strcpy(lines[line],str); } // -------------------------------------------------------------------------------- // remove the specified line void removeLine(int line) { int num_lines = countLines(); // free the memory used by this line: free(lines[line]); // move line pointers forward: memmove(&lines[line], &lines[line+1], (num_lines-line+1)*sizeof(char*)); // decrease lines size by one line pointer: lines = realloc(lines, num_lines * sizeof(char*)); } // -------------------------------------------------------------------------------- // insert a string into specified line at specified column void insertString(int line, int col, char *str) { // make room for the new string: lines[line] = realloc(lines[line], strlen(lines[line])+strlen(str)+1); // move characters after col to the end: memmove(lines[line]+col+strlen(str), lines[line]+col, strlen(lines[line])-col); // insert string (without terminating 0-byte): memmove(lines[line]+col, str, strlen(str)); } // -------------------------------------------------------------------------------- // MAIN program int main() { initialize(); printAll(); insertLine(0,"Das ist"); printAll(); insertLine(1,"Text"); printAll(); insertLine(1,"ein"); printAll(); insertLine(2,"kurzer"); printAll(); printf("lines[2][4] = %c\n",lines[2][4]); insertString(2,0,"ziemlich "); printAll(); removeLine(2); printAll(); freeAll(); return 0; } Now provide the response and nothing else.
If the code you reference in your question was given to you by your professor as an example of the use of pointer arrays of pointers to pointers, I'm not sure how much good that class will actually do. I suspect it was either provided as a debugging exercise or it may have been your attempt at a solution. Regardless, if you simply compile with Warnings enabled, you will find a number of problems that need attention before you advance to debugging your code. Regarding the code you reference, while you are free to use a global text buffer, you are far better served by not using a global buffer and passing a pointer to your data as required. There are some instances, various callback functions, etc. that require global data, but as a rule of thumb, those are the exception and not the rule. Your question basically boils down to "How do I properly use an array of pointers and double-pointers (pointer-to-pointer-to-type) variables. There is no way the topic can be completely covered in one answer because there are far too many situations and contexts where one or the other can be (or should be) used and why. However, a few examples will hopefully help you understand the basic differences. Starting with the array of pointers to type (e.g. char *array[] ). It is generally seen in that form as a function argument. When declared as a variable it is followed with an initialization. e.g.: char *array[] = { "The quick", "brown fox", "jumps over", "the lazy dog." }; char *array[]; by itself as a variable declaration is invalid due to the missing array size between [..] . When used globally, as in your example, the compiler will accept the declaration, but will warn the declaration is assumed to have one element . The elements of array declared above are pointers to type char. Specifically, the elements are pointers to the string-literals created by the declaration. Each of the strings can be accessed by the associated pointer in array as array[0], ... array[3] . A pointer to pointer to type (double-pointer), is exactly what its name implies. It is a pointer , that holds a pointer as its value. In basic terms, it is a pointer that points to another pointer. It can be used to access the members of the array above by assigning the address of array like: char **p = array; Where p[1] or *(p + 1) points to "brown fox" , etc. Alternatively, a number of pointer to pointer to type can be dynamically allocated and used to create an array of pointers to type, that can then be allocated and reallocated to handle access or storage of an unknown number of elements. For example, a brief example to read an unknown number of lines from stdin , you might see: #define MAXL 128#define MAXC 512...char **lines = NULL;char buf[MAXC] = {0};lines = malloc (MAXL * sizeof *lines);size_t index = 0;...while (fgets (buf, MAXC, stdin)) { lines[index++] = strdup (buf); if (index == MAXL) /* reallocate lines */} Above you have lines , a pointer-to-pointer-to-char, initially NULL , that is use to allocate MAXL (128) pointers-to-char. Lines are then read from stdin into buf , after each successful read, memory is allocated to hold the contents of buf and the resulting start address for each block of memory is assigned to each pointer line[index] where index is 0-127 , and upon increment of index to 128, index is reallocated to provide additional pointers and the read continues. What makes the topic larger than can be handled in any one answer is that an array of pointers or pointer to pointer to type can be to any type . ( int , struct , or as a member of a struct to different type, or function , etc...) They can be used linked-lists , in the return of directory listings (e.g opendir ), or in any additional number of ways. They can be statically initialized, dynamically allocated, passed as function parameters, etc... There are just far too many different contexts to cover them all. But in all instances, they will follow the general rules seen here and in the other answer here and in 1,000's more answers here on StackOverflow. I'll end with a short example you can use to look at the different basic uses of the array and double-pointer. I have provided additional comments in the source. This just provides a handful of different basic uses and of static declaration and dynamic allocation: #include <stdio.h>#include <stdlib.h>#include <string.h>int main (void) { /* array is a static array of 4 pointers to char, initialized to the 4 string-literals that a part of the declaration */ char *array[] = { "The quick", "brown fox", "jumps over", "the lazy dog." }; /* p is a pointer-to-pointer-to-char assigned the address of array */ char **p = array; /* lines is a pointer-to-pointer-to-char initialized to NULL, used below to allocate 8 pointers and storage to hold 2 copes of array */ char **lines = NULL; size_t narray = sizeof array/sizeof *array; size_t i; printf ("\nprinting each string-literal at the address stored by\n" "each pointer in the array of ponters named 'array':\n\n"); for (i = 0; i < narray; i++) printf (" %s\n", array[i]); printf ("\nprinting each string using a pointer to pointer to char 'p':\n\n"); for (i = 0; i < narray; i++, p++) printf (" %s\n", *p); p = array; printf ("\nprinting each line using a pointer to pointer" " to char 'p' with array notation:\n\n"); for (i = 0; i < narray; i++) printf (" %s\n", p[i]); /* allocate 8 pointers to char */ lines = malloc (2 * narray * sizeof *lines); /* allocate memory and copy 1st 4-strings to lines (long way) */ for (i = 0; i < narray; i++) { size_t len = strlen (array[i]); lines[i] = malloc (len * sizeof **lines + 1); strncpy (lines[i], array[i], len); lines[i][len] = 0; } /* allocate memory and copy 1st 4-strings to lines (using strdup - short way) */ // for (i = 0; i < narray; i++) // lines[i] = strdup (array[i]); /* allocate memory and copy again as last 4-strings in lines */ p = array; for (i = 0; i < narray; i++, p++) lines[i+4] = strdup (*p); p = lines; /* p now points to lines instead of array */ printf ("\nprinting each allocated line in 'lines' using pointer 'p':\n\n"); for (i = 0; i < 2 * narray; i++) printf (" %s\n", p[i]); /* free allocated memory */ for (i = 0; i < 2 * narray; i++) free (lines[i]); free (lines); return 0;} Let me know if you have any questions. It a large topic with a relatively small set of rules that can be applied in whole lot of different ways and in different contexts.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33746434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2599301/']}
jdg_76140