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 | 42505531 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to select rows that are DISTINCT ON some separate, independent sets of columns? Suppose I want all the rows which match the following conditions: distinct on (name, birth) distinct on (name, height) So that, out of the following table, the rows marked with a red cross would not be distinct (with an indication of the failing clause): name birth height--------------------------William 1976 1.82James 1981 1.68Mike 1976 1.68Tom 1967 1.79William 1976 1.74 ❌ (name, birth)William 1981 1.82 ❌ (name, height)Tom 1978 1.92Mike 1963 1.68 ❌ (name, height)Tom 1971 1.86James 1981 1.77 ❌ (name, birth)Tom 1971 1.89 ❌ (name, birth) In the above example, if the DISTINCT ON clause had just been DISTINCT ON (name, birth, height) , then all the rows would have been considered distinct. Tried and didn't work: SELECT DISTINCT ON (name, birth) (name, height) ... SELECT DISTINCT ON (name, birth), (name, height) ... SELECT DISTINCT ON ((name, birth), (name, height)) ... SELECT DISTINCT ON (name, birth) AND (name, height) ... SELECT DISTINCT ON (name, birth) AND ON (name, height) ... SELECT DISTINCT ON (name, birth) DISTINCT ON (name, height) ... SELECT DISTINCT ON (name, birth), DISTINCT ON (name, height) ...
Now provide the response and nothing else.
| As commented , there is ambiguity in the question. The number of result rows can differ for every call. If you are satisfied with arbitrary results, @klin's solution is good enough. Else, you need to define requiremens more closely. Like: distinct on (name, birth) , pick smallest height first, then smallest ID as tiebreaker Or: distinct on (name, height) , pick earliest birth first, then smallest ID as tiebreaker Your table should have a primary key (or some way to identify rows uniquely): CREATE TEMP TABLE tbl ( tbl_id serial PRIMARY KEY , name text, birth int, height numeric);INSERT INTO tbl (name, birth, height)VALUES ('William', 1976, 1.82), ('James', 1981, 1.68), ('Mike', 1976, 1.68), ('Tom', 1967, 1.79), ('William', 1976, 1.74), ('William', 1981, 1.82), ('Tom', 1978, 1.92), ('Mike', 1963, 1.68), ('Tom', 1971, 1.86), ('James', 1981, 1.77), ('Tom', 1971, 1.89); Query: SELECT DISTINCT ON (name, height) *FROM ( SELECT DISTINCT ON (name, birth) * FROM tbl ORDER BY name, birth, height, tbl_id -- pick smallest height, ID as tiebreaker ) sub ORDER BY name, height, birth, tbl_id ; -- pick earliest birth, ID as tiebreaker tbl_id | name | birth | height--------+---------+-------+-------- 2 | James | 1981 | 1.68 8 | Mike | 1963 | 1.68 4 | Tom | 1967 | 1.79 9 | Tom | 1971 | 1.86 7 | Tom | 1978 | 1.92 5 | William | 1976 | 1.74 6 | William | 1981 | 1.82(7 rows) -- !!! A DISTINCT ON query without deterministic ORDER BY can return any arbitrary row from each set of dupes. Applied once, you still get a deterministic number of rows (with arbitrary picks). Applied repeatedly, the resulting number of rows is arbitrary, too. Related: Select first row in each GROUP BY group? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42505531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2091169/']} | jdg_78441 |
stackexchange | llm_judgeable_groundtruth_similarity | 54099218 |
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 install Docker inside an alpine container and run docker images?I could install, but could not start docker and while running get "docker command not found error".
Now provide the response and nothing else.
| Dockerfile for running docker-cli inside alpine FROM alpine:3.10RUN apk add --update docker openrcRUN rc-update add docker boot Build docker image docker build -t docker-alpine . Run container ( host and the alipne container will share the same docker engine ) docker run -it -v "/var/run/docker.sock:/var/run/docker.sock:rw" docker-alpine:latest /bin/sh | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/54099218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10674157/']} | jdg_78442 |
stackexchange | llm_judgeable_groundtruth_similarity | 514999 |
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 having problems with dense sets as my lecturer didn't really develop an intuition for dense sets in my class. So can any of you please help me with that? And can you please tell me (the general case) how I should go about proving that a set is dense in R.
Now provide the response and nothing else.
| A set $D$ is dense in $\Bbb R$ if every non-empty open interval of $\Bbb R$ contains a point of $D$; in symbols, $D$ is dense in $\Bbb R$ if and only if $D\cap(a,b)\ne\varnothing$ whenever $a,b\in\Bbb R$ and $a<b$. The set $\Bbb Q$ of rationals is dense in $\Bbb R$: if $a$ and $b$ are real numbers, and $a<b$, there is always a rational number between $a$ and $b$, so $\Bbb Q\cap(a,b)\ne\varnothing$. There is also always an irrational number between $a$ and $b$, so $\Bbb R\setminus\Bbb Q$, the set of irrationals, is also dense in $\Bbb R$. And of course $\Bbb R$ itself is dense in $\Bbb R$. Another example of a dense subset of $\Bbb R$ is $\Bbb R\setminus\Bbb Z$, the set of real numbers that are not integers: you can easily prove that if $a<b$, the interval $(a,b)$ contains a non-integer. Similarly, $\Bbb R\setminus F$ is dense for any finite $F\subseteq\Bbb R$. Here are a couple of less obvious examples. Let $$D=\left\{\frac{2m+1}{2^n}:n\in\Bbb N\text{ and }m\in\Bbb Z\right\}\;;$$ the elements of $D$ are the dyadic rationals , the rational numbers whose denominators in lowest terms are powers of $2$. This set $D$ is dense in $\Bbb R$; you might try to prove that $D\cap(a,b)\ne\varnothing$ whenever $a<b$. HINT: For a fixed $n$, the dyadic rationals with denominator $2^n$ are $\frac1{2^n}$ apart. Finally, let $C$ be the middle-thirds Cantor set ; then $C$ does not contain any non-empty open interval, so $\Bbb R\setminus C$ intersects every non-empty open interval and is therefore dense in $\Bbb R$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/514999', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76118/']} | jdg_78443 |
stackexchange | llm_judgeable_groundtruth_similarity | 16543528 |
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 installed BB tools for Eclipse, just added and removed BB Nature to one of my projects.And now, I can't compile it (for Android). Eclipse told me about some troubles in AndroidManifest.xml: native-code: armeabi AndroidManifest.xml /VitocarsAndroidApp AndroidManifest.xml BlackBerry Verifying Problem But the manifest is OK, no one line is highlighted: <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.asap.vitocarsandroidapp" android:versionCode="5" android:versionName="1.04" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <application android:name="com.asap.vitocarsandroidapp.system.VitocarsApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.asap.vitocarsandroidapp.LoginActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.asap.vitocarsandroidapp.TableViewActivity" android:label="@string/title_activity_table_view" > </activity> <activity android:name="com.asap.vitocarsandroidapp.PartActivity" android:label="@string/title_activity_part" > </activity> <activity android:name="com.asap.vitocarsandroidapp.PhotoViewActivity" android:label="@string/title_activity_photo_view" > </activity> <activity android:name="com.asap.vitocarsandroidapp.UserRegisterActivity" android:label="@string/title_activity_user_register" > </activity> <activity android:name="com.asap.vitocarsandroidapp.ConfirmPhoneActivity" android:label="@string/title_activity_confirm_phone" > </activity> <activity android:name="com.asap.vitocarsandroidapp.OfficeActivity" android:label="@string/title_activity_office" > </activity> <activity android:name="com.asap.vitocarsandroidapp.PriceOfferActivity" android:label="@string/title_activity_price_offer" > </activity> <activity android:name="com.asap.vitocarsandroidapp.RegionOrderActivity" android:label="@string/title_activity_region_order" > </activity> <activity android:name="com.asap.vitocarsandroidapp.MapView" android:label="@string/title_activity_map_view" > </activity> </application></manifest> I already spent a lot of time, trying to solve it. Maybe, somebody can help me?
Now provide the response and nothing else.
| Following example shows a simplest way to serialize struct into char array and de-serialize it. #include <iostream>#include <cstring>#define BUFSIZE 512#define PACKETSIZE sizeof(MSG)using namespace std;typedef struct MSG{ int type; int priority; int sender; char message[BUFSIZE];}MSG;void serialize(MSG* msgPacket, char *data);void deserialize(char *data, MSG* msgPacket);void printMsg(MSG* msgPacket);int main(){ MSG* newMsg = new MSG; newMsg->type = 1; newMsg->priority = 9; newMsg->sender = 2; strcpy(newMsg->message, "hello from server\0"); printMsg(newMsg); char data[PACKETSIZE]; serialize(newMsg, data); MSG* temp = new MSG; deserialize(data, temp); printMsg(temp); return 0;}void serialize(MSG* msgPacket, char *data){ int *q = (int*)data; *q = msgPacket->type; q++; *q = msgPacket->priority; q++; *q = msgPacket->sender; q++; char *p = (char*)q; int i = 0; while (i < BUFSIZE) { *p = msgPacket->message[i]; p++; i++; }}void deserialize(char *data, MSG* msgPacket){ int *q = (int*)data; msgPacket->type = *q; q++; msgPacket->priority = *q; q++; msgPacket->sender = *q; q++; char *p = (char*)q; int i = 0; while (i < BUFSIZE) { msgPacket->message[i] = *p; p++; i++; }}void printMsg(MSG* msgPacket){ cout << msgPacket->type << endl; cout << msgPacket->priority << endl; cout << msgPacket->sender << endl; cout << msgPacket->message << endl;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16543528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1331598/']} | jdg_78444 |
stackexchange | llm_judgeable_groundtruth_similarity | 41483207 |
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 send a local notifications on every Monday. Let say that I have a scenario in which I have to send a medication taking reminder on every Monday for one month. So it will be total 4 notification in a month. My code is as below but I can't figure out the following things;1)How to send the notifications on a specific day2)How to limit the notification for a max end date. The code for sending the notification is as follows; let notification = UILocalNotification() notification.alertBody = "Take Medication" notification.alertAction = "open" // text that is displayed after "slide to..." on the lock screen - defaults to "slide to view" notification.fireDate = NSDate() notification.userInfo = ["title": "notification app", "UUID": "Some Unique Guid"]UIApplication.sharedApplication().scheduleLocalNotification(notification) Can anyone please help?Regards,neena
Now provide the response and nothing else.
| Is it possible to use Hibernate and Mysql with ReactiveCrudRepository instead of CrudRepository ? TL;DR: Not with Hibernate and MySQL, but with R2DBC and Postgres, Microsoft SQL Server or H2.Take a look at Spring Data R2DBC . Long Version Why not JPA? With Hibernate/JPA included this won't happen in the foreseeable future.JPA is based on the idea that you load part of your data model into memory, manipulate the resulting object model and let JPA transform these changes.All this within a single transaction. This is kind of the opposite how one deals with a reactive store where you try to make atomic changes and try to decouple the loading, processing and storing and all this without blocking. Why not JDBC? So we have to look at the technology level below JPA: JDBC.But JDBC is still blocking: You send a SQL statement to your database and then JDBC will block until you get the result.And again this goes against the idea of reactive: Never block.One could wrap this in a thread pool to mitigate this to some extent, but that is more of a workaround than a solution. Why R2DBC? There are some suitable drivers for some databases that could be used for reactive repositories.But they are proprietary and thereby not a good basis for something that really should eventually work across all (relevant) relational databases. For some time the Spring Data team hoped that ADBA would fill that gap.But discussions on the mailing list made it clear that ADBA was not aiming for reactive but only for asynchronous.Again not what we needed for a reactive repository abstraction. So early in 2018 various people living at the intersection or reactive and relational decided that we need a standard for reactive database access. R2DBC ( R eactive R elational D atabase C onnectivity) is a proposal for such a standard.The hope is that it either helps convincing Oracle to move ADBA to a reactive approach or if that doesn't happen it becomes the standard itself. And with already three implementations available chances for the second option look promising. R2DBC itself is mainly an SPI, i.e. an API that is to be implemented by database providers.The SPI is designed in a way that puts minimal requirements on implementers.But this also makes R2DBC somewhat cumbersome to use.The idea is that other libraries will step up and build libraries designed for usability on top of that SPI, as it happened with JDBC. Spring Data R2DBC Spring Data R2DBC is one such library and it offers what you asked for: Support for ReactiveCrudRepository although it is independent of JPA/Hibernate and there is no support for MySQL yet. State of the projects Both R2DBC and Spring Data R2DBC didn't have a production release yet and it will take at least several months to get there. Spring Data R2DBC just released the first milestone.See the release article for its current capabilities . R2DBC is on its 6th milestone. See the release article for details . See also this answer: Why does Spring not provide reactive (non-blocking) clients for relational databases? Original answer as a reference for archeologists: As of now (Jan 2017) it is not possible. The currently relevant release for the reactive part of Spring Data is Spring Data Kay M1 (You can check if there is a newer version available on the project home page ) And a blog post from the Spring Data team about that release and specifically the reactive parts in it starts with (emphasis mine): Spring Data Kay M1 is the first release ever that comes with support for reactive data access. Its initial set of supported stores — MongoDB, Apache Cassandra, and Redis — all ship reactive drivers already, which made them very natural candidates for such a prototype. The reason is that there is no standard non-blocking way to access a relational database. So only those that support this kind of API are supported right now. One could implement a ReactiveCrudRepository using JPA or JDBC and delegate the work to a thread pool. This would provide an async API on the outside, but would still consume the resources for the Threads and block between independent data accesses, so only a small part of the benefits of the reactive approach would get realized. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41483207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5546031/']} | jdg_78445 |
stackexchange | llm_judgeable_groundtruth_similarity | 529318 |
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:
From man tar : -f, --file ARCHIVE use archive file or device ARCHIVE Please consider: tar -zxvf myFile.tar.gz As far as I understand, z means "gzipped tarball", x means "extract", v means "verbose output" but about f I am not sure. If we already give the file name myFile.tar.gz , why is the f argument needed?
Now provide the response and nothing else.
| It's the option you use to specify the actual pathname of the archive you would want to work with, either for extracting from or for creating or appending to, etc. If you don't use -f archivename , different implementations of tar will behave differently (some may try to use a default device under /dev , the standard input or output stream, or the file/device specified by an environment variable). In the command line that you quote, tar -zxvf myFile.tar.gz which is the same as tar -z -x -v -f myFile.tar.gz you use this option with myFile.tar.gz as the option-argument to specify that you'd like to extract from a particular file in the current directory. Consult the manual for tar on your system to see what data stream or device the utility would use if you don't use the -f option. The GNU tar implementation, for example, has a --show-defaults option that will show the default options used by tar , and this will probably include the -f option (this default may be overridden by setting the TAPE environment variable). | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/529318', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']} | jdg_78446 |
stackexchange | llm_judgeable_groundtruth_similarity | 45166757 |
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 reading this article on InfoQ quoting Reinhold: Developers can still use the Java class path in Java 9 for the Java runtime to search for classes and resource files. It's just that with Java 9's modules, developers no longer need the class path. So now my question is: what is the proper Java 9 way to do the tasks listed above? How do you dynamically load e.g. an image (short of fiddling with relative paths)? Even more interestingly, how would one check if a class is available and make a decision dynamically (e.g. check if Jackson is available and, if so, use it for JSON serialization and if not use something else)? The article also mentions Spring Boot already supporting Java 9, and Spring Boot definitely does a lot of dynamic loading. So maybe someone knows the priece of code from Spring that I can look at?
Now provide the response and nothing else.
| First, to set the record straight, I neither said nor wrote the textquoted above. I’d never have put it that way. That’s just sloppyreporting on the part of the publications involved. The most important thing to understand about class loading and resourcelookup in Java 9 is that, at a fundamental level, they have not changed.You can search for classes and resources in the same way that you alwayshave, by invoking Class::forName and the various getResource* methodsin the Class and ClassLoader classes, regardless of whether your codeis loaded from the class path or the module path. There are still threebuilt-in class loaders, just as there were in JDK 1.2, and they have thesame delegation relationships. Lots of existing code therefore justworks, out-of-the-box. There are some nuances, as noted in JEP261 : The concrete typeof the built-in class loaders has changed, and some classes formerlyloaded by the bootstrap class loader are now loaded by the platform classloader in order to improve security. Existing code which assumes that abuilt-in class loader is a URLClassLoader , or that a class is loaded bythe bootstrap class loader, may therefore require minor adjustments. A final important difference is that non-class-file resources in a moduleare encapsulated by default, and hence cannot be located from outsidethe module unless their effective package is open .To load resources from your own module it’s best to use theresource-lookup methods in Class or Module , which can locate anyresource in your module, rather than those in ClassLoader , which canonly locate non-class-file resources in the open packages of a module. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/45166757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/294657/']} | jdg_78447 |
stackexchange | llm_judgeable_groundtruth_similarity | 7649558 |
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 business reasons I'd like to restrict my Android application strictly to tablet devices. At the moment, I can limit the app to Honeycomb devices by setting: android:minSdkVersion="11" But the next version of Android (Ice Cream Sandwich) will have a higher version number for both the tablet and phone versions of the OS. Is there any manifest attribute I can specify to restrict it to tablet devices? (Honeycomb or any later tablet version)
Now provide the response and nothing else.
| You will find this link awesome: http://android-developers.blogspot.com/2011/09/preparing-for-handsets.html The problem with what we call "tablet" is that the definition is not the same for evryone.I think about the Archos 5IT that is the same size than a phone but branded with "tablet" name. Same issue with Dell Streak. I would personnaly not call that a tablet.. So if you want to restrict to 7 or 5 inches devices, you should use xlargeScreens and largeScreens. (There is also a bug in HTC flyer - 7 inches- that uses largeScreens, blame HTC) I guess that playing with Screen size in Manifest will fit your needs: <supports-screens android:smallScreens="false" android:normalScreens="false" android:largeScreens="false" android:xlargeScreens="true" android:anyDensity="true" android:requiresSmallestWidthDp="600" android:compatibleWidthLimitDp="integer" android:largestWidthLimitDp="integer"/> | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7649558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48810/']} | jdg_78448 |
stackexchange | llm_judgeable_groundtruth_similarity | 416164 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let me start by saying that of course conventions are important, there should be a rule of thumb for some cases that is representing the best action to follow by, in order to prevent mistakes and make stuff more simple. Now for the topic of the question/discussion. I am working on a side project of a DNS server written in Go, and have been reading RFC 1034 & RFC 1035. RFC 1035 describe the Zones master file that stores all the DNS records inside of it, with some other data like TTL, record type and authority who sent it. RFC 1035 was written in 1987 and I understand why it was using a text file in order to store its data. While designing my project I was thinking about using a local database like PostgreSQL serving under the localhost. While looking a bit more into the subject, I found out that big companies who serves DNS servers like Microsoft are using the text file format as well, I guess that its because of keeping the convention "alive", but I just cant find any reason not to kill it and improve the system. Do you think I should use the text file, or a local database? Why does companies keep using old methods? Thank you for any answer, that might point to something i didnt think about.
Now provide the response and nothing else.
| The zone file format is a standardized format. Standard are good, because, well, they are standardized. They give a common ground. Why do we still use TCP/IP? Because every device in the world (modulo tiny embedded devices) speaks it. Can we do better? Sure! We can update TCP/IP. We can even try and replace it. But that would mean replacing the entire infrastructure of what is, essentially the basis of almost all modern life. If you do use local database for configuration, and your server ends up running an important zone, then how am I going to send my zone data to you? As a SQL INSERT INTO statement? Note that there is nothing in the RFC you quoted that says you must use a zone file. It only defines the format for the zone file in case you use one . Of course , you will not be using the zone file as the runtime database. It is a configuration file, not a data structure. In fact, the very RFC you quoted has this to say ( bold emphasis mine): 6.1.2 Database While name server implementations are free to use any internal datastructures they choose , the suggested structure consists of three majorparts: A "catalog" data structure which lists the zones available tothis server, and a "pointer" to the zone data structure. Themain purpose of this structure is to find the nearest ancestorzone, if any, for arriving standard queries. Separate data structures for each of the zones held by thename server. A data structure for cached data. (or perhaps separate cachesfor different classes) | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/416164', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/375344/']} | jdg_78449 |
stackexchange | llm_judgeable_groundtruth_similarity | 151918 |
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:
I have a Dataset ds with a straightforward tabular structure containing one column Date whose values are DateObject s, and a number of other columns of real-valued numbers. I can plot the value of one of these columns using: DateListPlot[ds[All,{"Date","Column1"}]] This plots the values in Column1 against an X-axis using the dates from Date as expected: How can I extend this behaviour to display lines for more than one column? Attempting: DateListPlot[ds[All,{"Date","Column1","Column2"}]] results in: DateListPlot: Unable to automatically determine horizontal coordinates for the given data and DataRange. Attempting: DateListPlot[ds[All,{"Date",#}]& /@ {"Column1","Column2"}] DateListPlot: { Dataset[<<150>>] , Dataset[<<150>>] } is not a valid dataset or list of datasets. Is there an adjustment to either of these input approaches that will fix the flaws in my approach, or if not how can this be achieved?
Now provide the response and nothing else.
| The query ds[All,{"Date","Column1"}] returns a list of associations whose values represent date-value pairs. The query ds[All, "Date", "Column1", "Column2"}] returns a list of associations with multiple values for each date. DateListPlot will accept the first format, but not the second. To plot multiple series, we must reformat the data into a shape that is acceptable to DateListPlot . For example, we could generate multiple lists of date-value pairs: ds[Transpose /* DateListPlot, {{#Date, #Column1}, {#Date, #Column2}}&] Discussion For discussion purposes, we will define a sample dataset: ds = Range[5] // Query[Dataset , <| "date" -> (DatePlus["2005-01-01", {#, "Year"}]&) , "v1" -> Sin , "v2" -> Cos , "v3" -> Sec|> ] As noted in the question, we can plot a single column of values easily: ds[DateListPlot, {"date", "v1"}] but the same technique fails for multiple columns: ds[DateListPlot, {"date", "v1", "v2"}] The reason is that DateListPlot can handle the date-value pairs that are returned by the first query: ds[First /* Values, {"date", "v1"}] // Normal(* <|"date" -> "Sun 1 Jan 2006 00:00:00", "v1" -> Sin[1]|> *) But DateListPlot does not presently (V11.1) accept an association with more than one value per date as is returned by the second query: ds[First, {"date", "v1", "v2"}] // Normal(* <|"date" -> "Sun 1 Jan 2006 00:00:00", "v1" -> Sin[1], "v2" -> Cos[1]|> *) To plot multiple columns, we must reshape the data to conform to one of the formats acceptable to DateListPlot . For example, it will accept multiple lists of date-values pairs: ds[Transpose /* DateListPlot, {{#date, #v1}, {#date, #v2}, {#date, #v3}} &] Alternatively: ds[(Query[All, {"date", #} /* Values] & /@ {"v1", "v2", "v3"}) /* DateListPlot] In both queries we had to take care that the date-value pairs were lists -- not associations. This is due to another limitation of DateListPlot . While DateListPlot will accept a single set of associations containing date-value pairs, it cannot presently handle a list of such sets. We must convert the associations to lists to work around this restriction. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/151918', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/51229/']} | jdg_78450 |
stackexchange | llm_judgeable_groundtruth_similarity | 17472 |
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:
Let $R$ be a commutative ring and $m\subseteq R$ be a maximal ideal. Can you describe the set of prime ideals of the $R/m^2$. Are they all maximal ?
Now provide the response and nothing else.
| $m/m^2$ is a maximal ideal of $R/m^2$, and it is nilpotent; it is therefore the nilradical, and being prime, is the only prime ideal of $R/m^2$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/17472', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5422/']} | jdg_78451 |
stackexchange | llm_judgeable_groundtruth_similarity | 9018584 |
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 searched for a solution to this problem on the Internet and checked the Stack Overflow questions, but none of the solutions worked for my case. I want to create a foreign key from table sira_no to metal_kod. ALTER TABLE sira_no ADD CONSTRAINT METAL_KODU FOREIGN KEY(METAL_KODU) REFERENCES metal_kod(METAL_KODU) ON DELETE SET NULL ON UPDATE SET NULL ; This script returns: Error Code: 1005. Can't create table 'ebs.#sql-f48_1a3' (errno: 150) I tried adding an index to the referenced table: CREATE INDEX METAL_KODU_INDEX ON metal_kod (METAL_KODU); I checked METAL_KODU on both tables (charset and collation), but I couldn't find a solution to this problem. How can I fix this problem? Here is the metal_kod table: METAL_KODU varchar(4) NO PRIDURUM bit(1) NOMETAL_ISMI varchar(30) NOAYAR_YOGUNLUK smallint(6) YES 100
Now provide the response and nothing else.
| Error Code: 1005 -- there is a wrong primary key reference in your code Usually it's due to a referenced foreign key field that does not exist. It might be you have a typo mistake, or check case it should be same, or there's a field-type mismatch. Foreign key-linked fields must match definitions exactly. Some known causes may be: The two key fields type and/or size doesn’t match exactly. For example, if one is INT(10) the key field needs to be INT as well and not BIGINT or SMALLINT or TINYINT . You should also check that one is not SIGNED and the other is UNSIGNED . They both need to be exactly the same. One of the key field that you are trying to reference does not have an index and/or is not a primary key. If one of the fields in the relationship is not a primary key, you must create an index for that field. The foreign key name is a duplicate of an already existing key. Check that the name of your foreign key is unique within your database. Just add a few random characters to the end of your key name to test for this. One or both of your tables is a MyISAM table. In order to use foreign keys, the tables must both be InnoDB . (Actually, if both tables are MyISAM then you won’t get an error message - it just won’t create the key.) In Query Browser, you can specify the table type. You have specified a cascade ON DELETE SET NULL , but the relevant key field is set to NOT NULL . You can fix this by either changing your cascade or setting the field to allow NULL values. Make sure that the Charset and Collate options are the same both at the table level as well as individual field level for the key columns. You have a default value (that is, default=0) on your foreign key column One of the fields in the relationship is part of a combination (composite) key and does not have its own individual index. Even though the field has an index as part of the composite key, you must create a separate index for only that key field in order to use it in a constraint. You have a syntax error in your ALTER statement or you have mistyped one of the field names in the relationship The name of your foreign key exceeds the maximum length of 64 characters. For more details, refer to: MySQL Error Number 1005 Can’t create table | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9018584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/809807/']} | jdg_78452 |
stackexchange | llm_judgeable_groundtruth_similarity | 11780 |
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:
I have a table with data, for example MT = {{1, 80.3, 1, 4, 68}, {2, 80.5, 1, 5.5, 102}, {3, 80.0, 0, 4.2, 78}, {4, 80.4, 0, 3, 17}, {5, 80.2, 1, 5, 180}}; I can plot column 1 against column 2 with L1 = Table[MT[[i, 1]], {i, 1, 5}];L2 = Table[MT[[i, 2]], {i, 1, 5}];ListPlot[Table[{L1[[i]], L2[[i]]}, {i, 1, 5}]] Now I want to do is the following: I want to plot column 1 against column 2 if the entry in column 3 is == 1. (So that only the points of rows 1,2,5 are shown) Does anyone know how to do that? Thanks alot!
Now provide the response and nothing else.
| Before I answer your actual question, let me first show you how to simplify your code a lot. First, instead of Table[MT[[i, 1]], {i, 1, 5}] you can simply write Table[[All, 1]] , which means "take all rows, but only the first column). Obviously you also can do the same with Table[MT[[i, 1]], {i, 1, 5}] . You can also get rid of your third Table by observing that you can also select a list of rows by giving a list of indices. That is, you don't need L1 and L2 at all (unless you need them for your further code, of course), and can simply write ListPlot[MT[[All, {1, 2}]] ] Solution using Select Now to plot only the rows where the third index is 3, the best way is to first generate a list which only contains those lines, and plot that. For this purpose Mathematica provides the function Select , which takes a list and a predicate function, and returns a list of all elements for which this function returns true. Your table is a list of rows, and you want to select rows, therefore you can apply Select directly to the list. This could be done as follows: (* the predicate function *)thirdElementIsOne[row_] := (row[[3]] == 1)(* the sublist *)selectedRows = Select[MT, thirdElementIsOne];(* plot the first two columns *)ListPlot[selectedRows[[All, {1, 2}]] ] Now it seems quite wasteful to provide a function definition (and waste another symbol) for the second argument of Select . But Mathematica has a solution for this: pure functions (note however that Mathematica's use of the term "pure functions" don't correspond to what elsewhere is meant by that term; in other languages one usually speaks of "unnamed functions" or "lambda functions" for this concept). A pure function can be written in the form Function[argument, expression] (or, for more than one argument, Function[{arguments}, expression] ). So the above code could also be written as (* the sublist *)selectedRows = Select[MT, Function[row, row[[3]] == 1] ];(* plot the first two columns *)ListPlot[selectedRows[[All, {1, 2}]] ] But given the simplicity of the function, even this syntax seems unnecessarily verbose. Thus Mathematica offers an even terser syntax: If you write any expression followed by an & , it defines a pure function. With this syntax there's of course no way to name arguments (which can be a problem if you have nested pure functions). Instead, you write the first argument as # or #1 (both are equivalent; # is shorter, but #1 is more consistent if you have more arguments), the second one as #2 , etc. In the case above, there is just one argument (the row), therefore you can write (* the sublist *)selectedRows = Select[MT, #[[3]] == 1&];(* plot the first two columns *)ListPlot[selectedRows[[All, {1, 2}]] ] Now the expression is so short that it again doesn't seem to make sense to store it in a separate variable (unless you need it again later), therefore let's just insert it in the ListPlot command to get ListPlot[Select[MT, #[[3]] == 1&][[All, {1, 2}]] ] Solution using Position If your table gets large, and there are many rows containing 1 in the third column, you might not want to actually copy all that data. In that case, you might want to first get a list of row indices, and use that to select the data to plot. To this end, we need the indices of rows where the third column is 1 . To Get a list of indices, there's the Mathematica function Position . It takes a list and a pattern, and gives a list of indices for elements matching the pattern. Now what a pattern is and how they are matched is a topic in itself, however in this case all you have to know is that to match a given specific expression you normally use the expression itself as pattern. Now the list we need to examine is the third column of ML , which, as described in the beginning, can be obtained as MT[[All, 3]] . The expression we want to select for is 1 . Therefore the expression we need is Position[MT[[All, 3]], 1](*==> {{1}, {2}, {5}}*) However as you can see above, this does not return a list of indices, but a list of one-element list of indices. This is because in general, you need several indices to specify a position (e.g. if we had applied it to ML itself, you would need two indices to specify the position of any 1 in it), and thus the elements returned are lists giving all the elements. However, knowing that our list has only one-element sublists, we can use Flatten to get rid of the extra level: Flatten@Position[MT[[All, 3]], 1](*==> {1, 2, 5}*) (The @ syntax I've used here is just another way to apply a function to a single argument, which saves you a keystroke: Flatten@x is exactly equivalent to Flatten[x] .) Now that we have a list of indices, we can just use it as first index to ML : ListPlot[MT[[Flatten@Position[MT[[All, 3]], 1], {1, 2}]] ] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/11780', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/3053/']} | jdg_78453 |
stackexchange | llm_judgeable_groundtruth_similarity | 26469151 |
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 is my If Else Statement for my homework but it doesn't work the way I expected it to be. When I enter 82 as the grade, it says "Your grade is = ú". Instead of 'B', it displays a character which I didn't declare. Same goes to the others. Instead of 'A' - @Instead of 'C' - ╬Instead of 'D' - (shows nothing)Instead of 'F' - ″ #include <iostream>using namespace std;int main(){ int score; char grade; char A, B, C, D, F; cout << "Enter your total score: "; cin >> score;if (score >= 85)grade=A;else if (score >= 75)grade=B;else if (score >= 65)grade=C;else if (score >= 55)grade=D;elsegrade=F; cout << "Your grade is = " << grade << endl;return 0;cin.get();} Thanks in advance!!!
Now provide the response and nothing else.
| You declare these variables, but never set them to anything char A, B, C, D, F; You should assign values to them const char A = 'A';const char B = 'B';const char C = 'C';const char D = 'D';const char F = 'F'; Although in this case, even the above may be superfluous. You could simply do if (score >= 85) grade = 'A';else if (score >= 75) grade = 'B';else if (score >= 65) grade = 'C';else if (score >= 55) grade = 'D';else grade = 'F'; Then you can get rid of the char variables all together. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26469151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3992725/']} | jdg_78454 |
stackexchange | llm_judgeable_groundtruth_similarity | 44953041 |
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 alias in my .zshrc file: alias rmcons="docker rm -f $(docker ps -aq)" But after trying to execute it, it removes only one container and then it prints $rmconsef8197f147fbzsh: command not found: c2ea2673f9e4zsh: command not found: 4603059f1618zsh: command not found: 40ad60328595 How can I remove all containers that docker ps -aq shows?
Now provide the response and nothing else.
| You need to use single quotes ( '' ) instead of double quotes ( "" ). alias rmcons='docker rm -f $(docker ps -aq)' If you use double quotes, than the command substitution $(docker ps -aq) will be evaluated when you define the alias. In your example this was equivalent to alias rmcons="docker rm -f ef8197f147fbc2ea2673f9e44603059f161840ad60328595" As the newlines are command separators (like ; ) this alias is substituted by four commands: docker rm -f ef8197f147fb , c2ea2673f9e4 , 4603059f1618 and 40ad60328595 . The last three of which do not exist on your system, hence "command not found". It also means that the same output of docker ps -aq - as it was on alias definiton - will be used and not as it would be when running the alias. On the other hand, if you use single quotes, the alias will actually substituted by the exact command you defined: docker rm -f $(docker ps -aq) . Although docker ps -aq will still return output with newlines, these newlines are now only parsed word separators between arguments. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44953041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1581687/']} | jdg_78455 |
stackexchange | llm_judgeable_groundtruth_similarity | 60209503 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
First of all, here is my code: #include <iostream>#include <memory>#include <vector>class Animal {public: virtual void display() = 0;};class Dog : public Animal { std::string name;public: Dog(std::string n) : name(n) {} void display() override { std::cout << "I'm a dog and my name is: " << name << std::endl; }};class Cat : public Animal { std::string name;public: Cat() {} Cat(std::string n) : name(n) {} void display() override { std::cout << "I'm a cat and my name is: " << name << std::endl; }};int main(){ Dog D1("Spike"); Dog D2("Razor"); Cat C1("Cat"); std::vector<std::unique_ptr<Animal>> vectorOfAnimals; std::unique_ptr<Animal> pointer1 = std::make_unique<Dog>(D1); std::unique_ptr<Animal> pointer2 = std::make_unique<Dog>(D2); std::unique_ptr<Animal> pointer3 = std::make_unique<Cat>(C1); std::unique_ptr<Animal> pointer4 (nullptr); vectorOfAnimals.push_back(std::move(pointer1)); vectorOfAnimals.push_back(std::move(pointer2)); vectorOfAnimals.push_back(std::move(pointer3)); vectorOfAnimals.push_back(std::move(pointer4)); for(auto& animals : vectorOfAnimals) { animals = nullptr; } if(!vectorOfAnimals[0]) { std::cout << "First element is nullptr!" << std::endl; vectorOfAnimals[0] = std::move(pointer1); } for(auto& animals : vectorOfAnimals) { if(!animals) { std::cout << "This is a nullptr!" << std::endl; } else { animals->display(); } } return 0;} I created an abstract class with 2 derived classes. Then, pushed backed some unique pointers in a vector of unique pointers to base class. For learning purposes, then, I assigned to all elements of vector nullptr and tried to transfer ownership of first pointer created called "pointer1" to first element of vector, but it doesn't work, first element remains nullptr. Where I'm wrong ?
Now provide the response and nothing else.
| std::move is not something you do just to get your code to compile. It actually has a function, a purpose, a result.* The result is that your data has been moved away. It's gone. It's in the container now; pointer1 etc remain unconnected to the pointers in the vector, and (more importantly) no longer point to anything. As such, this makes no sense: vectorOfAnimals[0] = std::move(pointer1); Think about the word "unique" in the name unique_ptr . * std::move itself doesn't actually move anything. But, for our purposes today, close enough. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60209503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12892622/']} | jdg_78456 |
stackexchange | llm_judgeable_groundtruth_similarity | 2753477 |
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 report with appendixes. What I want is to use a different style on the page numbering when the appendixes start. I use Arabic numbering until I reach the appendixes. Then I would want to do something like this: I want the custom page numbering to be: Chapter: ASection: {Chapter}{1} (A-1) \newpage\pagenumbering{custompagenumbering} Is this possible?
Now provide the response and nothing else.
| Some paragraph. Some paragraph. Some paragraph. Some paragraph. Some paragraph.\newpage\setcounter{page}{1}\renewcommand{\thepage}{A-\arabic{page}}Some paragraph. Some paragraph. Some paragraph. Some paragraph. Some paragraph. Would this be anywhere near what you want to do? This is how you can manipulate the page counter, and the \thepage command that determines what will be printed as page number. \roman{page} would give roman numbers, \alph{page} a , b , c ... The other sensible solution is to use the fancyhdr package, as suggested before. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2753477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24872/']} | jdg_78457 |
stackexchange | llm_judgeable_groundtruth_similarity | 3523752 |
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 scratching my head a bit at how model binders do their work in ASP.Net MVC. To be specific, the BindModel() method has a ModelBindingContext parameter that holds the model name and type, but I don't understand how the ModelBindingContext receives these values. An MVC model has to be populated from posted form values or query string parameters, or other sources of data. But what mechanism determines the model type handed to the ModelBindingContext, and how is one model type chosen over another model type, over even (say) a simple list containing the individual posted values? It just appears to me the ModelBindingContext "knows" the type of model it's being handed, and I'm not sure where that's coming from or the workflow involved in populating it.
Now provide the response and nothing else.
| Interesting question. Here is a simple overview of what MVC does. It's all handled by the ControllerActionInovker class. This is not in specific order, but is close. ControllerActionInovker determines the parameter type via reflection. Next ValueProviders are created from the HttpContext Request Form, Route, QueryString, etc. properties. You can also provide your own value providers. These ValueProviders are supplied to a ModelBindingContext via a collection that acts as a virtual ValueProvider. Then ControllerActionInovker looks for a ModelBinder for the specific type. If it doesn't find one it defaults to the built in DefaultModelBinder. In most cases the DefaultModelBinder is used. It's job is to create a Model, and use the ValueProviders to connect the properties with values using the model properties names as a key. When the ValueProviders have a value, they return a ValueProviderResult object that is responsible for type conversion. You can see this for yourself in the ASP.net MVC source located at codeplex.com . Look for the ControllerActionInvoker class and the GetParameterValue method. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3523752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172617/']} | jdg_78458 |
stackexchange | llm_judgeable_groundtruth_similarity | 2557002 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to improve this: private static int CountNewlines(string s){ int len = s.Length; int c = 0; for (int i=0; i < len; i++) { if (s[i] == '\n') c++; } return c;} I'm particularly concerned about the Item accessor on the string. Not sure if it is just pointer arithmetic like C/C++.
Now provide the response and nothing else.
| I tested these implementations private static int Count1(string s){ int len = s.Length; int c = 0; for (int i=0; i < len; i++) { if (s[i] == '\n') c++; } return c+1;}private static int Count2(string s){ int count = -1; int index = -1; do { count++; index = s.IndexOf('\n', index + 1); } while (index != -1); return count+1;}private static int Count3(string s){ return s.Count( c => c == '\n' ) + 1;}private static int Count4(string s){ int n = 0; foreach( var c in s ) { if ( c == '\n' ) n++; } return n+1;}private static int Count5(string s){ var a = s.ToCharArray(); int c = 0; for (int i=0; i < a.Length; i++) { if (a[i]=='\n') c++; } return c+1;} Here are my timing results for 100000 iterations on a string of ~25k. Lower is faster. Time FactorCount1 4.8581503 1.4Count2 4.1406059 1.2Count3 45.3614124 13.4Count4 3.3896130 1.0Count5 5.9304543 1.7 Surprisingly, to me, the Enumerator implementation was fastest for me, by a significant degree - 20% faster than the next closest implementation. The results were repeatable, regardless of the order in which the methods were run. I also used a warmup phase to insure transient effects (jit, etc) were factored out. This was for a release build (/optimize+) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2557002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48082/']} | jdg_78459 |
stackexchange | llm_judgeable_groundtruth_similarity | 306325 |
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:
For the following circuit i am confused to as why Resistor R4 when measured on the breadboard is 35k ohms, when it is meant to be 47k Ohms (as it is a 47 k ohm resistor. Also when it is taken out of the circuit and measured it is fine and gives the 47k ohm as expected) . The other resistors when measured match up to what they are meant to be. I assume the reason it is giving this reading is due to the configuration it is in? Such as something to do with the voltage divider, maybe something else? Note for the circuit schematics i have just put 35k ohms just to seeif my simulated results would match up to what the breadboard circuitoutputted on an oscilloscope. It is actually meant to be 47k ohms In short Not understanding why the 47k ohm resistor (R4) reads 35k ohm on the multimeter How do i calculate what this resistor value will be due to the difference? As in i find what value i want, in this case i needed 47k ohm for the specified application but due to this resistor value difference, how am i meant to see what 47k will actually be. As in will i need to use a 56k or something to get the 47k due to the difference? Hence what formula am i meant to use to find what value this resistor will actually be when in theory its meant to be 47k ohms? Circuit Schematics Circuit implemented on the breadboard
Now provide the response and nothing else.
| Not understanding why the 47k ohm resistor (R4) reads 35k ohm on the multimeter The LM386 input impedance is \$\text{50k}\Omega\$. What you're really measuring is the 47k, in parallel with 24k and 50k in series. This is the equivalent circuit. simulate this circuit – Schematic created using CircuitLab How do i calculate what this resistor value will be due to the difference? As in i find what value i want, in this case i needed 47k ohm for the specified application but due to this resistor value difference, how am i meant to see what 47k will actually be. As in will i need to use a 56k or something to get the 47k due to the difference? Hence what formula am i meant to use to find what value this resistor will actually be when in theory its meant to be 47k ohms? It looks like you're just trying to attenuate and filter a square wave. The datasheet only gives typical values for input impedance, so you can't rely on it being tightly controlled. You're going to have to decide how much variance you can tolerate. The easiest thing to do is keep your circuit as designed, and put a cheap rail-rail op amp in as a buffer. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/306325', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/148421/']} | jdg_78460 |
stackexchange | llm_judgeable_groundtruth_similarity | 22677935 |
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 found this great piece of code on jsfiddle for fading between two colors onScroll using jQuery and the Color plugin.What I would like to do is be able to fade three or more colors onScroll down the page.I have tried (failing miserably) to edit the code myself but am just too new to JS and jQuery.Help please? $(document).ready(function(){ //** notice we are including jquery and the color plugin at //** http://code.jquery.com/color/jquery.color-2.1.0.jsvar scroll_pos = 0;var animation_begin_pos = 0; //where you want the animation to beginvar animation_end_pos = 1000; //where you want the animation to stopvar beginning_color = new $.Color( 'rgb(210,50,98)' ); //we can set this here, but it'd probably be better to get it from the CSS; for the example we're setting it here.var ending_color = new $.Color( 'rgb(0,197,209)' ); ;//what color we want to use in the end$(document).scroll(function() { scroll_pos = $(this).scrollTop(); if(scroll_pos >= animation_begin_pos && scroll_pos <= animation_end_pos ) { // console.log( 'scrolling and animating' ); //we want to calculate the relevant transitional rgb value var percentScrolled = scroll_pos / ( animation_end_pos - animation_begin_pos ); var newRed = beginning_color.red() + ( ( ending_color.red() - beginning_color.red() ) * percentScrolled ); var newGreen = beginning_color.green() + ( ( ending_color.green() - beginning_color.green() ) * percentScrolled ); var newBlue = beginning_color.blue() + ( ( ending_color.blue() - beginning_color.blue() ) * percentScrolled ); var newColor = new $.Color( newRed, newGreen, newBlue ); //console.log( newColor.red(), newColor.green(), newColor.blue() ); $('body').animate({ backgroundColor: newColor }, 0); } else if ( scroll_pos > animation_end_pos ) { $('body').animate({ backgroundColor: ending_color }, 0); } else if ( scroll_pos < animation_begin_pos ) { $('body').animate({ backgroundColor: beginning_color }, 0); } else { }}); }); Here is the fiddle: http://jsfiddle.net/cgspicer/V4qh9/
Now provide the response and nothing else.
| See Sebastien Lorber's answer which fixes a bug in my implementation. Use the onInput event, and optionally onBlur as a fallback. You might want to save the previous contents to prevent sending extra events. I'd personally have this as my render function. var handleChange = function(event){ this.setState({html: event.target.value});}.bind(this);return (<ContentEditable html={this.state.html} onChange={handleChange} />); jsbin Which uses this simple wrapper around contentEditable. var ContentEditable = React.createClass({ render: function(){ return <div onInput={this.emitChange} onBlur={this.emitChange} contentEditable dangerouslySetInnerHTML={{__html: this.props.html}}></div>; }, shouldComponentUpdate: function(nextProps){ return nextProps.html !== this.getDOMNode().innerHTML; }, emitChange: function(){ var html = this.getDOMNode().innerHTML; if (this.props.onChange && html !== this.lastHtml) { this.props.onChange({ target: { value: html } }); } this.lastHtml = html; }}); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22677935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2948514/']} | jdg_78461 |
stackexchange | llm_judgeable_groundtruth_similarity | 27291131 |
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 application use CRC32 to check two contents or two files are same or not.But when I try it use to generate unique id, I see the problem, with the two different string, the CRC32 can be same. Here is my Java code. Thanks in advance. public static String getCRC32(String content) { byte[] bytes = content.getBytes(); Checksum checksum = new CRC32(); checksum.update(bytes, 0, bytes.length); return String.valueOf(checksum.getValue());}public static void main(String[] args){ System.out.println(getCRC32("b5a7b602ab754d7ab30fb42c4fb28d82")); System.out.println(getCRC32("d19f2e9e82d14b96be4fa12b8a27ee9f")); }
Now provide the response and nothing else.
| Yes, that's what CRCs are like. They're not unique IDs. They're likely to be different for different inputs, but they don't have to be. After all, you're providing more than 32 bits of input, so you can't expect to have more than 2 32 different inputs to all produce different CRCs. A longer cryptographic hash (e.g. SHA-256) is far more likely to give different outputs for different inputs, but it's still not impossible (and can't be, due to the amount of input data vs output data). The big difference between a CRC and a cryptographic hash is that a CRC is relatively easy to "steer" if you want to - it's not terribly hard to find collisions, and it's used to protect against accidental data corruption. Cryptographic hashes are designed to protect against deliberate data corruption by some attacker - so it's hard to deliberately create a value targeting a specific hash. As an aside, your use of String.getBytes() without specifying a charset is problematic - it uses the platform-default encoding, so if you run the same code on two machines with the same input, you can get different results. I would strongly encourage you to use a fixed encoding (e.g. UTF-8). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27291131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4022390/']} | jdg_78462 |
stackexchange | llm_judgeable_groundtruth_similarity | 317344 |
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:
Most of the components I have selected for my project have 2012(mm) footprint while some others have 1608, 3225 and 6432. Does it matter that some components have a different footprint? What is a good design practise?
Now provide the response and nothing else.
| Generally you will have some choice for many parts- for example, resistors that are not critical in value or dissipating a lot of power can be (inch) 0402, 0603, 0805 or 1206. Ceramic capacitors that are not near the limits of what can be made in a given size may be available in several case sizes. There are a few other factors- the size of the part affects the overall size of the PCB, which may point towards smaller sizes. You may have reels and reels of parts on the shelf and wish to use them. The price vs. size curve is typically bathtub shaped with the smallest available parts expensive and few suppliers, and the larger parts (which are used less and less in high volume) more expensive and harder to source. If you are hand soldering the board, (inch) 0402 = metric 01005 and smaller are harder to handle than larger parts. They also come more to a reel. For high power dissipation resistors, or very high accuracy resistors (especially of higher values) larger sizes are advantageous or necessary. For capacitors- you may be able to buy the value and voltage you need in an 0603 from one supplier at a high price and with nasty voltage coefficient, but there are a plethora of suppliers making 0805 parts which are better and cheaper. Assembly wise, it doesn't really matter too much- provided you don't go nuts on making the parts ultra-tiny. Most PCB assembly suppliers can handle the various sizes (though at the very small end some may have older equipment that can't handle really tiny parts well). As a practical matter, larger resistors are often marked, which can be an advantage. Parts smaller than 0603 (inch) are seldom, if ever, marked. You may notice that 'glue' logic chips come in quite a wide range of packages, and logic families, just as the market is narrowing due to increased use of CPLDs, FPGAs, and incorporation of similar (very small scale, usually) functionality on processors. So I would suggest being careful about picking packages without multiple sources if the product has a long life cycle. It is not always the largest packages that become discontinued, sometimes the smaller ones don't catch on. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/317344', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/155896/']} | jdg_78463 |
stackexchange | llm_judgeable_groundtruth_similarity | 21160134 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Dear power Pandas experts: I'm trying to implement a function to flatten a column of a dataframe which has element of type list, I want for each row of the dataframe where the column has element of type list, all columns but the designated column to be flattened will be duplicated, while the designated column will have one of the value in the list. The following illustrate my requirements: input = DataFrame({'A': [1, 2], 'B': [['a', 'b'], 'c']}) A B0 1 [a, b]1 2 cexpected = DataFrame({'A': [1, 1, 2], 'B': ['a', 'b', 'c']}, index=[0, 0, 1]) A B0 1 a0 1 b1 2 c I feel that there might be an elegant solution/concept for it, but I'm struggling. Here is my attempt, which does not work yet. def flattenColumn(df, column): '''column is a string of the column's name. for each value of the column's element (which might be a list), duplicate the rest of columns at the correspdonding row with the (each) value. ''' def duplicate_if_needed(row): return concat([concat([row.drop(column, axis = 1), DataFrame({column: each})], axis = 1) for each in row[column][0]]) return df.groupby(df.index).transform(duplicate_if_needed) In recognition of alko's help, here is my trivial generalization of the solution to deal with more than 2 columns in a dataframe: def flattenColumn(input, column): ''' column is a string of the column's name. for each value of the column's element (which might be a list), duplicate the rest of columns at the corresponding row with the (each) value. ''' column_flat = pandas.DataFrame( [ [i, c_flattened] for i, y in input[column].apply(list).iteritems() for c_flattened in y ], columns=['I', column] ) column_flat = column_flat.set_index('I') return ( input.drop(column, 1) .merge(column_flat, left_index=True, right_index=True) ) The only limitation at the moment is that the order of columns changed, the column flatten would be at the right most, not in its original position. It should be feasible to fix.
Now provide the response and nothing else.
| I guess easies way to flatten list of lists would be a pure python code, as this object type is not well suited for pandas or numpy. So you can do it with for example >>> b_flat = pd.DataFrame([[i, x] ... for i, y in input['B'].apply(list).iteritems() ... for x in y], columns=list('IB'))>>> b_flat = b_flat.set_index('I') Having B column flattened, you can merge it back: >>> input[['A']].merge(b_flat, left_index=True, right_index=True) A B0 1 a0 1 b1 2 c[3 rows x 2 columns] If you want the index to be recreated, as in your expected result, you can add .reset_index(drop=True) to last command. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21160134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/126164/']} | jdg_78464 |
stackexchange | llm_judgeable_groundtruth_similarity | 686571 |
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 kind of new to unit testing, using Microsoft.VisualStudio.TestTools.UnitTesting ; The 0.GetType() is actually System.RuntimeType , so what kind of test do I need to write to pass Assert.IsInstanceOfType(0.GetType(), typeof(int)) ? --- following up, this is my own user error... Assert.IsInstanceOfType(0, typeof(int))
Now provide the response and nothing else.
| Change the call to the following Assert.IsInstanceOfType(0, typeof(int)); The first parameter is the object being tested, not the type of the object being tested. by passing 0.GetType(), you were saying is "RunTimeType" an instance of System.int which is false. Under the covers thes call just resolves to if (typeof(int).IsInstanceOfType(0)) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/686571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21909/']} | jdg_78465 |
stackexchange | llm_judgeable_groundtruth_similarity | 6386662 |
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 a regex to find all chars that are NOT a-z or 0-9 I don't know the syntax for the NOT operator in regex. I want the regex to be NOT [a-z, A-Z, 0-9]. Thanks in advance!
Now provide the response and nothing else.
| It's ^. Your regex should use [^a-zA-Z0-9] . Beware: this character class may have unexpected behavior with non-ascii locales. For instance, this would match é. Edited If the regexes are perl-compatible (PCRE), you can use \s to match all whitespace. This expands to include spaces and other whitespace characters. If they're posix-compatible, use [:space:] character class (like so: [^a-zA-Z0-9[:space:]] ). I would recommend using [:alnum:] instead of a-zA-Z0-9 . If you want to match the end of a line, you should include a $ at the end. Turning on multiline mode is only when your match should extend across multiple lines, and it reduces performance for larger files since more must be read into memory. Why don't you include a copy of sample input, the text you want to match, and the program you are using to do so? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6386662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/280785/']} | jdg_78466 |
stackexchange | llm_judgeable_groundtruth_similarity | 164723 |
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:
I compared Survivability (live or die) using tibial Intraosseous (io), humerus io, tibial io, intravenous epinephrine for patients who have cardiac arrest. We had a control group that received no drug. Do I need to do a Bonferroni correction? .05/5.?
Now provide the response and nothing else.
| Ching, You do not have to make your data set balanced in terms of 1’s and 0’s. All you need is sufficient number of 1’s for the maximum likelihood to converge. Looking at the distribution of 1’s (100,000) in your dataset, you should not have any problems. You can do a simple experiment here Sample 10 % of the 1’s and 10% of the 0’s and use a weight of 10 for both Sample 100% of the 1’s and 10% of the 0’s and use a weight of 10 for the 0’s In both cases, you will get identical estimates. Again the idea of weighting is related to sampling. If you are using the whole data set you should not weight it. If I were you I would just use 10% if 1's and 10% of 0's. In R, you would use glm . Here is a sample code: glm(y ~ x1 + x2, weights = wt, data =data, family = binomial("logit")) In your dataset there should be a variable wt for weights. If you use 10% of both 0's and 1's, your wt variable will have a value of 10. If you use 10% of the 0's and 100% of 1's: wt variable will have a value of 10 for observations with y=0 and 1 for observations with y=1 | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/164723', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/84146/']} | jdg_78467 |
stackexchange | llm_judgeable_groundtruth_similarity | 1738665 |
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'd like to trim the output from uptime 20:10 up 23 days, 3:28, 3 users, load averages: 3.84 1.06 0.64 so that it just shows: 23 days I've tried using sed, but I'm not sure it's the right tool for the job, and don't have much experience using it. How can I achieve the output I want?
Now provide the response and nothing else.
| Consider using cut . uptime | tr "," " " | cut -f6-8 -d" " seems to work on my MacBook. Here I've also used tr to kill an extraneous ",". There is a bit of an issue with different formats for short and long uptimes. A possible sed solution: uptime | sed 's/.*up \([^,]*\), .*/\1/' which doesn't rely on the string "days" appearing in the output of uptime . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1738665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16511/']} | jdg_78468 |
stackexchange | llm_judgeable_groundtruth_similarity | 3951017 |
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 used to think that in C99, even if the side-effects of functions f and g interfered, and although the expression f() + g() does not contain a sequence point, f and g would contain some, so the behavior would be unspecified: either f() would be called before g(), or g() before f(). I am no longer so sure. What if the compiler inlines the functions (which the compiler may decide to do even if the functions are not declared inline ) and then reorders instructions? May one get a result different of the above two? In other words, is this undefined behavior? This is not because I intend to write this kind of thing, this is to choose the best label for such a statement in a static analyzer.
Now provide the response and nothing else.
| The expression f() + g() contains a minimum of 4 sequence points; one before the call to f() (after all zero of its arguments are evaluated); one before the call to g() (after all zero of its arguments are evaluated); one as the call to f() returns; and one as the call to g() returns. Further, the two sequence points associated with f() occur either both before or both after the two sequence points associated with g() . What you cannot tell is which order the sequence points will occur in - whether the f-points occur before the g-points or vice versa. Even if the compiler inlined the code, it has to obey the 'as if' rule - the code must behave the same as if the functions were not interleaved. That limits the scope for damage (assuming a non-buggy compiler). So the sequence in which f() and g() are evaluated is unspecified. But everything else is pretty clean. In a comment, supercat asks: I would expect function calls in the source code remain as sequence points even if a compiler decides on its own to inline them. Does that remain true of functions declared "inline", or does the compiler get extra latitude? I believe the 'as if' rule applies and the compiler doesn't get extra latitude to omit sequence points because it uses an explicitly inline function. The main reason for thinking that (being too lazy to look for the exact wording in the standard) is that the compiler is allowed to inline or not inline a function according to its rules, but the behaviour of the program should not change (except for performance). Also, what can be said about the sequencing of (a(),b()) + (c(),d()) ? Is it possible for c() and/or d() to execute between a() and b() , or for a() or b() to execute between c() and d() ? Clearly, a executes before b, and c executes before d. I believe it is possible for c and d to be executed between a and b, though it is fairly unlikely that it the compiler would generate the code like that; similarly, a and b could be executed between c and d. And although I used 'and' in 'c and d', that could be an 'or' - that is, any of these sequences of operation meet the constraints: Definitely allowed abcd cdab Possibly allowed (preserves a ≺ b, c ≺ d ordering) acbd acdb cadb cabd I believe that covers all possible sequences. See also the chat between Jonathan Leffler and AnArrayOfFunctions — the gist is that AnArrayOfFunctions does not think the 'possibly allowed' sequences are allowed at all. If such a thing would be possible, that would imply a significant difference between inline functions and macros. There are significant differences between inline functions and macros, but I don't think the ordering in the expression is one of them. That is, any of the functions a, b, c or d could be replaced with a macro, and the same sequencing of the macro bodies could occur. The primary difference, it seems to me, is that with the inline functions, there are guaranteed sequence points at the function calls - as outlined in the main answer - as well as at the comma operators. With macros, you lose the function-related sequence points. (So, maybe that is a significant difference...) However, in so many ways the issue is rather like questions about how many angels can dance on the head of a pin - it isn't very important in practice. If someone presented me with the expression (a(),b()) + (c(),d()) in a code review, I would tell them to rewrite the code to make it clear: a();c();x = b() + d(); And that assumes there is no critical sequencing requirement on b() vs d() . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3951017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139746/']} | jdg_78469 |
stackexchange | llm_judgeable_groundtruth_similarity | 44898 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking to configure iterm2 to output the correct hexcodes that correspond to in emacs. There's a whole bunch of mappings predefined but it's very cryptic. I'm a little bit lost as to how these mappings are translated and if there is a table of how these mappings work.
Now provide the response and nothing else.
| You can add: For C-M-left: Send escape sequence: [1;7DFor C-M-right: Send escape sequence: [1;7CFor C-M-up: Send escape sequence: [1;7AFor C-M-down: Send escape sequence: [1;7B And this will work with Emacs if you set the term in iTerm2 to be reported as xterm . To know how to figure all this out, well its complicated, and I just went down this rabbit whole myself, so here I'll explain it all. How terminals work First off, you have to understand how Terminals work. Basically a terminal will get the input from the keyboard or mouse directly. So when you type or use the mouse, the terminal receives the exact keys that were pressed. The terminal's job is to translate those pressed keys or mouse events into actual text. So when you press on the key A , the terminal receives that signal from the keyboard, and its the terminal that decides if this key should map to the character a . You could imagine a terminal in a different keyboard layout might actually choose that the A key on your US keyboard when in AZERTY should actually map to the character q . So the terminal's job is to translate from actual keyboard and mouse events into characters to send to the connected shell or command line application. That means when an application is running in your shell, it does not receive the actual keyboard and mouse events, but instead it receives characters as translated by the terminal. Now because terminals are super old, this translation of keyboard and mouse events to characters only supported the ASCII character range, which is composed of 128 total characters. By default, most terminal will do the right thing when translating the simple keyboard events that have clear direct mappings to ASCII. For example, all pressed single letter keys a-z (as per the keyboard layout) becomes their corresponding ASCII (97 to 122 range). Now all of those keys pressed with the Shift modifier held or CapsLock turned on will map to their corresponding upper-case character A-Z (65 to 90 range). So when it comes to those normal mappings that have a simple logical correspondence to the ASCII characters, generally it all works, and no custom mapping in your Terminal need to be configured. Where things get weird is that 128 characters is not enough to represent all possible keyboard and mouse events. What happened since then is that first, Terminals were extended to support Unicode with UTF-8 encoding. UTF-8 was chosen, because it is backwards compatible with ASCII. That means that if you were to press the keys on some keyboard that logically map to some Unicode character, say the character Բ , well the Terminal would send over that character using UTF-8 encoding to the shell or application its connected too. But even though they now support Unicode, there are some keyboard and mouse event that have no representation in Unicode, because Unicode is not meant for keyboard and mouse events, its meant for representing text. So the question (ASCII or Unicode) is what character should map to some keyboard event like: Ctrl+Alt+Home ? Logically, none of these are characters, the Home button doesn't represent a character, neither does Ctrl or Alt . Now in Unicode you have some characters for these, for example the MacOS Ctrl character is ⌃ which is Unicode U+2303, but even then, you wouldn't want the Ctrl key to map to U+2303, because then what if you wanted to actually type U+2303 so that inside VIM it typed ⌃ ? So you can't use the Unicode for indicating a Ctrl key-press using the macOS Unicode control character or it would now be ambiguous with if you are actually trying to type the control character or are just pressing the Ctrl key. Now in ASCII, it turned out people had something called Function Keys , basically the range 0 to 31 and 127. Those are called as such because they were meant to perform a function instead of printing a character. So back in the days, people thought that apart from typing a few characters to have them printed, there would be a common set of typing functions someone could run and those would map to the character codes in ASCII 0 to 31 and 127. For example, ASCII 127 is DEL (Delete), which was meant to call the delete character function to delete a typed character. ASCII 13 was meant to run the carriage return function, to introduce a new line, and so on. Naturally, for those functions that still make sense, Terminals also generally do the correct mapping for those. So pressing the Delete key will send the ASCII 127 character to the shell or application. So this will work great for TAB, Backspace, Escape, Return, and Delete. The other functions don't make as much sense nowadays. For example, you have start of header which is too concrete and not really useful, it goes as follows: Character Dec Hex Octal HTML Function^A 1 0x01 0001 ^A SOH start of header But as you see, these characters were also called Control Keys I think because you did have to press Control+A to execute the start of header function. So what Terminals do here is they continue to use all these Control+ ASCII characters as a way to send the keyboard event Ctrl+ . But again, there is only a few of these (range 0 to 31). So if you press Ctrl+A the terminal maps it to ASCII 1. What's annoying is there isn't even enough for all Ctrl+english letter combination, because some of them are already used by TAB and Return: Character Dec Hex Octal HTML Function^I 9 0x09 0011 ^I HT horizontal tab [\t]^M 13 0x0d 0015 ^M CR carriage return [\r] You also get a few extras that allow for Ctrl+ one of @,\,],^,_ and you could have Ctrl+[ but that's taken for Escape so it will collide. Alright, so now if you have been following, you can go to https://www.barcodefaq.com/ascii-chart-char-set/ to see the list of ASCII characters and you should have a good idea of what keypress will be sent to your shell or application by your terminal. Examples: Ctrl+@ => ASCII DEC: 0, CHAR: ^@, INTERPRETED AS: Ctrl+@Ctrl+B => ASCII DEC: 2, CHAR: ^B, INTERPRETED AS: Ctrl+BCtrl+[ => ASCII DEC: 27, CHAR: ^[, INTERPRETED AS: ESCShift+a => ASCII DEC: 65, CHAR: A, INTERPRETED AS: Aa => ASCII DEC: 97, CHAR: a, INTERPRETED AS: aDEL => ASCII DEC: 127, CHAR: <invisible>, INTERPRETED AS: Delete How terminals send keyboard and mouse events that don't fit the ASCII range? As we saw, there's not enough characters to send all the keyboard and mouse events, especially those that don't have a logical character associated to them like Ctrl+Alt+Home . In order to support these, different terminals came up with their own scheme, no standard was established, and everything just got messy, but overtime some terminals have become the "most used" and their way of doing things is often the ones best supported by applications and shells. Generally, what terminals will do is that for keyboard or mouse events with no direct mapping to ASCII, they will make up a combination of ASCII characters that they use to represent more keyboard and mouse events. So for example, they might say that Ctrl+Alt+Home will be represented as the string of characters: ^[[1;7H This is just ASCII once more, so a terminal could decide that: Ctrl+Alt+Home => ASCII (in decimal): [27,91,49,59,55,72] Back to iTerm2 Key Mappings What you see in iTerm2's Key Mapping are all those additional mappings for stuff that fall outside the ASCII range. Though I think you could also use it to remap how iTerm2 maps the normal keys even within the ASCII range if you wanted. You have two useful settings: Send hex codes This lets you tell iTerm2 that a specific keyboard shortcut should send the following sequence of ASCII characters (where it takes the ASCII chars in their hexadecimal representation). So refer too: https://www.barcodefaq.com/ascii-chart-char-set/ to see the hex code for each ASCII character. With that you can tell iTerm2 to send any arbitrary sequence of ASCII characters for any arbitrary keyboard key press event. Send escape sequence But generally, terminals like xterm have used a sequence of ASCII characters that always starts with the ASCII Escape character ^[ which is ASCII decimal 27 or ASCII hex 0x1b. Because that's so common, iTerm2 has a "Send escape sequence" where it lets you type the ASCII characters using your keyboard (so you can input them as text instead of hex or decimal) which it will automatically prepend with the ASCII Escape char or ^[ aka ASCII decimal 27 or hex 0x1b. How do I know what I should map those shortcuts outside the ASCII range so they work in most shells and terminal applications? This is a little tricky, because each shell or application running in the terminal might not understand the same ASCII sequence to mean the same key-presses. And like I said, there is no real standard for it either. But some older terminals had established some convention for some additional key-press combinations, that's where for example in iTerm2 you can load the xterm defaults preset. This will load the set of added key-presses for which the xterm terminal (an old popular terminal) had itself added by default. Because xterm is popular, most shells and terminal applications will understand those. Beyond that, it really depends on the terminal application in question, and you need to check their documentation and hopefully they document that stuff. There's really no standards? Like I said, each old popular terminal like VT-102 , xterm , etc. will have had their own additional key-presses, and those are mostly "standard". But none of them offered a scheme that covered all possible mouse and keyboard events. But, since then, there are 2 conventions that emerged which attempt to systematically cover all keypresses: Fixterm (aka libtickit or libvterm) The convention for this is: ^[[<char-code>;<modifer-code>u I'm not sure where the list of valid <char-code> and <modifier-code> comes from though. xterm's modifyOtherKeys The convention for this is: ^[27;<modifer-code>;<char-code>;~ I'm also not sure where the list of valid <char-code> and <modifier-code> comes from though, but I believe they are the same as with fixterm. Please note the xterm convention predates fixterm convention by many years. Neither are yet very popular, and I would say they are trying to be a "standard", but don't expect this to work with all apps. If you really just care about Emacs? For me, most exotic keyboard shortcuts I care about are for use with Emacs. Other apps tend to have shortcuts within the ASCII range, which works as-is. What I found for Emacs is that if you inspect the emacs-lisp variable: input-decode-map it'll show you all the ASCII sequences that Emacs support, it uses ASCII decimals to do so. For each combinations of sequence it shows what EMACS interprets the sequence as. So you can use that to bind the shortcut in iTerm2 to the sequence Emacs is configured to interpret it as. Also you can use the function: (read-key-sequence "?") and press some keyboard combination and Emacs will show you what it interprets it too. Useful trick A useful trick is to run cat -v in your terminal and now it will show you the ASCII characters of all the key combos and everything you press to see what your terminal currently maps them too. It won't show invisible stuff like Delete though. What about Alt? I forgot to mention that a lot of terminals will also make it so that Alt or Meta are mapped to ASCII 27 (the Escape character). So when you press Alt+key it will send the sequence: ^[<key> so it'll send ASCII 27 for Escape followed by the character or character sequence that maps to the key you typed along with it. That's why in terminal Emacs, ESC is used for almost all M- style shortcuts as well, so M-x can also be performed with ESC x . Emacs will thus interpret ESC key as M-key . What about shift? Shift is normally not sent by the terminal, instead it normally simply change the character to be sent, like Shift+a sends the upper-case A character. Or pressing Shift+5 will send % (on a US layout`. You can map a custom sequence for Shift+5 instead which you could have Emacs recognize as S-5 instead of % . Revisiting fixterm and xterm modifyOtherKeys I also didn't mention that newer Emacs by default have in input-decode-map most of the mappings necessary to interpret both fixterm and xterm modifyOtherKeys generic schemes. That said, the way Emacs does it is hard-coded, it misses some of them, so not all of them will work as-is. Also both conventions are not super well defined when there exist another way to send the same, as when will they use the convention versus try to be backwards compatible with some prior sequence or strategy that was used. Anyways, that means that for Emacs and iTerm2, you can tick the Report modifiers using CSI u in iTerm2 Keys config, and a lot of things will now "just work" in Emacs (though not all). | {} | {'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/44898', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/20384/']} | jdg_78470 |
stackexchange | llm_judgeable_groundtruth_similarity | 235457 |
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:
In my school, there is a trend of using computer software for teaching a first course in Chemistry for undergraduate students. I hypothesized that the use of this tool could make the students achieve better scores than without this help. So far what I have done is the following: I chose two groups, both of them were going to follow the same topics. Only in one of them the use of the computer software was commendatory. I make an entrance test about basic chemistry knowledge to both groups and approximately 100 percent of both classes failed that examination. I had compiled the results of the mid-term exam and the final exam of both groups and I have seen an increase in the final marks of the group that was using the computerized tool. I have read that this seems like a quasi experiment. I have gathered some information about this techniques, but apart from the basic stuff I am a little bit lost of what statistical techniques should I perform to gather a conclusion that this software tool should be encouraged to be used. I have performed a hypothesis test, but I believe this is not enough. Any advice? My statistics knowledge is very basic.
Now provide the response and nothing else.
| The central question is whether you assigned students completely at random to the experimental groups. If yes you can use a standard test for independent samples to assess the significance of the group difference. This is probably the hypothesis test that you have already done. If no , it is indeed a quasi experiment also called a non-randomized experiment or broken experiment. There are many statistical techniques available to correct for selective assignment including propensity score techniques, regression technqiues, and combinations of both. The central question you need to answer to use these techniques is whether you know what caused the assignment to groups. Were certain students assigned to the computerized group (e.g. older/younger, better/worse, male/female, richer/poorer, smaller/taller....)? And do you have data on the variables determining the assignment? Then you need to adjust for the imbalance in these covariates using one of the above mentioned techniques. The easiest, albeit not 'best', adjustment method is Analysis of Covariance, a regression technique which comes with the assumptions of linearity and normality in small samples. You can imagine it like a t-test where in addition you control for the confounding variables you identified as the responsible one for the treatment group assignment. Standard software packages like Excel, Stata, Spss, SAS or R have easy to use implementations of this technique. Since you say that your statistics knowledge is very basic collaborating with a skilled analyst may be a good additional option in this situation, because the less basic techniques involving propensity scores can get a bit complicated. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/235457', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/69395/']} | jdg_78471 |
stackexchange | llm_judgeable_groundtruth_similarity | 1285979 |
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 is a simple one (I think). Is there a system built in function, or a function that someone has created that can be called from Delphi, that will display a number of bytes (e.g. a filesize), the way Windows displays in a file's Properties box? e.g. This is how Windows property box displays various sizes: 539 bytes (539 bytes)35.1 KB (35,974 bytes)317 MB (332,531,365 bytes)2.07 GB (2,224,617,077 bytes) The display is smart about using bytes, KB, MB or GB, and shows only 3 significant digits for the KB, MB and GB. It then follows that by displaying the exact number of bytes in parenthesis with commas separating the thousands. It is a very nice display, well thought out. Does anyone know of such a function? Edit: I'm very surprised there wasn't a function for this. Thanks for your helpful ideas. I've come up with this, which seems to work: function BytesToDisplay(A:int64): string;var A1, A2, A3: double;begin A1 := A / 1024; A2 := A1 / 1024; A3 := A2 / 1024; if A1 < 1 then Result := floattostrf(A, ffNumber, 15, 0) + ' bytes' else if A1 < 10 then Result := floattostrf(A1, ffNumber, 15, 2) + ' KB' else if A1 < 100 then Result := floattostrf(A1, ffNumber, 15, 1) + ' KB' else if A2 < 1 then Result := floattostrf(A1, ffNumber, 15, 0) + ' KB' else if A2 < 10 then Result := floattostrf(A2, ffNumber, 15, 2) + ' MB' else if A2 < 100 then Result := floattostrf(A2, ffNumber, 15, 1) + ' MB' else if A3 < 1 then Result := floattostrf(A2, ffNumber, 15, 0) + ' MB' else if A3 < 10 then Result := floattostrf(A3, ffNumber, 15, 2) + ' GB' else if A3 < 100 then Result := floattostrf(A3, ffNumber, 15, 1) + ' GB' else Result := floattostrf(A3, ffNumber, 15, 0) + ' GB'; Result := Result + ' (' + floattostrf(A, ffNumber, 15, 0) + ' bytes)';end; This is probably good enough, but is there anything better?
Now provide the response and nothing else.
| See the following functions, all in the shlwapi library . StrFormatByteSizeA (DWord parameter) StrFormatByteSizeW (Int64 parameter) StrFormatByteSize64 (In Unicode mode, it's really StrFormatByteSizeW ) StrFormatByteSizeEx (Vista SP2; can control rounding) Any of them will give you the first portion of your desired display format. Check the documentation or write your own tests to confirm that they give the conversions you expect regarding whether a megabyte consists of 1000 or 1024 kilobytes. For the second part of your display format, you can start with the answers to another Stack Overflow question: How to convert int to currency? (He was really asking how to insert commas, not specifically about money.) But perhaps that question is the wrong avenue to go down since all the suggestions there, as well as FloatToStrF , fail at the upper limits of Int64 . You'll lose a few bytes, but I consider those pretty important bytes since the purpose of the second value in that display format is to provide an exact number. Once you have all the pieces, glue them together. I'm using a hypothetical IntToStrCommas function here, and if you want to implement that as FloatToStrF , go ahead. function BytesToDisplay(const num: Int64): string;var // If GB is the largest unit available, then 20 characters is // enough for "17,179,869,183.99 GB", which is MaxUInt64. buf: array[0..20] of Char;begin if StrFormatByteSize64(num, buf, Length(buf)) = nil then raise EConvertError.CreateFmt('Error converting %d', [num]); Result := Format('%s (%s bytes)', [buf, IntToStrCommas(num)]);end; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1285979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30176/']} | jdg_78472 |
stackexchange | llm_judgeable_groundtruth_similarity | 4498513 |
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 to calculate the time a user spends on site. It is difference between logout time and login time to give me something like "Mr X spent 4 hours and 43 minutes online". So to store the4 hours and 43 minutes i declared it like this: duration time NOT NULL Is this valid or a better way to store this? I need to store in the DB because I have other calculations I need to use this for + other use cases.
Now provide the response and nothing else.
| Storing it as an integer number of seconds will be the best way to go. The UPDATE will be clean and simple - i.e. duration = duration + $increment As Tristram noted, there are limitations to using the TIME field - e.g. " TIME values may range from '-838:59:59' to '838:59:59' " The days/hours/minutes/seconds display formatting won't be hardcoded. The execution of your other calculations will almost surely be clearer when working with an integer "number of seconds" field. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4498513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/549798/']} | jdg_78473 |
stackexchange | llm_judgeable_groundtruth_similarity | 9745899 |
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 basically I have two classes, Book and Author . Books can have multiple authors and authors can have multiple books. Books have the following default scope. default_scope :order => "publish_at DESC" On the Author show page I want to list all the books associated with that author so I say the following... @author = Author.find(params[:id])@books = @author.books All is good so far. The author#show page lists all books belonging to that author ordered by publication date. I'm also working on a gem that is able to sort by the popularity of a book. @books = @author.books.sort_by_popularity The problem is that whenever it tries to sort, the default_scope always gets in the way. And if I try to unscope it before it will get rid of the author relation and return every book in the database. For example @books = @author.books.unscoped.sort_by_popularity # returns all books in database I'm wondering if I can use the ActiveRelation except() method to do something like this (which seems like it should work but it doesn't. It ignores order, just not when it is a default_scope order) def sort_by_popularity self.except(:order).do_some_joining_magic.order('popularity ASC') # |------------| |---------------------|end Any ideas as to why this doesn't work? Any ideas on how to get this to work a different way? I know I can just get rid of the default_scope but I'm wondering if there another way to do this.
Now provide the response and nothing else.
| You should be able to use reorder to completely replace the existing ORDER BY: reorder(*args) Replaces any existing order defined on the relation with the specified order. So something like this: def self.sort_by_popularity scoped.do_some_joining_magic.reorder('popularity ASC')end And I think you want to use a class method for that and scoped instead of self but I don't know the whole context so maybe I'm wrong. I don't know why except doesn't work. The default_scope seems to get applied at the end (sort of) rather than the beginning but I haven't looked into it that much. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9745899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/834216/']} | jdg_78474 |
stackexchange | llm_judgeable_groundtruth_similarity | 560040 |
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 to do conditional compilation in Python ? Is it using DEF ?
Now provide the response and nothing else.
| Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled "on the fly", you can think of it as being similar to a interpreted language like Basic or Perl. 1 You can do something equivalent to conditional compile by just using an if statement. For example: if FLAG: def f(): print "Flag is set"else: def f(): print "Flag is not set" You can do the same for the creation classes, setting of variables and pretty much everything. The closest way to mimic IFDEF would be to use the hasattr function. E.g.: if hasattr(aModule, 'FLAG'): # do stuff if FLAG is defined in the current module. You could also use a try/except clause to catch name errors, but the idiomatic way would be to set a variable to None at the top of your script. Python code is byte compiled into an intermediate form like Java, however there generally isn't a separate compilation step. The "raw" source files that end in .py are executable. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/560040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46646/']} | jdg_78475 |
stackexchange | llm_judgeable_groundtruth_similarity | 9398544 |
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 two threads. I am invoking one (the SocketThread ) first and then from that one I am invoking another thread (the 'ProcessThread'). My issue is that, during the execution the CPU usage is 50%. It reduces to 0% when I add TimeUnit.NANOSECONDS.sleep(1) in the ProcessThread run method. Is this the right method to modify? Or any advice in general for reducing the CUP utilization. Below is my code: public class SocketThread extends Thread { private Set<Object> setSocketOutput = new HashSet<Object>(1, 1); private BlockingQueue<Set<Object>> bqSocketOutput; ProcessThread pThread; @Override public void run() { pThread = new ProcessThread(bqSocketOutput); pThread.start(); for(long i=0; i<= 30000; i++) { System.out.println("SocketThread - Testing" + i); } }}public class ProcessThread extends Thread { public ProcessThread(BlockingQueue<Set<Object>> bqTrace) { System.out.println("ProcessThread - Constructor"); } @Override public void run() { System.out.println("ProcessThread - Exectution"); while (true) { /* try { TimeUnit.NANOSECONDS.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } }}
Now provide the response and nothing else.
| The permissions you are seeing in the AWS Management Console directly are based on the initial and comparatively simple Access Control Lists (ACL) available for S3, which essentially differentiated READ and WRITE permissions, see Specifying a Permission : READ - Allows grantee to list the objects in the bucket WRITE - Allows grantee to create, overwrite, and delete any object in the bucket These limitations have been addressed by adding Bucket Policies (permissions applied on the bucket level) and IAM Policies (permissions applied on the user level), and all three can be used together as well (which can become rather complex, as addressed below), see Access Control for the entire picture. Your use case probably asks for a respective bucket policy, which you an add directly from the S3 console as well. Clicking on Add bucket policy opens the Bucket Policy Editor , which features links to a couple of samples as well as the highly recommended AWS Policy Generator , which allows you to assemble a policy addressing your use case. For an otherwise locked down bucket, the simplest form might look like so (please ensure to adjust Principal and Resource to your needs): { "Statement": [ { "Action": [ "s3:PutObject" ], "Effect": "Allow", "Resource": "arn:aws:s3:::<bucket_name>/<key_name>", "Principal": { "AWS": [ "*" ] } } ]} Depending on your use case, you can easily compose pretty complex policies by combining various Allow and Deny actions etc. - this can obviously yield inadvertent permissions as well, thus proper testing is key as usual; accordingly, please take care of the implications when using Using ACLs and Bucket Policies Together or IAM and Bucket Policies Together . Finally, you might want to have a look at my answer to Problems specifying a single bucket in a simple AWS user policy as well, which addresses another commonly encountered pitfall with policies. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9398544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/867662/']} | jdg_78476 |
stackexchange | llm_judgeable_groundtruth_similarity | 6555561 |
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 to get installed version of an application (say, MyApp) using C#. I will do this much,1. Create a 'Set Up' for MyApp of version 5.62. Install MyApp. I will create another application (say VersionTracker)to get the version of installed applications. So if I pass the name 'MyApp' I would like to get the version as '5.6'. If another application say Adobe Reader is installed in my system, I want to get the version of Adobe Reader if I pass 'Adobe Reader'. I need to know how to build 'VersionTracker'
Now provide the response and nothing else.
| The first and the most important thing is that not all applications do save their version somewhere in the system. To be honest, only a few of them do that. The place where you should look are the Windows Registry. Most of installed applications put their installation data into the following place: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall However, it's not that easy - on 64bit Windows, the 32bit (x86) applications save their installation data into another key, which is: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall In these keys there are many keys, some of them have got "easy-readable" name, such as Google Chrome , some of them got names such as {63E5CDBF-8214-4F03-84F8-CD3CE48639AD} . You must parse all these keys into your application and start looking for the application names. There are usually in DisplayName value, but it's not always true. The version of the application is usually in DisplayVersion value, but some installers do use another values, such as Inno Setup: Setup Version , ... Some application do have their version written in their name, so it's possible that the application version is already in the DisplayName value. Note: It's not easy to parse all these registry keys and values and to "pick" the correct values. Not all installers save the application data into these keys, some of them do not save the application version there, etcetera. However, it's usual that the application use these registry keys. [Source: StackOverflow: Detecting installed programs via registry , browsing my own registry] Alright, so now when you know where you should look, you have to program it all in C#. I won't write the application for you, but I'll tell you what classes you should use and how to. First, you need these: using System;using Microsoft.Win32; To get to your HKEY_LOCAL_MACHINE , create a RegistryKey like this: RegistryKey baseRegistryKey = Registry.LocalMachine; Now you need to define subkeys: string subKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";// or "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall" Now you need to go to the subkey, so create a new RegistryKey : RegistryKey uninstallKey = baseRegistryKey.OpenSubKey(subKey); Now you need to go thru all the subkeys that are there, so first we get the names of all the subkeys: string[] allApplications = uninstallKey.GetSubKeyNames(); Now you must go thru all the subkeys yourself , one by one, by creating a new registry key (you don't have to, but I'll do it): RegistryKey appKey = baseRegistryKey.OpenSubKey(subKey + "\\" + applicationSubKeyName); where applicationSubKeyName is the name of the subkey you're currently checking. I recommend foreach statement, which helps you (you must however have some experience with C# already, I'm not going to tell you how to use foreach here). Now check the application's name and compare it with name of your desired application (you cannot rely on the subkey name, because, as I already said, they can be called for example {63E5CDBF-8214-4F03-84F8-CD3CE48639AD} , so you must check the name here): string appName = (string)appKey.GetValue("DisplayName"); If it's the correct application (you must check it yourself), find the version: string appVersion = (string)appKey.GetValue("DisplayVersion"); Et voilà, you have the version. At least there's like a 60 - 80% chance you have... Remember! If some key or value doesn't exist, the method returns null . Remember to check if the returned value is null everytime, otherwise your application will crash. Where to find more? The Code Project: Read, write and delete from registry with C# I really hope I helped you. And if you wanted to know something else and I didn't understand your question, then, please, ask better next time. :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6555561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/767445/']} | jdg_78477 |
stackexchange | llm_judgeable_groundtruth_similarity | 109644 |
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 compute: $\int_{0}^{1}e^x(1-x)^{100}dx$. I tried to use integration by parts but it didn't work out for me(since I need to do that 100 times, and obviously there's a shorter solution) , I substituted $(1-x)=u$ and got $e\int_0^1e^{-t}t^{100}$, again I can't do with that much. Any suggestion how should solve this integral? Thanks a lot guys!
Now provide the response and nothing else.
| For what it's worth: Write$$t^{100}e^{-t}=t^{100}(1-t+{t^2\over 2!}-{t^3\over 3!}-\cdots )=t^{100}-t^{101}+{t^{102}\over 2!}-{t^{103}\over 3!}-\cdots$$ The above series is uniformly convergent on $[0,1]$; thus:$$\eqalign{\int_0^1 e^{-t}t^{100}\,dt&=\sum_{n=0}^\infty \int_0^1 (-1)^n{t^{100+n}\over n!}\cr&=\sum_{n=0}^\infty (-1)^n{t^{101+n}\over({101+n}) n!}\Bigl|_0^1\cr &=\sum_{n=0}^\infty (-1)^n{1\over({101+n}) n!}. \cr}$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/109644', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14829/']} | jdg_78478 |
stackexchange | llm_judgeable_groundtruth_similarity | 2464950 |
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 looked under the hood for EnumSet.allOf and it looks very efficient, especially for enums with less than 64 values. Basically all sets share the single array of all possible enum values and the only other piece of information is a bitmask which in case of allOf is set in one swoop. On the other hand Enum.values() seems to be a bit of black magic. Moreover it returns an array, not a collection, so in many cases it must be decorated with Arrays.asList( ) to be usable in any place that expects collection. So, should EnumSet.allOf be more preferable to Enum.values ? More specifically, which form of for iterator should be used: for ( final MyEnum val: MyEnum.values( ) ); or for ( final MyEnum val: EnumSet.allOf( MyEnum.class ) );
Now provide the response and nothing else.
| Because I did not receive the answer to my question on which one is more efficient, I've decided to do some testing of my own. I've tested iteration over values() , Arrays.asList( values() ) and EnumSet.allOf( ) .I've repeated these tests 10,000,000 times for different enum sizes. Here are the test results: oneValueEnum_testValues 1.328oneValueEnum_testList 1.687oneValueEnum_testEnumSet 0.578TwoValuesEnum_testValues 1.360TwoValuesEnum_testList 1.906TwoValuesEnum_testEnumSet 0.797ThreeValuesEnum_testValues 1.343ThreeValuesEnum_testList 2.141ThreeValuesEnum_testEnumSet 1.000FourValuesEnum_testValues 1.375FourValuesEnum_testList 2.359FourValuesEnum_testEnumSet 1.219TenValuesEnum_testValues 1.453TenValuesEnum_testList 3.531TenValuesEnum_testEnumSet 2.485TwentyValuesEnum_testValues 1.656TwentyValuesEnum_testList 5.578TwentyValuesEnum_testEnumSet 4.750FortyValuesEnum_testValues 2.016FortyValuesEnum_testList 9.703FortyValuesEnum_testEnumSet 9.266 These are results for tests ran from command line. When I ran these tests from Eclipse, I got overwhelming support for testValues . Basically it was smaller than EnumSet even for small enums. I believe that the performance gain comes from optimization of array iterator in for ( val : array ) loop. On the other hand, as soon as you need a java.util.Collection to pass around, Arrays.asList( ) looses over to EnumSet.allOf , especially for small enums, which I believe will be a majority in any given codebase. So, I would say you should use for ( final MyEnum val: MyEnum.values( ) ) but Iterables.filter( EnumSet.allOf( MyEnum.class ), new Predicate< MyEnum >( ) {...}) And only use Arrays.asList( MyEnum.values( ) ) where java.util.List is absolutely required. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2464950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/185722/']} | jdg_78479 |
stackexchange | llm_judgeable_groundtruth_similarity | 159445 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would prefer that no one, even me, could encrypt my files. I have no use for it, and don't want it. Is there a way to permanently disable any sort of encryption at the OS level? If not, is this a possible improvement that a future file system could incorporate? Or is it fundamentally impossible to prevent?
Now provide the response and nothing else.
| Read-only file systems can by definition not be written to (At least not digitally. What you do with a hole puncher and a neodymium magnet is your own business). Examples: Live CDs, from which you can boot into an operating system which will look the same on every boot. WORM (Write Once Read Many) devices, used for example by financial institutions which have to record transactions for many years with no means of altering or deleting them digitally. Writable partitions mounted as read-only. This can of course be circumvented by a program with root access. Versioning file systems would be more practical, but are not common. Such systems might easily include options to transparently write each version of a file (or its difference from the previous version) to a WORM device or otherwise protected storage. Both of these solve the underlying issue: Not losing the original data in case of encryption by malicious software. | {} | {'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/159445', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/148256/']} | jdg_78480 |
stackexchange | llm_judgeable_groundtruth_similarity | 49570 |
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:
When obtaining MCMC samples to make inference on a particular parameter, what are good guides for the minimum number of effective samples that one should aim for? And, does this advice change as the model becomes more or less complex?
Now provide the response and nothing else.
| The question you are asking is different from "convergence diagnostics". Lets say you have run all convergence diagnostics(choose your favorite(s)), and now are ready to start sampling from the posterior. There are two options in terms of effective sample size(ESS), you can choose a univariate ESS or a multivariate ESS. A univariate ESS will provide an effective sample size for each parameter separately, and conservative methods dictate, you choose the smallest estimate. This method ignores all cross-correlations across components. This is probably what most people have been using for a while Recently, a multivariate definition of ESS was introduced. The multivariate ESS returns one number for the effective sample size for the quantities you want to estimate; and it does so by accounting for all the cross-correlations in the process. Personally, I far prefer multivariate ESS. Suppose you are interested in the $p$-vector of means of the posterior distribution. The mESS is defined as follows$$\text{mESS} = n \left(\dfrac{|\Lambda|}{|\Sigma|}\right)^{1/p}. $$Here $\Lambda$ is the covariance structure of the posterior (also the asymptotic covariance in the CLT if you had independent samples) $\Sigma$ is the asymptotic covariance matrix in the Markov chain CLT (different from $\Lambda$ since samples are correlated. $p$ is number of quantities being estimated (or in this case, the dimension of the posterior. $|\cdot|$ is the determinant. mESS can be estimated by using the sample covariance matrix to estimate $\Lambda$ and the batch means covariance matrix to estimate $\Sigma$. This has been coded in the function multiESS in the R package mcmcse . This recent paper provides a theoretically valid lower bound of the number of effective samples required. Before simulation, you need to decide $\epsilon$: the precision. $\epsilon$ is the fraction of error you want the Monte Carlo to be in comparison to the posterior error. This is similar to the margin of error idea when doing sample size calculations in the classical setting. $\alpha$: the level for constructing confidence intervals. $p$: the number of quantities you are estimating. With these three quantities, you will know how many effective samples you require. The paper asks to stop simulation the first time $$ \text{mESS} \geq \dfrac{2^{2/p} \pi}{(p \Gamma(p/2))^{2/p}} \dfrac{\chi^2_{1-\alpha, p}}{\epsilon^2},$$ where $\Gamma(\cdot)$ is the gamma function. This lower bound can be calculated by using minESS in the R package mcmcse . So now suppose you have $p = 20$ parameters in the posterior, and you want $95\%$ confidence in your estimate, and you want the Monte Carlo error to be 5% ($\epsilon = .05$) of the posterior error, you will need > minESS(p = 20, alpha = .05, eps = .05)[1] 8716 This is true for any problem (under regularity conditions). The way this method adapts from problem to problem is that slowly mixing Markov chains take longer to reach that lower bound, since mESS will be smaller. So now you can check a couple of times using multiESS whether your Markov chain has reached that bound; if not go and grab more samples. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/49570', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/966/']} | jdg_78481 |
stackexchange | llm_judgeable_groundtruth_similarity | 45080712 |
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 Android Studio 3.0, once we create a project, a folder named mipmap-anydpi-v26 is automatically created in the res directory. What actually does it do? Why do we need it? How will we utilize it for development purposes? Also, there are two XML files automatically created in this folder after project setup. Why do these XML files reside in a mipmap folder? I thought we should keep all XML files in a drawable folder instead of mipmap.
Now provide the response and nothing else.
| Android Studio 3 creates an adaptive icon for your app which is only available in SDK 26 and up. Launcher icons should be put into the mipmap folders. If you look at your manifest, you can see that it references ic_launcher android:icon="@mipmap/ic_launcher" If you look in your mipmap folder, you see your normal 5 different launcher icons which will be used for anything lower than SDK 26. For SDK 26 and up, it uses the XML files from the anydpi-v26 folder to make use of adaptive icon. <?xml version="1.0" encoding="utf-8"?><adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <background android:drawable="@drawable/ic_launcher_background"/> <foreground android:drawable="@mipmap/ic_launcher_foreground"/></adaptive-icon> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45080712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3806413/']} | jdg_78482 |
stackexchange | llm_judgeable_groundtruth_similarity | 27663466 |
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 create a folder in the internal storage of an app so I can download files to it. But it doesn't seem to work. I've been looking for a solution for hours and hours but I can't find one and it's starting to drive me crzay. This the code to create the folder: String intStorageDirectory = Environment.getDataDirectory().toString();File folder = new File(intStorageDirectory, "testthreepdf");folder.mkdirs(); This code always returns "DOES NOT EXIST": File f = new File(Environment.getDataDirectory() + "/testthreepdf");if(f.exists()){ Log.i("testApp", f.toString() + "EXISTS");}else { Log.i("testApp", f.toString() + " DOES NOT EXIST");} These are the android permissions: <uses-permission android:name="android.permission.INTERNET" ></uses-permission><uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" ></uses-permission><uses-permission android:name="android.permission.READ_PHONE_STATE" ></uses-permission> Anybody know what's wrong with this code?
Now provide the response and nothing else.
| Environment.getDataDirectory() returns the top-level data folder shared by all apps. You can't create folders there. To create folders in your app's data folder, use getFilesDir() instead, like this: String intStorageDirectory = getFilesDir().toString();File folder = new File(intStorageDirectory, "testthreepdf");folder.mkdirs(); You need a Context to call getFilesDir(). For more information about the difference between getDataDirectory() and getFilesDir(), see this StackOverflow question . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27663466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2907960/']} | jdg_78483 |
stackexchange | llm_judgeable_groundtruth_similarity | 15617138 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
<input type="button" value="Delete" onclick="deleteMember(@Model.ID, '@ViewBag.returnUrl')"/> That code has 4 errors, 2 syntax error and 2 Unterminated string constant. What should I do to fix these errors?
Now provide the response and nothing else.
| You could break it out in a an Html.Raw Call: <input type="button" value="Delete" onclick="@(Html.Raw(String.Format("deleteMember({0}, '{1}')", Model.ID, Html.Encode(ViewBag.returnUrl) )))"/> Or assign it to a string first, then reference that variable in the attribute. @{ String onclick = String.Format("deleteMember({0}, '{1}')", Model.ID, Html.Encode(ViewBag.returnUrl));}<input type="button" value="delete" onclick="@onclick" /> Third option is to separate concerns; Keep markup and scripts separate. Neil beat me to it, but something like: <input type="button" value="delete" data-task="delete" data-id="@Model.ID" data-returnurl="@ViewBag.returnUrl" /><!-- .... --><script> var buttons = document.getElementsByTagName('INPUT'); for (var b = 0; b < buttons.length; b++){ if (buttons[b].type != 'button') continue; switch (buttons[b].getAttribute('data-task') || ''){ case 'delete': // read data-id & data-returnurl. Do something with them, and // move on. break; // other actions case 'add': case 'update': default: break; } }</script> Though it's strange the first parenthesis messes with razor (even though it's declared in an attribute). I wouldn't expect this behavior myself. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15617138', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/682763/']} | jdg_78484 |
stackexchange | llm_judgeable_groundtruth_similarity | 34594297 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is my emoji one fiddle. https://jsfiddle.net/L8a9zazh/ How do i resize the emojis and make it align in center with text and make it look neat. Css: img.emojione { // Override any img styles to ensure Emojis are displayed inline margin: 0px !important; display: inline !important;}
Now provide the response and nothing else.
| Your content should always be placed within HTML tags that give context to what structural component you're trying to build. In the fiddle example below, we encapsulate the emoji inside a span tag which in turn is wrapped in a p tag for the wording content. By doing this, we can target specific CSS on the emoji content to vertical align within the p tag without having to deal with line-height. The font-size CSS property can control unicode characters and font-face content. Update 1 I see now that you're trying to convert the chars to an image; your jsfiddle was broken because it wasn't using the jquery framework and you don't have to declare onLoad; instead this should all be set in the js settings window pane. Update 2: updated jsfiddle Example https://jsfiddle.net/L8a9zazh/15/ HTML <br><br><p>Hello world I'm buzz </p><br><br><p id="wrong-test">Hello world I'm buzz <span class="emoji"></span></p> CSS img.emojione { // Override any img styles to ensure Emojis are displayed inline margin: 0px !important; display: inline !important; height: auto; width: 50px;}p#wrong-test { border-top: 1px solid black; border-bottom: 1px solid black; display: inline-block;}span.emoji { font-size: 30px; vertical-align: middle; line-height: 2;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34594297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5694067/']} | jdg_78485 |
stackexchange | llm_judgeable_groundtruth_similarity | 241967 |
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 playing with the new stuff of C#3.0 and I have this code (mostly taken from MSDN ) but I can only get true,false,true... and not the real value : int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var oddNumbers = numbers.Select(n => n % 2 == 1); Console.WriteLine("Numbers < 5:"); foreach (var x in oddNumbers) { Console.WriteLine(x); } How can I fix that to show the list of integer?
Now provide the response and nothing else.
| Change your "Select" to a "Where" int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var oddNumbers = numbers.Where(n => n % 2 == 1); Console.WriteLine("Odd Number:"); foreach (var x in oddNumbers) { Console.WriteLine(x); } The "Select" method is creating a new list of the lambda result for each element (true/false). The "Where" method is filtering based on the lambda. In C#, you could also use this syntax, which you may find clearer: var oddNumbers = from n in numbers where n % 2 == 1 select n; which the compiler translates to: var oddNumbers = numbers.Where(n => n % 2 == 1).Select(n => n); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/241967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13913/']} | jdg_78486 |
stackexchange | llm_judgeable_groundtruth_similarity | 2857550 |
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:
Let $\varphi: \mathbb{Z_4}\to S_4$ be a homomorphism. From theory I have: Since $1_{\mathbb{Z_4}}$ is the identity element in $\mathbb{Z_4}$ , $\varphi(1_\mathbb{Z_4})=1_{s_4}$ . $\varphi(1^{-1})=\varphi(3)=(\varphi(1))^{-1}, \varphi(2^{-1})=\varphi(2)=(\varphi(2))^{-1}$ These don't seem enough to find all homomorphisms. What am I missing?
Now provide the response and nothing else.
| There are problems with your calculation. You seem to be confusing the additive and multiplicative structure on $\mathbb{Z}_4$. If you say that the inverse of 1 is 3, then this means you consider the additive structure. But then the unit element is 0, not 1. But I can answer your question. Let $\mathbb{Z}_4$ be the ADDITIVE group of residue classes $\pmod 4$. Then the image of $1$ uniquely determines a homomorphism from $\mathbb{Z}_4$ to another group. This image can be any element whose order divides 4, and exactly those. So your question can be rephrased as follows: how many elements are there in $S_4$ whose order is 1, 2 or 4? There is exactly 1 element of order 1, the identity. There are $\binom{4}{2}= 6$ transpositions and 3 permutations that are products of two disjoint transpositions. So there are 9 elements of order 2. Finally, there are 6 elements of order 4 in $S_4$. So the answer is: there are $1+9+6= 16$ elements of order 1, 2 or 4 in $S_4$, hence 16 homomorphisms from $\mathbb{Z}_4$ into $S_4$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2857550', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/552954/']} | jdg_78487 |
stackexchange | llm_judgeable_groundtruth_similarity | 41965927 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have a string like: url = "https://example.com/user/tr_auth.php?key=34432&cmp_id=344&tr_id={user_id}" I want to update the cmp_id=344 to be say cmp_id=44553 . What's the best way to accomplish this? I can't gsub per say because I don't know what cmp_id might be equal, only that it will be a URL parameter in the string. It seems like I want to do something like uri = URI.parse(url)params = CGI.parse(uri.query) But then, how do I re-build the string swapping out the cmp_id parameter to be 44553 ? Thanks!
Now provide the response and nothing else.
| If you are dealing with a web application (and/or Rails as the tag seems to indicate), then you certainly have Rack available. Rack::Utils has methods to parse and build a query. url = "https://example.com/user/tr_auth.php?key=34432&cmp_id=344&tr_id={user_id}"uri = URI.parse(url)query = Rack::Utils.parse_query(uri.query)# => {"key"=>"34432", "cmp_id"=>"344", "tr_id"=>"{user_id}"}# Replace the valuequery["cmp_id"] = 44553uri.query = Rack::Utils.build_query(query)uri.to_s# => "https://example.com/user/tr_auth.php?key=34432&cmp_id=44553&tr_id=%7Buser_id%7D" Also note that Rack, by default, escapes the query. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41965927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2650407/']} | jdg_78488 |
stackexchange | llm_judgeable_groundtruth_similarity | 628091 |
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 need to use a sed command to search a text file and replace $Date$ with: $Date: 2021-01-06... $ where ... is the text for the date. I have a sed command that will search for Date and replace it with Date: 2021-01-06... : sed "s/Date/Date $(date)/" but I can't get a sed command to work to replace $Date$ . Also, I was able to get a sed command to replace $Date using sed "s/\$Date/\$Date $(date)/" but I can't figure out the syntax to search and replace $Date$ . I tried: sed "s/\$Date\$/\$Date $(date) \$/" but it does not work.
Now provide the response and nothing else.
| I tried: sed "s/\$Date\$/\$Date $(date) \$/" but it does not work. Because \$ in double-quotes only tells the shell not to interpret (expand) $ , but then there's sed . It gets s/$Date$/$Date … $/ (where … denotes what $(date) expanded to) and interprets the second $ as an anchor matching the end of the line. In s/regexp/replacement/ $ is interpreted as the anchor only at the end of regexp . So you need to escape this particular $ also for sed , i.e. you need sed to literally get \$ . This can be done with: sed "s/\$Date\\$/\$Date $(date) \$/" or sed "s/\$Date\\\$/\$Date $(date) \$/" It works with two or three backslashes because double-quoted $ before / does not need to (but may) be escaped, and to get \ you need \\ in double-quotes. This is kinda complicated, therefore consider single-quoting all fragments that don't need to be double-quoted: sed 's/$Date\$/$Date '"$(date)"' $/' Here all $ characters that should get to sed are single-quoted; and the only \ that should get to sed is also single-quoted. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/628091', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/338943/']} | jdg_78489 |
stackexchange | llm_judgeable_groundtruth_similarity | 1809619 |
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 Nodejs, there are virtually no blocking I/O operations. This means that almost all nodejs IO code involves many callbacks. This applies to reading and writing to/from databases, files, processes, etc. A typical example of this is the following: var useFile = function(filename,callback){ posix.stat(filename).addCallback(function (stats) { posix.open(filename, process.O_RDONLY, 0666).addCallback(function (fd) { posix.read(fd, stats.size, 0).addCallback(function(contents){ callback(contents); }); }); });};...useFile("test.data",function(data){ // use data..}); I am anticipating writing code that will make many IO operations, so I expect to be writing many callbacks. I'm quite comfortable with using callbacks, but I'm worried about all the recursion. Am I in danger of running into too much recursion and blowing through a stack somewhere? If I make thousands of individual writes to my key-value store with thousands of callbacks, will my program eventually crash? Am I misunderstanding or underestimating the impact? If not, is there a way to get around this while still using Nodejs' callback coding style?
Now provide the response and nothing else.
| None of the code you show is using recursion. When you call useFile it calls posix.stat() , which returns, and useFile terminates as it has run to completion. At some later time, when the call to posix.stat() has completed within the underlying system and the results are available, the callback function you added for that will be executed. That calls posix.open() , and then terminates as it has run to completion. Once the file has been successfully opened, the callback function for that will execute, calling posix.read() , and will then terminate as it, too, has run to completion. Finally, when the results of the read are available, the innermost function will be executed. The important point is that each function runs to completion, as the calls to the posix.*() functions are non-blocking: that is, they return immediately, having caused some magic to be started off in the underlying system. So each of your functions terminates, and later an event will cause the next function to execute; but at no point is there any recursion. The nested structure of the code can give one the impression that the stuff inside will have to finish before the stuff outside can get to its own end point. But in this style of asynchronous event-driven programming it makes more sense to see the nesting in terms of deeper => happens-later-than . EDIT: Try adding some logging statements immediately before the end of each nested function; this will help to illustrate that the order in which they complete is from the outside inwards. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1809619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50505/']} | jdg_78490 |
stackexchange | llm_judgeable_groundtruth_similarity | 45994973 |
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 Numpy one-dimensional array of 1 and 0. for e.g a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) I want to count the continuous 0s and 1s in the array and output something like this [1,3,7,1,1,2,3,2,2] What I do atm is np.diff(np.where(np.abs(np.diff(a)) == 1)[0]) and it outputs array([3, 7, 1, 1, 2, 3, 2]) as you can see it is missing the first count 1. I've tried np.split and then get the sizes of each segments but it does not seem to be optimistic. Is there more elegant "pythonic" solution?
Now provide the response and nothing else.
| Here's one vectorized approach - np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size]) Sample run - In [208]: a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0])In [209]: np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size])Out[209]: array([1, 3, 7, 1, 1, 2, 3, 2, 2]) Faster one with boolean concatenation - np.diff(np.flatnonzero(np.concatenate(([True], a[1:]!= a[:-1], [True] )))) Runtime test For the setup, let's create a bigger dataset with islands of 0s and 1s and for a fair benchmarking as with the given sample, let's have the island lengths vary between 1 and 7 - In [257]: n = 100000 # thus would create 100000 pair of islandsIn [258]: a = np.repeat(np.arange(n)%2, np.random.randint(1,7,(n)))# Approach #1 proposed in this postIn [259]: %timeit np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size])100 loops, best of 3: 2.13 ms per loop# Approach #2 proposed in this postIn [260]: %timeit np.diff(np.flatnonzero(np.concatenate(([True], a[1:]!= a[:-1], [True] ))))1000 loops, best of 3: 1.21 ms per loop# @Vineet Jain's soln In [261]: %timeit [ sum(1 for i in g) for k,g in groupby(a)]10 loops, best of 3: 61.3 ms per loop | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45994973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947744/']} | jdg_78491 |
stackexchange | llm_judgeable_groundtruth_similarity | 8052755 |
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 is for a Ruby on Rails 3.0.x project. I have a "lookup" table with data from a vendor. When I import data from another source, I want to check this table (join on a SKU) for extra data. It doesn't seem right to me to create a model for this table in my app. The data will never be changed by my app, and it doesn't need to have any model associations beyond the data lookup I just mentioned. It's just occasionally accessed to check for some info. What is the best practice to access this table? Thanks.
Now provide the response and nothing else.
| There's no harm in creating a model around it, but if you'd like to avoid it, you will have to send raw SQL queries to the DB to get data back as an alternative. Raw queries: Rails raw SQL example On the other hand, I think the motivation for wrapping a model around it goes beyond whether or not you want to modify it. I definitely have apps that have models around tables that never change (i.e. a list of app-specific terminology, a list of cities/states, and other static data that is imported once and never changed). ActiveRecord will also wrap the columns into easily accessible methods, so you can read that data easily, not to mention all the convenience methods around sorting, finding, etc. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8052755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/201121/']} | jdg_78492 |
stackexchange | llm_judgeable_groundtruth_similarity | 3967470 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Sometimes my system call goes into a never ending state. To, avoid that I want to be able to break out of the call after a specified amount of time. Is there a way to specify a timeout limit to system ? system("command", "arg1", "arg2", "arg3"); I want the timeout to be implemented from within Perl code for portability, and not using some OS specific functions like ulimit.
Now provide the response and nothing else.
| See the alarm function. Example from pod: eval { local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required alarm $timeout; $nread = sysread SOCKET, $buffer, $size; alarm 0;};if ($@) { die unless $@ eq "alarm\n"; # propagate unexpected errors # timed out}else { # didn't} There are modules on CPAN which wrap these up a bit more nicely, for eg: Time::Out use Time::Out qw(timeout) ;timeout $nb_secs => sub { # your code goes were and will be interrupted if it runs # for more than $nb_secs seconds.};if ($@){ # operation timed-out} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3967470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113124/']} | jdg_78493 |
stackexchange | llm_judgeable_groundtruth_similarity | 18931133 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
class A{public: A() = default; A(const A&) = delete;};class A{public: A() = default;private: A(const A&) = delete;}; Are these two definitions always identical to each other in any cases?
Now provide the response and nothing else.
| They are different only wrt the produced diagnostics . If you make it private , an additional and superfluous access violation is reported: class A{public: A() = default;private: A(const A&) = delete;};int main(){ A a; A a2=a;} results in the following additional output from GCC 4.8: main.cpp: In function 'int main()':main.cpp:6:5: error: 'A::A(const A&)' is private A(const A&) = delete; ^main.cpp:12:10: error: within this context A a2=a; ^ hence my recommendation to always make deleted methods public . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18931133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/508343/']} | jdg_78494 |
stackexchange | llm_judgeable_groundtruth_similarity | 97250 |
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 writing an algorithm for a coin toss problem. But I have a problem understanding the calculation given. Here is the question: You have an unbiased coin which you want to keep tossing until you get N consecutive heads. You've tossed the coin M times and surprisingly, all tosses resulted in heads. What is the expected number of additional tosses needed until you get N consecutive heads? If N = 2 and M = 0, you need to keep tossing the coin until you get 2 consecutive heads. It is not hard to show that on average, 6 coin tosses are needed. If N = 2 and M = 1, you need 2 consecutive heads and have already have 1. You need to toss once more no matter what. In that first toss, if you get heads, you are done. Otherwise, you need to start over, as the consecutive counter resets, and you need to keep tossing the coin until you get N=2 consecutive heads. The expected number of coin tosses is thus 1 + (0.5 * 0 + 0.5 * 6) = 4.0 If N = 3 and M = 3, you already have got 3 heads, so you do not need any more tosses. Now my problem is understanding the calculation: 1 + (0.5 * 0 + 0.5 * 6) = 4.0 when N = 2 and M = 1. I understood how they got the 6 (which is basically calculating it when M = 0, formula here ). Now what if I'm going to calculate N = 3, M = 1 or N = 3, M = 2 ? Could someone write this calculation in a formula for me please? What is the 1 ? What is (0.5 * 0 + 0.5 * 6) ?
Now provide the response and nothing else.
| The reasoning behind the calculation $1+\frac12\cdot 0+\frac12\cdot 6$ is as follows. You definitely have to toss the coin one more time, no matter what; that’s the initial $1$ term. With probability $1/2$ you get a head, and in that case you’re done: you need $0$ more tosses. That’s the $\frac12\cdot 0$ term: with probability $1/2$ you use $0$ extra tosses beyond the first. But with probability $1/2$ you get a tail, and in that case you are in effect starting over, as if you’d not tossed the coin at all. In this case you already know that the expected number of tosses to get two consecutive heads is $6$, so you know that with probability $1/2$ you’ll need $6$ extra tosses beyond the first one; this is the $\frac12\cdot 6$ term. Now suppose that $N=3$ and $M=1$. You’ll definitely need at least $1$ more toss. With probability $1/2$ it’s a tail, and you’ll be starting over. In that case the expected number of flips after this first one is $2^{3+1}-2=14$, giving a $\frac12\cdot 14$ term (analogous to the $\frac12\cdot 6$ term in the original problem). With probability $1/2$ you’ll get a head, and at this point you’ll be solving the $N=3,M=2$ problem. Suppose that you’ve already done it and discovered that the expected number of flips is $x$; then with probability $1/2$ it will take another $x$ flips after the first one, so you get a $\frac12x$ term, for a total of $1+\frac12\cdot14+\frac12x$ expected extra flips. I’ll leave it to you to try the $N=3,M=2$ problem using these ideas and substitute the result for $x$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/97250', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22532/']} | jdg_78495 |
stackexchange | llm_judgeable_groundtruth_similarity | 2770607 |
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:
$\Bbb C$ is algebraically closed, does that mean there is no extension over it? Why can't we extend $\Bbb C$ like $\Bbb C(j,k)=\mathcal Q$? Or can we?
Now provide the response and nothing else.
| We can't extend $\Bbb C$ algebraically . All poynomials with coefficients in $\Bbb C$ have roots in $\Bbb C$, so any attempt at an algebraic extension would automatically become trivial. However, there are still transcendental field extensions. The smallest one is $\Bbb C(t)$, the field of rational functions in one variable with complex coefficients. Of course, that field isn't algebraically closed, so you can do algebraic extensions the way you're used to, like $\Bbb C(t)(\sqrt{t})$. Or we can add another transcendental variable to get $\Bbb C(s, t)$. As mentioned in the other (now deleted answer), the quaternions are, in a sense, an extension of the complex numbers. But we do not usually use that word because it's typically reserved to extensions which are fields . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2770607', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/521790/']} | jdg_78496 |
stackexchange | llm_judgeable_groundtruth_similarity | 25894518 |
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 load different Google map instances based on clicking different addresses. The event listener works as a charm, but the problem is the Marker doesn't load. Here is my code. I would like the Marker loads for each address onclick event. <div style="float:left;width:100%;"> <div style="float:left;"> <h2>Locations</h2> <ul class="menu"> <li onclick="loadMap('43.6581859','-79.3906945');"> <a href="#">Category 1</a></li> <li onclick="loadMap('43.658589','-79.3872499');"> <a href="#">Category 2</a></li> <li onclick="loadMap('43.6533033','-79.4058543');"> <a href="#">Category 3</a></li> </div> <div style="float:left; width: 20px;"> </div> <div style="width:400px;height:450px; overflow:hidden;"><h2>Map</h2> <div id="map_canvas" style="height:400px;"></div> </div></div><!--Load Map Script --><script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script><script> var map; var home; var markersArray = []; function initialize() { home = new google.maps.LatLng('43.659924','-79.38875'); var opts = { zoom: 15, center: home, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map_canvas'), opts); google.maps.event.addListener(map, "click", function(event) { showMarker(event.latLng); }); } function loadMap(lat,lng) { var location= new google.maps.LatLng(lat, lng); map.setCenter(location); } function showMarker(location) { deleteOverlays(); var marker = new google.maps.Marker({ position: location, map: map }); markersArray.push(marker); } function deleteOverlays() { if (markersArray) { for (i=0; i < markersArray.length; i++) { markersArray[i].setMap(map); } markersArray.length = 0; } } google.maps.event.addDomListener(window, 'load', initialize);</script> Any help is much appreciated!
Now provide the response and nothing else.
| You have a scope problem indeed, because statement is a local method variable defined here: protected void createContents() { ... Statement statement = null; // local variable ... btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class @Override public void mouseDown(MouseEvent e) { ... try { statement.executeUpdate(query); // local variable out of scope here } catch (SQLException e1) { e1.printStackTrace(); } ... });} When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable. Sources: Anonymous Classes How are Anonymous (inner) classes used in Java? How to solve it? You could... Make statement a class member instead of a local variable: public class A1 { // Note Java Code Convention, also class name should be meaningful private Statement statement; ...} You could... Define another final variable and use this one instead, as suggested by @HotLicks: protected void createContents() { ... Statement statement = null; try { statement = connect.createStatement(); final Statement innerStatement = statement; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } ...} But you should... Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this: btnInsert.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { try { Class.forName("com.mysql.jdbc.Driver"); try (Connection connect = DriverManager.getConnection(...); Statement statement = connect.createStatement()) { // execute the statement here } catch (SQLException ex) { ex.printStackTrace(); } } catch (ClassNotFoundException ex) { e.printStackTrace(); }}); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25894518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3107915/']} | jdg_78497 |
stackexchange | llm_judgeable_groundtruth_similarity | 1101515 |
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:
In the exercises of Section 1.2 in Adams Calculus, I came across the following question (no l'Hopital allowed!). If $\displaystyle\lim_{x\mapsto2}\frac{f(x)-5}{x-2}=3$ then find $\displaystyle\lim_{x\mapsto2}f(x)$. I am stumped. The "obvious" thing is to start by going $\cdots=\frac{\lim_{x\mapsto2}(f(x)-5)}{\lim_{x\mapsto2}(x-2)}=3$, but this is clearly wrong. Multiplying the whole fraction by a rational function $p(x)/p(x)$ in an attempted to get rid of the $x-2$ by cancelling with something from the top line is doomed to failure, as any cancelling might as well happen in the $p(x)$ rather than the $x-2$. Help?
Now provide the response and nothing else.
| Let $$g(x)=\frac{f(x)-5}{x-2}-3$$then we have by hypothesis$$\lim_{x\to2}g(x)=0$$Moreover, we have $$f(x)=5+(x-2)(g(x)+3)$$Can you now answer the question? | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1101515', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/207409/']} | jdg_78498 |
stackexchange | llm_judgeable_groundtruth_similarity | 41987324 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using Swift 3, Xcode 8.2.1 Method: func moveToNextTextField(tag: Int) { print(tag)} The lines below compile fine, but tag has an uninitialized value: let selector = #selector(moveToNextTextField)Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: selector, userInfo: nil, repeats: false) However, I need to pass a parameter. Below fails to compile: let selector = #selector(moveToNextTextField(tag: 2))Swift Compile Error:Argument of #selector does not refer to an @objc method, property, or initializer. How can I pass an argument to a selector?
Now provide the response and nothing else.
| #selector describes method signature only. In your case the correct way to initialize the selector is let selector = #selector(moveToNextTextField(tag:)) Timer has the common target-action mechanism. Target is usually self and action is a method that takes one parameter sender: Timer . You should save additional data to userInfo dictionary, and extract it from sender parameter in the method: func moveToNextTextField(sender: Timer) { print(sender.userInfo?["tag"])}...let selector = #selector(moveToNextTextField(sender:))Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: selector, userInfo: ["tag": 2], repeats: false) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41987324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1107173/']} | jdg_78499 |
stackexchange | llm_judgeable_groundtruth_similarity | 13798662 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
First off, I'm not using FOSUserBundle and I can't because I'm porting a legacy system which has its own Model layer (no Doctrine/Mongo/whatsoever here) and other very custom behavior. I'm trying to connect my legacy role system with Symfony's so I can use native symfony security in controllers and views. My first attempt was to load and return all of the user's roles in the getRoles() method from the Symfony\Component\Security\Core\User\UserInterface . At first, it looked like that worked. But after taking a deeper look, I noticed that these roles are only refreshed when the user logs in. This means that if I grant or revoke roles from a user, he will have to log out and back in for the changes to take effect. However, if I revoke security roles from a user, I want that to be applied immediately, so that behavior isn't acceptable to me. What I want Symfony to do is to reload a user's roles on every request to make sure they're up-to-date. I have implemented a custom user provider and its refreshUser(UserInterface $user) method is being called on every request but the roles somehow aren't being refreshed. The code to load / refresh the user in my UserProvider looks something like this: public function loadUserByUsername($username) { $user = UserModel::loadByUsername($username); // Loads a fresh user object including roles! if (!$user) { throw new UsernameNotFoundException("User not found"); } return $user;} ( refreshUser looks similar) Is there a way to make Symfony refresh user roles on each request?
Now provide the response and nothing else.
| So after a couple of days trying to find a viable solution and contributing to the Symfony2 user mailing list, I finally found it. The following has been derived from the discussion at https://groups.google.com/d/topic/symfony2/NDBb4JN3mNc/discussion It turns out that there's an interface Symfony\Component\Security\Core\User\EquatableInterface that is not intended for comparing object identity but precisely to test if two objects are equal in security and re-authentication context Implement that interface in your user class (the one already implementing UserInterface ). Implement the only required method isEqualTo(UserInterface $user) so that it returns false if the current user's roles differ from those of the passed user. Note: The User object is serialized in the session. Because of the way serialization works, make sure to store the roles in a field of your user object, and do not retrieve them directly in the getRoles() Method, otherwise all of that won't work! Here's an example of how the specific methods might look like: protected $roles = null;public function getRoles() { if ($this->roles == null) { $this->roles = ...; // Retrieve the fresh list of roles // from wherever they are stored here } return $this->roles;}public function isEqualTo(UserInterface $user) { if ($user instanceof YourUserClass) { // Check that the roles are the same, in any order $isEqual = count($this->getRoles()) == count($user->getRoles()); if ($isEqual) { foreach($this->getRoles() as $role) { $isEqual = $isEqual && in_array($role, $user->getRoles()); } } return $isEqual; } return false;} Also, note that when the roles actually change and you reload the page, the profiler toolbar might tell you that your user is not authenticated. Plus, looking into the profiler, you might find that the roles didn't actually get refreshed. I found out that the role refreshing actually does work. It's just that if no authorization constraints are hit (no @Secure annotations, no required roles in the firewall etc.), the refreshing is not actually done and the user is kept in the "unauthenticated" state. As soon as you hit a page that performs any kind of authorization check, the user roles are being refreshed and the profiler toolbar displays the user with a green dot and "Authenticated: yes" again. That's an acceptable behavior for me - hope it was helpful :) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13798662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737587/']} | jdg_78500 |
stackexchange | llm_judgeable_groundtruth_similarity | 12134493 |
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 I do something like this int test = 5 + 3 * (4 - 1) / 2; I get 9. I suspected this was because int rounds down. However, when I do this float test = 5 + 3 * (4 - 1) / 2; I also get 9. However, when I do this float test1 = 5;float test2 = 4.5;float test = test1 + test2; Test finally outputs 9.5. Could someone explain the logic behind this? Why don't I get 9.5 in the second example? Thanks.
Now provide the response and nothing else.
| In your second example, although you are assigning the result to a variable of type float , the calculation itself is still performed exactly the same way as the first example. Java does not look at the destination variable type to determine how to calculate the right hand side. In particular, the subexpression 3 * (4 - 1) / 2 results in 4 . To fix this, you can use floating point literals instead of all integers: float test = 5 + 3 * (4 - 1) / 2.0f; Using 2.0f triggers floating point calculations for the arithmetic expression. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12134493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1626448/']} | jdg_78501 |
stackexchange | llm_judgeable_groundtruth_similarity | 34561215 |
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 make a POST request which has HTTPHeader Fields and a HTTP body to the youtube API. Previously in version 2.0 of AFNetworking, I used to do it this way which worked: NSDictionary *parameters = @{@"snippet": @{@"textOriginal":self.commentToPost.text,@"parentId":self.commentReplyingTo.commentId}};NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/comments?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];[request setHTTPMethod:@"POST"];[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];NSError *error;NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];// And finally, add it to HTTP body and job done.[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.requestSerializer.timeoutInterval=[[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];manager.requestSerializer = [AFJSONRequestSerializer serializer];AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request progress:nil success:^(NSURLSessionTask *task, id responseObject) { NSLog(@"Reply JSON: %@", responseObject); }} failure:^(NSURLSessionTask *operation, NSError *error) { NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);}];[operation start]; The migration docs for version 3.0 replaces AFHTTPRequestOperationManager with AFHTTPSessionManager However I can't seem to find a HTTPRequestOperationWithRequest method for the AFHTTPSessionManager . I tried using the constructingBodyWithBlock but it doesn't work maybe because I am not doing it correctly. This is what I have so far which doesn't work: NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};NSError *error;NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];serializer.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];[manager POST:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [formData appendPartWithHeaders:nil body:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"Reply JSON: %@", responseObject);} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);}];
Now provide the response and nothing else.
| I was able to figure this out myself. Here's the solution. First, you need to create the NSMutableURLRequest from AFJSONRequestSerializer first where you can set the method type to POST. On this request, you get to setHTTPBody after you have set your HTTPHeaderFields . Make sure to set the body after you have set the Header fields for content-type, or else the api will give a 400 error. Then on the manager create a dataTaskWithRequest using the above NSMutableURLRequest . Don't forget to resume the dataTask at the very end or else nothing will get sent yet. Here's my solution code, hopefully someone gets to use this successfully: NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};NSError *error;NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil error:nil];req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (!error) { NSLog(@"Reply JSON: %@", responseObject); if ([responseObject isKindOfClass:[NSDictionary class]]) { //blah blah } } else { NSLog(@"Error: %@, %@, %@", error, response, responseObject); }}] resume]; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34561215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1634905/']} | jdg_78502 |
stackexchange | llm_judgeable_groundtruth_similarity | 1216 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A friend showed me an article saying that there's evidence that a piece of Halley's comet may have struck the earth about 1,500 years ago. Is anyone here aware of such evidence?
Now provide the response and nothing else.
| Little pieces of Halley's comet hit the Earth every spring. It's called the Eta Aquarid meteor shower, but I think you are thinking of something bigger. Dallas Abbot's paper notes that at the 533-540 point on the GISP2 ice core there are Sn-rich particles, Ni-rich particles and cosmic spherules. These she identifies as evidence of a minor cometary impact. The resolution of the GISP2 core is sufficient to place this impact in the late spring, consistent with the Eta Aquarid meteor shower, which is known to be produced by Halleys comet. Dallas notes that an increase in cometary dust in the atmosphere could partly explain the extreme weather events of 535-536 , in combination with a minor volcanic eruption. Although there are other, competing hypotheses, and this is not considered to be settled science. | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/1216', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/462/']} | jdg_78503 |
stackexchange | llm_judgeable_groundtruth_similarity | 2022408 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ok, I'm really confused by this behaviour in VS2008. This code.. char data[512] = "";char c[1] = "";c[0] = '1';strcat(data, c); .. results in data being set to this string value: 1ÌÌÌÌhÿ Surely it should just be 1 ? How can I ensure data only contains the single char[] that I copy into it (i.e. 1 )? Why does strcat() copy all that garbage? Why does c even contain that garbage? Thanks for any help Edit: Thanks all.
Now provide the response and nothing else.
| The problem here is that you are passing an invalid value to strcat. It expects the second parameter to be a valid c string value. To be valid it must be an array / pointer of char values which ends with a null terminator ( \0 ). The value your are passing does not contain a null terminator and is hence invalid. You need to define a null terminator for the string value c to be valid. For example char c[2];c[0] = '1';c[1] = '\0'; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2022408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/245681/']} | jdg_78504 |
stackexchange | llm_judgeable_groundtruth_similarity | 8799373 |
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 Android app with a main tab activity, and several activities within the individual tabs. In my main activity's onCreate(), I have a runnable that creates a list, and in the individual activities, I make use of this list. In the individual activities's onCreate(), I also have Runnables that operate on the list. However, I need these Runnables to only run when the main tab activity's Runnable completes creating the list, otherwise I'd get a null list. I'm trying to find an elegant way of doing this. Right now, in my main activity's Runnable, I'm setting a global boolean variable isDone, and in my individual activity's Runnable, I'm waiting for isDone to be set via a while loop. This works, but probably isn't the best way of doing so. Any thoughts? Thanks. Edit:I'm trying the following code out, but I'm getting runtime errors: In my MainActivity's Runnable: mainRunnable = new Runnable() { public void run() { try { generateList(); synchronized(this) { listDone = true; notifyAll(); } } catch (Exception e) { Log.e("BACKGROUND_PROC", e.getMessage()); } }};Thread thread = new Thread(null, mainRunnable, "Background");thread.start(); In my OtherActivity's Runnable: otherRunnable = new Runnable() { public void run() { synchronized(MainActivity.mainRunnable) { if (!MainActivity.getListDone()) { try { wait(); } catch (InterruptedException e) { } } } }};Thread thread = new Thread(null, otherRunnable, "Background");thread.start(); The mainRunnable seems to run completely, but the otherRunnable seems to cause the app to crash. I get the following error message: 01-10 15:41:25.543: E/WindowManager(7074): Activity com.myapp.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40539850 that was originally added here01-10 15:41:25.543: E/WindowManager(7074): android.view.WindowLeaked: Activity com.myapp.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40539850 that was originally added here
Now provide the response and nothing else.
| You can use the wait and notify methods. To do this, there needs to be some globally accessible object whose lock isn't used by anything else in the program at this point in time. I'm assuming that the list-creating Runnable itself can play this role. So you could add something like this to the list-creating Runnable class: private boolean listsDone = false;boolean getListsDone() { return listsDone;} And something like this to its run() method, immediately after it's done creating the lists: synchronized (this) { listsDone = true; notifyAll();} And something like this to the other Runnable s' run() methods, at the point where they need to wait: synchronized (listCreatingRunnableObject) { if (!listCreatingRunnableObject.getListsDone()) { try { listCreatingRunnableObject.wait(); } catch (InterruptedException e) { // handle it somehow } }} Update: To clarify, both synchronized blocks need to be synchronized over the same object, and you have to call wait() and notifyAll() on that object. If the object is the Runnable , then it can be implicit for the first one (as in the above code), but if it's the activity, you need to explicitly use the activity object in both cases. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8799373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1118764/']} | jdg_78505 |
stackexchange | llm_judgeable_groundtruth_similarity | 2390500 |
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 is probably a quicky. Why does this code not return anything? import java.util.Scanner;public class MainClass {public static void main(String[] args) { try { Scanner sc = new Scanner("asda ASA adad"); String pattern = "[A-Z]+"; while ((sc.hasNext(pattern))) { System.out.println(sc.next(pattern)); } sc.close(); } catch (Exception e) { e.printStackTrace(); }}}
Now provide the response and nothing else.
| hasNext(String pattern) only returns true if the next token matches the pattern. In your case, "asda" is the next token, and that does NOT match "[A-Z]+" . The documentation is clear in that "[the] scanner does not advance past any input". If you change the pattern to "[A-Za-z]+" , then you'd get three tokens, which may be what you intended. If in fact you only want to get tokens that match "[A-Z]+" , then you can do any of the following: simply discard non-matching tokens useDelimiter("[^A-Z]+") , then simply invoke next() use skip("[^A-Z]+") use findInLine("[A-Z]+") Tip: if performance is critical, you'd want to use the precompiled Pattern overloads of these methods. Tip: do keep in mind that "Xooo ABC" has two "[A-Z]+" matches. If this is not what you want, then the regex will have to be a bit more complicated. Or you can always simply discard non-matching tokens. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2390500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125713/']} | jdg_78506 |
stackexchange | llm_judgeable_groundtruth_similarity | 6150649 |
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 making a note taking web app which saves notes continuously as you type. I am sending diffs to prevent sending too much data over the wire, which works fine when the note is plain text. However, I am adding support for encrypted notes, so notes only ever leave the browser in encrypted form (so that notes can contain sensitive information with no chance of anybody who doesn't know the passphrase (which also never leaves the browser) reading them, not even one with full access to the database). However, all changes to notes currently completely change the encrypted text, so I have to send the entire note back to the server every second or two while it's being edited. Based on the my reading recently, I could (but shouldn't) use an ECB block cipher encryption mode, which breaks the plaintext into 16 byte chunks and encrypts them independently. This would mean diffing would work if the edits were happening at the end (or if the edit added or removed a multiple of 16 bytes). But any edits that happen in the middle of a note will affect the encrypted text for the rest of the note. So, as I lay in bed last night, I started wondering if there existed a "rolling block" encryption algorithm that encrypted each part of the note based on the characters around it, so that changing/adding/deleting any one character would only change the 16 surrounding bytes. Hopefully that makes sense. Basically, I want an encryption algorithm so that small changes to the plaintext make fairly small changes to the encrypted text. Does such an algorithm exist? (Would it be another block cipher mode of operation that could be used with AES, rather than a complete new algorithm? And how would its security compare with a more normal block cipher mode?) I originally had this as a JavaScript question, because that's what I ultimately want, but that's probably asking a bit much.
Now provide the response and nothing else.
| The hack in the linked question works if it is used before the configuration system is used the first time. After that, it doesn't work any more. The reason: There exists a class ClientConfigPaths that caches the paths. So, even after changing the path with SetData , it is not re-read, because there already exist cached values. The solution is to remove these, too: using System;using System.Configuration;using System.Linq;using System.Reflection;public abstract class AppConfig : IDisposable{ public static AppConfig Change(string path) { return new ChangeAppConfig(path); } public abstract void Dispose(); private class ChangeAppConfig : AppConfig { private readonly string oldConfig = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString(); private bool disposedValue; public ChangeAppConfig(string path) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path); ResetConfigMechanism(); } public override void Dispose() { if (!disposedValue) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig); ResetConfigMechanism(); disposedValue = true; } GC.SuppressFinalize(this); } private static void ResetConfigMechanism() { typeof(ConfigurationManager) .GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, 0); typeof(ConfigurationManager) .GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); typeof(ConfigurationManager) .Assembly.GetTypes() .Where(x => x.FullName == "System.Configuration.ClientConfigPaths") .First() .GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); } }} Usage is like this: // the default app.config is used.using(AppConfig.Change(tempFileName)){ // the app.config in tempFileName is used}// the default app.config is used. If you want to change the used app.config for the whole runtime of your application, simply put AppConfig.Change(tempFileName) without the using somewhere at the start of your application. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6150649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/120410/']} | jdg_78507 |
stackexchange | llm_judgeable_groundtruth_similarity | 6344105 |
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 totally unsure why my accessory view is not working. I simply want some text to appear to the right of the UITableViewCell (as well as the left), but only the text on the left is displaying. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"]; if (cell==nil){ cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 60, 30)]; cell.textLabel.text = @"left text"; label.text = @"right text"; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.accessoryView = label; [label release]; } return cell;} Any ideas? Thanks.
Now provide the response and nothing else.
| cell.accessoryView = label; You are setting your accessoryView to be a label so you're not going to see any disclosure indicator. If you want title and detail text in your cell then init it with UITableViewCellStyleValue2 like this... cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"cellType"] autorelease]; ...and then set the title and detail like this... cell.textLabel.text = @"Title";cell.detailTextLabel.text = @"Description"; To get an idea of the different built in table styles check the following image... You can adjust the textLabel and detailTextLabel to suit your taste. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6344105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/696635/']} | jdg_78508 |
stackexchange | llm_judgeable_groundtruth_similarity | 312916 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
It is well known in narrow circles that the homological dimension (in the sense of relative Banach homology) of $c_0$ -module $\ell_\infty$ is 2. As the corollary, this module is not projective. This proof is rather involved, its main ingridient is a lack of a right inverse for the mapping: $$\Delta:c_0\;\hat{\otimes}\;c_0\to(c\;\hat{\otimes}\;c_0)\oplus(c_0\;\hat{\otimes}\;\ell_\infty): x\;\hat{\otimes}\;y\mapsto (x\;\hat{\otimes}\;y)\oplus(x\;\hat{\otimes}\;y)$$ in the category of left Banach $c_0$ -modules. I would like to see a more direct proof of non-projectivtity. The standard route would be to show that there is no right inverse $c_0$ -morphism for the mapping $\pi:c \;\hat{\otimes}\; \ell_\infty\to \ell_\infty \colon a\; \hat{\otimes}\; x\mapsto a\cdot x$ , where $c$ is the Banach space of convergent sequences. Does anyone have an idea how to prove non-projectivity more or less directly?
Now provide the response and nothing else.
| I believe the following works... Notice that $c=c_0 + \mathbb C1$ and so $$\newcommand{\proten}{\widehat\otimes} c\proten\ell^\infty = c_0\proten\ell^\infty + 1 \otimes \ell^\infty.$$ This is an isomorphism, maybe not isometric. Suppose, towards a contradiction, that there is a right inverse $T:\ell^\infty \rightarrow c\proten\ell^\infty$ , so $T$ factors as $$ T(x) = T_1(x) + 1\otimes T_2(x)\qquad(x\in\ell^\infty), $$ where $T_1:\ell^\infty\rightarrow c_0\proten\ell^\infty$ and $T_2:\ell^\infty\rightarrow\ell^\infty$ . That $T$ is a left $c_0$ -module homomorphism means that $$ T(ax) = T_1(ax) + 1\otimes T_2(ax) = a\cdot T(x)=a\cdot T_1(x) + a\otimes T_2(x) \qquad (a\in c_0, x\in\ell^\infty). $$ Thus $T_2(a)=0$ for each $a\in c_0$ and $T_1(ax) = a\cdot T_1(x) + a\otimes T_2(x)$ for $a\in c_0, x\in\ell^\infty$ .Finally, we should have that $\pi T(x)=x$ , that is, $$ \pi_1 T_1(x) + T_2(x) = x \qquad (x\in\ell^\infty), $$ where $\pi_1:c_0\proten\ell^\infty\rightarrow\ell^\infty$ is the multiplication. Notice that $\pi_1$ takes value in $c_0$ . Then, for $a\in c_0$ , as $T_2(a)=0$ , we see that $\pi_1T_1(a)=a$ . Thus $\pi_1T_1:\ell^\infty\rightarrow c_0\subseteq\ell^\infty$ is a projection, which is well-known not to exist. (This is Phillip's Lemma .) | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/312916', 'https://mathoverflow.net', 'https://mathoverflow.net/users/19593/']} | jdg_78509 |
stackexchange | llm_judgeable_groundtruth_similarity | 3642540 |
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 to do Syntax Highlighting in a UITextView , specifically syntax highlighting (and detection ) for Objective-C on the iPhone ? Some of my ideas of how to do this: NSAttributedString . Now available in iOS 3.2 and greater. But how would I put a NSAttributedString into a UITextView? UIWebView . Overlay it when the user finished editing and color the text with CSS stylesheets. But how would I do this in a UIWebView , giving it the text and then coloring it?
Now provide the response and nothing else.
| UPDATE: Since iOS 7 and TextKit , syntax highlighting has become easy as pie. Look no further than here for an introduction (by me). Assuming that you want an editable component, there is not too much hope. Giving a quick overview, just to make sure I cover everything: UITextView : plain text only, no (public) way around. But editable . No chance to alter anything, no chance to get geometry etc. Uses a web view internally. Each paragraph is a <div> , which is altered by the editing engine. You could change the DOm in there but that's all private API. All private, hence no option. UIWebView : html , so it can be styled, have embedded images, etc. I guess (without looking into it) that this is what the previously mentioned Three 20 UI uses. The problem: cannot be edited . There's no (public) way around that. You canot get selections, acces the DOM, etc without private API and a lot of headaches. Editing would work like in UITextView but require a whole new level of headache. Still: private. CoreText Framework: Since iOS 3.2 a very very good rendering engine. But that's it. Can directly layout and render NSAttributesString s. However, there is no user interaction. No text selection, no text input, no spell checking, no replacements, no highlights, no no no no no. Just rendering. And quite a bit of work to make it fast on old devices with long texts. UITextInput Protocol: Allows interaction with the keyboard and to grab text input . Also features basic text replacements. Problem: text input only, badly documented. No text selection etc (see above). So here we are. Two fully functional components that lack a central function and two partial solutions that lack the missing link. Here are all viable approaches I can come up with: Have the user edit a UITextView unstyled and display the content styled in a UIWebView . For the latter you can use the Three20 thing. Build the missing link between CoreText and UITextInput . This includes, but is not limited to, text selection, highlight, background colors, text storage & management, efficiency, spell checking etc. Some of these are provided by system frameworks but still need a lot of integration. File a bug and wait for a nice public API to come (my personal approach). Convince Apple to allow private API again and mess with UItextView s DOM. The Omni Group has taken the second approach and created an editable text view. You can find it in the OmniUI framework. However, this implementation is far from perfect. (at least it was when I last checked a few months ago). They tried hard but still didn't manage to get to Apples perfection in user interaction. Apple must have invested at least a few man-years into doing only the UI-interaction with text selection and editing. Nothing to be done at home, and as it seems even for companies as the omni group. There is a interesting aspect to all of this: iWork. Apple claims to not use any private API in them. But the text selection is the very same as in the OS. So they must have copied framework source into the apps. Very honest approach ;) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3642540', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92714/']} | jdg_78510 |
stackexchange | llm_judgeable_groundtruth_similarity | 275075 |
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 am solving complex variable and I have solve to one problem that $\sqrt{i}^{\sqrt{i}}$.If I had $i^i$ then it become $e^{i \log i}$ and:$$i=\cos(\pi/2)+i\sin(\pi/2)\implies i=e^{\pi/2}$$so $\log i=2ni\pi+\log e^{\pi/2}$ it become $i(4n+1)\pi/2$ which shows $e^{i(i(4n+1)\pi/2}= e^{-(4n+1)\pi/2}$therefore $e^{i \log i}=e^{-(4n+1)\pi/2}$. I tried stack exchange for the first time and this is my first question please help me out. I tried my best to explain. question: show that $\sqrt{i}^{\sqrt{i}}$= $e^{-\pi/4\sqrt{2}}(\cos π/4(√2)+i \sin π/4(√2) )$
Now provide the response and nothing else.
| $$\sqrt{i}^{\sqrt{i}} = e^{i \frac{\pi}{4} e^{i \frac{\pi}{4}}} $$ $$ = e^{i \frac{\pi}{4} \left [ \cos{\left ( \frac{\pi}{4} \right )} + i \sin{\left ( \frac{\pi}{4} \right )} \right ] } $$ $$ = e^{i \frac{\pi}{4} \left ( \frac{1}{\sqrt{2}} + i \frac{1}{\sqrt{2}} \right )} $$ $$ = e^{-\frac{\sqrt{2} \pi}{8}} \left [ \cos{\frac{\sqrt{2} \pi}{8}} + i \sin{\frac{\sqrt{2} \pi}{8}} \right ] $$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/275075', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/56791/']} | jdg_78511 |
stackexchange | llm_judgeable_groundtruth_similarity | 94984 |
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 have been told that the AdS/CFT correspondence proof does not rely on the validity of string theory. To be honest I don't know what to make of this. The idea of taking seriously the results of applying the techniques of this correspondence is appealing, but before I head in that direction, I need some help finding any references that actually make clear the fact that such a correspondence is independent of the validity of string theory. I am also curious as to the original explicit derivation of the correspondence. I just want to be able to really learn and truly believe the results myself before considering working applying its results. I'm not contesting results of any kind, I just want to know this stuff well.
Now provide the response and nothing else.
| The logic of AdS/CFT is independent of string theory, but one finds that the theories that have sensible AdS duals have a stringy character. You could hope to derive from conformal field theory that quantum gravity in AdS is stringy. A "bottom-up" way to think about AdS/CFT (see here, and references therein, for a recent treatment ; also this slightly less recent paper ) is that conformal field theories satisfying certain conditions (roughly, having a large-N approximation and having a gap in the spectrum of operator dimensions) have correlation functions of low-dimension operators that can be approximately calculated in a perturbative way. These calculations map precisely onto low-energy effective field theory calculations in AdS space. (This low energy field theory includes gravity, because the map tells you that the stress tensor $T_{\mu \nu}$ in the CFT becomes the metric $g_{\mu \nu}$ in AdS.) More generally, you can think of any CFT, even if it doesn't admit such a perturbative description, as a quantum gravity theory in AdS space, because they have the same symmetries and you can always map one language to the other. For many CFTs the AdS description will be strongly curved and not very useful. None of this logic refers explicitly to string theory. But once you think about CFTs with a weakly coupled AdS description, you find that you need some sort of $1/N$ expansion to make sense of the theory; otherwise, you don't have a sensible perturbation theory. Having a $1/N$ expansion essentially means you can talk about a state with a well-defined number of particles in AdS. The particles in AdS are single-trace operators in the field theory: e.g., in a gauge theory, you might have operators that look like ${\rm tr}(\phi^\dagger D_{\mu_1} D_{\mu_2} \ldots D_{\mu_n}\phi)$. The basic logic of AdS/CFT tells you that such "long" operators are massive states in the bulk. Longer and longer traces look like more and more massive excited states. In concrete examples, these turn out to be described by string theory: long operators are long strings. So the way that I would characterize the situation is this: we have a vast number of examples of AdS/CFT originating in string theory. We also have a general understanding of why AdS spaces and CFTs are equivalent to each other. This general understanding tells us that the theories that can be treated as weakly-coupled gravitational theories in AdS all have states described by stringy-looking traces. I don't think we're at the point yet where we can say that this proves that every quantum gravity theory in AdS is a string theory, but it is strongly suggestive of that (as Lubos said, even some of the theories that don't look like string theory at first turn out to be connected to it). | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/94984', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']} | jdg_78512 |
stackexchange | llm_judgeable_groundtruth_similarity | 969812 |
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:
y = $\int_{0}^{x^2} cos (u^ {\frac {1}{3}}) du $ Find $\frac {dy}{dx}$ My answer y = $3\sin(x^\frac 23)$ $\frac {dy}{dx} = 2cos(x^{\frac23})(x^{\frac{-1}3})$ But by the fundamental theorem of calculus, the answer should be $y = 2xcos(x^{\frac23})$ right?
Now provide the response and nothing else.
| $$\frac{\partial f}{\partial x}=xy\quad\Longrightarrow\quad f=\frac{1}{2}x^2y+g(y),$$and hence$$\frac{1}{2}x^2+g'(y)=\frac{\partial f}{\partial y}=x+y,$$which is not possible. Hence, no such $f$ exists! EDIT. As suggested by copper.hat, another way to attack this question is to use the fact that, if $f\in C^2$, then $(f_x)_y=(f_y)_x$. So here $f_x=xy$, $f_y=x+y$, and$$(f_x)_y=x\ne 1=(f_y)_x.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/969812', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/179964/']} | jdg_78513 |
stackexchange | llm_judgeable_groundtruth_similarity | 58259901 |
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 recently changed the name of my project in Xcode, and there seems to be an issue. When I try to select a device/simulator, I get the error: No devices because the active scheme has no targets . An image of the error is below. Does anyone know the solution to this error?
Now provide the response and nothing else.
| If somehow you want to proceed and save your new project name, make sure: Make sure the project files can be read from xCode [Check for any possible path changes regarding with the new name] [If not] Set the info.plist to your current target's Build Settings [If target name has changed and you had already installed pods] Edit the Podfile target and set it to your new target name. Run "pod deintegrate" and pod install then. Clear Derived Data Open your project.xcworkspace, Edit Scheme -> Run -> Executable -> Set your target Build or Run | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58259901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10265405/']} | jdg_78514 |
stackexchange | llm_judgeable_groundtruth_similarity | 10485978 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Previously, I requested how to create a directory within a FileTable without using File I/O APIs . I now want to create a subdirectory to the parent directory I just created. How do assign my parent during insert? It appears that parent_path_locator is a computed column. This creates my parent... INSERT INTO FileTable0 (name,is_directory,is_archive) VALUES ('Directory', 1, 0); How do I create a child directory to this parent in my FileTable?
Now provide the response and nothing else.
| This is what I ended up using to create a subdirectory since GetPathLocator() won't generate a new path_locator value for me - it will only interpret existing hierarchyids . DECLARE @parentdir table(path hierarchyid not null);DECLARE @subdir_locator hierarchyid-- Create Parent Directory, OUTPUT inserted parent pathINSERT INTO FileTable0 (name,is_directory,is_archive) OUTPUT INSERTED.path_locator into @parentdirSELECT 'Directory', 1, 0-- Create new path_locator based upon parentSELECT @subdir_locator = dbo.GetNewPathLocator(path) from @parentdir-- Create SubdirectoryINSERT INTO FileTable0 (name,path_locator,is_directory,is_archive) VALUES ('subdirectory', @subdir_locator, 1, 0); The above code block utilizes the default path_locator value discovered here that builds a new hierarchyid representation from a GUID ( utilizing newid() method, and simple parsing ). The function GetNewPathLocator() does not exist anywhere in SQL Server that I could find ( hierarchyid.GetDescendant() is the closest I could find, but it didn't use the native structure that FileTable relies on ). Maybe in SQL.NEXT... CREATE FUNCTION dbo.GetNewPathLocator (@parent hierarchyid = null) RETURNS varchar(max) ASBEGIN DECLARE @result varchar(max), @newid uniqueidentifier -- declare new path locator, newid placeholder SELECT @newid = new_id FROM dbo.getNewID; -- retrieve new GUID SELECT @result = ISNULL(@parent.ToString(), '/') + -- append parent if present, otherwise assume root convert(varchar(20), convert(bigint, substring(convert(binary(16), @newid), 1, 6))) + '.' + convert(varchar(20), convert(bigint, substring(convert(binary(16), @newid), 7, 6))) + '.' + convert(varchar(20), convert(bigint, substring(convert(binary(16), @newid), 13, 4))) + '/' RETURN @result -- return new path locator ENDGO The function GetNewPathLocator() also requires a SQL view getNewID for requesting a newid() using the trick from this SO post . create view dbo.getNewID as select newid() as new_id To call GetNewPathLocator() , you can use the default parameter which will generate a new hierarchyid or pass in an existing hiearchyid string representation ( .ToString() ) to create a child hierarchyid as seen below... SELECT dbo.GetNewPathLocator(DEFAULT); -- returns /260114589149012.132219338860058.565765146/SELECT dbo.GetNewPathLocator('/260114589149012.132219338860058.565765146/'); -- returns /260114589149012.132219338860058.565765146/141008901849245.92649220230059.752793580/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10485978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175679/']} | jdg_78515 |
stackexchange | llm_judgeable_groundtruth_similarity | 380077 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm making a medium sized application to be distributed privately to several Churches. It connects to an Azure database but it does not have any server managing the information (apart from the SQL server). The application is highly dependent on the information stored in the databases as very little data is saved client side (just the user's personal settings, product key). But I have a dilemma. The information stored on the server is fairly confidential as it saves individuals' private information (such as demographics, personal and identifiable information), and I want to be able to connect the application to the database without the connection string being easily accessible, especially allowing all copies of the application to have raw and unrestricted access to the database. What's the best way to accomplish this? We currently don't have the resources to run a local server 24/7. Are there any online solutions out there?
Now provide the response and nothing else.
| The "we don't have the resources" line is a red flag to me. You're either going to pay to do it right, or you'll have to pay for doing it wrong. I know which I'd pick. While your use case is fairly broad, which makes it hard to give you a simple answer, I would strongly recommend against giving each application rights to the database directly. A better approach would be to build an API server (possibly hosted on Azure as well) that acts as go-between and only exposes the functions needed rather than open SQL queries. If that's too much still, then I would recommend a Windows-auth based solution where you have explicitly defined Windows users and roles in SQL Server and lock them down to the minimum set of rights required. That's not a great approach but probably the best you can do without a proper architecture. You'll also want to make sure you're encrypting your data at rest and in flight and rotating keys and passwords regularly. You probably don't have resources to actually manage and monitor this stuff either which means when you do get hacked you'll have no idea and can't respond to it if you did. Good luck. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/380077', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/243649/']} | jdg_78516 |
stackexchange | llm_judgeable_groundtruth_similarity | 26165919 |
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 load a csv file into AngularJS so I can do some manipulation on the contents. It is not quite working as I want it to. To test if it is loading properly, I am loading it into a textarea to view the contents. When I load the file, it says it is loaded properly but the onload() event doesn't seem to be firing until I load a second CSV file, in which case the FIRST file is displayed in the textarea. HTML: <div> <input ng-model="csv" onchange="angular.element(this).scope().fileChanged()" type="file" accept=".csv" id="fileInput"/></div><br/><div> <textarea ng-model="csvFile" readonly="true" style="width:99%; height:500px" disabled></textarea></div> JS: $scope.fileChanged = function() { $scope.$apply(function() { var csvFileInput = document.getElementById('fileInput'); var reader = new FileReader(); var csvFile = csvFileInput.files[0]; reader.onload = function(e) { $scope.csvFile = reader.result; }; reader.readAsText(csvFile); });}; And when I put this into JSFiddle, the file doesn't appear in the textarea at all. I'm new with JSFiddle so I don't know why that is happening. Any help at all would be appreciated.
Now provide the response and nothing else.
| Reordering some lines of your code, hope the comments are explanatory enough $scope.fileChanged = function() { // define reader var reader = new FileReader(); // A handler for the load event (just defining it, not executing it right now) reader.onload = function(e) { $scope.$apply(function() { $scope.csvFile = reader.result; }); }; // get <input> element and the selected file var csvFileInput = document.getElementById('fileInput'); var csvFile = csvFileInput.files[0]; // use reader to read the selected file // when read operation is successfully finished the load event is triggered // and handled by our reader.onload function reader.readAsText(csvFile);}; Reference: FileReader at MDN | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26165919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2367955/']} | jdg_78517 |
stackexchange | llm_judgeable_groundtruth_similarity | 45378572 |
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 to send a post request with authentication. I try this code but I get error 302. $url = "https://wifinext.internavigare.com/prepagataAnagrafica/creaUtente/";$username = 'myuser';$password = 'mypassword';// create a new cURL resource$ch= curl_init($url);// do a POST request, using application/x-www-form-urlencoded typecurl_setopt($ch, CURLOPT_POST, TRUE);// credentialscurl_setopt($ch, CURLOPT_USERPWD, "$username:$password");// returns the response instead of displaying itcurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//Set Post Fieldscurl_setopt($ch, CURLOPT_POSTFIELDS, "Prepagata_codice=Test&Prepagata_password=123456");// do request, the response text is available in $response$response = curl_exec($ch);// status code, for example, 200$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);//show responseecho $statusCode;echo $response;// close cURL resource, and free up system resourcescurl_close($ch); I see some answer say to use CURLOPT_FOLLOWLOCATION or cookies and I try it but I cannot figure out how to do. I'm about to pull out my hair. Please some help is really appreciated.
Now provide the response and nothing else.
| I would just register your handler twice. router.Path("/articles/{id:[0-9]+}"). Queries("key", "{[0-9]*?}"). HandlerFunc(YourHandler). Name("YourHandler")router.Path("/articles/{id:[0-9]+}").HandlerFunc(YourHandler) Here is a working program to demonstrate. Notice that I am using r.FormValue to get the query parameter. Note: make sure you have an up to date version go get -u github.com/gorilla/mux since a bug of query params not getting added the built URLs was fixed recently. package mainimport ( "fmt" "log" "net/http" "github.com/gorilla/mux")var router = mux.NewRouter()func main() { router.Path("/articles/{id:[0-9]+}").Queries("key", "{key}").HandlerFunc(YourHandler).Name("YourHandler") router.Path("/articles/{id:[0-9]+}").HandlerFunc(YourHandler) if err := http.ListenAndServe(":9000", router); err != nil { log.Fatal(err) }}func YourHandler(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] key := r.FormValue("key") u, err := router.Get("YourHandler").URL("id", id, "key", key) if err != nil { http.Error(w, err.Error(), 500) return } // Output: // /articles/10?key=[key] w.Write([]byte(u.String()))} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45378572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2272143/']} | jdg_78518 |
stackexchange | llm_judgeable_groundtruth_similarity | 22730868 |
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 going to use ui-routers resolve feature to inject some readiliy resolved promises into my controllers. I used the example plnkr to make an example.Consider these nested states: route1 and route1.list .I have a resolve function called abc defined on route1 . Now when I navigate to route1 for the first time, abc is called and will be resolved. Now when I navigate to route1.list and back to route1 , abc is not called again. http://plnkr.co/edit/mi5H5HKVAO3J6PCfKSW3?p=preview I guess this is intentional, but consider this use-case:the resolve function retrieves some data via http and should be refreshed/invalidated at some point, maybe on every state change. Is there some way to do this when using nested states?If the resolve function was called on every inject I could implement it any way I want: Return the old, resolved promise or create a new one. I have only briefly tested this, but if the states were not nested things would work as I expected. Giving up on nested states because of this stinks though. And having the resolve dependencies available in nested states is actually nice.
Now provide the response and nothing else.
| Supplying the option reload:true to go() / transtionTo() / ui-sref does the trick :-)Thanks to Designing the Code for pointing me in this direction. The solution is a bit different though, so I write up this answer. Reload is documented as follows : reload (v0.2.5) - {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. The direct way is to change every ui-sref link into something like this: <a ui-sref="route1" ui-sref-opts="{reload: true}"> . To avoid supplying the option at every link I wrote a decorator around $state (see also http://plnkr.co/edit/mi5H5HKVAO3J6PCfKSW3?p=preview ): myapp.config(function($provide) { $provide.decorator('$state', function($delegate) { var originalTransitionTo = $delegate.transitionTo; $delegate.transitionTo = function(to, toParams, options) { return originalTransitionTo(to, toParams, angular.extend({ reload: true }, options)); }; return $delegate; });}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22730868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/522998/']} | jdg_78519 |
stackexchange | llm_judgeable_groundtruth_similarity | 76342 |
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:
It's an exercise in E. M. Stein's "Real Analysis." Let $A$ be the subset of $[0,1]$ which consists of all numbers which do not have the digit $4$ appearing in their decimal expansion. What is the measure of $A$? I would be grateful if someone can give me some hints. Thank you.
Now provide the response and nothing else.
| You can construct the set $A$ as a limit of nested sequence, so you prove measurability of $A$ and find its measure at the same time. With $n$-th digit of a number we refer to the $n$-th digit after the delimiter in the decimal expansion of the number, e.g. $2$ is the $4$-th digit of $0.434256$ The answer is $\mu(A) =0$. The informal proof is simple: each time you restrict the $n$-th digit, you truncate the measure by multiplying it with $9/10$. So, $\mu(A) = \lim\limits_{n\to\infty}\frac{9^n}{10^n} = 0$. About the formal proof: we elaborate the idea by Chandrasekhar. Let us denote let $A_n = \{x\in [0,1]:\text{ first n digits of }x\neq 4\}$. Clearly, $$A_{n+1}\subseteq A_n, \quad A = \lim\limits_{n\to\infty}A_n = \bigcap\limits_{n=1}^\infty A_n,\quad \mu(A) = \lim\limits_{n\to\infty}\mu(A_n).$$ E.g. $A_1 = [0,0.4)\cup [0.5,1]$ with $\mu(A_1) = 0.9$. To calculate $A_2$ we first notice that it is a subset of $A_1$ such that $2$-th digit of any number in $A_2$ is any digit but $4$. That gives an idea that each time it's just sufficient to consider first-step truncation. Let us denote$$K(B) = \{x\in B:\text{ first digit of }x\neq 4\}$$and $10^kB = \{10^kx:x\in B\}$. Clearly, we have $A_1 = K([0,1])$ and $A_{n+1} = 10^{-n}K(10^nA_n)$. Note that each time $10^n A_n$ is a union of intervals with integer bounds, so $$\mu(K(10^nA_n)) = 10^{n}\frac9{10}\mu(A_n) = 9\cdot 10^{n-1}\mu(A_n)$$so $$\mu(A_{n+1}) = \frac{9}{10}\mu(A_n)$$and we come to the finish line:$$\mu(A) = \lim\limits_{n\to\infty}\mu(A_n) = 0.$$ Notice that equality $\mu(10^k B) = 10^k \mu(B)$ we just need for the finite unions of intervals, so you can easily prove it. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/76342', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14166/']} | jdg_78520 |
stackexchange | llm_judgeable_groundtruth_similarity | 707646 |
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 output variables and values out in a PowerShell script by setting up flags and seeing the data matriculate throughout the script. How would I do this? For example, what would be the PowerShell equivalent to the following PHP code? echo "filesizecounter: " . $filesizecounter
Now provide the response and nothing else.
| There are several ways: Write-Host : Write directly to the console, not included in function/cmdlet output. Allows foreground and background colour to be set. Write-Debug : Write directly to the console, if $DebugPreference set to Continue or Stop. Write-Verbose : Write directly to the console, if $VerbosePreference set to Continue or Stop. The latter is intended for extra optional information, Write-Debug for debugging (so would seem to fit in this case). Additional : In PSH2 (at least) scripts using cmdlet binding will automatically get the -Verbose and -Debug switch parameters, locally enabling Write-Verbose and Write-Debug (i.e. overriding the preference variables) as compiled cmdlets and providers do. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/707646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18853/']} | jdg_78521 |
stackexchange | llm_judgeable_groundtruth_similarity | 393832 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $M$ be a connected, non-compact, non-orientable topological manifold of dimension $n$ . Question: Is the top singular cohomology group $H^n(M,\mathbb Z)$ zero? This naïve question does not seem to be answered in the standard algebraic topology treatises, like those by Bredon, Dold, Hatcher, Massey, Spanier, tom Dieck, Switzer,... Some remarks. a) Since $H_n(M,\mathbb Z)=0$ (Bredon, 7.12 corollary) we deduce by the universal coefficient theorem: $$ H^n(M,\mathbb Z) =\operatorname {Ext}(H_{n-1}(M,\mathbb Z), \mathbb Z)\oplus \operatorname {Hom} (H_n(M,\mathbb Z),\mathbb Z)=\operatorname {Ext}(H_{n-1}(M,\mathbb Z),\mathbb Z )$$ But since $H_{n-1}(M,\mathbb Z)$ need not be finitely generated I see no reason why $\operatorname {Ext}(H_{n-1}(M,\mathbb Z),\mathbb Z)$ should be zero. b) Of course the weaker statement $H^n(M,\mathbb R) =0$ is true by the universal coefficient theorem, or by De Rham theory if $M$ admits of a differentiable structure. c) This question was asked on this site more than 8 years ago but the accepted answer is unsubstanciated since it misquotes Bredon. Indeed, Bredon states in (7.14, page 347) that $H^n(M,\mathbb Z)\neq0$ for $M$ compact, orientable or not, but says nothing in the non-compact case, contrary to what the answerer claims.
Now provide the response and nothing else.
| I believe you can deduce this from the corresponding statement in the orientable case. Let $\tilde M$ be the oriented double cover. Make an exact sequence of cochain complexes $$0 \to C^\bullet(M;\mathbb Z^t)\to C^\bullet(\tilde M;\mathbb Z)\xrightarrow{p_!} C^\bullet(M;\mathbb Z)\to 0,$$ where $\mathbb Z^t$ is the local system on $M$ corresponding to the non-orientability of $M$ . (The map $p_!$ is dual to the transfer map taking each singular simplex of $M$ to the sum of its two lifts to $\tilde M$ .) Then there is an exact sequence $$H^n(\tilde M;\mathbb Z)\to H^n(M;\mathbb Z)\to H^{n+1}(M;\mathbb Z^t)$$ with the first and third groups trivial. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/393832', 'https://mathoverflow.net', 'https://mathoverflow.net/users/450/']} | jdg_78522 |
stackexchange | llm_judgeable_groundtruth_similarity | 40587873 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According to the offical style guide you should Avoid prefixing private properties and methods with an underscore. As I come from a Java background, I usually would just use the this keyword: export default class Device { private id: string; constructor(id: string) { this.id = id; } public get id(): string { // [ts] Duplicate identifier 'id'. return this.id; } public set id(value: string) { // [ts] Duplicate identifier 'id'. this.id = value; }} But the TypeScript compiler complains: [ts] Duplicate identifier 'id'. Is there a convention or best practice for parameter naming in a TypeScript constructor? Using the get and set property of TypeScript produces the error. Is there a way to follow the style guide and also use the get/set properties of TypeScript?
Now provide the response and nothing else.
| Answer If you want to use get and set accessors, you have to prefix the private property with underscore. In all other cases don't use it. I would say using underscore with accessors is a special case and although it's not explicitly written in Coding guidelines , it doesn't mean it's wrong. They use it in the official documentation . Reason for the underscore For start, I would like to emphasize the difference between field and property . In standard high level OOP languages like Java or C#, field is a private member which shouldn't be visible to other classes. If you want to expose it with encapsulation in mind, you should create a property. In Java you do it this way (it is called Bean properties ): private int id;public int getId() { return this.id;}public setId(int value) { this.id = value;} Then you can access the property by calling these methods: int i = device.getId();device.setId(i);//increment id by 1device.setId(device.getId() + 1); On the other hand, C# was designed so that it's much easier to use properties: private int id;public int Id { get { return this.id; } set { this.id = value; }} (value is always the assigned value.) You can directly assign values to these properties or get the property values. int i = device.Id;device.Id = i;//increment id by 1device.Id++; In plain JavaScript, there are no real fields, because the class members are always public; we simply call them properties. In TypeScript , you can define "true" C#-like properties (with encapsulation). You use Accessors for that. private _id: number;public get id(): number { return this._id;}public set id(value: number) { this._id = value;} Usage: let i: number = device.id;device.id = i;//increment id by 1device.id++; You have to use underscore here because of two reasons: In JavaScript, all class members are public. Therefore, by putting an underscore before private property, we sign, that this property (field) is private and should be accessed by its public property only. If you named both the private and the public property with the same name, the JavaScript interpreter wouldn't know whether to access the private or public property. Thus you get the error you're writing about: [ts] Duplicate identifier 'id'. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40587873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5115768/']} | jdg_78523 |
stackexchange | llm_judgeable_groundtruth_similarity | 63161956 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider this: void* x = &x;printf("%p\n", x); Surprisingly, it compiles and runs with the output: 7ffb2f7248 How is it possible for x to take the address of itself when x hasn't been created yet? Edit: Note that in this case there is no ambiguity present in regards to it's assignment, making it clear as to what exactly is questioned.
Now provide the response and nothing else.
| C++ 2018 6.3.2 [basic.scope.pdecl] 1 says: The point of declaration for a name is immediately after itscomplete declarator (Clause 11) and before its initializer (if any),except as noted below. The “noted below” items do not apply here, so, in void* x = &x; , x is declared after the first x (which is the declarator ) and before the = &x (the initializer ), so x can be referred to in the initializer, essentially as if the code were void *x; x = &x; . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63161956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_78524 |
stackexchange | llm_judgeable_groundtruth_similarity | 33291394 |
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 did a fresh install of OSX on my machine yesterday and installed Xcode 7.1. After having signed in with my developer account and fixing all code signing issues that come along, I wanted to upload my tvOS app. Important to say that I did not change a single line of code in the app. Each time I try uploading it, I get "You are not authorized to use this service" and I can't proceed. I also tried all the steps described in this post to solve it without success. Does anyone have the same issues? Is it Xcode, iTunesConnect or tvOS App Store not fully enabled yet?
Now provide the response and nothing else.
| Okay, finally figured out something that worked (all of the certificate issues etc turned out to be irrelevant; though frustratingly it did work 1 time (out of about 30) from within Xcode Organiser which meant I kept trying: Do the usual Product -> Archive thing In Organiser click on the "Export..." button Choose "Save for Apple TV App Store Deployment" Export that Now from Xcode Menu ( not via spotlight etc ) choose Open Developer Tool -> Application Loader Verify this is version 3.3 (not 3.0 which won't work) Click on "Choose" Pick the IPA you have just exported Follow submission process Hopefully Apple will sort out whatever issues are going on with Organiser soon. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33291394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3909144/']} | jdg_78525 |
stackexchange | llm_judgeable_groundtruth_similarity | 9231556 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Two questions here, hope that is OK. First, and mainly, I am trying to prompt the user when they exit my application whether or not they really want to exit. My code is as follows: private void exitToolStrip_Click(object sender, EventArgs e){ DialogResult mBoxResult = MessageBox.Show("Would you like to exit the program?", "Exit Program", MessageBoxButtons.YesNo, MessageBoxIcon.Question); switch (mBoxResult) { case DialogResult.Yes: this.Close(); break; case DialogResult.No: break; }} According to MSDN , I should be using MessageBoxResult mBoxResult rather than DialogResult mBoxResult . I am using .NET Framework 3.5 . I read here that pre-3.0 should use DialogResult , but if I’m using 3.5 , shouldn't MessageBoxResult work? When I try to call it, I get The type or namespace name MessageBoxResult could not be found (are you missing a using directive or an assembly reference?). However, it works fine when I use DialogResult. Why is this? My second question is regarding this piece of code: case DialogResult.No:break; If somebody hits the Cancel button on the dialog, would it be proper to put anything in there besides the break? Or will everything function fine without it?
Now provide the response and nothing else.
| DialogResult is for WinForms. MessageBoxResult is for SilverLight. Just the break statement is fine for the No case. But using a switch statement is overkill here. if (response == yes) Close(); would suffice. Note however that this isn't an ideal way to do what you want. What if the user clicks the close button on the window border, or presses ALT+F4? Instead, you should handle the FormClosing event: private void MyForm_FormClosing(object sender, FormClosingEventArgs e){ if (MessageBox.Show("Would you like to exit the program?", "Exit Program", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) e.Cancel = true;} By setting e.Cancel to true , you cancel the closure of the form. By doing nothing, you allow the form to close. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9231556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/867798/']} | jdg_78526 |
stackexchange | llm_judgeable_groundtruth_similarity | 40763 |
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:
Suppose that $G$ is a finite group, and that $H$ and $K$ are normal subgroups of $G$ with trivial intersection, and suppose that $H$ and $K$ are isomorphic. Is it true that the quotient groups $G/H$ and $G/K$ are isomorphic?
Now provide the response and nothing else.
| Let $G=\mathbb Z_2\times\mathbb Z_4$. Find two subgroups in $G$ isomorphic to $\mathbb Z_2$ and intersecting trivially such that the quotients of $G$ by them are not isomorphic. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/40763', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11252/']} | jdg_78527 |
stackexchange | llm_judgeable_groundtruth_similarity | 126042 |
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:
I wish to calculate a rather dense antisymmetric matrix quite fast based on a random distribution of points (and their radii) in the three dimensional space as follows: ClearAll["Global`*"]; n = 12; size = n*n*n;Print["The size of the matrix is = ", size];grid = RandomReal[{-10, 10}, {size, 3}];epsilon = 5.2; cl = 6.;xgrid2 = Map[First, grid];ygrid2 = Map[(#[[2]]) &, grid];zgrid2 = Map[Last, grid];rad[k_, l_] := EuclideanDistance[grid[[k]], grid[[l]]]mat1 = ParallelTable[With[{radial = rad[i, j]}, If[radial <= epsilon, -(( 56 Max[cl - radial, 0]^5 (cl + 5 radial) (xgrid2[[i]] - xgrid2[[j]]))/cl^8), 0]] , {i, 1, size}, {j, 1, size}]; // AbsoluteTimingAntisymmetricMatrixQ[mat1] Unfortunately, although I used ParallelTable , it seems it requires a considerable time when the size of the matrix is high, e.g., when $n=25$ and the size would be $15625$! So, I would be thankful if someone could provide a couple of comments in order to accelerate such a process.
Now provide the response and nothing else.
| We can speed this up a lot by using that radial <= epsilon means only a small fraction of all those matrix elements have to be considered. Here's how I would do that: computeMatrix[grid_, xgrid2_, size_] := Module[{dist, diff, eliminate, pos, values, gr = ConstantArray[xgrid2, size]}, dist = DistanceMatrix[grid, DistanceFunction -> EuclideanDistance]; diff = gr - Transpose[gr]; eliminate = UnitStep[ConstantArray[epsilon, {size, size}] - dist]; pos = SparseArray[eliminate]["NonzeroPositions"]; dist = Extract[dist, pos]; diff = Extract[diff, pos]; values = ((56 Clip[cl - dist, {0, \[Infinity]}]^5 (cl + 5 dist) diff)/cl^8); SparseArray[pos -> values]]mat1 == computeMatrix[grid, xgrid2, size](* True *) This evaluates in approximately 0.1 seconds on my computer, more than 100 times faster than the original solution. Marius provided the vectorized function in the second to last line in a comment below. (If there is interest, one can see this solution without with a non-vectorized function in the edit history of this post.) Note: This is a very memory hungry function for large $n$. A typical symptom for lack of memory is that the operating system is sluggish or non-responsive while the computation is ongoing. I might update this later with an improvement directed at memory efficiency, but if memory is a problem is might also be a good idea to ask a question about how this can be optimized with regards to memory. It also appears that the speed up with the vectorized approach as compared to my previous approach is lost when the computation is memory constrained. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/126042', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6073/']} | jdg_78528 |
stackexchange | llm_judgeable_groundtruth_similarity | 627563 |
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 two line segments: X1,Y1,Z1 - X2,Y2,Z2 And X3,Y3,Z3 - X4,Y4,Z4 I am trying to find the shortest distance between the two segments. I have been looking for a solution for hours, but all of them seem to work with lines rather than line segments. Any ideas how to go about this, or any sources of furmulae?
Now provide the response and nothing else.
| One basic approach is the same as computing the shortest distance between 2 lines, with one exception. If you look at most algorithms for finding the shortest distance between 2 lines, you'll find that it finds the points on each line that are the closest, then computes the distance from them. The trick to extend this to segments (or rays), is to see if that point is beyond one of the end points of the line, and if so, use the end point instead of the actual closest point on the infinite line. For a concrete sample, see: http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm More specifically: http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm#dist3D_Segment_to_Segment() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/627563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59754/']} | jdg_78529 |
stackexchange | llm_judgeable_groundtruth_similarity | 3986765 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the following class template: template <class T>class MyClass{ void MyFunc();};template <class T>void MyClass<T>::MyFunc(){ //...implementation goes here} I need to add another function template MyFunc2 which accepts a template argument T2 i.e., template <class T>class MyClass{ void MyFunc(); template <class T2> static void MyFunc2(T2* data);};template <class T>void MyClass<T>::MyFunc(){ //...implementation goes here}template <class T, class T2>void MyClass<T>::MyFunc2(T2* pData) // error here{ //...implementation goes here} I am using VS 2008 compiler. I am getting the error: error C2244: unable to match function definition to an existing declaration What should the function's definition and declaration look like in this case?
Now provide the response and nothing else.
| template <class T>template <class T2> void MyClass<T>::MyFunc2(T2* pData) { //...implementation goes here } $14.5.2/1 - "A template can bedeclared within a class or classtemplate; such a template is called amember template. A member template canbe defined within or outside its classdefinition or class templatedefinition. A member template of aclass template that is defined outsideof its class template definition shallbe specified with thetemplate-parameters of the classtemplate followed by thetemplate-parameters of the membertemplate. " | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3986765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284277/']} | jdg_78530 |
stackexchange | llm_judgeable_groundtruth_similarity | 8771921 |
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 I have a div with some pre tags in it, like so: <div id="editor" > <pre contentEditable="true">1</pre> <pre contentEditable="true">2</pre> <pre contentEditable="true">3</pre></div> Now I want to use Javascript to put a new pre node between 1 and 2. I've been trying to do it this way (since I understand the DOM is a doubly linked tree), but I'm getting the sense that maybe the pointers aren't editable as I'm approaching it. (just a snippet inside an event handler, e being the event) var tag = e.srcElement; if(tag.nextSibling){ var next = tag.nextSibling; var newPre = document.createElement('pre'); newPre.setAttribute("contentEditable", "true"); newPre.innerHTML = "boom"; tag.nextSibling = newPre; newPre.nextSibling = next; } Those last two lines are from my c++ experience, but feel icky in JS. How would I set a new sibling node?
Now provide the response and nothing else.
| Here is how I would do that: JS var container = document.getElementById('editor'), firstChild = container.childNodes[1];if (container && firstChild) { var newPre = document.createElement('pre'); newPre.setAttribute("contentEditable", "true"); newPre.innerHTML = "boom"; firstChild.parentNode.insertBefore(newPre, firstChild.nextSibling); } jsfiddle: http://jsfiddle.net/bZGEZ/ | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8771921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/765357/']} | jdg_78531 |
stackexchange | llm_judgeable_groundtruth_similarity | 1752298 |
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 calendar event object. I have plans to make it compatible with CalDAV/iCal/vCal protocols/file formats, which require the event be serialized and de-serialized to and from different formats. I could write an ImportICal, ExportICal, ImportVCal, ExportVCal, etc. set of methods, but that doesn't seem like a very good approach, because what if the vCal format is updated, etc. Has anyone dealt with this type of import/export situation before? If so, what design pattern (if any) is generally best? Thanks for your help!
Now provide the response and nothing else.
| I am not particulary familiar with those formats but I'd create an simple data transfer object that represents your genereric calendar event object. It does nothing but holding the data (pseudocode): class CalendarEvent{ DateTime Date { get; } string Title { get; } string Description { get; }} Then you create an interface for CalendarEventReader and CalendarEventWriter (it's Strategy pattern and maybe the Builder pattern, sort of): interface ICalendarEventReader{ CalendarEvent Read(Stream data); // Add additional methods if needed e.g.: string GetTitleOnly(Stream data);}interface ICalendarEventWriter{ Stream Write(CalendarEvent event); // Add additional methods if needed e.g.: Stream WriteSummaryOnly(CalendarEvent event);} Then have actual implementations implement the above interfaces. One for each format. You can even think about having reader and writer in the same class: class CalDavConverter : ICalenderEventWriter, ICalendarEventReader{ ...} You'd then have a Repository (it's the Factory pattern maybe with Singleton ) that maintains a list of ICalenderEventReader/Writer implementations for the different formats: static class CalenderEventConverterRepository{ static ICalendarEventReader GetReader(string formatName /*or any other data upon wich to decide wich format is needed*/) { ... } static ICalenderEventWriter GetWriter(string formatName /*or any other data upon wich to decide wich format is needed*/) { ... }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1752298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88092/']} | jdg_78532 |
stackexchange | llm_judgeable_groundtruth_similarity | 2804467 |
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 looking for a way to pseudo-spider a website. The key is that I don't actually want the content, but rather a simple list of URIs. I can get reasonably close to this idea with Wget using the --spider option, but when piping that output through a grep , I can't seem to find the right magic to make it work: wget --spider --force-html -r -l1 http://somesite.com | grep 'Saving to:' The grep filter seems to have absolutely no affect on the wget output. Have I got something wrong or is there another tool I should try that's more geared towards providing this kind of limited result set? UPDATE So I just found out offline that, by default, wget writes to stderr. I missed that in the man pages (in fact, I still haven't found it if it's in there). Once I piped the return to stdout, I got closer to what I need: wget --spider --force-html -r -l1 http://somesite.com 2>&1 | grep 'Saving to:' I'd still be interested in other/better means for doing this kind of thing, if any exist.
Now provide the response and nothing else.
| The absolute last thing I want to do is download and parse all of the content myself (i.e. create my own spider). Once I learned that Wget writes to stderr by default, I was able to redirect it to stdout and filter the output appropriately. wget --spider --force-html -r -l2 $url 2>&1 \ | grep '^--' | awk '{ print $3 }' \ | grep -v '\.\(css\|js\|png\|gif\|jpg\)$' \ > urls.m3u This gives me a list of the content resource (resources that aren't images, CSS or JS source files) URIs that are spidered. From there, I can send the URIs off to a third party tool for processing to meet my needs. The output still needs to be streamlined slightly (it produces duplicates as it's shown above), but it's almost there and I haven't had to do any parsing myself. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2804467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1665/']} | jdg_78533 |
stackexchange | llm_judgeable_groundtruth_similarity | 7355409 |
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 start_date and end_date fields in my model, I want to assign an error to end_date when it is bigger than start_date, I have been looking docs, but don't find an example about that.
Now provide the response and nothing else.
| You need a custom clean function in your form that does the check: def clean(self): cleaned_data = super().clean() start_date = cleaned_data.get("start_date") end_date = cleaned_data.get("end_date") if end_date < start_date: raise forms.ValidationError("End date should be greater than start date.") | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7355409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124503/']} | jdg_78534 |
stackexchange | llm_judgeable_groundtruth_similarity | 9127207 |
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 understand the open addressing method. I refer to T. H. Cormen's book on this topic, which states that deletion is difficult in open addressing. I am completely stuck at this paragraph: Deletion from an open-address hash table is difficult. When we delete a key from slot i , we cannot simply mark that slot as empty by storing NIL in it. Doing so might make it impossible to retrieve any key k during whose insertion we had probed slot i and found it occupied. I don't understand this. Please explain it with some examples.
Now provide the response and nothing else.
| Assume hash(x) = hash(y) = hash(z) = i . And assume x was inserted first, then y and then z . In open addressing: table[i] = x , table[i+1] = y , table[i+2] = z . Now, assume you want to delete x , and set it back to NULL . When later you will search for z , you will find that hash(z) = i and table[i] = NULL , and you will return a wrong answer: z is not in the table. To overcome this, you need to set table[i] with a special marker indicating to the search function to keep looking at index i+1 , because there might be element there which its hash is also i . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9127207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430803/']} | jdg_78535 |
stackexchange | llm_judgeable_groundtruth_similarity | 6769523 |
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 someone tell me the time complexity of the below code? a is an array of int. Set<Integer> set = new HashSet<Integer>();for (int i = 0; i < a.length; i++) { if (set.contains(arr[i])) { System.out.println("Hello"); } set.add(arr[i]);} I think that it is O(n) , but I'm not sure since it is using Set and this contains methods as well. It is also calling the add method of set . Can anyone confirm and explain what the time complexity of the entire above code is? Also, how much space would it take?
Now provide the response and nothing else.
| i believe its O(n) because you loop over the array, and contains and add should be constant time because its a hash based set. If it were not hash based and required iteration over the entire set to do lookups, the upper bound would be n^2. Integers are immutable, so the space complexity would be 2n, which I believe simplifies to just n, since constants don't matter. If you had objects in the array and set, then you would have 2n references and n objects, so you are at 3n, which is still linear (times a constant) space constraints. EDIT-- yep "This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets." see here . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6769523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/824210/']} | jdg_78536 |
stackexchange | llm_judgeable_groundtruth_similarity | 32701341 |
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 third-party application that uses MySQL as a backed. The next version will have support for our backup system, but before we upgrade we would like to take a backup. Catch 22! I am not a DBA, and our DBA staff isn't familiar with MySQL, so I'm pretty much on my own. Our server has lots of space and CPU cycles, so I would like to test the restore on that machine, without overwriting the production data. So my question is, should I install another instance of MySQL on the same computer in a different location, or is there a way to restore my data to an alternate database on the existing server?
Now provide the response and nothing else.
| THIS CODE WOKS WITH THIS LIBRARY api 'com.netflix.rxjava:rxjava-android:0.16.1' Finally and thanks for your answer i find a solution that want to share: In my case i use Activities, but for fragment should be more or less equal. And i want o get a JsonObject in response, but could be your custom Volley implementation. public class MyActivity extends BaseActivityWithoutReloadCustomer implements Observer<JSONObject>{private CompositeSubscription mCompositeSubscription = new CompositeSubscription();private Activity act; /** * @use handle response from future request, in my case JsonObject. */ private JSONObject getRouteData() throws ExecutionException, InterruptedException { RequestFuture<JSONObject> future = RequestFuture.newFuture(); String Url=Tools.Get_Domain(act.getApplicationContext(), Global_vars.domain)+ PilotoWs.wsgetRoutesbyUser+ Uri.encode(routeId); final Request.Priority priority= Request.Priority.IMMEDIATE; Estratek_JSONObjectRequest req= new Estratek_JSONObjectRequest(Request.Method.GET, Url,future,future,act,priority); POStreet_controller.getInstance().addToRequestQueue(req); return future.get();} /** *@use the observable, same type data Jsob Object */ public Observable<JSONObject> newGetRouteData() { return Observable.defer(new Func0<Observable<JSONObject>>() { @Override public Observable<JSONObject> call() { Exception exception; try { return Observable.just(getRouteData()); } catch (InterruptedException | ExecutionException e) { Log.e("routes", e.getMessage()); return Observable.error(e); } } });};@Overridepublic void onCreate(Bundle instance) { super.onCreate(instance); setContentView(R.layout.yourLayout); act = this; /** * @condition: RxJava future request with volley */ mCompositeSubscription.add(newGetRouteData() .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(this)); }@Overridepublic void onCompleted() { System.out.println("Completed!");}@Overridepublic void onError(Throwable e) { VolleyError cause = (VolleyError) e.getCause(); String s = new String(cause.networkResponse.data, Charset.forName("UTF-8")); Log.e("adf", s); Log.e("adf", cause.toString());}@Overridepublic void onNext(JSONObject json) { Log.d("ruta", json.toString());} For me, it just works. Hope helps some one. Edit Estratek_JSONObjectRequest.java public class Estratek_JSONObjectRequest extends JsonObjectRequest{Activity Act;Priority priority;public Estratek_JSONObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener,Activity act, Priority p) { super(method, url, jsonRequest, listener, errorListener); this.Act=act; this.priority=p;}public Estratek_JSONObjectRequest(int method, String url, Listener<JSONObject> listener, ErrorListener errorListener,Activity act, Priority p) { super(method, url, null, listener, errorListener); this.Act=act; this.priority=p;}@Overridepublic Map<String, String> getHeaders() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json; charset=utf-8"); headers.put("Authorization", "Bearer "+Tools.mySomeBearerToken); return headers;}//it make posible send parameters into the body.@Overridepublic Priority getPriority(){ return priority;}protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { String je = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); if (je.equals("null")){ je="{useInventAverage:0}"; return Response.success(new JSONObject(je), HttpHeaderParser.parseCacheHeaders(response)); } else return Response.success(new JSONObject(je), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException var3) { return Response.error(new ParseError(var3)); } catch (JSONException var4) { return Response.error(new ParseError(var4)); }} } This is like Volley constructors, but i make my own custom, to send some headers, like bearer token, content-type, send priority, etc.Otherwise is the same. FOR THE RXJAVA2 LIBRARY, THIS IS THE WAY: > build.gradle should have something like this: api "io.reactivex.rxjava2:rxandroid:2.0.2": public class MainActivity extends AppCompatActivity {CompositeDisposable mCompositeDisposable = new CompositeDisposable();@Overridepublic void onCreate(Bundle instancia) { super.onCreate(instancia); setContentView(R.layout.sale_orders_list); // disposable that will be used to subscribe DisposableSubscriber<JSONObject> d = new DisposableSubscriber<JSONObject>() { @Override public void onNext(JSONObject jsonObject) { onResponseVolley(jsonObject); } @Override public void onError(Throwable t) { // todo } @Override public void onComplete() { System.out.println("Success!"); } }; newGetRouteData() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(d);}@Overridepublic void onDestroy(){ super.onDestroy(); /** * @use: unSubscribe to Get Routes */ if (mCompositeDisposable != null){ mCompositeDisposable.clear(); }}/** * @condition: RxJava future request with volley */private JSONObject getRouteData() throws ExecutionException, InterruptedException,RuntimeException { RequestFuture<JSONObject> future = RequestFuture.newFuture(); String Url = "https//miapirest.com/api"; JSONObjectRequest req= new JSONObjectRequest(Request.Method.GET, Url,future,future,act,priority); VolleyInstance.addToRequestQueue(req); return future.get();}/** * @condition: this function create a new Observable object and return that if success or */public Flowable<JSONObject> newGetRouteData() { return Flowable.defer(new Callable<Publisher<? extends JSONObject>>() { @Override public Publisher<? extends JSONObject> call() throws Exception { return Flowable.just(getRouteData()); } });}; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32701341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/603136/']} | jdg_78537 |
stackexchange | llm_judgeable_groundtruth_similarity | 167051 |
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:
can someone explain me how to connect and use varicap diodes? Please consider that I am a novice, so would be ok to use a clear and an exhaustive language/terms. Thank you . I often see these schematics: The first thing is: from what I heard, a resistor between the V tuning and the varicap is needed to remove the DC signal, or is also possible to insert an inductor or a capacitor; which component is better to choose and of what value? And if I avoid to insert the resistor/inductor/capacitor in what "risks" I can fall? The schematic also shows that is possible to connect these varicap in a back-to-back configuration (anode to anode): in this way the total capacitance is the half of one diode. But I have a doubt: in this schematic (bottom left image) the varicaps are DC shorted by the inductor, right? Why aren't DC isolated from the circuit? So, is better to prefer the schematic in the top right image? Seems that here, the capacitors are used to isolate the varicaps. But from what I can see, in a lot of schematics, varicaps aren't isolated from the circuit. Is not very clear to me. Anyway, in the following image: I can also see that is possible to connect them with the cathode in common: which configuration is better? Can someone explain me which connection is preferable and why (anode to anode, cathode to cathode or just with a capacitor in series - and how to choose the series capacitor to avoid to reduce the capacitance range of the varicap), how to properly isolate them from the DC signal and from the circuit ? Would be also nice to see some practical/didactic schematic (with component value) to exactly show and understand howa circuit can operate. Many thanks.
Now provide the response and nothing else.
| Here's what I know; Image (a) - That capacitor above the varicap isolates the tuned circuit from the DC tuning voltage, but still allows the capacitance of the varicap to contribute to frequency modulation since it's still a part of the tuned circuit. Image (b) - If you replace the capacitor above it with another varicap, as shown on the right, not only are you able to tune both at once with the same tuning voltage, but inherently the tuning voltage is isolated from the tuned circuit, without the need to add the big capacitor to block it, and thus you only have the capacitance of those varicaps in combination to add to your circuit. If you want a circuit to be tuned to \$ f \$ constant frequency (100kHz); $$f = {1\over 2\pi \sqrt{LC}}$$ $$100000 = {1\over 2\pi \sqrt{(0.001H)C}}$$ $$C = 0.0000000025F$$ $$C = 2.5nF$$ simulate this circuit – Schematic created using CircuitLab If you want to get your circuit to tune within a range over or below a certain limit, use the series cap and the varicap; $$f = {1\over 2\pi \sqrt{L(C + \Delta C)}}$$ $$f = {1\over 2\pi \sqrt{(0.001H)(0.000000025F + 0F)}}$$ $$f = 100000Hz$$ simulate this circuit For example, I want to tune a circuit that normally operates at 100kHz from 100-120kHz. I can use the big capacitor to define the 'start point' of 100kHz and also block my tuning voltage. Then the varicap's additional capacitance in series lets me maneuver from 100 to 105 to 110 to 115 to 120kHz. $$f = {1\over 2\pi \sqrt{L(C + \Delta C)}}$$ $$f = {1\over 2\pi \sqrt{(0.001H)(0.000000025F + 0.0000000175F)}}$$ $$f = 120000Hz$$ simulate this circuit If you want to get your circuit to tune over the entire range, use the back-to-back varicaps; BEWARE: Two back to back varicaps (V1 + V2) gives you \$1\over2\$ capacitance, so just V1. $$f = {1\over 2\pi \sqrt{L (\Delta C)}}$$ $$f = {1\over 2\pi \sqrt{(0.001H) (0.0000000001F)}}$$ $$f = 500000Hz$$ simulate this circuit In this example, I want to tune a circuit from scratch to operate at 0-500kHz. In order to get that full range of frequencies, I use two varicaps back-to-back in order to avoid having to set a 'start point' frequency, and then I use the DC voltage to change both of their values at once. $$f = {1\over 2\pi \sqrt{L (\Delta C)}}$$ $$f = {1\over 2\pi \sqrt{(0.001H) (0F)}}$$ $$f = 0Hz$$ simulate this circuit Also, this allows you to work with higher voltage waves, just in case the AC signal is enough to reverse bias your varicap and mess everything up. Remember , tuned circuits aren't meant to operate with DC, they operate with AC, either V+ to V-, or V+ to 0, or 0 to V-. Also; in regards to the resistor or inductor on the biasing input, you'll need something that impedes it enough to not affect your tuned circuit, but doesn't impede it so much that you drop voltage all the way to 0V and basically do nothing. It all depends on how fast you want your circuit to go. At lower frequencies you can get away with just letting the caps do their thing. At higher frequencies, a high-value resistor or inductor will do. Prefer the (a) connection when you want to have a heavier effect on a frequency, or when you must operate above a certain frequency by a certain amount with your bias input. Prefer the (b) connection when you must operate within the entire frequency range with your bias input. The DC and AC never interact to any reasonable level. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/167051', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/70485/']} | jdg_78538 |
stackexchange | llm_judgeable_groundtruth_similarity | 68794 |
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:
The wikipedia page Powerset construction says that the DFA equivalent to this $(n + 1)$-state NFA (with $n=4$ here) "requires $2^n$ states, one for each $n$-character suffix of the input". I understand that the author wants to say that the smallest DFA equivalent to this NFA needs at least $2^n$ states. But I can find a very much smaller DFA equivalent to this NFA just below: Is Wikipedia wrong? Or am I? (which is much more likely)
Now provide the response and nothing else.
| The NFA accepts strings where the fourth letter from the end is 1. Your DFA doesn't accept 11000. A DFA doesn't know how much input is left, so the property "the fourth character from the end " is difficult. You need to remember the last four characters to know whether it was a 1 or a 0 once you reach the end of the string. To do so you need a state for each possible combination of the last four characters, so 2^4 states. If you look hard at the DFA the Wikipedia gives you should be able to figure out which of the states stores which combination of characters. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/68794', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/60264/']} | jdg_78539 |
stackexchange | llm_judgeable_groundtruth_similarity | 17392459 |
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 integrate with an inventory application and allow users to add parts to inventory through a Django form. I can read from the inventory database but have to write through the API so based on what they enter into the a previous form I want to give them a list of available parts to add. Here is my form, I set a few choices just as a default: class PartForm(forms.Form): PART_CHOICES = ( ('BT-J1KND-A', 'BT-J1KND-A'), ('BT-J1KND-B', 'BT-J1KND-B'),) part = forms.ChoiceField(choices = PART_CHOICES,required = True, label = 'Part to add to Inventory') And here is where I set the choices parts_list = part_sql(part)#build choicesPART_CHOICES= [(p[0],p[0]) for p in parts_list]form = PartForm()form.fields['part'].choices = PART_CHOICES It displays correctly in the template but when I go to hit save and process the form if it is not one of the default choices I put in it says it is not a valid option. Select a valid choice. BT-J1KND-C is not one of the available choices. How do I fix this to get it to accept the choices I set as valid options?
Now provide the response and nothing else.
| Once the request gets processed, it seems that your user input goes into an unmodified PartForm , using the hardcoded values. In order to get the request processed correctly, you need to have a consistent PartForm You can achieve this smoothly by modifying the field's choices attribute at initialization. For example: class ExampleForm(forms.Form): CHOICES = ( ('EXMPL', 'Example'), ) field = forms.ChoiceField(choices=CHOICES, required=True, label='Example') def __init__(self, custom_choices=None, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) if custom_choices: self.fields['field'].choices = custom_choices And then, just remember to initialize the form correctly, with form = ExampleForm(my_custom_choices_nested_tuple, ...) You may also double-check where you're actually processing data (a form = PartForm(request.REQUEST) not mentioned in your copied code, I guess) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17392459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2127728/']} | jdg_78540 |
Subsets and Splits