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
|
35529532
|
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 building an Electron application based on React and Redux. I'm starting with the electron-react-boilerplate , which is pretty minimalistic and easy to understand. I want the user to open a file on the Electron menu, and as a result, I want to call a reducer and change the Redux application state. Pretty simple concept. The problem is that I don't know how to change the Redux state from outside my root component. The Electron menu is defined in the main.js file . The root component is defined in the index.js file , together with the Redux state (the store variable). In the main.js file, I want to do something like this: submenu: [{ label: '&Open', accelerator: 'Ctrl+O', click: function() { // I want to change my app Redux state here. But I don't know how. } } Any idea?
Now provide the response and nothing else.
|
You could obtain the filename in the main process and then send it to the renderer process via Electron IPC, for example: In main.js // mainWindow = new BrowserWindow();submenu: [{ label: '&Open', accelerator: 'Ctrl+O', click: () => { // popup a dialog to let the user select a file // ... // then send the filename to the renderer process mainWindow.webContents.send('open-file', selectedFilename); }}] In index.js import { ipcRenderer } from 'electron';ipcRenderer.on('open-file', (event, filename) => { store.dispatch({ type: 'OPEN_FILE', filename });});
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35529532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192729/']}
|
jdg_76641
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
690964
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a very long input string that's multiline, in a local variable $INPUT, for example: abcdef How do I trim it to n lines max, let's say n=3, and add a message at the end: abc... message too long This is what I have, don't work on multi-line: $OUTPUT=$('$INPUT' | awk '{print substr($0, 1, 15) "...")
Now provide the response and nothing else.
|
How about output=$(echo "$input" | awk -v n=3 'NR>n {print "... message too long"; exit} 1') or output=$(echo "$input" | sed -e '3{a\... message too long' -e 'q}') output=$(echo "$input" | sed -e '3{$!N;s/\n.*/\n... message too long/' -e 'q}') POSIXly output=$(echo "$input" | sed -e '3{ $!N s/\n.*/\n... message too long/ q }') or with GNU sed: output=$(echo "$input" | sed -e '4{i\... message too long' -e 'Q}')
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/690964', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/514514/']}
|
jdg_76642
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
772388
|
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 C# how can I test a file is a jpeg? Should I check for a .jpg extension? Thanks
Now provide the response and nothing else.
|
Several options: You can check for the file extension: static bool HasJpegExtension(string filename){ // add other possible extensions here return Path.GetExtension(filename).Equals(".jpg", StringComparison.InvariantCultureIgnoreCase) || Path.GetExtension(filename).Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase);} or check for the correct magic number in the header of the file: static bool HasJpegHeader(string filename){ using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open, FileAccess.Read))) { UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8) UInt16 marker = br.ReadUInt16(); // JFIF marker (FFE0) or EXIF marker(FFE1) return soi == 0xd8ff && (marker & 0xe0ff) == 0xe0ff; }} Another option would be to load the image and check for the correct type. However, this is less efficient (unless you are going to load the image anyway) but will probably give you the most reliable result (Be aware of the additional cost of loading and decompression as well as possible exception handling): static bool IsJpegImage(string filename){ try { using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename)) { // Two image formats can be compared using the Equals method // See http://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat.aspx // return img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg); } } catch (OutOfMemoryException) { // Image.FromFile throws an OutOfMemoryException // if the file does not have a valid image format or // GDI+ does not support the pixel format of the file. // return false; }}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/772388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_76643
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17390260
|
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 object, for example HttpWebResponse ,that implements IDisposable , and therefore should be disposed. Having this: HttpWebResponse a = ....; What will be the correct way of handling the object? a.Dispose(); Or: if (a!= null) a.Dispose(); Should I even care if the object is null? Can't I just Dispose it anyway?
Now provide the response and nothing else.
|
It's generally recommend to wrap anything which implements IDisposable with the using statement using (var a = new HttpWebResponse(...)){} It's the equivalent of writing var a = new HttpWebResponse(...);try{ // use a}finally{ if (a != null) a.Dispose();} Should I even care if the object is null? Can't I just Dispose of it anyway Well no, because if you attempt to call Dispose on a null object the application will throw a NullReferenceException . Given your circumstance where you feel the using statement isn't a valid option another neat of way tidying this up is to write an extension method e.g. public static class Ext{ public static void SafeDispose(this object obj) { if (obj != null) obj.Dispose(); }}...var a = new ...;a.SafeDispose(); This then would allow you to call the method on a null object.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17390260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/990635/']}
|
jdg_76644
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
178661
|
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 need to implement time zones in a very large and old Delphi system, where there's a central SQL Server database and possibly hundreds of client installations around the world in different time zones. The application already interacts with the database by only using the date/time of the database server. So, all the time stamps saved in both the database and on the client machines are the date/time of the database server when it happened, never the time of the client machine. So, when a client is about to display the date/time of something (such as a transaction) which is coming from this database, it needs to show the date/time converted to the local time zone. This is where I get lost. I would naturally assume there should be something in SQL to recognize the time zone and convert a DateTime field dynamically. I'm not sure if such a thing exists though. If so, that would be perfect, but if not, I need to figure out another way. This Delphi system (multiple projects) utilizes the SQL Server database using ADO components, VCL data-aware controls, and QuickReports (using data sources). So, there's many places where the data goes directly from the database query to rendering on the screen, without any code to actually put this data on the screen. In the end, I need to know when and how should I get the properly converted time? What is the proper way to ensure that I handle Dates and Times correctly in a legacy application?
Now provide the response and nothing else.
|
Dates and timezones are tricky things, and generally no matter what kind of technology stack you are working on there is rarely a turn key solution. Most databases will store a date or timestamp as little more than the exact date or timestamp that was given to it. When talking with a database through queries they are generally under the assumption that all dates and timestamps represent a point in time under the same time zone. In other words, if I write a query to see if Aug 2nd 2012 4:10pm is before the same date at 5:10pm then that will evaluate to true returning me that record. Suppose the record was saved as 4:10pm Eastern Standard Time when my database server is in Pacific Standard Time. The database is time zone agnostic and now my query is not returning the data I expect. Convert all application dates and times to UTC or GMT before persisting Languages like Java, Javascript and C# treat dates and times a bit differently. They will generally measure time as a number of milliseconds from a given universal point in time. This is the universal time as that specific number of milliseconds from 0 represents a number of different dates or times in different timezones at any given point. Most of these languages generally have a solid Date and Time API or a good third party library can be found that make viewing this millisecond count in a number of timezones as painless as possible. Unless otherwise specified, if I use a standard data access API in a common language, most will take a date object and convert it into the date and time of the servers default timezone in the specified database format. Figure out how your language data access API and database stores dates and how it interprets them from the database and try to store your dates at the database level in GMT. Likewise when querying make sure that Date objects or variables in your language are representing a millisecond count that is equivalent to the GMT date time stored in the database. Persist Time Zones for Dates that are used in Business Logic What I mean by this is that perhaps if you have a Modified Date column in your database, then it may not be important to business logic, however a column Appointment Date probably will be important. Somewhere in your schema you need to determine where locale specific data is stored and store the Time Zone to define that locale in the appropriate parent table. Your business logic that is considering dates, or your presentation logic that is preparing dates for display must be able to fetch the appropriate Time Zone so that when I am comparing 4:10pm to 5:10pm, that I am comparing dates from the appropriate universal time. 4:10pm EST and 4:10pm PST are seperate points in universal time. Again a good Date and Time API or third party library makes date comparisons easy, when you understand the underlying nature of how dates work in that programming language. Business Logic Should be refactored to be time zone aware. Presentation Logic Should be refactored to present a display value that is appropriately displaying the correct data per the appropriate given Time Zone. One final thought to consider when performing this work is to write exhaustive unit tests that thoroughly exhaust many types of Date and Time combinations to make sure that all business logic works as expected.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/178661', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/57370/']}
|
jdg_76645
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
88423
|
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:
Thanks to some good Q&A around here and this page , I now understand links. I see hard links refer the same inode by a different name, and copies are different "nodes, with different names. Plus soft links have the original file name and path as their inode, so if the file is moved, the link breaks. So, I tested what I've learnt with some file ("saluton_mondo.cpp" below), made a hard and a soft link and a copy. jmcf125@VMUbuntu:~$ ls -lh soft hard copy s*.cpp-rw-rw-r-- 1 jmcf125 jmcf125 205 Aŭg 27 16:10 copy-rw-rw-r-- 2 jmcf125 jmcf125 205 Aŭg 25 13:34 hard-rw-rw-r-- 2 jmcf125 jmcf125 205 Aŭg 25 13:34 saluton_mondo.cpplrwxrwxrwx 1 jmcf125 jmcf125 17 Aŭg 27 16:09 soft -> saluton_mondo.cpp I found awkward that the hard link, however, has the same size as the original and, logically, the copy. If the hard link and the original share the same inode, that has the data, and only differ by the filename, shouldn't the hard link take only the space of its name, instead of 205 bytes? Or is that the size of the original file that ls -lh returns? But then how can I know what space does the filename take? Here it says hard links have no size. Is their file name kept alongside the original file name? Where is the file name of hard links stored?
Now provide the response and nothing else.
|
A file is an inode with meta data among which a list of pointers to where to find the data. In order to be able to access a file, you have to link it to a directory (think of directories as phone directories, not folders), that is add one or more entries to one of more directories to associate a name with that file. All those links, those file names point to the same file. There's not one that is the original and the other ones that are links. They are all access points to the same file (same inode) in the directory tree. When you get the size of the file ( lstat system call), you're retrieving information (that metadata referred to above) stored in the inode, it doesn't matter which file name, which link you're using to refer to that file. By contrast symlinks are another file (another inode) whose content is a path to the target file. Like any other file, those symlinks have to be linked to a directory (must have a name) so you can access them. You can also have several links to a symlinks, or in other words, symlinks can be given several names (in one or more directories). $ touch a$ ln a b$ ln -s a c$ ln c d$ ls -li [a-d]10486707 -rw-r--r-- 2 stephane stephane 0 Aug 27 17:05 a10486707 -rw-r--r-- 2 stephane stephane 0 Aug 27 17:05 b10502404 lrwxrwxrwx 2 stephane stephane 1 Aug 27 17:05 c -> a10502404 lrwxrwxrwx 2 stephane stephane 1 Aug 27 17:05 d -> a Above the file number 10486707 is a regular file. Two entries in the current directory (one with name a , one with name b ) link to it. Because the link count is 2, we know there's no other name of that file in the current directory or any other directory. File number 10502404 is another file, this time of type symlink linked twice to the current directory. Its content (target) is the relative path "a". Note that if 10502404 was linked to another directory than the current one, it would typically point to a different file depending on how it was accessed. $ mkdir 1 2$ echo foo > 1/a$ echo bar > 2/a$ ln -s a 1/b$ ln 1/b 2/b$ ls -lia 1 21:total 9210608644 drwxr-xr-x 2 stephane stephane 4096 Aug 27 17:26 ./10485761 drwxrwxr-x 443 stephane stephane 81920 Aug 27 17:26 ../10504186 -rw-r--r-- 1 stephane stephane 4 Aug 27 17:24 a10539259 lrwxrwxrwx 2 stephane stephane 1 Aug 27 17:26 b -> a2:total 9210608674 drwxr-xr-x 2 stephane stephane 4096 Aug 27 17:26 ./10485761 drwxrwxr-x 443 stephane stephane 81920 Aug 27 17:26 ../10539044 -rw-r--r-- 1 stephane stephane 4 Aug 27 17:24 a10539259 lrwxrwxrwx 2 stephane stephane 1 Aug 27 17:26 b -> a$ cat 1/bfoo$ cat 2/bbar Files have no names associated with them other than in the directories that link them. The space taken by their names is the entries in those directories, it's accounted for in the file size/disk usage of the directories. You'll notice that the system call to remove a file is unlink . That is, you don't remove files, you unlink them from the directories they're referenced in. Once unlinked from the last directory that had an entry to a given file, that file is then destroyed (as long as no process has it opened).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/88423', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/45907/']}
|
jdg_76646
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13020310
|
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 decide on tooltip or popover .. or use both based on need.Here is the issue. I have a bootstrap top stationary navbar on my site. The site is white and the navbar is dark blue. When using the tooltip it overlays over the navbar and has a slight opacity to it which I really don't care for.When using the popover it has no opacity but hides behind the top navbar. So I guess this is a dual question if I want to use both. How do I take off the opacity of the tooltip and make the popover hover over the topbar. Having the option of using both would ideal.
Now provide the response and nothing else.
|
Both of these changes can be solved using a bit of CSS. I recommend that you do not directly modify the Twitter Bootstrap CSS, but instead link to a different stylesheet. Make sure to include this new stylesheet after including the Bootstrap stylesheet so that it overrides the Bootstrap CSS. At the time of writing, the most recent version of Bootstrap is 2.1.1, so all comments are based off of that assumption. For Tooltip The effect of the tooltip is defined in the .tooltip.in rule on line 5003 as follows: .tooltip.in { opacity: 0.8; filter: alpha(opacity=80);} To remove the effect, insert in your new stylesheet the following: .tooltip.in { opacity: 1; filter: alpha(opacity=100);} For Popover On the web, one object is placed under another due to a lower z-index. The z-index of popover is defined in line 5080 as follows: .popover { position: absolute; top: 0; left: 0; z-index: 1010; ...} In this version of Bootstrap, however, the default (static) navbar, does not have an explicit z-index set, so it defaults to 0. Since that is the case, the popover should already be over the navbar. If you are using an older version of Bootstrap, you can fix this by finding the z-index of the navbar and setting the z-index of the popover to a higher number. You can do that by adding the following code to the new stylesheet: .popover { z-index: ###;}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13020310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1763097/']}
|
jdg_76647
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
348568
|
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:
Are there any tips that can help me create clean code when I'm working with something poorly documented and completely new to me? It is easy to write a clean code when we are writing something for the second time. However usually problems we are approaching are new to us. Let's say we're working with a poorly documented library: we have created our first, well-designed implementation, but after compiling it appears it doesn't work. We find some quick fix on the forum and paste it. It still doesn't work, so we are quickly searching for another code snippet to paste. Some time after our clean code is full of quick solutions taken from the Internet. In the end, our program starts working. We look again at our code and it looks obnoxious - one big procedure full of "temporary" solutions we applied while trying to make it work. We've got two choices: rewrite everything from the scratch hoping that refactored code will work, or leave it as it is since it is working. In most companies, the second approach is taken, at least until more tutorials for the library are released. Sometimes we don't have a possibility to debug every single line we're adding. Also when we are working with the badly documented library, usually we need to guess which part of code made our program work. I'm having the biggest problems when providing engineering solutions when debugging is really time-consuming, since you need to launch the program on a real device.
Now provide the response and nothing else.
|
If you do not know how a library works, don't fiddle around with your production code and throw wild guesses of code snippets at it until the code seems to work. This is unprofessional cowboy coding. Instead, write exploration tests to find out how the lib really works, and when you have enough confidence you understood what happens, then write your production code. This forces you to keep your "temporary" solutions in the tests, and helps you to keep the production code clean. Moreover, try to give your test methods good names and some description of what they are testing, then your tests become the missing documentation in form of examples. Besides that, I think @DaveGauer's answer contains lots of good advice. You should try to develop an attitude of cleaning up things immediately, before they run out of your control. Separating your "experimental code" from your production code might help you with this.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/348568', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/271843/']}
|
jdg_76648
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
368021
|
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:
according to Are there guidelines on how many parameters a function should accept? , a method should not have too many parameters. However, some answers suggest this issue can be solved by builder pattern: Builder b=new Builder();b.setParm1("a");b.setParm2("b");...Obj obj=b.createObj(); or encapsulate parameters in a single object. ObjectParam op=new ObjectParam();op.param1="a";op.param2="b";...obj.f(op); But I doubt if it solves the problem, because I think the methods about just align the parameters at better way (i.e.:from horizontally to vertically), but it doesn't change the nature that the tasks depend on too many parameters. And if I want the chain of parameters have better looking, I can use a new line for each parameter like it: https://softwareengineering.stackexchange.com/a/331680/248528 so my question is, is "too many parameters" a visual issue (hard to read a long single line of code), or a logical issue (the task nature depends on too much parameters and needs break down)? If it is more about a visual issue, does a new line for each parameter solves the issue?
Now provide the response and nothing else.
|
It is first and foremost a logical issue (which often comes with visual issues, too). The wrong solution to this is by trying only to improve the visual problem by encapsulate parameters in a single object [...] just align the parameters at better way (i.e.:from horizontally to vertically) Encapsulating parameters in an object does not mean to put five parameters in an arbitrary container with some meaningless name like ObjectParam . Instead, encapsulating a group of parameters in an object should create a new abstraction (or reuse an existing one). Like encapsulating three parameters "X,Y,Z" in a parameter "position of type Point3D , or encapsulating parameters "startDate, endDate" in an object DateInterval or encapsulating parameters documentTitle, documentText, author in an object Document grouping these parameters together If the method in stake has a lot of unrelated parameters you cannot come up with a good grouping name, then it has probably too many parameters and too many responsibilities.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/368021', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/248528/']}
|
jdg_76649
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28351405
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Edit: There is a related issue being discussed on Github but in another mode of deployment (Typesafe Activator UI and not Docker). I was trying to simulate a system reboot in order to verify the Docker restart policy which declares to be able to re-run containers in the correct order. I have a Play framework application written in Java. The Dockerfile looks like this: FROM ubuntu:14.04## [Java8, ...]#RUN chmod +x /opt/bin/playappCMD ["/bin/bash"] I start it using $ docker run --restart=always -d --name playappcontainer "./opt/bin/playapp" . When I $ service docker stop && service docker restart and then $ docker attach playappcontainer the console tells me: Play server process ID is 7This application is already running (Or delete /opt/RUNNING_PID file) Edit: Same result when I follow the recommendation of the Play documentation to change the location of the file to /var/run/play.pid with -Dpidfile.path=/var/run/play.pid . Play server process ID is 7This application is already running (Or delete /var/run/play.pid file). So: Why is the file containing the RUNNING_PID not deleted when the docker daemon stops, gets restartet and restarts previously run containers? When I $ docker inspect playappcontainer , it tells me: "State": { "ExitCode": 255, "FinishedAt": "2015-02-05T17:52:39.150013995Z", "Paused": false, "Pid": 0, "Restarting": true, "Running": true, "StartedAt": "2015-02-05T17:52:38.479446993Z"}, Although: The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL. from the Docker reference on $ docker stop To kill a running Play server, it is enough to send a SIGTERM to the process to properly shutdown the application. from the Play Framework documentation on stopping a Play application
Now provide the response and nothing else.
|
I've just dockerized a Play! application and was also running into this issue - restarting the host caused the Play! application to fail to start in its container because RUNNING_PID had not been deleted. It occurred to me that as the Play! application is the only process within its container, always has the same PID, and is taken care of by Docker, the RUNNING_PID file is (to the best of my knowledge) not actually needed. As such I overrode pidfile.path to /dev/null by placing javaOptions in Universal ++= Seq( "-Dpidfile.path=/dev/null") in my project's build.sbt. And it works - I can reboot the host (and container) and my Play! application starts up fine. The appeal for me of this approach is it does not require changing the way the image itself is produced by sbt-native-packager, just the way the application runs within it. This works with sbt-native-packager 1.0.0-RC2 and higher (because that release includes https://github.com/sbt/sbt-native-packager/pull/510 ).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28351405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/795734/']}
|
jdg_76650
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3955223
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There's plenty of discussion on the best algorithm - but what if you're already in production? How do you upgrade without having to reset on the user? EDIT/DISCLAIMER: Although I originally wanted a "quick fix" solution and chose orip's response, I must concede that if security in your application is important enough to be even bothering with this issue, then a quick fix is the wrong mentality and his proposed solution is probably inadequate.
Now provide the response and nothing else.
|
One option is to make your stored hash include an algorithm version number - so you start with algorithm 0 (e.g. MD5) and store 0:ab0123fe then when you upgrade to SHA-1, you bump the version number to 1: 1:babababa192df1312 (no, I know these lengths probably aren't right). That way you can always tell which version to check against when validating a password. You can invalidate old algorithms just by wiping stored hashes which start with that version number. If you've already got hashes in production without a version number, just choose a scheme such that you can easily recognise unversioned hashes - for example, using the above scheme of a colon, any hash which doesn't contain a colon must by definition predate the versioning scheme, so can be inferred to be version 0 (or whatever).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3955223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/476426/']}
|
jdg_76651
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
131009
|
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:
General question: Could some explain what the command apt-get update does and when I really should use it? Remarks Please give a detailed answer . Not just a copy of the man page, unless your version is really detailed (I put one definition from man page below). apt-get update : Used to re-synchronize the package index files from their sources. The indexes of available packages are fetched from the location(s) specified in /etc/apt/sources.list(5). An update should always be performed before an upgrade or dist-upgrade. Sub-questions: Where is stored the package index? On a database? On a file? What happens if I do apt-get install without updating the cache? Is there a chance that the remote package would not exist anymore and that the link would be broken? Is there some agreed politic about deb repositories? For example, should a repository only contains the last version of a package, or on the contrary should it contains all versions available for a specific distribution release? Context I ask my question because I am studying the Docker framework . One of its feature is the Dockerfile , which allows you to build a sort of OS image by executing some instruction from this file.One property of this image is that it should always be the same, whatever the context is (time of build, etc). I'm afraid that if I launch apt-get update command at different time, the result would be different and so my images would be different.
Now provide the response and nothing else.
|
apt-get update downloads the list of available packages. The list of packages can change over time. New packages are added, and old packages are removed. Thus if you have a really old cache, and you try to do an apt-get install , it might try to download a package which no longer exists. How long an old package is kept in a repository is up to the repo maintainer (your distribution). As such, if you're using something like docker, where the cache might be very out of date, you should always run apt-get update before installing any packages. The reason for removing and adding packages is mostly bug fixes & security updates. Though if you're using 3rd party repos like PPA, anything goes. When using something like docker for containerization in a corporate environment, you should build the container once, and then move that container through your various release environments (development, staging, production), and not rebuild the container each time. This will make sure you don't get a different container that hasn't been tested. To answer your question of where the cache files live, /var/lib/apt/lists .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/131009', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/61862/']}
|
jdg_76652
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19093
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Genesis 4:1 states: וְהָאָדָם, יָדַע אֶת-חַוָּה אִשְׁתּוֹ; וַתַּהַר, וַתֵּלֶד אֶת-קַיִן, וַתֹּאמֶר, קָנִיתִי אִישׁ אֶת-יְהוָה. And Adam knew (אֶת־) Eve his wife; and she conceived, and bare (אֶת־) Cain, and said, I have gotten a man from (אֶת־) the Lord. (Genesis 4:1 KJV) The same word appears to be repeated. The first and second times it is not translated, the third time it is. In addition the two are treated as a different word, as Strong's #853 and #854 . What is the difference between the two?
Now provide the response and nothing else.
|
This is not the "same word" repeated and used in different ways. These are homonyms , i.e., two different words: the first אֶת־ is the sign of the definite direct object (= I. אֵת at link -- as discussed in relation to Genesis 1), which is untranslatable -- there is no English equivalent. When suffixes are added to it, it has the form ʾōt - or ʾôt -. the second אֶת־ is the preposition " with " (= II. אֵת at link); when suffixes are added to it, it has the form ʾitt- . These are two different words. By way of analogy, the English word " rock " might be a helpful example: "rock" as a noun ("stone, solid mineral", like granite) comes from Old French rocque ; but "rock" as a verb ("move from side-to-side") comes from Middle Dutch rucken . They might look the same, but they have different origins and different meanings
|
{}
|
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/19093', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/8450/']}
|
jdg_76653
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
613268
|
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, $f:(-1,1)\rightarrow\mathbb{R}$ be a function continuous at $x=0$ and given that $f(x)=f(x^2)$ for all $x\in(-1,1)$. Prove that, $f(x)=f(0)$ $\forall x\in(-1,1)$.Ok. First give me some hint.
Now provide the response and nothing else.
|
$$f(x)=f(x^2)=f(x^4)=\ldots = f(x^{2^n})$$ where $n$ is any natural number So if we let $n$ be infinitely large then, since $x\in (−1,1)$,$x^{2^n}$ tends to $0$ Hence, $$f(x)=f(0)$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/613268', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/108546/']}
|
jdg_76654
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
603755
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to dynamically add IPs to a block list via htaccess. I was hoping someone could tell me if the following will work in my case (I'm unsure how to test via localhost). My .htaccess file will have the following by default: order allow,denyallow from all IPs will be dynamically appended: Order Deny,AllowAllow from allDeny from 192.168.30.1 The way I understand this is that it is by default allow all with the optional list of deny rules. If I'm not mistaken Order Deny,Allow will look at the Deny list first, is this correct? And does the Allow from all rule need to be at the end? EDIT 1 If I'm not mistaken I need to do this based on jeffatrackaid's answer: Order Allow,DenyAllow from allDeny from 192.168.30.1 EDIT 2 For the sake of completeness, this is probably more appropriate for my requirements: Order Deny,AllowDeny from 192.168.30.1
Now provide the response and nothing else.
|
This rule allows everyone into your site. Order Deny,AllowAllow from allDeny from 192.168.30.1 The Order directive determines the order in which your rules are processed. With Order deny,allow the deny list will be processed first then the allow list. With Apache, all rules are processed with the last one matching being the effective rule. So in this case, your last rule would be allow from all . This means that 192.168.30.1 would initially be denied but then allowed since the allow rules are processed last. This would produce the same result Order Deny,AllowAllow from allDeny from 192.168.30.1Allow from 192.168.30.1 Think of it this way. The allow/deny rules are simply separate lists of IPs to be allowed/denied. The order directive determines the order in which these lists areprocessed. Apache evaluates all rules and acts on the result of thelast matching rule. The major confusion is that this is very different from how firewalls work where rule order and first match is often what determines access. See: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/603755', 'https://serverfault.com', 'https://serverfault.com/users/224080/']}
|
jdg_76655
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26483724
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With the release of OS X 10.10 Yosemite, Apple upgraded its Apache server to version 2.4. At release time, mod_perl 2.0.8 was incompatible with Apache 2.4, and mod_perl 2.0.9 had not yet been officially released ( more info ). So, Apache was included without mod_perl. I work locally on a web site using perl and need to install mod_perl. I'm an experienced programmer, but I have never done anything like this before and have only my main machine to work on. I don't mind spending some time to figure this out, but I can't afford to bork my local server. How does one install mod_perl on OS X Yosemite? Sub-questions: which version should I install? do I download it to the install location or elsewhere? where do I install it? are there other dependencies that need to be installed beforehand? do I have to re-create the apache install or is the mod_perl installation self-contained? I'm experienced in bash and very comfortable using Terminal.
Now provide the response and nothing else.
|
mod_perl 2.0.8 (latest stable) won't cut it--it's unaware of the deprecation of MPM_NAME in apache 2.4.xDownload the latest dev via svn: svn checkout https://svn.apache.org/repos/asf/perl/modperl/trunk/ mod_perl-2.0 The Changes file lists this version as 2.0.9-dev Xcode 6.01 won't cut it--it's apache headers will make mod_perl think you're running apache 2.2.26; get Xcode 6.1 (released Oct 20). Makefile.PL will still have trouble finding ap_release.h (to get your apache version). It's here: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/apache2/ap_release.h Makefile.PL will look by default in /usr/include/apache2 . It will also look for apr headers in /usr/include/apr-1 because the Yosemite-included /usr/bin/apr-1-config will tell it that's where they are (they're actually in /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/apr-1 ) /usr/bin/apr-1-config --includedir/usr/include/apr-1 I tried setting env vars MP_AP_PREFIX and MP_APR_CONFIG appropriately, but those values seemed to be ignored. So I made things easier on myself: $ sudo ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/apache2 /usr/include/apache2$ sudo ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/apr-1 /usr/include/apr-1 (thanks to Sean Coyne) Per Jason A. Crome's blog post "llvm/clang on OS X defaults to C99, but mod_perl expects the 89 "standard" $ perl Makefile.PL MP_CCOPTS=-std=gnu89; make ; sudo make install The LoadModule line for mod_perl has been removed from Yosemite's /etc/apache2/httpd.conf file. Add LoadModule perl_module libexec/apache2/mod_perl.so to the module section of /etc/apache2/httpd.conf
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26483724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/72958/']}
|
jdg_76656
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29753629
|
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 using MAMP 3.2.1 on Mac OS X 10.9.5 and trying to change my Ports so I can go to localhost/... instead of localhost:8888/... in my browser. When I go to change the ports in Preferences the option I have is "Set Web & MySQL ports to 80 & 3306", however when I do this, the Apache server does not restart. I have seen other posts that say rename envvars to __envvars but mine is called envvars_ so I'm guessing that's irrelevant. Any suggestions?
Now provide the response and nothing else.
|
This is rather older post but I faced the same issue today. As it turned out there was already one more Apache running on port 80 and was clashing with the new MAMP port setup. Hopefully this will help you: Setup ports to 80 (Apache), 81 (nginx) and 3306 (mysql) in your MAMP configuration. Quit your MAMP From CLI type sudo apachectl stop From CLI type ps -A | grep httpd and you shouldn't see any running process (apart from your grep) Start your MAMP (at this point MAMP should start Apache since 80 port is not in use)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29753629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4653673/']}
|
jdg_76657
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8151333
|
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 just found an interesting problem between translating some data: VB.NET: CByte(4) << 8 Returns 4 But C#: (byte)4 << 8 Returns 1024 Namely, why does VB.NET: (CByte(4) << 8).GetType() return type {Name = "Byte" FullName = "System.Byte"} Yet C#: ((byte)4 << 8).GetType() returns type {Name = "Int32" FullName = "System.Int32"} Is there a reason why these two treat the binary shift the same? Following from that, is there any way to make the C# bit shift perform the same as VB.NET (to make VB.NET perform like C# you just do CInt(_____) << 8 )?
Now provide the response and nothing else.
|
According to http://msdn.microsoft.com/en-us/library/a1sway8w.aspx byte does not have << defined on it for C# (only int, uint, long and ulong. This means that it will use an implciit conversion to a type that it can use so it converts it to int before doing the bit shift. http://msdn.microsoft.com/en-us/library/7haw1dex.aspx says that VB defines the operation on Bytes. To prevent overflow it applies a mask to your shift to bring it within an appropriate range so it is actually in this case shifting by nothing at all. As to why C# doesn't define shifting on bytes I can't tell you. To actually make it behave the same for other datatypes you need to just mask your shift number by 7 for bytes or 15 for shorts (see second link for info).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8151333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288747/']}
|
jdg_76658
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
654454
|
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 $A$ be a ring and $A^\times$ be the collection of unit elements of $A$. If $A$ is a commutative ring, then $A^\times$ is a commutative group. Conversely, if $A^\times $ is a commutative group, does $A$ necessarily be a commutative ring? Is there any counterexample?
Now provide the response and nothing else.
|
Let $K$ be a field. Consider the free $K$-algebra on two generators $x,y$. Its unit group is $K^*$, hence commutative, but $x,y$ don't commute. Here is a more explicit example: Consider the ring of upper-triangular $2 \times 2$-matrices over $\mathbb{F}_2$. It has $8$ elements and it is in fact the smallest noncommutative ring. The unit group has just two elements, namely the identity matrix and $\begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}$. A group of order $2$ is commutative.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/654454', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/92728/']}
|
jdg_76659
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
198584
|
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:
a) Relays used in the construction of electric circuits function properly with probability .9. Assuming that the circuits operate independently, what is the probability that current will flow when the relays are activated? b) If we know that current is flowing, what is theprobability that switches 1 and 4 are functioning properly? I denote $F_1$ the event switch 1 fails and $W_1$ the event switch 1 works and use the subscript $_S$ for the whole system and $1\leq i\neq j\neq k\neq l\leq4$ . Part a) is easy: this is $1-P(F_S)$ and $$P(F_S)=P(F_S|F_iF_jW_kW_l)P(F_iF_jW_kW_l)+P(F_S|F_iF_jF_kW_l)P(F_iF_jF_kW_l)+P(F_S|F_iF_jF_kF_l)P(F_iF_jF_kF_l)\\=4.1^2.9^2+4*.1^3*.9+1^4=.9639$$ (which, the back pages of the book confirms, is the correct answer). Now, for part b) I think there are 7 combinations that allow the current to flow: $$\{1:W_2W_4F_1F_3\}\\\{2:W_1W_3F_2F_4\}\\\{3:W_1W_2W_3F_4\}\\\{4:W_1W_2W_4F_3\}\\\{5:W_1W_3W_4F_2\}\\\{6:W_2W_3W_4F_1\}\\\{7:W_1W_2W_3W_4\}$$ Of these only combination 7,5 and 4 have $W_1W_4$ in them so that $$P(W_1W_4??|F_S)=\frac{2*.1*.9^3+.9^4}{.9639}\approx.831$$ And when I do a classical approach using the Bayes formula I get to the same number. However the book says the correct answer is $.916$. I must add, I have done 40 exercises off this book already and it would be the first time one of the answers is incorrect. The book is very well edited. Therefore my guess is that I misunderstand the question. So, here is my question: what is my mistake?
Now provide the response and nothing else.
|
I got the same answer, using a probability tree. A simulation supports it, as in this R example. N <- 1e6set.seed(17)x <- matrix(runif(4*N) < 0.9, nrow=4)flows <- (x[1,] & x[3,]) | (x[2,] & x[4,])on.1.4 <- x[1,] & x[4,]mean(flows) # Should approximate 0.9639sum(flows & on.1.4) / sum(flows) The output from these million iterations (in which 963,956 evidenced a flow) is [1] 0.963956[1] 0.8320089 The first number is comfortably close to $0.9639$ while the other clearly shows $0.832$ is plausible while $0.916$ is not. The standard error in the second calculation will be approximately $$\sqrt{0.832(1-0.832)/963956} \approx 0.00019,$$ showing the simulated estimate of $0.8320089$ is within $0.4$ standard errors of $0.9^3(1 + 2(0.1)) \approx 0.83193$. Because of the special nature of the probabilities involved, we can also exhaustively enumerate the possibilities, as in this code: p <- c(rep(1,9), 0)X <- as.matrix(expand.grid(G1=p, G2=p, G3=p, G4=p))flows <- (X[,1] & X[,3]) | (X[,2] & X[,4])on <- X[,1] & X[,4]sum(flows & on)sum(flows) The output shows the completely accurate answer is $8019/9639 = 0.8319328\cdots$. Of course, the computer can easily enumerate all $16$ possibilities in the probability tree. But you and I already did that manually, with the same results.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/198584', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/42397/']}
|
jdg_76660
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33502419
|
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 determine how I might save a collapsible panel's collapsed state using $.cookie. This question has been helpful so far, but still missing the end solution. Any solutions I have found so far have only saved the last rolled down panel so when the page is reloaded the only panel saved is the last one. What I need is to save all panels that are rolled down rather than just one. Link to jCookie plugin on Github. Link to demo on JSFiddle UPDATE It has been suggested that LocalStorage is a more appropriate solution to what I am trying to achieve. If you can comment on why and what local storage is that would be much appreciated. UPDATE 2 because of the suggestion that local storage would be an improvement over using cookies for this problem. The selected answer was based off this. However as mentioned by Robin, there are downsides to using this technique on HTTPS sites. HTML <div class="panel panel-default"> <div data-toggle="collapse" data-target="#panel1" class="panel-heading collapsed"> <h4 class="panel-title"> <a> Panel 1 </a> </h4> </div> <div id="panel1" class="panel-collapse collapse"> <div class="panel-body"> </div> </div></div><div class="panel panel-default"> <div data-toggle="collapse" data-target="#panel2" class="panel-heading collapsed"> <h4 class="panel-title"> <a> Panel 2 </a> </h4> </div> <div id="panel2" class="panel-collapse collapse"> <div class="panel-body"> </div> </div></div><div class="panel panel-default"> <div data-toggle="collapse" data-target="#panel3" class="panel-heading collapsed"> <h4 class="panel-title"> <a> Panel 3 </a> </h4> </div> <div id="panel3" class="panel-collapse collapse"> <div class="panel-body"> </div> </div></div> jQUERY $(".panel .panel-collapse").on('shown.bs.collapse', function (){ var active = $(this).attr('id'); $.cookie('activePanelGroup', active);});$(".panel .panel-collapse").on('hidden.bs.collapse', function (){ $.removeCookie('activePanelGroup');});var last = $.cookie('activePanelGroup');if (last != null){ //remove default collapse settings $(".panel .panel-collapse").removeClass('in'); //show the account_last visible group $("#" + last).addClass("in");}
Now provide the response and nothing else.
|
This will create a cookie for every panel when it's shown and remove the cookie when the panel is hidden. $(".panel .panel-collapse").on('shown.bs.collapse', function (){ var active = $(this).attr('id'); $.cookie(active, "1");});$(".panel .panel-collapse").on('hidden.bs.collapse', function (){ var active = $(this).attr('id'); $.removeCookie(active);}); So, when loading the document, we check every cookie and expand the panel. $(document.ready(function(){ var panels=$.cookie(); //get all cookies for (var panel in panels){ //<-- panel is the name of the cookie if ($("#"+panel).hasClass('panel-collapse')) // check if this is a panel { $("#"+panel).collapse("show"); } } }); USING LOCALSTORAGE However, as someone suggested, using localStorage may be a better option. localStorage is great for this. $(".panel .panel-collapse").on('shown.bs.collapse', function (){ var active = $(this).attr('id'); var panels= localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels); if ($.inArray(active,panels)==-1) //check that the element is not in the array panels.push(active); localStorage.panels=JSON.stringify(panels);});$(".panel .panel-collapse").on('hidden.bs.collapse', function (){ var active = $(this).attr('id'); var panels= localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels); var elementIndex=$.inArray(active,panels); if (elementIndex!==-1) //check the array { panels.splice(elementIndex,1); //remove item from array } localStorage.panels=JSON.stringify(panels); //save array on localStorage}); When you load the page, get the values of localStorage and show the panels. $(document.ready(function(){ var panels=localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels); //get all panels for (var i in panels){ //<-- panel is the name of the cookie if ($("#"+panels[i]).hasClass('panel-collapse')) // check if this is a panel { $("#"+panels[i]).collapse("show"); } } }); EDIT: See it working: FIDDLE
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33502419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2500842/']}
|
jdg_76661
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30486033
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
(An update to this question has been added.) I am a graduate student at the university of Ghent, Belgium; my research is about emotion recognition with deep convolutional neural networks. I'm using the Caffe framework to implement the CNNs. Recently I've run into a problem concerning class imbalance. I'm using 9216 training samples, approx. 5% are labeled positively (1), the remaining samples are labeled negatively (0). I'm using the SigmoidCrossEntropyLoss layer to calculate the loss. When training, the loss decreases and the accuracy is extremely high after even a few epochs. This is due to the imbalance: the network simply always predicts negative (0). (Precision and recall are both zero, backing this claim) To solve this problem, I would like to scale the contribution to the loss depending on the prediction-truth combination (punish false negatives severely). My mentor/coach has also advised me to use a scale factor when backpropagating through stochastic gradient descent (sgd): the factor would be correlated to the imbalance in the batch. A batch containing only negative samples would not update the weights at all. I have only added one custom-made layer to Caffe: to report other metrics such as precision and recall. My experience with Caffe code is limited but I have a lot of expertise writing C++ code. Could anyone help me or point me in the right direction on how to adjust the SigmoidCrossEntropyLoss and Sigmoid layers to accomodate the following changes: adjust the contribution of a sample to the total loss depending on the prediction-truth combination (true positive, false positive, true negative, false negative). scale the weight update performed by stochastic gradient descent depending on the imbalance in the batch (negatives vs. positives). Thanks in advance! Update I have incorporated the InfogainLossLayer as suggested by Shai . I've also added another custom layer that builds the infogain matrix H based on the imbalance in the current batch. Currently, the matrix is configured as follows: H(i, j) = 0 if i != jH(i, j) = 1 - f(i) if i == j (with f(i) = the frequency of class i in the batch) I'm planning on experimenting with different configurations for the matrix in the future. I have tested this on a 10:1 imbalance. The results have shown that the network is learning useful things now: (results after 30 epochs) Accuracy is approx. ~70% (down from ~97%); Precision is approx. ~20% (up from 0%); Recall is approx. ~60% (up from 0%). These numbers were reached at around 20 epochs and didn't change significantly after that. !! The results stated above are merely a proof of concept, they were obtained by training a simple network on a 10:1 imbalanced dataset. !!
Now provide the response and nothing else.
|
Why don't you use the InfogainLoss layer to compensate for the imbalance in your training set? The Infogain loss is defined using a weight matrix H (in your case 2-by-2) The meaning of its entries are [cost of predicting 1 when gt is 0, cost of predicting 0 when gt is 0 cost of predicting 1 when gt is 1, cost of predicting 0 when gt is 1] So, you can set the entries of H to reflect the difference between errors in predicting 0 or 1. You can find how to define matrix H for caffe in this thread . Regarding sample weights, you may find this post interesting: it shows how to modify the SoftmaxWithLoss layer to take into account sample weights. Recently, a modification to cross-entropy loss was proposed by Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He, Piotr Dollár Focal Loss for Dense Object Detection , (ICCV 2017) . The idea behind focal-loss is to assign different weight for each example based on the relative difficulty of predicting this example (rather based on class size etc.). From the brief time I got to experiment with this loss, it feels superior to "InfogainLoss" with class-size weights.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30486033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4841248/']}
|
jdg_76662
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14130315
|
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 my ant script I want to exit (stop executing build) without failing when a condition is met. I have tried to use: <if> <equals arg1="${variable1}" arg2="${variable2}" /> <then> <fail status="0" message="No change, exit" /> </then></if> Ant script is stopped on condition but build is failed. I want to the build to be stopped but with no errors. I'm using "Invoke Ant" step in Jenkins. Thanks.
Now provide the response and nothing else.
|
I would suggest to refactor your ant script by reconsidering your approach. If you approach your problem with "execution of a build when a certain condition is met" instead of "failing the build if another condition is met" it is easier to implement: <!-- add on top of your build file --><if> <equals arg1="${variable1}" arg2="${variable2}" /> <then> <property name="runBuild" value="true"/> </then> <else> <property name="runBuild" value="false"/> </else></if><!-- add to the target that shall be executed conditionally --><target name="myTarget" if="${runBuild}">...<!-- exit message as separate target --><target name="exitTarget" unless="${runBuild}"> <echo message="No Change, exit" /></target>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14130315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1944161/']}
|
jdg_76663
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2709406
|
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 $p$ be a polynomial of fourth degree having extremum at $x=1$ and $x=2$ and $\lim \limits_{x \to0}\left(1+\frac{p(x)}{x^2}\right)=2$. Then the value to $p(2)$ is? This problem was in my book, I tried but I am not getting a clue as to how to begin.
Now provide the response and nothing else.
|
Note that the limit exists if $$\lim \limits_{x \to0} \frac{p(x)}{x^2}=1$$ and if $p(0)=0$, then by L'Hôpital $$\lim \limits_{x \to0} \frac{p(x)}{x^2}=\lim \limits_{x \to0} \frac{p'(x)}{2x}=1$$ then $p'(0)=0$ and by L'Hôpital $$\lim \limits_{x \to0} \frac{p'(x)}{2x}=\lim \limits_{x \to0} \frac{p''(x)}{2}=1\implies p''(0)=2$$ Moreover we know that $p'(1)=p'(2)=0$. Then for $p(x)=ax^4+bx^3+cx^2+dx+e=0$ we deduce $p(0)=0 \implies e=0$ $p'(0)=0 \implies d=0$ $p''(0)=2 \implies 2c=2 \implies c=1 $ then $p(x)=ax^4+bx^3+x^2=0$ and now apply $p'(1)=0$ and $p'(2)=0$ that is $4a+3b+2=0$ $32a+12b+4=0$ that is $a=\frac14$ and $b=-1$ then $$p(x)=\frac14x^4-x^3+x^2$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2709406', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/527573/']}
|
jdg_76664
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21968161
|
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 the following textfile into my SdCard.now i want to parse this file via Json parser,and i want to parse and read this file and display data into my textview,how i can do this? {"data": [ { "id": "1", "title": "Farhan Shah", "duration": 10, }, { "id": "2", "title": "Noman Shah", "duration": 10, }, { "id": "3", "title": "Ahmad Shah", "duration": 10, }, { "id": "4", "title": "Mohsin Shah", "duration": 10, }, { "id": "5", "title": "Haris Shah", "duration": 10, } ]} This is the code: File sdcard = Environment.getExternalStorageDirectory(); //Get the text file File file = new File(sdcard,"textarabics.txt"); String UTF8 = "utf8"; int BUFFER_SIZE = 8192; //Read text from file StringBuilder text = new StringBuilder(); i get the file,but now i have no idea that how i can parse the data?
Now provide the response and nothing else.
|
Read the JSON file using File from SD card and use JSONObject to parse it. Here a starting code: import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;public class ReadJsonFile {public ReadFile (){ try { File yourFile = new File(Environment.getExternalStorageDirectory(), "path/to/the/file/inside_the_sdcard/textarabics.txt"); FileInputStream stream = new FileInputStream(yourFile); String jsonStr = null; try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); jsonStr = Charset.defaultCharset().decode(bb).toString(); } catch(Exception e){ e.printStackTrace(); } finally { stream.close(); }/* String jsonStr = "{\n\"data\": [\n {\n \"id\": \"1\",\n \"title\": \"Farhan Shah\",\n \"duration\": 10\n },\n {\n \"id\": \"2\",\n \"title\": \"Noman Shah\",\n \"duration\": 10\n },\n {\n \"id\": \"3\",\n \"title\": \"Ahmad Shah\",\n \"duration\": 10\n },\n {\n \"id\": \"4\",\n \"title\": \"Mohsin Shah\",\n \"duration\": 10\n },\n {\n \"id\": \"5\",\n \"title\": \"Haris Shah\",\n \"duration\": 10\n }\n ]\n\n}\n"; */ JSONObject jsonObj = new JSONObject(jsonStr); // Getting data JSON Array nodes JSONArray data = jsonObj.getJSONArray("data"); // looping through All nodes for (int i = 0; i < data.length(); i++) { JSONObject c = data.getJSONObject(i); String id = c.getString("id"); String title = c.getString("title"); String duration = c.getString("duration"); //use > int id = c.getInt("duration"); if you want get an int // tmp hashmap for single node HashMap<String, String> parsedData = new HashMap<String, String>(); // adding each child node to HashMap key => value parsedData.put("id", id); parsedData.put("title", title); parsedData.put("duration", duration); // do what do you want on your interface } } catch (Exception e) { e.printStackTrace(); } }} Ddon't forget to add read storage on your mainfest: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21968161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2919655/']}
|
jdg_76665
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21279188
|
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 want to test an inclusion of a module into a class. I am trying define a new class in RSpec: describe Statusable do let(:test_class) do class ModelIncludingStatusable < ActiveRecord::Base include Statusable statuses published: "опубликовано", draft: "черновик" end end describe '#statuses' do it 'sets STATUSES for a model' do test_class::STATUSES.should == ["опубликовано", "черновик"] end endend And I get an error: TypeError: [ActiveModel::Validations::InclusionValidator] is not a class/module This is probably because in Statusable I have: validates_inclusion_of :status, :in => statuses, :message => "{{value}} должен быть одним из: #{statuses.join ','}" But if I comment it out, I get: TypeError: ["опубликовано", "черновик"] is not a class/module Maybe new class definition isn't the best option, what do I do then? And even if it's not, how can I define a class in RSpec? And how do I fix this error?
Now provide the response and nothing else.
|
Do not define new constant in tests otherwise it will pollute other tests. Instead, use stub_const . Also, for this is an unit test of Statusable module. If ActiveRecord model is not a necessity, better not to use it. You can also use class_eval to avoid not opening this class(no matter fake or not) actually describe Statusable do before do stub_const 'Foo', Class.new Foo.class_eval{ include Statusable } Foo.class_eval{ statuses published: "foo", draft: "bar"} end context '#statuses' do it 'sets STATUSES for a model' do FOO::STATUSES.should == ["foo", "bar"] end endend Though I copied your assertion, I would suggest not to insert a constant say STATUS into the class/module(Foo) who includes this module. Instead, a class method would be better expect(Foo.status).to eq(["foo", "bar"])
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21279188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801058/']}
|
jdg_76666
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
383039
|
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:
How do you find $$\lim_{n \to\infty} \dfrac{\ln(\ln(\frac{n}{n-1}))}{\ln(n)}$$ I know it's $-1$, but I had to plot it.
Now provide the response and nothing else.
|
Hint: You can use L'hopital's rule twice. Added: If you use L'hopital's rule twice then you get the expression $$ -\frac{n}{n-1}. $$ Another approach: $$ \dfrac{\ln(\ln(\frac{n}{n-1}))}{\ln(n)} = \dfrac{\ln(-\ln(1-\frac{1}{n}))}{\ln(n)}= \dfrac{\ln(-(-\frac{1}{n}-O(\frac{1}{n^2})))}{\ln(n)}\sim \frac{\ln(\frac{1}{n})}{\ln(n)}=-\frac{\ln(n)}{\ln(n)}=-1.$$ Note that, in the above derivations, we used the Taylor series of $$\ln(1-x)=-x-\frac{x^2}{2}-\dots\,,$$ and the following property of $\ln(x)$ $$ \ln(1/a) = -\ln(a). $$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/383039', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/73391/']}
|
jdg_76667
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54767397
|
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 problem with bottom app bar, because I want the icons to be displayed to me in the first picture Instead I got this:
Now provide the response and nothing else.
|
You can place a custom layout inside your BottomAppBar .The only thing is that you will need to align items in your custom layout manually. <com.google.android.material.bottomappbar.BottomAppBar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" style="@style/Widget.MaterialComponents.BottomAppBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:backgroundTint="@android:color/white" app:contentInsetLeft="0dp" app:contentInsetStart="0dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageButton android:id="@+id/first_menu_item" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginBottom="8dp" android:src="@drawable/ic_first_icon" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@+id/second_menu_item" app:layout_constraintHorizontal_chainStyle="packed" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageButton android:id="@+id/second_menu_item" android:layout_width="0dp" android:layout_height="wrap_content" android:src="@drawable/ic_second_icon" app:layout_constraintBottom_toBottomOf="@+id/first_menu_item" app:layout_constraintEnd_toStartOf="@+id/placeholder" app:layout_constraintHorizontal_chainStyle="packed" app:layout_constraintStart_toEndOf="@+id/first_menu_item" /> <View android:id="@+id/placeholder" android:layout_width="70dp" android:layout_height="0dp" android:visibility="invisible" app:layout_constraintBottom_toBottomOf="@+id/first_menu_item" app:layout_constraintEnd_toStartOf="@+id/third_menu_item" app:layout_constraintHorizontal_chainStyle="packed" app:layout_constraintStart_toEndOf="@+id/second_menu_item" app:layout_constraintTop_toTopOf="@+id/first_menu_item" /> <ImageButton android:id="@+id/third_menu_item" android:layout_width="0dp" android:layout_height="wrap_content" android:src="@drawable/ic_third_icon" app:layout_constraintBottom_toBottomOf="@+id/first_menu_item" app:layout_constraintEnd_toStartOf="@+id/fourth_menu_item" app:layout_constraintHorizontal_chainStyle="packed" app:layout_constraintStart_toEndOf="@+id/placeholder" /> <ImageButton android:id="@+id/fourth_menu_item" android:layout_width="0dp" android:layout_height="wrap_content" android:src="@drawable/ic_fourth_icon" app:layout_constraintBottom_toBottomOf="@+id/first_menu_item" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_chainStyle="packed" app:layout_constraintStart_toEndOf="@+id/third_menu_item" app:layout_constraintTop_toTopOf="@+id/first_menu_item" /> </androidx.constraintlayout.widget.ConstraintLayout></com.google.android.material.bottomappbar.BottomAppBar> You will have something like this:
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54767397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8874893/']}
|
jdg_76668
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19049822
|
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 want to have an custom OpenFileDialog form within my project where I can add/remove buttons and customize whatever I want like a normal form. This is mainly so that it fits into the theme I am using, additionally, I can add custom buttons. Is there any tutorials on how I could construct my own? Are there any pre-existing projects I can use straight out of the download?
Now provide the response and nothing else.
|
I hope that will fit your requirements: You will need one TreeView and an ImageList Code You will need System.Runtime.InteropServices; And following code to get the associated icon from the path: [StructLayout(LayoutKind.Sequential)] public struct SHFILEINFO { public IntPtr hIcon; public IntPtr iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; class Win32 { public const uint SHGFI_ICON = 0x100; public const uint SHGFI_LARGEICON = 0x0; // 'Large icon public const uint SHGFI_SMALLICON = 0x1; // 'Small icon [DllImport("shell32.dll")] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); } private int GetIconOfFile_Folder(string Path) { IntPtr hImgSmall; //the handle to the system image list IntPtr hImgLarge; //the handle to the system image list string fName; // 'the file name to get icon from SHFILEINFO shinfo = new SHFILEINFO(); //Use this to get the small Icon hImgSmall = Win32.SHGetFileInfo(Path, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON); //Use this to get the large Icon //hImgLarge = SHGetFileInfo(fName, 0, //ref shinfo, (uint)Marshal.SizeOf(shinfo), //Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON); //The icon is returned in the hIcon member of the shinfo //struct System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon); imageList1.Images.Add(myIcon); return imageList1.Images.Count - 1; } Use following Method to Get all your Drives (best place it in your constructor/Form_Load): private void GetAllDrives() { DriveInfo[] drives = DriveInfo.GetDrives(); foreach (var drive in drives) { TreeNode rootTreeNode = new TreeNode(); rootTreeNode.Text = drive.Name; rootTreeNode.Tag = drive.Name; rootTreeNode.ImageIndex = GetIconOfFile_Folder(drive.Name); rootTreeNode.SelectedImageIndex = rootTreeNode.ImageIndex; rootTreeNode.Nodes.Add(" "); //Placeholder to enable expanding (+) treeView1.Nodes.Add(rootTreeNode); } } Then you will need an EventHandler for the Expand-Event, which will call the method GetFilesAndFolder() private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e) { e.Node.Nodes.Clear(); GetFilesAndFolder(e.Node, (string)e.Node.Tag); } private void GetFilesAndFolder(TreeNode tn, string Path) { try { string[] Directories = Directory.GetDirectories(Path); string[] Files = Directory.GetFiles(Path); foreach (string dir in Directories) { TreeNode dirTreeNode = new TreeNode(); dirTreeNode.Tag = dir; dirTreeNode.Text = new DirectoryInfo(dir).Name; dirTreeNode.ImageIndex = GetIconOfFile_Folder(dir); dirTreeNode.SelectedImageIndex = dirTreeNode.ImageIndex; dirTreeNode.Nodes.Add(" "); tn.Nodes.Add(dirTreeNode); } foreach (string file in Files) { TreeNode fileTreeNode = new TreeNode(); fileTreeNode.Tag = file; fileTreeNode.Text = new FileInfo(file).Name; fileTreeNode.ImageIndex = GetIconOfFile_Folder(file); fileTreeNode.SelectedImageIndex = fileTreeNode.ImageIndex; tn.Nodes.Add(fileTreeNode); } } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } Finally I have created an EventHandler for the NodeDoubleClick-Event in the TreeView: private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { if (CheckIfPathIsFile(e.Node.Tag.ToString()) == true) //If the Tag (Path) is a File { //Do something with the Path (close this Form + return Path) } } private bool CheckIfPathIsFile(string Path) { // get the file attributes for file or directory FileAttributes attr = File.GetAttributes(Path); //detect whether its a directory or file if ((attr & FileAttributes.Directory) == FileAttributes.Directory) return false; else return true; }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19049822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2609115/']}
|
jdg_76669
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47654539
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I made a hover effect which toggles a top block to slide up/down at the same time the bottom block slides up / down . As you can see in the Fiddle: https://jsfiddle.net/wmaL1pm5/1/ However, if you swipe your mouse fast on and off the block the hover effects keeps repeating even if you are not on that block anymore. In my HTML I have 2 row's with each 3 row containing 3 of these blocks. If you swipe your mouse of these rows all of the blocks are repeating their hover effect. How can I prevent the hover effect from looping if you hover another block or if your mouse is on the current block. Below my current jQuery code: $(".usp-hover").mouseenter( function(){ $( this ).find( ".usp-block-title" ).slideToggle('slow') $( this ).find( ".usp-block-hover" ).removeClass("usp-block-hidden"); $( this ).find( ".usp-block-hover" ).slideDown('slow')});$(".usp-hover").mouseleave( function(){ $( this ).find( ".usp-block-title" ).slideToggle('slow') $( this ).find( ".usp-block-hover" ).slideToggle('slow')});
Now provide the response and nothing else.
|
Update Since Kotlin 1.3 reflection natively supports calling suspending functions via KFunction.callSuspend and KFunction.callSuspendBy , so the above workaround is no longer needed. Original Answer Every suspend method in Kotlin is represented on JVM via CPS transformation that is explained in the coroutines design document . Java reflection is not aware about it and Kotlin reflection does not currently provide convenient means to perform invocation of suspending function either. You'll have to do invocation with CPS transformation yourself via helper function. I'd suggest to implement the following helper for this purpose: import java.lang.reflect.Methodimport kotlin.coroutines.experimental.intrinsics.*suspend fun Method.invokeSuspend(obj: Any, vararg args: Any?): Any? = suspendCoroutineOrReturn { cont -> invoke(obj, *args, cont) } Now if you replace invoke with invokeSuspend in your code, then it is going to work just like expected.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47654539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4608052/']}
|
jdg_76670
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13351965
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A node application has required me to run node with a harmony flag, like: node --harmony app.js What is this harmony flag? What does it do and why can't the app run without it? I've tried looking into node command-line options ( node --help ), but it doesn't provide any details either. Node docs weren't of any help either.
Now provide the response and nothing else.
|
Typing man node has this on the harmony flag: --harmony_typeof (enable harmony semantics for typeof) type: bool default: false --harmony_scoping (enable harmony block scoping) type: bool default: false --harmony_modules (enable harmony modules (implies block scoping)) type: bool default: false --harmony_proxies (enable harmony proxies) type: bool default: false --harmony_collections (enable harmony collections (sets, maps, andweak maps)) type: bool default: false --harmony (enable all harmony features (except typeof)) type: bool default: false So --harmony is a shortcut to enable all the harmony features (e.g. --harmony_scoping , --harmony_proxies , etc.) From this blog post , it seems harmony enables new ECMAScript 6 features in the language. The reason your file won't run without harmony is because app.js is probably using non-backward compatible features from the new ECMAScript 6 standard (like block scoping, proxies, sets, maps, etc.)
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13351965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/117919/']}
|
jdg_76671
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
529757
|
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:
Prove that $(n^5 - n)$ divides by $30$ for every $ n\in N$, using induction only. How on earth do I do that? Thing is $(n^5 - n)$ can't be opened using any known formula...
Now provide the response and nothing else.
|
If you do want to stick with induction: The base for $n=0$ (or $n=1$) is clear. Assume that $n^5-n$ is divisible by $30$. You need to prove that $(n+1)^5-(n+1)$ is also divisible by $30$. Expanding, we get:$$\begin{align*}(n+1)^5-(n+1) &= n^5+5n^4+10n^3+10n^2+5n+1-n-1\\ &= (n^5-n)+5(n^4+2n^3+2n^2+n)\\ &= (n^5-n)+5n((n+1)^3-n(n+1))\\ &=(n^5-n)+5n(n+1)(n^2+n+1)\end{align*}$$By IH, $n^5-n$ is divisible by $30$, so it is left to show that $n(n+1)(n^2+n+1)$ is divisible by $6$. It easy to see that it is divisible by $2$. Show that it is divisible by $3$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/529757', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90230/']}
|
jdg_76672
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5857621
|
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 library uses several nested namespaces, laid out like the following: Library name Class name 1 Class name 2 Class name 3 [...] Utilities Class name 1 [...] Class name 2 [...] Class name 3 [...] [...] The "Utilities" namespace contains useful extensions to each of the classes that don't warrant being included in the actual class itself. The "Library name" namespace is necessary because it avoids broad conflicts with other libraries, the "Utilities" namespace is necessary to avoid the type of ambiguity that arises from things like this , and the "Class name" namespaces inside it avoid name clashes between utilities written for similar classes. Despite this, it's still an enormous hassle in practice. Take the following, for example: MyLibrary::MyContainer<int> Numbers = MyLibrary::Utilities::MyContainer::Insert(OtherContainer, 123, 456);// Oh God, my eyes... This makes me think I'm doing something seriously wrong. Is there an easier way to keep things organized, intuitive and unambiguous?
Now provide the response and nothing else.
|
Look at how the standard library (or boost) is organized. Nearly all of it is inside the single std namespace. There's just little to be gained by putting everything inside its own namespace. Boost puts most things inside boost , while major libraries get a single subnamespace ( boost::mpl , or boost::filesystem , for example). And libraries commonly define a single aux subnamespace for internal implementation details. But you don't typically see deep or fine-grained namespace hierarchies, because they're just painful to work with, and there's little to no benefit from them. Here are some good rules of thumb: Helper functions related to a specific class should be in the same namespace as the class, to enable ADL to work. Then you don't need to qualify the name of the helper function at all when calling it. (Like how you can call sort instead of std::sort on iterators defined in std ). For everything else, remember that the purpose of namespaces is to avoid name clashes and not much else. So all your library should be in a namespace, to avoid clashes with user code, but within that namespace, there's no technical need for further subnamespaces unless you plan to introduce clashing names. You may want to separate internals of your library into a sub-namespace, so users don't accidentally pick them up from the main namespace, similar to Boost's aux . But generally, I'd suggest as few nested namespaces as possible. And finally, I tend to make a point of using short, easy-to-type and easy-to-read names for my namespaces (again, std is a good example to follow. Short and to the point, and nearly always without further nested namespaces, so you don't get a cramp from having to write it often, and so it doesn't clutter your source code too much.) Just the first rule about helper functions and ADL would allow your example to be rewritten like this instead: MyLibrary::MyContainer<int> Numbers = Insert(OtherContainer, 123, 456); Then we could rename MyLibrary to, say, Lib : Lib::MyContainer<int> Numbers = Insert(OtherContainer, 123, 456); and you're down to something pretty manageable. There shouldn't be any clashes between similar utility functions for different classes. C++ allows you to overload functions, and specialize templates, so that you can have both an Insert(ContainerA) and Insert(ContainerB) in the same namespace. And of course, clashes between namespaces and classes are only possible if you actually have additional nested namespaces. Remember that within your Library namespace, you alone dictate which names are introduced. And so you can avoid name clashes just by, well, not creating any clashing names. A namespace to separate user code from library code is important because the two may not know about each others, and so clashes can occur unintentionally. But within your library, you can just give everything non-clashing names.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5857621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497934/']}
|
jdg_76673
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
715628
|
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:
The following is an excerpt from do Carmo's Differential Geometry of Curves and Surfaces about the first fundamental form: I don't understand what "without further references to the ambient space ${\Bbb R}^3$" means. When "treating metric questions on a regular surface", what does it mean by with references to the ambient space ${\Bbb R}^3$? without references to the ambient space ${\Bbb R}^3$? How does the example of calculating the arc length of a curve illustrate the difference of the two different ways above?
Now provide the response and nothing else.
|
Let $S \subset {\Bbb R}^3$ be a (sufficiently) smooth surface, and let $\sigma (t)$, $\tau(t)$ be two smooth curves in $S$. Suppose $\sigma(t)$ and $\tau(t)$ both pass through the point $p \in S$; without loss of generality we can take $\sigma(0) = \tau(0) = p$. Since $\sigma(t)$ and $\tau(t)$ are also curves in $\Bbb R^3$, their tangent vector fields $\sigma'(t)$, $\tau'(t)$ lie in $T \Bbb R^3$, the tangent bundle of $\Bbb R^3$. As such, we can take the inner product of $\sigma'(t)$ and $\tau'(t)$ at any point such as $p$ through which they both pass by exploiting the Euclidean inner product structure $\langle \cdot, \cdot \rangle_{\Bbb R^3}$, viz. by taking for example $\langle \sigma'(0), \tau'(0) \rangle_{\Bbb R^3}$; we can also obtain the magnitudes of these tangent vectors for any value of $t$ in a similar fashion, by taking e.g. $\Vert \sigma'(t) \Vert_{\Bbb R^3} = \sqrt{\langle \sigma'(t), \sigma'(t) \rangle_{\Bbb R^3}}$ with the analogous expression holding for $\tau(t)$. And, having the norms of these tangent vectors, we can in principle compute the lenths if curve segments such as $\sigma(t)$, $t_1 \le t_2$, via the formula $l(\sigma, t_1, t_2) = \int_{t_1}^{t_2} \Vert \sigma'(t) \Vert_{\Bbb R^3} dt; \tag{1}$ and again, the corresponding formula holds for $\tau(t)$. All these quantities are defined with reference to $\Bbb R^3$ , since the all invoke $\langle \cdot, \cdot \rangle_{\Bbb R^3}$ in their definitions, and indeed yield geometrical information about $\sigma(t)$, $\tau(t)$ which in no way requires knowledge of the surface $S$; we merely exploit the fact that $\sigma(t)$, $\tau(t)$ are curves in the ambient space $\Bbb R^3$. On the other hand, we may also define a tensor field $I: TS \times TS \to \Bbb R$ by taking $I(\sigma'(0), \tau'(0)) = \langle \sigma'(0), \tau'(0) \rangle_{\Bbb R^3} \tag{2}$ for tangent vectors $\sigma'(0), \tau'(0) \in T_pS$, allowing $p$ to vary over $S$ and adjusting $\sigma(t)$, $\tau(t)$ accordingly so that we always have $\sigma(0) = \tau(0) = p$ while the curves remain in $S$. Such a construction allows the definition of $I$ to be extended to all of $TS$. Once $I$ has been so defined, admittedly in terms of $\langle \cdot, \cdot \rangle_{\Bbb R^3}$, it may be viewed as a tensor field on $S$ without further reference to $\Bbb R^3$ ; all metric properties of $S$ may now be defined solely in terms of $I$: we have $\Vert \sigma'(0) \Vert_S = \sqrt{I(\sigma'(0), \sigma'(0))}, \tag{3}$ $l(\sigma, t_1, t_2) = \int_{t_1}^{t_2} \Vert \sigma'(t) \Vert_S dt, \tag{4}$ and we can define an inner product on $TS$ via $\langle \sigma'(0), \tau'(0) \rangle_S = I(\sigma'(0), \tau'(0)). \tag{5}$ We may now consider $I$ as a structure defined on $TS$ alone. Doing so, we obtain all metric properties of $S$ without need to again refer to $\Bbb R^3$. Hope this helps. Cheerio, and as always, Fiat Lux!!!
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/715628', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_76674
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10365225
|
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 string that stores a number and a unit for example x= '$120'y = ' 90 Degrees F'banana = '200 kgm'orange = '300 gm'total_weight = banana + orange/1000 and for example I want to add the weights total_weight = 200 + 300/1000 Thanks! I'm trying to extract the numbers only to do some operations with these... any idea of what the simplest way to do this? I'm only dealing with these two formats i.e. digits are at the begining or at the end of the string...
Now provide the response and nothing else.
|
The simplest way to extract a number from a string is to use regular expressions and findall . >>> import re>>> s = '300 gm'>>> re.findall('\d+', s)['300']>>> s = '300 gm 200 kgm some more stuff a number: 439843'>>> re.findall('\d+', s)['300', '200', '439843'] It might be that you need something more complex, but this is a good first step. Note that you'll still have to call int on the result to get a proper numeric type (rather than another string): >>> map(int, re.findall('\d+', s))[300, 200, 439843]
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10365225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/657929/']}
|
jdg_76675
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10721836
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For a web application I'm building I need to analyze a website, retrieve and rank it's most important keywords and display those. Getting all words, their density and displaying those is relatively simple, but this gives very skewed results (e.g. stopwords ranking very high). Basically, my question is: How can I create a keyword analysis tool in PHP which results in a list correctly ordered by word importance?
Now provide the response and nothing else.
|
Recently, I've been working on this myself, and I'll try to explain what I did as best as possible. Steps Filter text Split into words Remove 2 character words and stopwords Determine word frequency + density Determine word prominence Determine word containers Title Meta description URL Headings Meta keywords Calculate keyword value 1. Filter text The first thing you need to do is filter make sure the encoding is correct, so convert is to UTF-8: iconv ($encoding, "utf-8", $file); // where $encoding is the current encoding After that, you need to strip all html tags, punctuation, symbols and numbers.Look for functions on how to do this on Google! 2. Split into words $words = mb_split( ' +', $text ); 3. Remove 2 character words and stopwords Any word consisting of either 1 or 2 characters won't be of any significance, so we remove all of them. To remove stopwords, we first need to detect the language.There are a couple of ways we can do this: - Checking the Content-Language HTTP header - Checking lang="" or xml:lang="" attribute - Checking the Language and Content-Language metadata tagsIf none of those are set, you can use an external API like the AlchemyAPI . You will need a list of stopwords per language, which can be easily found on the web.I've been using this one: http://www.ranks.nl/resources/stopwords.html 4. Determine word frequency + density To count the number of occurrences per word, use this: $uniqueWords = array_unique ($keywords); // $keywords is the $words array after being filtered as mentioned in step 3$uniqueWordCounts = array_count_values ( $words ); Now loop through the $uniqueWords array and calculate the density of each word like this: $density = $frequency / count ($words) * 100; 5. Determine word prominence The word prominence is defined by the position of the words within the text.For example, the second word in the first sentence is probably more important than the 6th word in the 83th sentence. To calculate it, add this code within the same loop from the previous step:' $keys = array_keys ($words, $word); // $word is the word we're currently at in the loop$positionSum = array_sum ($keys) + count ($keys);$prominence = (count ($words) - (($positionSum - 1) / count ($keys))) * (100 / count ($words)); 6. Determine word containers A very important part is to determine where a word resides - in the title, description and more. First, you need to grab the title, all metadata tags and all headings using something like DOMDocument or PHPQuery ( dont try to use regex!)Then you need to check, within the same loop, whether these contain the words. 7. Calculate keyword value The last step is to calculate a keywords value.To do this, you need to weigh each factor - density, prominence and containers.For example: $value = (double) ((1 + $density) * ($prominence / 10)) * (1 + (0.5 * count ($containers))); This calculation is far from perfect, but it should give you decent results. Conclusion I haven't mentioned every single detail of what I used in my tool, but I hope it offers a good view into keyword analysis. N.B. Yes, this was inspired by the today's blogpost about answering your own questions!
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10721836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625231/']}
|
jdg_76676
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12223
|
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:
According to the precedence of logical connectives , operator $\rightarrow$ gets higher precedence than $\leftrightarrow$ operator. But what about associativity of $\rightarrow$ operator? The implies operator ($\rightarrow$) does not have the associative property. That means that $(p \rightarrow q) \rightarrow r$ is not equivalent to $p \rightarrow (q \rightarrow r)$. Because of that, the question comes op how $p \rightarrow q \rightarrow r$ should be interpreted. The proposition $p \rightarrow q \rightarrow r$ can be defined in multiple ways that make sense: $(p \rightarrow q) \rightarrow r$ (left associativity) $p \rightarrow (q \rightarrow r)$ (right associativity) $(p \rightarrow q) \land (q \rightarrow r)$ Which one of these definitions is used? I could not locate any book/webpage that mentions about associativity of logical operators in discrete mathematics. Please also cite the reference (book/reliable webpage) that you use to answer my question (as I'm planning to add this to wikipedia page about 'logical connectives'). Thanks. PS: I got this question when I saw this problem:Check if following compound proposition is tautology or not: $$ \mathrm{p} \leftrightarrow (\mathrm{q} \wedge \mathrm{r}) \rightarrow \neg\mathrm{r} \rightarrow \neg\mathrm{p}$$
Now provide the response and nothing else.
|
Some logical operators are associative: both $\wedge$ and $\vee$ are associative, as a simple check of truth tables verifies. Likewise, the biconditional $\leftrightarrow$ is associative. However, the implication $\rightarrow$ is not associative. Compare $(p\rightarrow q)\rightarrow r$ and $p\rightarrow(q\rightarrow r)$ . If all of $p$ , $q$ , and $r$ are false, then $p\rightarrow (q\rightarrow r)$ is true, because the antecedent is false; but $(p\rightarrow q\rightarrow r$ is false, because $r$ is false, but $p\rightarrow q$ is true. They also disagree with $p$ and $r$ are false but $q$ is true: then $p\rightarrow(q\rightarrow r)$ is true because the antecedent is false, but $(p\rightarrow q)$ is true, $r$ false, so $(p\rightarrow q)\rightarrow r$ is false. Since they take different values at some truth assignments, the two propositions are not equivalent, so $\to$ is not associative.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/12223', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4170/']}
|
jdg_76677
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12202861
|
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 using some of these tools for the first time. I have read through the docs but wanted to ask here exactly what I'm trying to achieve. I have a set of users that I want to test some actions I can do in a controller spec. When each user is created, there are a set of callbacks that take place to create associated objects. I'd like to have access to these user instances and the associated objects of that ActiveRecord class. So for example, a user will have a set of lists so I'd like to be able to call user1.lists for example. Also, I'd like to isolate this setup at the top and use either let's or a before black. It seems that just calling let like this: # will test that get_count_for_list will return 5describe ApiController do # why same name - seems really confusing! let(:user) { FactoryGirl.create(:user) } let(:user2) { FactoryGirl.create(:user2) } doesn't call the associated callbacks. Is this correct? Or is it possibly a timing issue? I like the syntax of using let and being able to access these objects in my ExampleGroups such as user.id but can't access user.lists. Currently I am doing something like: # will test that get_count_for_list will return 5describe ApiController do # why same name - seems really confusing! let(:user) { FactoryGirl.create(:user) } let(:user2) { FactoryGirl.create(:user2) } let(:user3) { FactoryGirl.create(:user3) } before do FactoryGirl.create(:user2) FactoryGirl.create(:user3) end but feel that there has to be a better way. Am I creating these user's twice? thx edit 1 I've isolated the code in question here. The global_id value is created via a callback. It exists correctly in the db and can be accessed via the corresponding find_by_email's but using the user2 var's doesn't provide access. require 'spec_helper'# will test that get_count_for_list will return 5describe ApiController do # why same name - seems really confusing! let!(:user) { FactoryGirl.create(:user) } let!(:user2) { FactoryGirl.create(:user2) } let!(:user3) { FactoryGirl.create(:user3) } before do session[:user_id]=user.id # works end describe 'FOLLOW / UNFOLLOW options' do it 'shall test the ability to follow another user' do puts "user1: " + user.global_id.to_s # doesn't output anything u2=User.find_by_email('[email protected]') # corresponds to user2 post :follow, :global_id => user2.global_id # doesn't work #post :follow, :global_id => u2.global_id #works u3=User.find_by_email('[email protected]') puts "user_3" + u3.global_id.to_s # outputs correct value post :follow, :global_id => user3.global_id #doesn't work #post :follow, :global_id => u3.global_id # works post :unfollow, :global_id => user.following.sample(1) response.code.should eq('200') end endend
Now provide the response and nothing else.
|
Check the rspec doc: https://www.relishapp.com/rspec/rspec-core/v/2-11/docs/helper-methods/let-and-let Note that let is lazy-evaluated: it is not evaluated until the first time the method it defines is invoked. You can use let! to force the method's invocation before each example. In other words if you use let along with factory_girl a record will not be created before let-variable invocation. The correct code is: # will test that get_count_for_list will return 5describe ApiController do # why same name - seems really confusing! let!(:user) { FactoryGirl.create(:user) } let!(:user2) { FactoryGirl.create(:user2) }
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12202861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152825/']}
|
jdg_76678
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6838
|
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:
The data: I have worked recently on analysing the stochastic properties of a spatio-temporal field of wind power production forecast errors. Formally, it can be said to be a process $$ \left (\epsilon^p_{t+h|t} \right )_{t=1\dots,T;\; h=1,\dots,H,\;p=p_1,\dots,p_n}$$ indexed twice in time (with $t$ and $h$) and once in space ($p$) with $H$ being the number of look ahead times (equals something around $24$, regularly sampled) , $T$ being the number of "forecast times" (i.e. times at which the forecast is issued, around 30000 in my case, regularly sampled), and $n$ being a number of spatial positions (not gridded, around 300 in my case). Since this is a weather related process, I also have plenty of weather forecast, analysis, meteorological measurments that can be used. Question: Can you describe me the exploratory analysis that you would perform on this type of data to understand the nature of the interdependence structure (that might not be linear) of the process in order to propose a fine modelling of it.
Now provide the response and nothing else.
|
We (A colleague and I) finally wrote a paper on that one. To summarized things we proposed two solution to quantify and give a statistical summary of the (spatio-temporal) propagation of errors along Denmark and along look ahead times. In the first one we compute the correlation between all pairs of wind farms and for all pairs of look ahead times (this is a function of 4 variables). When a pair is fixed, we showed that the correlation function has a local maxima along look ahead times, we said this is propagation! The temporal scale associated to a given pair of wind farms is given by the temporal lag for wich this local maximum is obtained. Plotting, for all pairs of wind farm the local maxima of correlation, the temporal lag that allows to obtain that and the spatial vector that joins the wind farms gives the right side of Figure 1. This can be used to compute a global propagation vector i.e. some sort of spatial average of the propagation speeds between pairs. Part of this is shown in left side of Figure 1, and guess what propagation of errors is West East in Denamrk (ok that was not a big surprise :)). We also analysed this conditionally to different meteorological situations in order to show the relationship between propagation and wind (speed,direction). The second one is orthogonal (in a sence :)) to the first one. For each time $t$ we fitted a spatio-temporal (along space and look ahead times) plannar wave model with constant propagation speed. This gives one propagation speed per forecast time $t$ (and $R^2$ measuring the quality of the fit obtained by the planar wave model). Then you can compute statistics on those speeds, eventually limiting to the cases when the planar wave fit is good. Results are seen in Figure 2. In the second case, we observed that the temporal average propagation speed has a similar magnitute as that obtained with the spatial average in the first case. If you want to look at this work more seriously, the paper is here .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/6838', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/223/']}
|
jdg_76679
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29363455
|
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 want to test a function returning a promise. In this particular test, the promise is expected to be rejected with an Error object containing the classical message field (in this test, it is expected to equal "my error message" ) and a custom field I added named code , which is a string (like "EACCESS", "ERIGHT", etc, in this test it is expected to equal "EFOO" ) I want to use chai-as-promised for that. return expect(foo()).to.eventually.be.rejectedWith("my error message"); This assertion is working but now I would like to test the code field too. How to do that?
Now provide the response and nothing else.
|
If you're using Chai-As-Promised (as you say you are), then it allows for chaining off of rejectedWith - and it sets the chain assertion object to be the error object - meaning anything after rejectedWith() is now going to assert on the Error. This lets you do cool things like: return expect(foo()).to.eventually .be.rejectedWith("my error message") .and.be.an.instanceOf(Error) .and.have.property('code', 'EFOO'); Some of the chai methods also chain, so you can use that to make some quite deeply nested assertions about the error: return expect(foo()).to.eventually .be.rejectedWith("my error message") .and.have.property('stack') .that.includes('myfile.js:30')
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29363455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25888/']}
|
jdg_76680
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12422297
|
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 want to know what is the difference between Adapter and Loader in Android. I have already looked up at the documentation but can't figure out the difference between them. Any help would be appreciated. Thanks!
Now provide the response and nothing else.
|
Both provide an abstraction for data access, but the Loader performs the query in the background whereas an Adapter executes in the current (presumably UI) thread. For example, a straightforward way to access a Content Provider is with a SimpleCursorAdapter. But querying large amounts of data directly from an Activity may cause it to become blocked resulting in an "Application Not Responding" message. Even if it doesn't, users will see an annoying delay in the UI. To avoid these problems, you should initiate a query on a separate thread, wait for it to finish, and then display the results. This is what the CursorLoader will do. That being said, they are sometimes used in conjunction with one another. In this example data is first loaded with a CursorLoader and then that cursor is updated in an Adapter of an AdapterView for display.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12422297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1671058/']}
|
jdg_76681
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31127594
|
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 see a lot of questions about the run-time complexity of python's built in methods, and there are a lot of answers for a lot of the methods (e.g. https://wiki.python.org/moin/TimeComplexity , https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt , Cost of len() function , etc.) What I don't see anything that addresses enumerate. I know it returns at least one new array (the indexes) but how long does it take to generate that and is the other array just the original array? In other words, I'm assuming it's O(n) for creating a new array (iteration) and O(1) for the reuse of the original array...O(n) in total (I think). Is the another O(n) for the copy making it O(n^2), or something else...?
Now provide the response and nothing else.
|
Assuming the naïve approach (enumerate duplicates the array, then iterates over it), you have O(n) time for duplicating the array, then O(n) time for iterating over it. If that was just n instead of O(n), you would have 2 * n time total, but that's not how O(n) works; all you know is that the amount of time it takes will be some multiple of n . That's (basically) what O(n) means anyway, so in any case, the enumerate function is O(n) time total.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31127594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4735805/']}
|
jdg_76682
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12832801
|
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 HTML page containing several <div> containers. I require to show these <div> containers based on the user id. For example: I have 4 <div> containers created in a page say div1, div2, div3 and div4. And I have two users: user1 and user2. I would like to show div1 and div3 when user 1 access to the page. and show div2 and div4 when user2 access it. I would like to use ng-hide and ng-show directives of AngularJS. How can I achieve this?
Now provide the response and nothing else.
|
I would set properties on the $scope in a user access object of some sort to toggle them whenever you load the user. Assuming the user is loaded when the controller is it could be something like so: app.controller('SecuredForm', function($scope) { //get your user from where ever. var user = getSomeUser(); // set your user permissions // here's some contrived example. $scope.permissions = { showAdmin: user.isRegistered && user.isAdmin, showBasic: user.isRegistered, showHelp: !user.isBanned }}); In your html you'd use those scope items to set show or hide your areas: <div ng-show="permissions.showAdmin"> <h3>Admin Area</h3> <!-- admin stuff here --></div><div ng-show="permissions.showBasic"> <h3>Basic Info</h3> <!-- admin stuff here --></div><div ng-show="permissions.showHelp"> <h3>Help</h3> <!-- help stuff here --></div> One thing to note is that ng-show and ng-hide are simply not displaying the HTML... the html is still on the client. So be sure when you're making calls back to the server that require permissions to alter something you're checking them at the server . You can't assume the user has permission to do something just because the form was visible. (You probably already know this, I just want to be thorough).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12832801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1736975/']}
|
jdg_76683
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
612231
|
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 having trouble proving the following two questions about constant functions. 1) If $w=f(z)$ is an analytic function that maps all $z$ in region $D$ to a portion of a line, then $f(z)$ is constant. 2) If $f(z)=u(z)+iv(z)$ is an entire function such that $u(z)v(z)=3$ for all points in the complex plane, then $f$ is constant. I understand that it is enough to prove that $f(z)$ is locally constant since the domain is a region. I tried using the fact that if the partial derivatives are both $0$, then $f(z)$ is locally constant and hence constant. Thanks.
Now provide the response and nothing else.
|
Wikipedia's statement of the theorem is Suppose $X$ is a compact Hausdorff space and $A$ is a subalgebra of $C(X,\mathbb R)$ which contains a non-zero constant function. Then $A$ is dense in $C(X,\mathbb R)$ if and only if it separates points. (Emphasis added.) What you've quoted from Rudin asserts only the "if" direction (separating points implies dense); for that statement, we can omit the assumption that $X$ is Hausdorff because (as noted by others here already) the assumption that $A$ separates points already implies that $X$ is Hausdorff. (If, as suggested in comments, it is thought misleading to omit this condition — as Rudin does — I would strongly prefer merely to add a remark to the effect that the hypothesis implies Hausdorffness, not to add redundant hypotheses, which only make theorems harder to use.) However, for the "only if" direction (dense implies separating points) the assumption that $X$ is Hausdorff cannot be dropped. (Example: if $X$ has at least two points and the trivial topology, i.e., only $\emptyset$ and $X$ are open, then $C(X,\mathbb R)$ is a dense subalgebra of itself but doesn't separate points.) I can't think of a use for this direction off the top of my head; I suspect it's much less important than the other direction.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/612231', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/116729/']}
|
jdg_76684
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9154719
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
if(isset($_POST['submit'])) { if(!isset($_POST['userName'])) { $username = 'Anonymous'; } else $username = $_POST['userName'];} I cannot get the $username to be "Anonymous"? It is either blank or the value of $_POST['userName'] .
Now provide the response and nothing else.
|
isset() will return true if the variable has been initialised. If you have a form field with its name value set to userName , when that form is submitted the value will always be "set", although there may not be any data in it. Instead, trim() the string and test its length if("" == trim($_POST['userName'])){ $username = 'Anonymous';}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9154719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/994538/']}
|
jdg_76685
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40920
|
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:
My question is inspired by this previous question, Are there any stars that orbit perpendicular to the Milky Way's galactic plane? . In the great answer posted by @ConnorGarcia, one commenter said he would be really jealous of anybody that could see the view of the Milky Way from close to the galactic poles, since a star stream passes close to them. I think, on the flip side, they would envy us due to their near complete isolation. Space travel outside their home system would be much harder, for example. Here on the galactic plane, near the Sun, I guess the average distance to the closest nighboring star is about ~10 Ly or less. The Alpha Centauri system is about 4 Ly away, for example. Regarding the galactic halo, I guess if we picked a random star there, its closest neighbor would be probably located > 100 Ly away. Is this estimate reasonable? Are there reliable figures on that?
Now provide the response and nothing else.
|
I did some rough calculations, and 100 light-years doesn't seem to be a bad guess. If we assume that the average mass of a halo star is $\sim0.3M_{\odot}$ , as would be expected for a typical IMF, and that the total stellar halo mass is $\sim10^9M_{\odot}$ ( Deason et al. 2019 ), then we should expect there to be $\sim3.3\times10^9$ halo stars. $^{\dagger}$ The halo extends to somewhere near 100 kpc, so if we take it to be roughly spherica-ishl, this leads to an average number density of $$n\approx\frac{3.3\times10^9\;\text{stars}}{\frac{4\pi}{3}(100\;\text{kpc})^3}\approx7.9\times10^{-7}\;\text{pc}^{-3}$$ and a mean inter-star distance of $l\approx n^{-1/3}\approx108\;\text{pc}$ . So my back-of-the-envelope result differs from yours by only a factor of 3. Now, the halo has a distinctly non-uniform density. It follows a power law of $r^{-n}$ , with an index somewhere near $n\approx3$ . Different surveys have yielded values ranging from $2.5\lesssim n\lesssim 3.5$ (ish), depending on the methodology and groups studied. The upshot is that in the outer halo, you'll certainly see much larger separations, whereas closer to the Galactic plane, you could see densities perhaps within a couple orders of magnitude of disk populations. $^{\dagger}$ Two things: First, the halo population's mass function should be different than a typical IMF, because it's composed largely of aging Population II stars - but I think $0.3M_{\odot}$ is still reasonably close. Second, I also checked the number by actually integrating via a Kroupa IMF (normalizing by total halo mass), (and again, maybe not a totally accurate distribution) and found a value within a factor of 2 of 3.3 billion.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/40920', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/34443/']}
|
jdg_76686
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
64404898
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hello there. As the title suggests, I currently have an issue inmy program. In the animation loader, I have a method that shouldload an animation from a collada file. It gets an Element as an input.The first thing I do is to collect the animation data. I do this by getting a node list with NodeList sources = element.getElementsByTagName("source"); And then I iterate through that node list: for(int i = 0; i < sources.getLength(); i++) { // Problem occurs here: Element sourceElement = (Element) (sources.item(i)); String id = sourceElement.getAttribute("id"); if(id.equals(inputId)) inputSource = FloatArraySource.loadFromElement(sourceElement); else if(id.equals(outputId)) outputSource = Matrix4fSource.loadFromElement(sourceElement); else if(id.equals(interpolationId)) interpolationSource = StringArraySource.loadFromElement(sourceElement); } The problem occurs on the commented line, and it crashes (only sometimes) with this following exception Cannot invoke "com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.changes()" because the return value of "com.sun.org.apache.xerces.internal.dom.NodeImpl.ownerDocument()" is null I can start the application three times in a row, and it crashes roughly one of four times. The strangest thing is the fact that it runs perfectly fine in debug mode. So, I'd be very happy if you could help me out with this issue. -Budschie Edit: Some people wanted that I post the full stack trace, so here it is: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.changes()" because the return value of "com.sun.org.apache.xerces.internal.dom.NodeImpl.ownerDocument()" is null at java.xml/com.sun.org.apache.xerces.internal.dom.NodeImpl.changes(NodeImpl.java:1887) at java.xml/com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl.item(DeepNodeListImpl.java:125) at java.xml/com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl.getLength(DeepNodeListImpl.java:116) at de.budschie.engine.assets_management.newcollada.AnimationLoader.loadTransformAnimation(AnimationLoader.java:77) at de.budschie.engine.assets_management.newcollada.AnimationLoader.loadAnimation(AnimationLoader.java:31) at de.budschie.engine.assets_management.newcollada.ColladaLoader.loadCollada(ColladaLoader.java:60) at de.budschie.engine.assets_management.DefaultResourceLoader.loadAll(DefaultResourceLoader.java:75) at de.budschie.engine.main.MainWindow.gameLoop(MainWindow.java:192) at de.budschie.engine.main.MainWindow.main(MainWindow.java:81) Another edit: Here's the way I load my collada files: Element colladaTag = null; try { colladaTag = getColladaTag(colladaFile); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Element libraryAnimations = (Element) colladaTag.getElementsByTagName("library_animations").item(0); Element libraryControllers = (Element) colladaTag.getElementsByTagName("library_controllers").item(0); Element libraryGeometries = (Element) colladaTag.getElementsByTagName("library_geometries").item(0); NodeList meshesList = null, controllersList = null; if(libraryGeometries != null) { meshesList = libraryGeometries.getElementsByTagName("geometry"); } if(libraryControllers != null) { controllersList = libraryControllers.getElementsByTagName("controller"); } if(libraryAnimations != null) { AnimationLoader.loadAnimation(colladaResult, libraryAnimations); } And here's what "getColladaTag()" looks like: private static Element getColladaTag(String path) throws Exception { File file = new File(path); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(file); return doc.getDocumentElement(); } catch(IOException | SAXException ex) { System.out.println("There is a problem with the file that couldn't be fixed."); ex.printStackTrace(); } return null; } Another small thing I noticed is that sometimes, the JVM itself crashes because of an access violation in the string builder... Very important edit: Whilest debugging I found out that I can't import com.sun.org.apache.xerces.internal.dom.NodeImpl . My program doesn't throw a ClassNotFoundException though... So, could that be a reason why the GC is so confused?
Now provide the response and nothing else.
|
use MediaQuery.removePadding widget with removeTop: true class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { final sc = ScrollController(initialScrollOffset: 0); final res = MaterialApp( title: 'Flutter Demo', home: Scaffold( appBar: AppBar( title: Text('Driver App'), ), body: null, drawer: Drawer( child: Container( padding: EdgeInsets.zero, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ DrawerHeader( child: Text('Drawer Header'), decoration: BoxDecoration( color: Colors.blue, ), margin: EdgeInsets.zero, ), Expanded( child: MediaQuery.removePadding( context: context, removeTop: true, child: Scrollbar( radius: Radius.circular(30), thickness: 10, controller: sc, isAlwaysShown: true, child: ListView( shrinkWrap: false, controller: sc, padding: EdgeInsets.only(top: 0), children: <Widget>[ ListTile( title: Text('Item 2'), onTap: () { // Update the state of the app. // ... }, ), ListTile( title: Text('Item 2'), onTap: () { // Update the state of the app. // ... }, ), ListTile( title: Text('Item 2'), onTap: () { // Update the state of the app. // ... }, ), ListTile( title: Text('Item 2'), onTap: () { }, ), ListTile( title: Text('Item 2'), onTap: () { }, ), ListTile( title: Text('Item 2'), onTap: () { }, ), ListTile( title: Text('Item 2'), onTap: () { }, ) ], ), ), ), ), ], ), ), // Populate the Drawer in the next step. ), ), ); return res; }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64404898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14468821/']}
|
jdg_76687
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15747277
|
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 anyway I can exit a java program after a couple of seconds e.g. 5 seconds. I know you can quit the java program using: System.exit(0); But I'm not sure whether the 0 stands for seconds since this code: System.exit(10); also exits instantly
Now provide the response and nothing else.
|
System.exit(0) specifies the exit error code of the program. you can put it on a timer and schedule the task import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class TimedExit {Timer timer = new Timer();TimerTask exitApp = new TimerTask() {public void run() { System.exit(0); }};public TimedExit() {timer.schedule(exitApp, new Date(System.currentTimeMillis()+5*1000)); }} and then you can just called TimedExit()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15747277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2217679/']}
|
jdg_76688
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14667
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In complex projective geometry, we have a specified Kähler class $\omega$ and we have a Lefschetz operator $L:H^i(X,\mathbb{C})\to H^{i+2}(X,\mathbb{C})$ given by $L(\eta)=\omega\wedge \eta$. We then define primitive cohomology $P^{n-k}(X,\mathbb{C})=\ker(L^{k+1}:H^{n-k}(X)\to H^{n+k+2}(X))$, and we even have a nice theorem, the Lefschetz decomposition, that says $H^m(X,\mathbb{C})=\oplus_k L^kP^{n-2k}$. Often, in papers, people just prove their result for primitive classes, as they seem to be easier to work with. So, what exactly ARE primitive classes? Sure, they're things that some power of $\omega$ kills, but what's the intuition? Why are they an interesting distinguished class? Is there a good reason to expect this decomposition?
Now provide the response and nothing else.
|
The primitive classes are the highest weight vectors. Hard Lefschetz says that the operator $L$ (which algebraic geometers know as intersecting with a hyperplane) is the "lowering operator" $\rho(F)$ in a representation $\rho \colon \mathfrak{sl}_2(\mathbb{C})\to End (H^\ast(X;\mathbb{C}))$. The raising operator $\rho(E)$ is $\Lambda$, the restriction to the harmonic forms of the the formal adjoint of $\omega \wedge \cdot$ acting on forms. The weight operator $\rho(H)$ has $H^{n-k}(X;\mathbb{C})$ as an eigenspace (= weight space), with eigenvalue (=weight) $k$. The usual picture of an irreducible representation of $\mathfrak{sl}_2(\mathbb{C})$ is of a string of beads (weight spaces) with $\rho(F)$ moving you down the string and decreasing the weight by 2, and $\rho(E)$ going in the opposite direction. The highest weight is an integer $k$, the lowest weight $-k$. From this picture, it's clear that the space of highest weight vectors in a (reducible) representation is $\ker \rho(E)$. It's also clear that, of the vectors of weight $k$, those which are highest weights are the ones in $\ker \rho(F)^{k+1}$. So the highest weight vectors in $H^{n-k}(X; \mathbb{C})$ are those in $\ker L^{k+1}$. Of course, all this ignores the rather subtle question of how to explain in an invariant way what this $\mathfrak{sl}_2(\mathbb{C})$, or its corresponding Lie group, really is. Added , slipping Mariano an envelope. But here's what that group is. Algebraic geometers, brace yourselves. Fix $x\in X$, and let $O_x = O(T_x X\otimes \mathbb{C})\cong O(4n,\mathbb{C})$. Then $O_x$ acts projectively on $\Lambda^\bullet (T_x X\otimes \mathbb{C})$ via the spinor representation (which lives inside the Clifford action). The holonomy group $Hol_x\cong U(n)$ also acts on complex forms at $x$, and the "Lefschetz group" $\mathcal{L}$ is the centralizer of $Hol_x$ in $O_x$. One proves that $\mathcal{L}\cong GL(\mathbb{C}\oplus \mathbb{C})$. Not only is this the right group, but its Lie algebra comes with a standard basis, coming from the splitting $T_x X \otimes\mathbb{C} = T^{1,0} \oplus T^{0,1}$. Now, $\mathcal{L}$ acts on complex forms on $X$, by parallel transporting them from $y$ to $x$, acting, and transporting back to $y$. Check next that the action commutes with $d$ and $*$, hence with the Laplacian, and so descends to harmonic forms = cohomology. Finally, check that the action of $\mathcal{L}$ exponentiates the standard action of $\mathfrak{gl}_2$ where the centre acts by scaling. (This explanation is Graeme Segal's, via Ivan Smith.)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/14667', 'https://mathoverflow.net', 'https://mathoverflow.net/users/622/']}
|
jdg_76689
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5221361
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Background A ResultSet has many Double value fields (with patterns like "###0.000" ). Some values can be null . Problem I want to replace null values with "N/A" , which is a String and cannot print to a Double field. Printing "0.00" for null values is unacceptable. Using an PrintWhenExpression value of ($F{value} != null) ? $F{value} : "N/A" does not work; it is not possible to use patterns in that way. Idea Add hidden fields that write "N/A". These fields will be printed only if value is null . Question Is there a better solution, and if so, what is it? Thank you.
Now provide the response and nothing else.
|
Solution #1 Your solution: Use a regular Double field ( doubleField ) for the column value. Add a static String text field at the same location. Change the Double field to Blank When Null . Set the PrintWhenExpression value for the String text field to: $F{doubleField} == null . Solution #2 The problem is, as you pointed out, that a Double and a String are two different data types. You can assign a String variable to the value of the Double using an appropriate expression. Then use the String variable as the field. The expression might resemble: ($F{doubleField} == null) ? "N/A" : new java.text.DecimalFormat("#.##").format($F{doubleField}) (Note: My preference is to use == instead of != . Think positive.) Solution #3 Change the SQL statement to pre-format the Double as a text string, and use the "N/A" in the string (by using a CASE or DECODE statement in the query). Avoid this solution, though, as it is not maintainable. Recommendation Do not hard-code the "N/A" string throughout the report(s); put the "N/A" text in a constant, or a parameter with a default value of "N/A".
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5221361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/551687/']}
|
jdg_76690
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
592718
|
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:
A physics professor told me that: "The QFT amplitude is always proportional to the tree-level amplitude, even for non-renormalizable theories". i.e. \begin{equation}\mathcal{M}^{n-loop}=\mathcal{M}^{tree}\times f(\lbrace p\rbrace)\end{equation} I could not find this claim in any of the QFT textbooks however. Is this true? If so, is there any easy way to see that this must be the case? I have heard that in some cases the tree level amplitude vanishes, so if the above statement is true, should it actually be stated that the amplitude is always proportional to the first non-vanishing loop order?
Now provide the response and nothing else.
|
No, $\mathcal{M}^{\text{n-loop}} = \mathcal{M}^{\text{tree}}\times f(p,\dots)$ is not true because there are real processes that have non-zero amplitude but no tree-level diagrams. The most famous, perhaps, is a Higgs boson decaying to two photons. This ended up being one of the most sensitive signatures in the search for the Higgs. There is no tree-level diagram for this because the photon is massless, but there are one-loop diagrams. Another example is photon-photon scattering . There are no tree-level, $\mathcal{O}(\alpha)$ diagrams for this process but there are one-loop, $\mathcal{O}(\alpha^2)$ diagrams. It is also not the case that $\mathcal{M}^{n\text{-loop}} = \mathcal{M}^{\text{min-loop}}\times f(p,\dots)$ . For example, consider electron-positron scattering in QED. The lowest-level interaction is the electron and position interacting through single photons, but the full process includes a channel where the electron and positron combine briefly into a positronium resonance before decaying again. Since positronium has a mass its propagator cannot be proportional to a photon propagator. That is $$\mathcal{M}^{\text{min}} = \frac{f_1}{s}+\frac{f_2}{t}$$ but $$\mathcal{M}^{\text{full}} = \frac{f_1}{s}+\frac{f_2}{t}+\frac{f_3}{s-m_{Ps}^2+im_{Ps}\Gamma_{Ps}}+\dots$$ where $m_{Ps}$ and $\Gamma_{Ps}$ are the mass and decay rate of positronium. The full amplitude has different poles than the lowest-level amplitude, so it can't be proportional.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/592718', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/106906/']}
|
jdg_76691
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11360030
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering what would be the best or easiest way to allow a user to select nothing in a selectOneMenu. My example: I have a list of registered users and the administrator should be able to filter the list of displayed users by some criterias. These criterias, like the usertype (employee, customer, ...) can be chosen by selectOneMenus, like this: <h:selectOneMenu value="#{myBean.selectedUsertype}" converter="#{usertypeConverter}"><f:selectItems value={myBean.usertypes}" /></h:selectOneMenu> When the corresponding selectOneMenu is being backed by a list of POJOs using a converter, how can I add an item to the list indicating that the user didn't choose any specific item? Currently I have a dummy usertype object displaying the label "---", but this is causing several problems in other areas of my application and I don't think that this is the best solution.
Now provide the response and nothing else.
|
Just explicitly set the select item value to null . <h:selectOneMenu value="#{bean.selectedItem}"> <f:selectItem itemValue="#{null}" itemLabel="--select--" /> <f:selectItems value="#{bean.availableItems}" /></h:selectOneMenu> No, an empty string like itemValue="" is not sufficient. It really has to be null . Otherwise you run into trouble as described in this Q&A: Using a "Please select" f:selectItem with null/empty value inside a p:selectOneMenu . If the item happen to be required="true" and you're using JSF 2.x, then you could add noSelectionOption="true" to the select item. This is only useful if you also set hideNoSelectionOption="true" on the selection component. It will then hide the empty option in the list once the enduser selects a different item, hereby making it impossible to re-select the empty option. <h:selectOneMenu value="#{bean.selectedItem}" hideNoSelectionOption="true"> <f:selectItem itemValue="#{null}" itemLabel="--select--" noSelectionOption="true" /> <f:selectItems value="#{bean.availableItems}" /></h:selectOneMenu> See also page 114 of The Definitive Guide to JSF under section "SelectItem tags": Note that a select item with value of #{null} can be used to present the default selection in case the bean property associated with selection component's value attribute is null . If you have consulted the tag documentation of <f:selectItem> , then you'll perhaps have noticed the noSelectionOption attribute and have thought that it was intended to represent a "no selection option". Actually, this isn't true. Many starters indeed think so, as you can see in many forums, Q&A sites, and poor-quality tutorials on the Internet. In spite of the misleading attribute name, it does not represent a "no selection option". A better attribute name would have been hideWhenOtherOptionIsSelected , and even then it works only when the parent selection component has explicitly a hideNoSelectionOption="true" attribute set. So, hideWhenOtherOptionIsSelectedAndHideNoSelectionOptionIsTrue would ultimately have been the most self-explanatory attribute name. Unfortunately, this wasn't very well thought out when the noSelectionOption was implemented in JSF 1.2. Requiring two attributes for this attribute to function shouldn't have been necessary. The primary purpose of this attribute pair is to prevent the web site user from being able to re-select the "no selection option" when the component has already a non- null value selected. For example, by having it prepared in a @PostConstruct method, or by re-rendering the component after a form submit with a non- null value. Copyright disclaimer: book is written by me.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11360030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1450061/']}
|
jdg_76692
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36113556
|
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 executed following commands (on Windows, using Git Bash) in the directory D:\vagrant\precise32\02-lamp\ $ vagrant box add precise32 http://files.vagrantup.com/precise32.box$ vagrant init precise32$ vagrant up Note. I haven't changed original Vagrantfile. I thought the directory D:\vagrant\precise32\02-lamp\ would be the place of the VDI-like file but it is not. The working directory serves as the shared folder . I found the location of the Vagrant box C:\Users\USER\.vagrant.d\boxes\precise32\0\virtualbox According to Where is Vagrant saving changes to the VM I found in the VirtualBox GUI the location of the Virtual hard drive file. Which is C:\Users\USER\VirtualBox VMs\02-lamp_default_1458429875795_57100\ I would like to put this file not in the system drive C:\ but in the data drive which is D:\ . How to set such vagrant configuration?
Now provide the response and nothing else.
|
For VirtualBox, you can change the location of what is known as the Default Machine Folder through the GUI's Preferences dialog box. This guide , while a couple of years old, works fine and I followed it last week for how to move an existing vagrant/VirtualBox drive to a new location. EDIT I have quoted the steps from the above link/guide, for posterity: Move ~/.vagrant.d to the external drive. I renamed it vagrant_home so I'd be able to see it without ls -a. Set VAGRANT_HOME to /path/to/drive/vagrant_home in ~/.bash_profile . Open the VirtualBox app, open Preferences, and set its Default Machine Folder to /path/to/drive/VirtualBox VMs . Close VirtualBox. Move your VirtualBox VMs folder to the drive. Reopen VirtualBox. You'll see your VMs are listed as "inaccessible". Remove them from the list. For each VM in your VirtualBox VMs folder on the external drive, browse to its folder in Finder and double-click the .vbox file to restore it to the VirtualBox Manager. (Is there an easier method than this?) Finally, move any existing Vagrant directories you've made with vagrant init (these are the directories with a Vagrantfile in each) to the external drive. Since these directories only store metadata you could leave them on your main drive, but it's nice to keep everything together so you could fairly easily plug the whole drive into another machine and start your VMs from there.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36113556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2793410/']}
|
jdg_76693
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3142713
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been self-studying from the amazing "Engineering Mathematics" by Stroud and Booth, and am currently learning about algebra, particularly logarithms. There is a question which I don't understand who they've solved. Namely, I'm supposed to express the following equations without logs: $$\ln A = \ln P + rn$$ The solution they provide is: $$A = Pe^{rn}$$ But I absolutely have no idea how they got to these solutions. (I managed to "decipher" some of the similar ones piece by piece by studying the rules of logarithms).
Now provide the response and nothing else.
|
The basic idea behind all basic algebraic manipulations is that you are trying to isolate some variable or expression from the rest of the equation (that is, you are trying to "solve" for $A$ in this equation by putting it on one side of the equality by itself). For this particular example (and indeed, most questions involving logarithms), you will have to know that the logarithm is "invertible"; just like multiplying and dividing by the same non-zero number changes nothing, taking a logarithm and then an exponential of a positive number changes nothing. So, when we see $\ln(A)=\ln(P)+rn$ , we can "undo" the logarithm by taking an exponential. However, what we do to one side must also be done to the other, so we are left with the following after recalling our basic rules of exponentiation: $$A=e^{\ln(A)}=e^{\ln(P)+rn}=e^{\ln(P)}\cdot e^{rn}=Pe^{rn}$$
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3142713', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97584/']}
|
jdg_76694
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
245767
|
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 am programming in Java, and I always make converters sort of like this: public OtherObject MyObject2OtherObject(MyObject mo){ ... Do the conversion return otherObject;} At the new workplace the pattern is: public void MyObject2OtherObject(MyObject mo, OtherObject oo){ ... Do the conversion} For me it is a little bit smelly, as I got used to not to change the incoming parameters. Is this incoming parameter alteration an antipattern or is it OK? Does it have some serious drawbacks?
Now provide the response and nothing else.
|
It's not an antipattern, it's a bad practice. The difference between an antipattern and a mere bad practice is here: anti-pattern definition . The new workplace style you show is a bad practice , vestigial or pre-OOP times, according to Uncle Bob's Clean Code. Arguments are most naturally interpreted as inputs to a function. Anything that forces you to check the function signature is equivalentto a double-take. It’s a cognitive break and should be avoided. In thedays before object oriented programming it was sometimes necessary tohave output arguments. However, much of the need for output argumentsdisappears in OO languages
|
{}
|
{'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/245767', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/138451/']}
|
jdg_76695
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2747025
|
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:
$$\lim_{n\to \infty} \frac{1}{n}\cdot \big((m+1)(m+2) \ldots(m+n)\big)^{\frac{1}{n}}$$ where $m$ is a fixed positive integer. Here is my attempt: According to Cauchy's theorem of limit if $\lim\limits_{n\to \infty}a_n=l$ then $\lim{(a_1a_2 \ldots a_n)}^{\frac{1}{n}}=l$ hence $\lim\limits_{n\to \infty}\frac {m+n}{n}$ $\Rightarrow lim_{n\to∞}(1+\frac{m}{n})=1$ I'm 90 percent clear that my solution is correct. If not then please give me the right solution.
Now provide the response and nothing else.
|
We have $$\frac {1}{n}[{(m+1)(m+2)............(m+n)}]^\frac{1}{n}=\left[\frac{{(m+1)(m+2)............(m+n)}}{n^n}\right]^\frac{1}{n}=a_n^\frac1n$$ and by ratio-root criteria $$\frac{a_{n+1}}{a_n}=\frac{{(m+1)(m+2)............(m+n+1)}}{(n+1)^{n+1}}\frac{n^n}{{(m+1)(m+2)............(m+n)}}=$$ $$=\frac{m+n+1}{n+1}\frac{1}{\left(1+\frac1n\right)^n}\to\frac1e \implies a_n^\frac1n\to \frac1e$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2747025', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/552258/']}
|
jdg_76696
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1248342
|
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:
$\text{Let }f:[0,1]\to \Bbb R\text{ be a continuous function}$Evaluate the function$$\lim_{n\to \infty}\int_{0}^{1}x^nf(x)\,dx$$ Here is my work: Given $\epsilon \gt 0$,since $f(x) \in C^0[0,1]$, by Weierstrass Approximation Theorem, there is a polynomial $p(x)$ s.t. $$|f(x)-p(x)|\lt \varepsilon$$ So we have $$\begin{align}\int_{0}^{1}x^n|f(x)-p(x)|\,dx & \lt \int_{0}^{1}x^n\varepsilon\, dx\\& = \left[\varepsilon\,\frac{x^{n+1}}{n+1} \right]_{0}^{1}\\& = \frac{\varepsilon}{n+1}\end{align}$$ Since $p(x)$ is a polynomial, suppose it has degree $m$, and has the form$$p(x)=a_0+a_1x+a_2x^2+\cdots+a_mx^m$$$a_i\in \Bbb R\text{ for each }i$. Integrate it we get$$\int_{0}^{1}x^n\,p(x)\,dx=\frac{a_0}{n+1}+\frac{a_1}{n+2}+\frac{a_2}{n+3}+\cdots+\frac{a_m}{n+m+1}$$By triangle inequality, $0\le |f(x)|\le |f(x)-p(x)|+|p(x)|$, so$$\begin{align}0\le \int_{0}^{1}x^n\,|f(x)|\,dx & \le \int_{0}^{1}x^n|f(x)-p(x)|\,dx+\int_{0}^{1}x^n|p(x)|\,dx\\& \le \int_{0}^{1}x^n|f(x)-p(x)|\,dx+\int_{0}^{1}x^n\sum_{i=0}^{m}\lvert a_ix^i\rvert\,dx\end{align}$$But we know that both $\int_{0}^{1}x^n|f(x)-p(x)|\,dx\text{ and }\int_{0}^{1}x^n\sum_{i=0}^{m}\lvert a_ix^i\rvert\,dx$ goes to $0 \text{ as }n\to \infty$Then by pinching, $$\int_{0}^{1}x^n\,|f(x)|\,dx\to 0\text{ as }n\to \infty$$then $$\int_{0}^{1}x^n\,f(x)\,dx\to 0\text{ as }n\to \infty$$ I don't I'm do the right thing? because I just come up with this idea, and seems strange.
Now provide the response and nothing else.
|
An idea: Since $\;f\;$ continuous in a closed, bounded interval it is bounded there, say by $\;M\;$ , and then $$\left|\int_0^1 x^nf(x)\,dx\right|\le\int_0^1 x^n|f(x)|dx\le M\int_0^1x^ndx=\frac M{n+1}\xrightarrow[n\to\infty]{}0$$ Indeed Weierstrass theorem....but not the approximation one. :)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1248342', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/198004/']}
|
jdg_76697
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
59527605
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From document SimpleDateTimePattern , yy should be the same with YY . Today is Dec 30, 2019 , now we get YY for today is 20 , yy for today is 19 . What's the difference between yy and YY in Java Time Pattern?
Now provide the response and nothing else.
|
yy is the calendar year, while YY is a week year. A week year can be different from the calendar year depending on which day the first of January falls. For example see ISO-8601 week year . Today (30 December 2019) is a good example, the calendar year is 2019, but the week year is 2020, because this week is week 1 of 2020. So yy will result in 19 , while YY results in 20 . The definition of the first week of a year from the wikipedia page : The ISO 8601 definition for week 01 is the week with the Gregorian year's first Thursday in it. The following definitions based on properties of this week are mutually equivalent, since the ISO week starts with Monday: It is the first week with a majority (4 or more) of its days in January. Its first day is the Monday nearest to 1 January. It has 4 January in it. Hence the earliest possible first week extends from Monday 29 December (previous Gregorian year) to Sunday 4 January, the latest possible first week extends from Monday 4 January to Sunday 10 January. It has the year's first working day in it, if Saturdays, Sundays and 1 January are not working days. If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. If 1 January is on a Friday, it is part of week 53 of the previous year. If it is on a Saturday, it is part of the last week of the previous year which is numbered 52 in a common year and 53 in a leap year. If it is on a Sunday, it is part of week 52 of the previous year. Some locales, like for example the US, don't follow ISO-8601, because there they use Sunday as the first day of the week, but they have similar rules for week years.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59527605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2992029/']}
|
jdg_76698
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
142803
|
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:
This is an attempt at a canonical question following this discussion on Meta . The aim is to produce basic answers that can be understood by the general audience. Let's say I browse the web and use different apps while connected to the network at work. Can my employer (who controls the network) see what websites I visit, what emails I send, my IM messages, what Spotify songs I listen to, etc? What are they able to see? Does it matter if I use my own computer, or one provided for me by my employer? Does it matter what programs I use, or what websites I visit?
Now provide the response and nothing else.
|
Yes. Always assume yes. Even if you are not sure, always assume yes. Even if you are sure, they might have a contract with the ISP, a rogue admin who installed a packetlogger, a video camera that catches your screen... yes. Everything you do at the workplace is visible to everyone . Especially everything you do on digital media. Especially personal things. Especially things you would not want them to see. One of the basic rules of Information Security is that whoever has physical access to the machine, has the machine. Your employer has physical access to everything: the machine, the network, the infrastructure . He can add and change policies, install certificates, play man in the middle. Even websites with 'SSL' can be intercepted. There are plenty of valid reasons for this, mostly related to their own network security (antivirus, logging, prohibiting access to certain sites or functionalities). Even if you get lucky and they cannot see the contents of your messages, they might still be able to see a lot of other things: how many connections you made, to which sites, how much data you sent, at what times... even when using your own device, even using a secure connection, network logs can be pretty revealing. Please, when you are at work, or using a work computer, or even using your own computer on the company network: always assume everything you do can be seen by your employer .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/142803', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/111078/']}
|
jdg_76699
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2408
|
Below is a question asked on the forum devops.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've a playbook that runs EOS commands against multiple devices. Currently the whole thing is done in bash, creates one massive text file log and an engineer compares each day's log to the previous one for irregularities. I'm attempting to have one simple playbooks that runs the commands and logs to json from which it'll be easier to automate the comparison, but I've just realised only logs from one device are saved as opposed to the two I'm testing against. ---- name: Checks hosts: myhosts connection: local tasks: - name: Run Commands eos_command: commands: - show ip pim neighbor | json - show ip bgp summary | json register: result - name: Save to file copy: content: "{{ result.stdout_lines | to_nice_json }}" dest: "/home/homedirectory/results.json" Would there be way to log both (and eventually all production) devices in the same file?
Now provide the response and nothing else.
|
This question has two approaches, and both has answers on SO: Convert all Ansible output to JSON with json stdout callback and parse it with your favourite tools. The eos_command output for each device will be under different host key in the resulting json.See this and this . Make run_once task to collect data from other hosts, like this: - debug: msg: "{{ ansible_play_hosts | map('extract', hostvars, 'result') | map(attribute='stdout_lines') | list }}" run_once: yes See this .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://devops.stackexchange.com/questions/2408', 'https://devops.stackexchange.com', 'https://devops.stackexchange.com/users/4853/']}
|
jdg_76700
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42996270
|
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 stuck with this incredibly silly error. I am trying to run pytest on a Raspberry Pi using bluepy. pi@pi:~/bluepy/bluepy $ pytest test_asdf.py============================= test session starts ==============================platform linux2 -- Python 2.7.9, pytest-3.0.7, py-1.4.33, pluggy-0.4.0rootdir: /home/pi/bluepy, inifile:collected 0 items / 1 errors==================================== ERRORS ==================================== ______________ ERROR collecting bluepy/test_bluetoothutility.py _______________ImportError while importing test module '/home/pi/bluepy/bluepy/test_asdf.py'.Hint: make sure your test modules/packages have valid Python names.Traceback:test_asdf:4: in <module> from asdf import AsDfasdf.py:2: in <module> from bluepy.btle import *E ImportError: No module named btle!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!=========================== 1 error in 0.65 seconds ============================ I realised that my problem could be that rootdir is showing incorrect path. It should be /home/pi/bluepy/bluepy I've been reading pytest docs but I just do not get it how to change the rootdir.
Now provide the response and nothing else.
|
Your problem is nothing to do with Pytest's rootdir. The rootdir in Pytest has no connection to how test package names are constructed and rootdir is not added to sys.path , as you can see from the problem you were experiencing. (Beware: the directory that is considered rootdir may be added to the path for other reasons, such as it also being the current working directory when you run python -m pytest .) The problem here, as others have described, is that the top-level bluepy/ is not in sys.path . The easiest way to handle this if you just want to get something running interactively for yourself is as per Cecil Curry's answer : cd to the top-level bluepy and run Pytest as python -m pytest bluepy/test_asdf.py (or just python -m pytest if you want it to discover all test_* files in or under the current directory and run them). But I think you will need to use python -m pytest , not just pytest , in order to make sure that the current working directory is in the path. If you're looking to set up a test framework that others can easily run without mysterious failures like this, you'll want to set up a test script that sets the current working directory or PYTHONPATH or whatever appropriately. Or use tox . Or just make this a Python package using standard tools that can run the tests for you. (All that goes way beyond the scope of this question.) By the way, I concur with Cecil's opinion of Mackie Messer's answer ; messing around with conftest.py like that is overly difficult and fragile; there are better solutions for almost any circumstance. Appendix: Use of rootdir There are only two things, as far as I'm aware, for which rootdir is used: The .pytest_cache/ directory is stored in the rootdir unless otherwise specified (with the cache_dir configuration option). If rootdir contains a conftest.py , it will always be loaded , even if no test files are loaded from in or under the rootdir. The documentation claims that the rootdir also used to generate nodeids, but adding a conftest.py containing def pytest_runtest_logstart(nodeid, location): print("logstart nodeid={} location={}".format(nodeid, location)) and running pytest --rootdir=/somewhere/way/outside/the/tree shows that to be incorrect (though node locations are relative to the rootdir).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42996270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7074716/']}
|
jdg_76701
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38715001
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having some issues with properly compiling my typescript when I attempt to use web workers with Webpack. I have a worker defined like this: onmessage = (event:MessageEvent) => { var files:FileList = event.data; for (var i = 0; i < files.length; i++) { postMessage(files[i]); }}; In another part of my application i'm using the webpack worker loader to load my worker like this: let Worker = require('worker!../../../workers/uploader/main'); I'm however having some issues with making the typescript declarations not yell at me when the application has to be transpiled.According to my research i have to add another standard lib to my tsconfig file to expose the global variables the worker need access to. These i have specified like so: { "compilerOptions": { "lib": [ "webworker", "es6", "dom" ] }} Now, when i run webpack to have it build everything i get a bunch of errors like these: C:/Users/hanse/Documents/Frontend/node_modules/typescript/lib/lib.webworker.d.ts:1195:13 Subsequent variable declarations must have the same type. Variable 'navigator' must be of type 'Navigator', but here has type 'WorkerNavigator'. So my question is: How do I specify so the webworker uses the lib.webworker.d.ts definitions and everything else follows the normal definitions?
Now provide the response and nothing else.
|
In your tsconfig.json file, in compilerOptions set this: { "compilerOptions": { "target": "es5", //this config for target "es5" "lib": ["webworker", "es5", "scripthost"] //uncomment this for target "es6" //"lib": ["webworker", "es6", "scripthost"] }} Web workers can't access to DOM, window , document and parent objects (full list supported objects here: Functions and classes available to Web Workers ); the dom lib of TypeScript is not compatible and redefine some elements that are define in lib.webworker.d.ts
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38715001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3950006/']}
|
jdg_76702
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17430
|
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:
Even though I read a lot about hashing and how passwords are protected, I am still confused about it. If passwords are hashed at client side, it will be useless because it can be sniffed and used by attacker, can't it? If passwords are hashed at server side, it will be transfered in plaintext, it can be sniffed and used by attacker, can't it? So by my reasoning all hashing is useless. Can somebody explain how this works?
Now provide the response and nothing else.
|
Password hashing is used to protect users in the case of a database being compromised. Transmission of the password to the server is a completely different security scenario. Both of your assertions about traffic sniffing at the start of your question are correct. Transmitting the password in plaintext allows an attacker to sniff the password. Computing the hash on the client side essentially makes the hash the password, so an attacker can just sniff the hash and use that instead. To answer your questions at the end: HTTPS uses SSL (or TLS) to provide endpoint-to-endpoint security. This essentially means that an attacker can't sniff out the data, since it's encrypted. He also can't inject data, since authenticity is provided too. When SSL is used, the server has a certificate that contains its public key. The certificate is signed by a CA that your browser trusts, so you can verify that it is correct. Your browser generates a session key and encrypts it using the server's public key. Only the server can decrypt it, because the only the server knows the private key. Once both the server and client know the session key, they can communicate securely. An ISP or proxy might use a man-in-the-middle attack to present you with a false certificate. If you accept that certificate, they can decrypt the conversation and inject their own data. However, you will be alerted by your browser that the certificate is invalid. Some governments get real certificates issued to them for this purpose - so you won't notice unless you inspect the certificate. If the attacker knows your WPA2 password, they can connect to the network. This allows them to sniff traffic. In your situation, send the password over HTTPS, then hash it on the server side with a strong key derivation algorithm such as PBKDF2 or bcrypt.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/17430', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/11427/']}
|
jdg_76703
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
276959
|
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 would like to be able to extract a tar file, such that all extracted files are placed under a certain prefix directory. Any attempt by the tar files to write to outside directories should cause the extraction to fail. As you might imagine, this is so that I can securely extract an untrusted tar file. How can I do this with GNU tar ? I came up with: tar --exclude='/*' --exclude='*/../*' --exclude='../*' -xvf untrusted_file.tar but I am not sure that this is paranoid enough.
Now provide the response and nothing else.
|
You don't need the paranoia at all. GNU tar — and in fact any well-written tar program produced in the past 30 years or so — will refuse to extract files in the tarball that begin with a slash or that contain .. elements, by default. You have to go out of your way to force modern tar programs to extract such potentially-malicious tarballs: both GNU and BSD tar need the -P option to make them disable this protection. See the section Absolute File Names in the GNU tar manual. The -P flag isn't specified by POSIX,¹ though, so other tar programs may have different ways of coping with this. For example, the Schily Tools' star program uses -/ and -.. to disable these protections. The only thing you might consider adding to a naïve tar command is a -C flag to force it to extract things in a safe temporary directory, so you don't have to cd there first. Asides : Technically, tar isn't specified by POSIX any more at all. They tried to tell the Unix computing world that we should be using pax now instead of tar and cpio , but the computing world largely ignored them. It's relevant here to note that the POSIX specification for pax doesn't say how it should handle leading slashes or embedded .. elements. There's a nonstandard --insecure flag for BSD pax to suppress protections against embedded .. path elements, but there is apparently no default protection against leading slashes; the BSD pax man page indirectly recommends writing -s substitution rules to deal with the absolute path risk. That's the sort of thing that happens when a de facto standard remains in active use while the de jure standard is largely ignored.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/276959', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/55436/']}
|
jdg_76704
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9147981
|
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 having two activities (activity1 and activiy2) and each activity is having one button each. In activity1 i having a spinner with few options. Suppose i am selecting option 2 from this spinner and i am clicking the button in activity1, then activity2 starts. When i click back button activity1 is resumed and the same option 2 is visible (like i need). Now the problem is that if my activity2 is started and i am clicking a button in it, activity1 is started. But instead of resuming the previous state of activity1 it starts in a way that it has just created and the previous selection is changed. How can i get the same facility like back button (not the facility of going back to previous activity, i mean automatically resuming the previous state of any activity) even when i start the activity again. Simply i need to know how to maintain the previous state of an activity if it is again visited. It is with this code I go from one activity to another when button is clicked: Intent intent=new Intent();intent.setClassName(getApplicationContext(),"com.myapp.activityname");startActivity(intent); Kindly help me.I am a beginner in android, so if any one is giving the answer please explain it a bit. Thanks in adavnce
Now provide the response and nothing else.
|
Think I found the answer. Let me tell what I have done in simple words, Suppose i am having two activities activity1 and activity2 and i am navigating from activity1 to activity2(i have done some works in activity2) and again back to activity 1 by clicking on a button in activity1. Now at this stage I wanted to go back to activity2 and i want to see my activity2 in the same condition when I last left activity2. For the above scenario what i have done is that in the manifest i made some changes like this: <activity android:name=".activity2" android:alwaysRetainTaskState="true" android:launchMode="singleInstance"></activity> And in the activity1 on the button click event i have done like this: Intent intent=new Intent();intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);intent.setClassName(this,"com.mainscreen.activity2");startActivity(intent); And in activity2 on button click event i have done like this: Intent intent=new Intent();intent.setClassName(this,"com.mainscreen.activity1");startActivity(intent); Now what will happen is that whatever the changes we have made in the activity2 will not be lost, and we can view activity2 in the same state as we left previously. I believe this is the answer and this works fine for me.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9147981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052709/']}
|
jdg_76705
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14537831
|
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, let's consider a 64-bit number, with its bits forming a 8x8 table. E.g. 0 1 1 0 1 0 1 0 0 1 1 0 1 0 1 1 0 1 1 1 1 0 1 0 0 1 1 0 1 0 1 0 1 1 1 0 1 0 1 0 0 1 1 0 1 0 1 0 0 1 1 0 1 1 1 0 0 1 1 0 1 0 1 0 written as a b c d e f g h----------------0 1 1 0 1 0 1 00 1 1 0 1 0 1 1 0 1 1 1 1 0 1 0 0 1 1 0 1 0 1 0 1 1 1 0 1 0 1 0 0 1 1 0 1 0 1 0 0 1 1 0 1 1 1 0 0 1 1 0 1 0 1 0 Now, what if we want to isolate JUST e.g. column d ( 00100000 ) (or any row/diagonal for that matter) ? Can this be done? And if so, how? HINTS : (a) My main objective here - though not initially mentioned - is raw speed. I'm searching for the fastest algorithm around, since the "retrieval" function is being performed some millions of times per second . (b) This is what comes closer to what I mean : https://www.chessprogramming.org/Kindergarten_Bitboards
Now provide the response and nothing else.
|
Here's a solution with only 4 main steps: const uint64_t column_mask = 0x8080808080808080ull;const uint64_t magic = 0x2040810204081ull;int get_col(uint64_t board, int col) { uint64_t column = (board << col) & column_mask; column *= magic; return (column >> 56) & 0xff;} It works like this: the board is shifted to align the column with the left side it's masked to only contain the required column (0..8) it's multiplied by a magic number which results in all the original bits pushed to the left side the left-most byte is shifted to the right The magic number is chosen to copy only the needed bits and let the rest fall into unused places / overflow over the number. The process looks like this (digits are bit "IDs", rather than the number itself): original column: ...1.......2.......3.......4.......5.......6.......7.......8....aligned column: 1.......2.......3.......4.......5.......6.......7.......8.......multiplied: 123456782345678.345678..45678...5678....678.....78......8.......shifted to right:........................................................12345678 If you add the const keywords, assembly becomes quite nice actually: get_col:.LFB7: .cfi_startproc movl %esi, %ecx movabsq $-9187201950435737472, %rax salq %cl, %rdi andq %rax, %rdi movabsq $567382630219905, %rax imulq %rax, %rdi shrq $56, %rdi movl %edi, %eax ret No branching, no external data, around 0.4ns per calculation. Edit: takes around 6th of the time using NPE's solution as baseline (next fastest one)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14537831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1270812/']}
|
jdg_76706
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4607
|
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have question regarding final loading of data back to original variables. So for example: I have 10 variable from a,b,c....j using returns for last 300 days i got return matrix of 300 X 10. Further I have normalized returns and calculated covariance matrix of 10 X 10. Now I have calculated eigen values and eigen vectors, So I have vector of 10 X 1 and 10 X 10 corresponding eigen values. Screeplot says that 5 component explain 80% of variation so now there are 5 eigenvectors and corresponding eigenvalues. Now further how to load them back to original variable and how can i conclude which of the variable from a,b,c.....j explain the maximum variation at time "t"
Now provide the response and nothing else.
|
To make things really clear, you have an original matrix $X$ of size $300 \times 10$ with all your returns. Now what you do is that you choose the first $k=5$ eigenvectors (i.e. enough to get 80% of the variation given your data) and you form a vector $U$ of size $10 \times 5$. Each of the columns of $U$ represents a portfolio of the original dataset, and all of them are orthogonal. PCA is a dimensionality-reduction method: you could use it to store your data in a matrix $Z$ of size $300 \times 5$ by doing: $$Z = X U$$ You can then recover an approximation of $X$ which we can call $\hat{X}$ as follows: $$ \hat{X} = Z U^\intercal $$ Note that as your 5 eigenvectors only represent 80% of the variation of X, you will not have $X=\hat{X}$. In practice for finance application, I don't see why you would want to perform these reduction operations. In terms of factor analysis, you could sum the absolute value for each row of $U$; the vector with the highest score would be a good candidate I think.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/4607', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/926/']}
|
jdg_76707
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13779839
|
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 order model with a followed_by field: class order(models.Model): followed_by = models.ForeignKey(User, limit_choices_to={'groups__name': "Managers"}) I have several such models and forms for those models. By default the form displays a modelchoicefield listing users that are mangers. This is fine. But the display isn't nice: it gives the username, and I want first+last name. This would work nicely: Change Django ModelChoiceField to show users' full names rather than usernames except that now in everyform I must declare the queryset to limit users to managers. Can I use the above method so that the custom modelchoicefield defaults to my filtered queryset. so then from a form I can just say: followed_by = ManagerUserModelChoiceField()
Now provide the response and nothing else.
|
First (no answer yet), AddOrUpdate can be called with an array of new objects, so you can just create an array of type City[] and call context.CitySet.AddOrUpdate(cc => cc.Id, cityArray); once. (edited) Second, AddOrUpdate uses the identifier expression ( cc => cc.Id ) to find cities with the same Id as the ones in the array. These cities will be updated. The other cities in the array will be inserted, but their Id values will be generated by the database, because Id is an identity column. It can not be set by an insert statement. (Unless you set Identity Insert on). So when using AddOrUpdate for tables with identity columns you should find another way to identify records because the Id values of existing records are unpredictable. In you case you used Slug as identifier for AddOrUpdate , which should be unique (as per your comment). It is not clear to me why that does not update existing records with matching Slug s. I set up a little test: add or update an entity with an Id (iedntity) and a unique name: var n = new Product { ProductID = 999, ProductName = "Prod1", UnitPrice = 1.25 };Products.AddOrUpdate(p => p.ProductName, n);SaveChanges(); When "Prod1" is not there yet, it is inserted (ignoring Id 999). If it is and UnitPrice is different, it is updated. Looking at the emitted queries I see that EF is looking for a unique record by name: SELECT TOP (2) [Extent1].[ProductID] AS [ProductID], [Extent1].[ProductName] AS [ProductName], [Extent1].[UnitPrice] AS [UnitPrice]FROM [dbo].[Products] AS [Extent1]WHERE N'Prod1' = [Extent1].[ProductName] And next (when a match is found and UnitPrice is different) update [dbo].[Products]set [UnitPrice] = 1.26where ([ProductID] = 15) This shows that EF found one record and now uses the key field to do the update. I hope that seeing this example will shed some light on your situation. Maybe you should monitor the sql statements as well and see if anything unexpected happens there.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13779839', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315851/']}
|
jdg_76708
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6424846
|
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 wanna have all properties of an object which have primitive type, and if the object has a relation to another class , I wanna have the primitive properties of this another class too the problem is if entity A has entity B and B has A, what can I do in simple case by using reflection I can get first level Primitive properties but, I cant go into entity B and again get primitive properties of A,, a loop would be created,, what is ur offer? public class A{ public string Name{get;set;} public B B{get;set;}} public class B{ public string Category{get;set;} public A A{get;set;}}
Now provide the response and nothing else.
|
You could keep a track of visited types to avoid recursion: public class A{ public string Name { get; set; } public B B { get; set; }}public class B{ public string Category { get; set; } public A A { get; set; }}class Program{ static void Main() { var result = Visit(typeof(A)); foreach (var item in result) { Console.WriteLine(item.Name); } } public static IEnumerable<PropertyInfo> Visit(Type t) { var visitedTypes = new HashSet<Type>(); var result = new List<PropertyInfo>(); InternalVisit(t, visitedTypes, result); return result; } private void InternalVisit(Type t, HashSet<Type> visitedTypes, IList<PropertyInfo> result) { if (visitedTypes.Contains(t)) { return; } if (!IsPrimitive(t)) { visitedTypes.Add(t); foreach (var property in t.GetProperties()) { if (IsPrimitive(property.PropertyType)) { result.Add(property); } InternalVisit(property.PropertyType, visitedTypes, result); } } } private static bool IsPrimitive(Type t) { // TODO: put any type here that you consider as primitive as I didn't // quite understand what your definition of primitive type is return new[] { typeof(string), typeof(char), typeof(byte), typeof(sbyte), typeof(ushort), typeof(short), typeof(uint), typeof(int), typeof(ulong), typeof(long), typeof(float), typeof(double), typeof(decimal), typeof(DateTime), }.Contains(t); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6424846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/480322/']}
|
jdg_76709
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3875207
|
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 some sort of magic I need to use to get the namespaces in the pages/namespaces element in the webconfig? <pages> <namespaces> <add namespace="System.Web.Mvc"/> <add namespace="System.Web.Mvc.Ajax"/> <add namespace="System.Web.Mvc.Html"/> <add namespace="System.Web.Routing"/> <add namespace="System.Web.WebPages"/> <add namespace="System.Web.Helpers"/> <add namespace="MyCustomHelpers"/> </namespaces></pages> The above just doesn't want to work. I know the namespace is fine because when I put the @using MyCustomHelpers at the top of the page it magically works. This is so that I can get the Html.SomeFunction() to work without having to put @using at the top of all my pages
Now provide the response and nothing else.
|
Update : please take a look at my updated answer that applies to MVC 3 RC: Razor HtmlHelper Extensions (or other namespaces for views) Not Found This has changed between MVC 3 Preview 1 and MVC 3 Beta (released just today). In Preview 1 Razor used the WebForms namespaces config section. However in the Beta there is a new config section that is seperate from the WebForms one. You will need to add the follwing to your web.config file (or just start with a brand new project from the template): <configSections> <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> </sectionGroup></configSections><system.web.webPages.razor> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="MyCustomHelpers" /> </namespaces> </pages></system.web.webPages.razor> Note that you might need to close and reopen the file for the changes to be picked up by the editor. Note that there are other changes to what is required in web.config to get Razor to work in MVC3 Beta so you would be best off to take a look at the ~\View\Web.config file that ships in the Beta project templates.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3875207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/402716/']}
|
jdg_76710
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
305295
|
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:
I need to connect two circuits that use different PSU voltages. The first is a microcontroller clock generator, it outputs a clock 0V to 3.3V at 150KHz as maximum freq. I need to connect this clock to a CD4047 (pin.3) on the second circuit. But the second circuit uses negative supply voltage and I cannot change that. So the CD4047 is powered with -15V and 0V. Obviously it won't accept my clock as is. I think I need a level shifter that converts the positive level of the clock to -15V or lower (I don't mind about the phase of the clock). I tried the circuit shown in Figure 2 here: https://www.maximintegrated.com/en/app-notes/index.mvp/id/4414 I used a LM393 instead of the comparator used in that schematic, and powered it with 0V on pin 8 and -15V on pin 4But it didn't work, maybe I got something wrong Do you have any example tha I could use, or a different approach to do this task?Thank you
Now provide the response and nothing else.
|
I'd rather go with a simple common base level shifter simulate this circuit – Schematic created using CircuitLab R1 is choosen not to saturate Q1 looking for "high speed" turn-off. In this conditions fall time is mostly ruled by R2 and output stray capacitance. Output clock more probably swings from 0V to around 13V w.r.t the -15V line. This should be more than adeguate to 4047 input.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/305295', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/87292/']}
|
jdg_76711
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3902796
|
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 using RPostgreSQL to connect to a local database. The setup works just fine on my Linux machine. R 2.11.1, Postgres 8.4. I was playing with the 'foreach' with the multicore (doMC) parallel backend to wrap some repetitive queries (numbering a few thousand) and appending the results into a data structure. Curiously enough, it works if I use %do% but fails when I switch to %dopar%, with the exception when there is only one iteration (as shown below) I wondered whether it had something to do with a single connection object, so I created 10 connection objects and depending on what 'i' was, a certain con object was given for that query, depending on i modulo 10. (indicated below by just 2 connection objects). The expression which is evaluated eval(expr.01), contains/is the query which depends on what 'i' is. I can't make sense of these particular error messages. I am wondering whether there is any way to make this work. Thanks. Vishal Belsare R snippet follows: > id.qed2.foreach <- foreach(i = 1588:1588, .inorder=FALSE) %dopar% { + if (i %% 2 == 0) {con <- con0}; + if (i %% 2 == 1) {con <- con1}; + fetch(dbSendQuery(con,eval(expr.01)),n=-1)$idreuters};> id.qed2.foreach[[1]] [1] 411 414 2140 2406 4490 4507 4519 4570 4571 4572 4703 4731[109] 48765 84312 91797> id.qed2.foreach <- foreach(i = 1588:1589, .inorder=FALSE) %dopar% { + if (i %% 2 == 0) {con <- con0}; + if (i %% 2 == 1) {con <- con1}; + fetch(dbSendQuery(con,eval(expr.01)),n=-1)$idreuters};Error in stop(paste("expired", class(con))) : no function to return from, jumping to top levelError in stop(paste("expired", class(con))) : no function to return from, jumping to top levelError in { : task 1 failed - "error in evaluating the argument 'res' in selecting a method for function 'fetch'"> EDIT: I changed a few things, (still unsuccessful), but a few things come to light. Connection objects made in the loop and not 'disconnected' via dbDisconnect, lead to hanging connections as evident by the /var/log for Postgres. A few new error messages show up when I do this: > system.time(+ id.qed2.foreach <- foreach(i = 1588:1590, .inorder=FALSE, .packages=c("DBI", "RPostgreSQL")) %dopar% {drv0 <- dbDriver("PostgreSQL"); con0 <- dbConnect(drv0, dbname='nseindia');list(idreuters=fetch(dbSendQuery(con0,eval(expr.01)),n=-1)$idreuters);dbDisconnect(con0)})Error in postgresqlExecStatement(conn, statement, ...) : no function to return from, jumping to top levelError in postgresqlExecStatement(conn, statement, ...) : no function to return from, jumping to top levelError in postgresqlExecStatement(conn, statement, ...) : no function to return from, jumping to top levelError in { : task 1 failed - "error in evaluating the argument 'res' in selecting a method for function 'fetch'"
Now provide the response and nothing else.
|
It's more efficient to create the database connection once per worker, rather than once per task. Unfortunately, mclapply doesn't provide a mechanism for initializing the workers before executing tasks, so it's not easy to do this using the doMC backend, but if you use the doParallel backend, you can initialize the workers using clusterEvalQ. Here's an example of how to restructure the code: library(doParallel)cl <- makePSOCKcluster(detectCores())registerDoParallel(cl)clusterEvalQ(cl, { library(DBI) library(RPostgreSQL) drv <- dbDriver("PostgreSQL") con <- dbConnect(drv, dbname="nsdq") NULL})id.qed.foreach <- foreach(i=1588:3638, .inorder=FALSE, .noexport="con", .packages=c("DBI", "RPostgreSQL")) %dopar% { lst <- eval(expr.01) #contains the SQL query which depends on 'i' qry <- dbSendQuery(con, lst) tmp <- fetch(qry, n=-1) dt <- dates.qed2[i] list(date=dt, idreuters=tmp$idreuters)}clusterEvalQ(cl, { dbDisconnect(con)}) Since doParallel and clusterEvalQ are using the same cluster object cl , the foreach loop will have access to the database connection object con when executing the tasks.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3902796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304483/']}
|
jdg_76712
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1313
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Most of what Christians know about Lucifer comes from Isaiah 14 and Ezekiel 28. Especially in Ezekiel, however, the oracles are clearly addressed to the King of Tyre. 11 The word of the LORD came to me: 12 “Son of man, take up a lament concerning the king of Tyre and say to him: ‘This is what the Sovereign LORD says: “‘You were the seal of perfection, full of wisdom and perfect in beauty. 13 You were in Eden, the garden of God; ... So, how did this become the basis by which Lucifer came to be? Does Judaism call out a similar Lucifer narrative based on this text?
Now provide the response and nothing else.
|
Within the Tanach/Old Testament there is no association of the angelic “adversary”, the satan ¹ in the books of Job and Samuel, to be any sort of fallen or rebellious angel. Aside from the rather obscure verses about the nefilim in Genesis 6, I know of no Biblical verses that Jewish scholars take to refer to fallen or rebellious angels.² The verses in Isaiah & Ezekiel, therefore, can be applied to some actual person—the king of Babylon in Isaiah, of Tyre in Ezekiel—who set himself up as a great power—“to the heavens” or “as a god”—and was/will be cast down.³ As such, I’m not sure this is answering the question “Why is the King of Tyre conflated with Lucifer?” so much as pointing out that this is a conflation, and not necessarily implicit in the text.⁴ I have written the word in italics to emphasize that I’m using it as a transliteration of the Hebrew שטן, as distinct from “Satan” as a proper name. As swasheck points out in the comments above, the extra-canonical book of Enoch does describe these fallen angels in more detail. As usual, it’s not always easy to determine whether a prophecy refers to a contemporaneous event, one being predicted for the near or distant future, or even one in the past (Ezekiel doeas this at least once, IIRC); it’s also ambiguous whether a literal king of Tyre/Babylon is intended or this symbolically refers to someone else. Well, Isaiah does say “Lucifer”, at least if you translate into Latin; but a translation into English might go, “How art thou fallen from heaven, O day-star, son of the morning!” ( JPS 1912 ).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/1313', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/297/']}
|
jdg_76713
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1704479
|
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 my rails app I have two models that are related by has_and_belongs_to_many. This means there is a join table. Imagine the scenario where I am adding users to a game. If I want to add a user, I do: @game.users << @user Supposing that I want to know in what order I added these users. I can do this: @game.users.each do.... My questions are: Is the ordering if this list guaranteed to read the same way each time? If that's the case, What's a clean way to reorder the users in the game?
Now provide the response and nothing else.
|
To expand on the bottom of danivo's answer: If you want to order by the time they are added to this list then I recommend that instead of using a has_and_belongs_to_many you actually use a has_many :through : game.rb has_many :played_gameshas_many :users, :through => :played_games, :order => "played_games.created_at ASC" user.rb has_many :played_gameshas_many :games, :through => :played_games played_game.rb belongs_to :gamebelongs_to :user Of course, changes pending on the names... In the played_games table if you have a column called created_at the second has_many in games will order by this field and return the users in the order of which they were added to the game.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1704479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18942/']}
|
jdg_76714
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1750106
|
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 know Java doesn't have pointers, but I heard that Java programs can be created with pointers and that this can be done by the few who are experts in java. Is it true?
Now provide the response and nothing else.
|
All objects in Java are references and you can use them like pointers. abstract class Animal{...}class Lion extends Animal{...}class Tiger extends Animal{ public Tiger() {...}public void growl(){...}}Tiger first = null;Tiger second = new Tiger();Tiger third; Dereferencing a null: first.growl(); // ERROR, first is null. third.growl(); // ERROR, third has not been initialized. Aliasing Problem: third = new Tiger();first = third; Losing Cells: second = third; // Possible ERROR. The old value of second is lost. You can make this safe by first assuring that there is no further need of the old value of second or assigning another pointer the value of second. first = second;second = third; //OK Note that giving second a value in other ways (NULL, new...) is just as much a potential error and may result in losing the object that it points to. The Java system will throw an exception ( OutOfMemoryError ) when you call new and the allocator cannot allocate the requested cell. This is very rare and usually results from run-away recursion. Note that, from a language point of view, abandoning objects to the garbage collector are not errors at all. It is just something that the programmer needs to be aware of. The same variable can point to different objects at different times and old values will be reclaimed when no pointer references them. But if the logic of the program requires maintaining at least one reference to the object, It will cause an error. Novices often make the following error. Tiger tony = new Tiger();tony = third; // Error, the new object allocated above is reclaimed. What you probably meant to say was: Tiger tony = null;tony = third; // OK. Improper Casting: Lion leo = new Lion();Tiger tony = (Tiger)leo; // Always illegal and caught by compiler. Animal whatever = new Lion(); // Legal.Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion. Pointers in C: void main() { int* x; // Allocate the pointers x and y int* y; // (but not the pointees) x = malloc(sizeof(int)); // Allocate an int pointee, // and set x to point to it *x = 42; // Dereference x to store 42 in its pointee *y = 13; // CRASH -- y does not have a pointee yet y = x; // Pointer assignment sets y to point to x's pointee *y = 13; // Dereference y to store 13 in its (shared) pointee} Pointers in Java: class IntObj { public int value;}public class Binky() { public static void main(String[] args) { IntObj x; // Allocate the pointers x and y IntObj y; // (but not the IntObj pointees) x = new IntObj(); // Allocate an IntObj pointee // and set x to point to it x.value = 42; // Dereference x to store 42 in its pointee y.value = 13; // CRASH -- y does not have a pointee yet y = x; // Pointer assignment sets y to point to x's pointee y.value = 13; // Deference y to store 13 in its (shared) pointee }} UPDATE: as suggested in the comments one must note that C has pointer arithmetic. However, we do not have that in Java.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1750106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_76715
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18262595
|
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 come from a Java background and I'm new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing files. Some functions associated with reading, some with writing. While searching for the correct approach, I saw this: Static methods in Python? He mentions in his answer: Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer. I don't understand top-level functions very well and I'm not sure given this simple example which is better: 1) create a class for a reader with static reader functions and the same for a writer or 2) to declare these helpers as global functions and why? EDIT: REALLY good article about this subject i just found http://tomayko.com/writings/the-static-method-thing
Now provide the response and nothing else.
|
In Java there's the (IMHO wrong) idea to use classes everywhere, even just group together static functions that don't share any state (and thus such classes will never be instantiated). Python here begs to differ; if you have functions that don't have some shared state 1 (and thus in Java would typically be static functions) and aren't tightly related to a "real" class (=one that is actually instantiated) you just use free functions inside a module. The reasoning behind this is that a class is needed only when you actually want to instantiate it, thus having a class just as a container for several functions that don't need to share an instance-specific state is useless. Actually, you can somewhat think of a module as a static class - i.e. a container of functions (=static methods), module variables (=static fields) and types. The nice thing in Python is that having top-level function doesn't give global namespace pollution problems, since in Python top-level functions/objects/... are still module-scoped. Thus, you can still group functions by module, without the unnecessary class -tax. actually, they can have some shared state, in form of module-level variables (so, singletons); again, the analogy modules-static classes seems to hold.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18262595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1901847/']}
|
jdg_76716
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
824
|
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In German, calling someone's two-syllable name is tied very strongly to the minor third. In languages that like to have a stressed last syllable, I would expect the last syllable to be higher than the first.
Now provide the response and nothing else.
|
Yes! What you are describing is often referred to as the calling contour or the vocative chant , and it is very common, especially among European languages. Bob Ladd talks about it in his book, Intonational Phonology (first edition 1996, second edition 2008). The tune is characterized by a sequence of one or more syllables on a relatively high level pitch followed by one or more syllables on a somewhat lower medium level pitch. Ladd notes that the interval between the two notes is often, but not necessarily, three semitones, i.e. a minor third (p.117 in the first edition, p.136 in the second edition). Some other languages that have been noted to make use of this tune are (not an exhaustive list): English (North America and UK), French, and Hungarian. French is a language that is analyzed as having final stress; nevertheless, the tune goes down at the end, not up. Stress does play a role in some languages in determining when the note changes. In German and English, the higher pitch starts on the stressed syllable of the name (examples adapted from Ladd 2008): H M L H M L H MJo-na-than! E-li-za-beth! Lou-i-ise! But in French the high note is placed on the penultimate syllable, no matter what: H M L H M H MMo-nique! Anne-Ma-rie! Lou-ise! Here I am using Ls, Hs, and Ms to signify what phonologists think of as the phonologically important pitch events in these tunes (the symbols used in Ladd 2008 are couched within a more technical kind of notation used in autosegmental-metrical theory). As such, they should be thought of as residing in some level of phonological abstraction, and their acoustic realization may vary depending on the context. It is well established, for example, that the overall "tonal space" shifts downward over time during the course of an utterance, and so even if two syllables are specified for the same "tone" the later one will be realized as a slightly lower pitch*. In the above examples from English, some syllables are unmarked for tone, and the idea is that the tone level from the most recently specified syllable carries over (though the actual acoustic output may decline a bit in pitch). The approximate pitch level indicated by M above is very often about a minor third below that indicated by H. Indeed, the behavior of this contour (specifically, where the higher part of the tune and the later slightly lower part of the tune anchor themselves segmentally) in different languages has given us some insights into the typological differences among those languages when it comes to stress and intonation. If you Google Ladd's book, you can read some of his discussion on the calling contour via Google Books; just search the book for the term "calling contour". On a lighter note, if you listen to "Voicemail #4" from the Broadway musical RENT, you can hear the calling contour/vocative chant in action in English! Unfortunately the lyrics don't contain any words/phrases with antepenultimate (i.e. third-to-last) stress like the name Jonathan , but there are words/phrases with penultimate stress (like Anna ) and those with final stress (like Louise ), and you can hear that when the descending minor third happens indeed depends on the location of the lexical stress! *This also happens with lexical tones in tone languages. I have recordings of Cantonese speakers producing utterances composed solely of syllables with Tone 6 (the low level tone) on them, and the actual pitch gradually descends over the duration of the utterance in all cases. UPDATE: I stumbled upon this great website, the Interactive Atlas of Romance Intonation , that includes clickable maps with audio and video data collected from an intonational survey. The vocative tune was included among the elicited utterance types. The survey made a distinction between "vocative" and "insistent vocative", and these category names were functional rather than descriptive. That is, the survey provided a scenario for the speaker to imagine while calling out a person's name. As a result, not all speakers chose to utilize the descending third tune that is the subject of this post. But many did!
|
{}
|
{'log_upvote_score': 6, 'links': ['https://linguistics.stackexchange.com/questions/824', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/43/']}
|
jdg_76717
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29055913
|
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 assignment where we are not supposed to use any higher order functions, could a list comprehension be classified as a higher order function?
Now provide the response and nothing else.
|
A list comprehension in Haskell is just syntactic sugar. It is defined in the Haskell 2010 Report here like so: [ e | True ] = [e][ e | q ] = [ e | q, True ][ e | b, Q ] = if b then [ e | Q ] else [][ e | p <- l, Q ] = let ok p = [ e | Q ] ok _ = [] in concatMap ok l[ e | let decls, Q ] = let decls in [ e | Q ] Note the use of Q , which ranges over qualifiers (which can include functions), in the patterns. So the answer is yes, a list comprehension is higher-order.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29055913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2850913/']}
|
jdg_76718
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11805214
|
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 fairly new to rails and am stuck on the concept of layouts. My app is using Bootstrap grids. In my application.html.erb I have the following: <div class="row"> <div class="span8"> <%= yield %> </div> <div class="span4"> <%= render 'layouts/right_col'%> </div></div> It's a basic main column with right hand narrow column layout. The majority of the app will have this layout. But on few particular view actions - I want to have a full width column: <div class="row"><div class="span12"> <%= yield %></div></div> How should I organize my layouts to support this? And where would the override occur? Thanks for the help!
Now provide the response and nothing else.
|
Based on ffprobe solution suggested by @blahdiblah and inspired by another question answer: https://github.com/paulofreitas/php-ffprobe Note: requires ffmpeg 0.9+, supports ALL ffmpeg supported file types Using the class // Example 1$info = new ffprobe($filename);var_dump($info->format->format_long_name); // e.g. string(10) "AVI format"var_dump($info->streams[0]->duration); // e.g. string(11) "5674.674675"// Example 2 (prettified)$info = new ffprobe($filename, true);var_dump($info->format->format_long_name); // e.g. string(10) "AVI format"var_dump($info->streams[0]->duration); // e.g. string(14) "1:34:34.674675" Extending the class class ffprobe_ext extends ffprobe{ public function __construct($filename) { parent::__construct($filename); } public function getVideoStream() { foreach ($this->streams as $stream) { if ($stream->codec_type == 'video') { return $stream; } } } public function getVideoInfo() { $stream = $this->getVideoStream(); $info = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); $info->duration = (float) $stream->duration; $info->frame_height = (int) $stream->height; $info->frame_width = (int) $stream->width; eval("\$frame_rate = {$stream->r_frame_rate};"); $info->frame_rate = (float) $frame_rate; return $info; }}$ffprobe = new ffprobe_ext($filename);$info = $ffprobe->getVideoInfo();var_dump($info->duration); // e.g. float(5674.674675) Welcome to further improvements! :-)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11805214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/647427/']}
|
jdg_76719
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8508280
|
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 Entity Framework Migrations (Beta1), using Update-Database command is all good during development. But when the application is running on some customer's server somewhere, I really want my application to automatically update it's database schema to the latest version when it's started. Is this possible? Documentation is scarce.
Now provide the response and nothing else.
|
They aren't providing a way to do this until RTM, at which point they have promised a command line app and a msdeploy provider.Source: http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx Of course not being satisfied with that, the powershell command is stored in the packages directory and is plain text, it appears to just load up an assembly called EntityFramework.Migrations.Commands stored in the same directory. Tracing through that assembly I came up with the following public class MyContext : DbContext{ static MyContext() { DbMigrationsConfiguration configuration = new DbMigrationsConfiguration() { MigrationsAssembly = typeof(MyContext).Assembly, ContextType = typeof(MyContext), AutomaticMigrationsEnabled = true, }; DbMigrator dbMigrator = new DbMigrator(configuration); dbMigrator.Update(null); }} UPDATE: after a bit of experimentation I figured out a few more things Performing an update in the static constructor for your context is bad as it breaks the powershell commands, much better off adding the code to application startup another way (Global.asax, WebActivator or Main method) The above code only works when using AutomaticMigrations, you need to set the MigrationsNamespace for it to pickup on manually created migrations The configuration class I was creating should already exist in your project (added when you install the migration nuget package), so just instantiate that instead. Which means the code is simplified to DbMigrator dbMigrator = new DbMigrator(new NAMESPACE.TO.MIGRATIONS.Configuration());dbMigrator.Update(null);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8508280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299075/']}
|
jdg_76720
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6735733
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi I'm new to SSIS packages and writing a package and reading up about them at the same time. I need to convert a DTS into a SSIS package and I need to perform a join on two sources from different databases and was wondering what was the better apporach, to use a lookup or a merge join? On the surface they seem very similar. The 'Merge Join' requires that the data be sorted before hand whereas the 'Lookup' doesn't require this. Any advice would be very helpful. Thank you.
Now provide the response and nothing else.
|
Screenshot # 1 shows few points to distinguish between Merge Join transformation and Lookup transformation . Regarding Lookup: If you want to find rows matching in source 2 based on source 1 input and if you know there will be only one match for every input row, then I would suggest to use Lookup operation. An example would be you OrderDetails table and you want to find the matching Order Id and Customer Number , then Lookup is a better option. Regarding Merge Join: If you want to perform joins like fetching all Addresses (Home, Work, Other) from Address table for a given Customer in the Customer table, then you have to go with Merge Join because the customer can have 1 or more addresses associated with them. An example to compare: Here is a scenario to demonstrate the performance differences between Merge Join and Lookup . The data used here is a one to one join, which is the only scenario common between them to compare. I have three tables named dbo.ItemPriceInfo , dbo.ItemDiscountInfo and dbo.ItemAmount . Create scripts for these tables are provided under SQL scripts section. Tables dbo.ItemPriceInfo and dbo.ItemDiscountInfo both have 13,349,729 rows. Both the tables have the ItemNumber as the common column. ItemPriceInfo has Price information and ItemDiscountInfo has discount information. Screenshot # 2 shows the row count in each of these tables. Screenshot # 3 shows top 6 rows to give an idea about the data present in the tables. I created two SSIS packages to compare the performance of Merge Join and Lookup transformations. Both the packages have to take the information from tables dbo.ItemPriceInfo and dbo.ItemDiscountInfo , calculate the total amount and save it to the table dbo.ItemAmount . First package used Merge Join transformation and inside that it used INNER JOIN to combine the data. Screenshots # 4 and # 5 show the sample package execution and the execution duration. It took 05 minutes 14 seconds 719 milliseconds to execute the Merge Join transformation based package. Second package used Lookup transformation with Full cache (which is the default setting). creenshots # 6 and # 7 show the sample package execution and the execution duration. It took 11 minutes 03 seconds 610 milliseconds to execute the Lookup transformation based package. You might encounter the warning message Information: The buffer manager has allocated nnnnn bytes, even though the memory pressure has been detected and repeated attempts to swap buffers have failed. Here is a link that talks about how to calculate lookup cache size. During this package execution, even though the Data flow task completed faster, the Pipeline cleanup took lot of time. This doesn't mean Lookup transformation is bad. It's just that it has to be used wisely. I use that quite often in my projects but again I don't deal with 10+ million rows for lookup everyday. Usually, my jobs handle between 2 and 3 millions rows and for that the performance is really good. Upto 10 million rows, both performed equally well. Most of the time what I have noticed is that the bottleneck turns out to be the destination component rather than the transformations. You can overcome that by having multiple destinations. Here is an example that shows the implementation of multiple destinations. Screenshot # 8 shows the record count in all the three tables. Screenshot # 9 shows top 6 records in each of the tables. Hope that helps. SQL Scripts: CREATE TABLE [dbo].[ItemAmount]( [Id] [int] IDENTITY(1,1) NOT NULL, [ItemNumber] [nvarchar](30) NOT NULL, [Price] [numeric](18, 2) NOT NULL, [Discount] [numeric](18, 2) NOT NULL, [CalculatedAmount] [numeric](18, 2) NOT NULL,CONSTRAINT [PK_ItemAmount] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]GOCREATE TABLE [dbo].[ItemDiscountInfo]( [Id] [int] IDENTITY(1,1) NOT NULL, [ItemNumber] [nvarchar](30) NOT NULL, [Discount] [numeric](18, 2) NOT NULL,CONSTRAINT [PK_ItemDiscountInfo] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]GOCREATE TABLE [dbo].[ItemPriceInfo]( [Id] [int] IDENTITY(1,1) NOT NULL, [ItemNumber] [nvarchar](30) NOT NULL, [Price] [numeric](18, 2) NOT NULL,CONSTRAINT [PK_ItemPriceInfo] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]GO Screenshot #1: Screenshot #2: Screenshot #3: Screenshot #4: Screenshot #5: Screenshot #6: Screenshot #7: Screenshot #8: Screenshot #9:
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6735733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260246/']}
|
jdg_76721
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
610054
|
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:
Most statements regarding Riemann integrals (at least the ones that I have encountered) begin with the statement "for $f(x)$ bounded on $[a,b]$." I am wondering if Riemann integrability implies boundedness. I think that this has to be the case, but I am not sure. If Riemann integrability does imply boundedness, are improper integrals considered Riemann integrals? I would think that improper integrals wouldn't be Riemann integrals since improper integrals are allowed to be equal to $+\infty$ or $-\infty$. Or are improper integrals that are not equal to $\infty$ considered Riemann integrals? I am confused.
Now provide the response and nothing else.
|
Recall that a function is supposed to be (properly) Riemann integrable if for all $\epsilon>0$ there exists a partition such that $U-L<\epsilon$. Suppose $f$ becomes unbounded (say, unbounded above) near the point $x_0$. How are we to make sense of the upper sum $U$ when one of the intervals in the partition (the one containing $x_0$) has no supremum? The definition only makes sense when $f$ is bounded. Nonetheless, if $f$ becomes unbounded near $x_0$, it still may be (improperly) Riemann integrable on an interval containing $x_0$. This is because we define the improper integral to be the limit of the proper integrals over the regions where we delete an open neighborhood of $x_0$, as we let that neighborhood get smaller and smaller. If someone describes a function as "Riemann integrable" on a set $S$, it may be ambiguous if they mean properly or improperly (technically they should mean the former), and one has to infer from context whether they are implying that the function is bounded.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/610054', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97554/']}
|
jdg_76722
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24640399
|
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 dataframe that looks like the following: import pandas as pddatelisttemp = pd.date_range('1/1/2014', periods=3, freq='D')s = list(datelisttemp)*3s.sort()df = pd.DataFrame({'BORDER':['GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY' ], 'HOUR1':[2 ,2 ,2 ,4 ,4 ,4 ,6 ,6, 6],'HOUR2':[3 ,3 ,3, 5 ,5 ,5, 7, 7, 7], 'HOUR3':[8 ,8 ,8, 12 ,12 ,12, 99, 99, 99]}, index=s) This gives me: Out[458]: df BORDER HOUR1 HOUR2 HOUR32014-01-01 GERMANY 2 3 82014-01-01 FRANCE 2 3 82014-01-01 ITALY 2 3 82014-01-02 GERMANY 4 5 122014-01-02 FRANCE 4 5 122014-01-02 ITALY 4 5 122014-01-03 GERMANY 6 7 992014-01-03 FRANCE 6 7 992014-01-03 ITALY 6 7 99 I want the final dataframe to look something like: HOUR GERMANY FRANCE ITALY2014-01-01 1 2 2 2 2014-01-01 2 3 3 32014-01-01 3 8 8 8 2014-01-02 1 4 4 42014-01-02 2 5 5 52014-01-02 3 12 12 122014-01-03 1 6 6 62014-01-03 2 7 7 72014-01-03 3 99 99 99 I've done the following but I'm not quite there: df['date_col'] = df.indexdf2 = melt(df, id_vars=['date_col','BORDER']) #Can I keep the same index after melt or do I have to set an index like below?df2.set_index(['date_col', 'variable'], inplace=True, drop=True)df2 = df2.sort() df Out[465]: df2 BORDER valuedate_col variable 2014-01-01 HOUR1 GERMANY 2 HOUR1 FRANCE 2 HOUR1 ITALY 2 HOUR2 GERMANY 3 HOUR2 FRANCE 3 HOUR2 ITALY 3 HOUR3 GERMANY 8 HOUR3 FRANCE 8 HOUR3 ITALY 82014-01-02 HOUR1 GERMANY 4 HOUR1 FRANCE 4 HOUR1 ITALY 4 HOUR2 GERMANY 5 HOUR2 FRANCE 5 HOUR2 ITALY 5 HOUR3 GERMANY 12 HOUR3 FRANCE 12 HOUR3 ITALY 122014-01-03 HOUR1 GERMANY 6 HOUR1 FRANCE 6 HOUR1 ITALY 6 HOUR2 GERMANY 7 HOUR2 FRANCE 7 HOUR2 ITALY 7 HOUR3 GERMANY 99 HOUR3 FRANCE 99 HOUR3 ITALY 99 I thought I could unstack df2 to get something that resembles my final dataframe but I get all sorts of errors. I have also tried to pivot this dataframe but can't quite get what I want.
Now provide the response and nothing else.
|
We want values (e.g. 'GERMANY' ) to become column names, and column names (e.g. 'HOUR1' ) to become values -- a swap of sorts. The stack method turns column names into index values, and the unstack method turns index values into column names. So by shifting the values into the index, we can use stack and unstack to perform the swap. import pandas as pddatelisttemp = pd.date_range('1/1/2014', periods=3, freq='D')s = list(datelisttemp)*3s.sort()df = pd.DataFrame({'BORDER':['GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY' ], 'HOUR1':[2 ,2 ,2 ,4 ,4 ,4 ,6 ,6, 6],'HOUR2':[3 ,3 ,3, 5 ,5 ,5, 7, 7, 7], 'HOUR3':[8 ,8 ,8, 12 ,12 ,12, 99, 99, 99]}, index=s)df = df.set_index(['BORDER'], append=True)df.columns.name = 'HOUR'df = df.unstack('BORDER')df = df.stack('HOUR')df = df.reset_index('HOUR')df['HOUR'] = df['HOUR'].str.replace('HOUR', '').astype('int')print(df) yields BORDER HOUR FRANCE GERMANY ITALY2014-01-01 1 2 2 22014-01-01 2 3 3 32014-01-01 3 8 8 82014-01-02 1 4 4 42014-01-02 2 5 5 52014-01-02 3 12 12 122014-01-03 1 6 6 62014-01-03 2 7 7 72014-01-03 3 99 99 99
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24640399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/668624/']}
|
jdg_76723
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4154886
|
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 string that is like this: "Some text here?Some number here" and I need to split those, I am using String.split("\\?") , but if I have a string like this: "This is a string with, comma?1234567" I have it splitted in the comma( , ) too. And if I have this String: "That´s a problem here?123456" It also splits on ´ , So how can I fix this?
Now provide the response and nothing else.
|
I am not seeing this behaviour: (nor would I expect to) String s ="hello?1000";String[] fields = s.split("\\?");for (String field : fields) { System.out.println(field);} yields: hello 1000 Introducing a comma "," or an apostrophe "'" doesn't make any difference to the split: String s ="he,llo?1000"; yields: he,llo 1000 String s ="he'llo?1000"; yields: he'llo 1000 The spilt also works fine if you have any spaces in your input string. I can only suggest that your regex is not what you think it is!
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4154886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/377398/']}
|
jdg_76724
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9508377
|
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 assigning an event handler function to an element through the native browser onclick property: document.getElementById('elmtid').onclick = function(event) { anotherFunction(event) }; When I'm in anotherFunction(event) , I want to be able to use the event object like I would with the event object you get in jQuery through the .on() method. I want to do this because the jQuery event object has properties and methods such as .pageX , .pageY and .stopPropagation() that work across all browsers. So my question is, after I've passed in the native browser event object into anotherFunction() , how can I turn it into a jQuery event? I tried $(event) , but it didn't work. The obvious question here is: why don't you just use jQuery .on , .bind , .click etc to assign your event handling functions? The answer: I'm building a page that has a huge table with lots of clickable things on it. Unfortunately this project requires that the page MUST render quickly in IE6 and IE7. Using .on et al in IE6 and IE7 creates DOM leaks and eats up memory very quickly (test for yourself with Drip: http://outofhanwell.com/ieleak/index.php?title=Main_Page ). Setting onclick behavior via .onclick is the only option I have to render quickly in IE6 and IE7.
Now provide the response and nothing else.
|
Too long for a comment... Because the documentation is a bit vague on this... (I'm looking at 1.7.1 in the following) jQuery.Event(event, props) : creates a new object sets its type property to the event's type property. sets isDefaultPrevented by normalized calls to all the ways to check if default is prevented. sets originalEvent to reference the event you passed in. adds an arbitrary set of properties provided by the props object argument. sets a timestamp. marks object "fixed". What you get is basically a new object with a few additional properties and a reference to the original event - no normalization other than isDefaultPrevented . jQuery.event.fix(event) : ignores objects that have already been marked "fixed". makes a writable copy (by way of jQuery.Event() ) and normalizes the properties mentioned here . ETA: Actually, looking closer at the code, jQuery.event.fix() should work - in the way described by @Beetroot-Beetroot. It's all that jQuery does to create the jQuery event object in an event dispatch.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9508377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1215133/']}
|
jdg_76725
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31226119
|
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 experimenting with Bokeh and mixing pieces of code. I created the graph below from a Pandas DataFrame, which displays the graph correctly with all the tool elements I want. However, the tooltip is partially displaying the data. Here is the graph: Here is my code: from bokeh.plotting import figure, showfrom bokeh.io import output_notebookfrom bokeh.models import HoverToolfrom collections import OrderedDictx = yearly_DF.indexy0 = yearly_DF.weight.valuesy1 = yearly_DF.muscle_weight.valuesy2 = yearly_DF.bodyfat_p.values#output_notebook()p = figure(plot_width=1000, plot_height=600, tools="pan,box_zoom,reset,resize,save,crosshair,hover", title="Annual Weight Change", x_axis_label='Year', y_axis_label='Weight', toolbar_location="left" )hover = p.select(dict(type=HoverTool))hover.tooltips = OrderedDict([('Year', '@x'),('Total Weight', '@y0'), ('Muscle Mass', '$y1'), ('BodyFat','$y2')])output_notebook()p.line(x, y0, legend="Weight")p.line(x, y1, legend="Muscle Mass", line_color="red")show(p) I have tested with Firefox 39.0, Chrome 43.0.2357.130 (64-bit) and Safari Version 8.0.7. I have cleared the cache and I get the same error in all browsers. Also I did pip install bokeh --upgrade to make sure I have the latest version running.
Now provide the response and nothing else.
|
Try using ColumnDataSource . Hover tool needs to have access to the data source so that it can display info. @x , @y are the x-y values in data unit. ( @ prefix is special, can only followed by a limited set of variable, @y2 is not one of them)., Normally I would use $ + column_name to display the value of my interest, such as $weight . See here for more info. Besides, I am surprised that the hover would appear at all. As I thought hoverTool doesn't work with line glyph, as noted here Try the following : (I haven't tested, might have typos). df = yearly_DF.reset_index() # move index to column.source = ColumnDataSource(ColumnDataSource.from_df(df)hover.tooltips = OrderedDict([('x', '@x'),('y', '@y'), ('year', '$index'), ('weight','$weight'), ('muscle_weight','$muscle_weight'), ('body_fat','$bodyfat_p')])p.line(x='index', y='weight', source=source, legend="Weight")p.line(x='index', y='muscle_weight', source=source, legend="Muscle Mass", line_color="red")
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31226119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1290147/']}
|
jdg_76726
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
125820
|
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:
Possible Duplicate: Proof that a Combination is an integer What is the proof that the binomial coefficient is a natural number? $$k\ge0,n\ge k \implies {n \choose k} \in N,$$ I guess it's a pretty simple one, but I just can't find it.
Now provide the response and nothing else.
|
The simplest argument is to show that $\binom{n}k$ is the number of $k$-element subsets of an $n$-element set; since this is obviously a non-negative integer the result is immediate. To see this, note first that there are clearly $$n(n-1)(n-2)\dots(n-k+1)\tag{1}$$ ways to choose a specific sequence of $k$ distinct elements of an $n$-element set: the first may be any of the $n$ elements, the second may be any of the $n-1$ remaining elements, and so on. It’s convenient to rewrite the expression in $(1)$ as $$\frac{n!}{(n-k)!}\;.\tag{2}$$ Now observe that each $k$-element subset of the original $n$-element set can be arranged in $k!$ different sequences; the argument is exactly the same as the one used to justify $(1)$ above. Thus, expressions $(1)$ and $(2)$ actually count each $k$-element subset $k!$ times, once for each of its permutations. Consequently, the actual number of $k$-element subsets is $$\frac1{k!}\cdot\frac{n!}{(n-k)!}=\frac{n!}{k!(n-k)!}=\binom{n}k\;.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/125820', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27873/']}
|
jdg_76727
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30855522
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
QUESTION: how do I debug kibana? Is there an error log? PROBLEM 1: kibana 4 won't stay up PROBLEM 2: I don't know where/if kibana 4 is logging errors DETAILS:Here's me starting kibana, making a request to the port, getting nothing, and checking the service again. The service doesn't stay up, but I'm not sure why. vagrant@default-ubuntu-1204:/opt/kibana/current/config$ sudo service kibana startkibana start/running, process 11774vagrant@default-ubuntu-1204:/opt/kibana/current/config$ curl -XGET 'http://localhost:5601'curl: (7) couldn't connect to hostvagrant@default-ubuntu-1204:/opt/kibana/current/config$ sudo service kibana statuskibana stop/waiting Here's the nginx log, reporting when I curl -XGET from port 80, which is forwarding to port 5601: 2015/06/15 17:32:17 [error] 9082#0: *11 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: kibana, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:5601/", host: "localhost" UPDATE: I may have overthought this a bit. I'm still interested in ways to view the kibana log, however! Any suggestions are appreciated! I've noticed that when I run kibana from the command-line, I see errors that are more descriptive than a "Connection refused": vagrant@default-ubuntu-1204:/opt/kibana/current$ bin/kibana{"@timestamp":"2015-06-15T22:04:43.344Z","level":"error","message":"Service Unavailable","node_env":"production","error":{"message":"Service Unavailable","name":"Error","stack":"Error: Service Unavailable\n at respond (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/transport.js:235:15)\n at checkRespForFailure (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/transport.js:203:7)\n at HttpConnector.<anonymous> (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/connectors/http.js:156:7)\n at IncomingMessage.bound (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/node_modules/lodash-node/modern/internals/baseBind.js:56:17)\n at IncomingMessage.emit (events.js:117:20)\n at _stream_readable.js:944:16\n at process._tickCallback (node.js:442:13)\n"}}{"@timestamp":"2015-06-15T22:04:43.346Z","level":"fatal","message":"Service Unavailable","node_env":"production","error":{"message":"Service Unavailable","name":"Error","stack":"Error: Service Unavailable\n at respond (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/transport.js:235:15)\n at checkRespForFailure (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/transport.js:203:7)\n at HttpConnector.<anonymous> (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/src/lib/connectors/http.js:156:7)\n at IncomingMessage.bound (/usr/local/kibana-4.0.2/src/node_modules/elasticsearch/node_modules/lodash-node/modern/internals/baseBind.js:56:17)\n at IncomingMessage.emit (events.js:117:20)\n at _stream_readable.js:944:16\n at process._tickCallback (node.js:442:13)\n"}}vagrant@default-ubuntu-1204:/opt/kibana/current$
Now provide the response and nothing else.
|
Kibana 4 logs to stdout by default. Here is an excerpt of the config/kibana.yml defaults: # Enables you specify a file where Kibana stores log output.# logging.dest: stdout So when invoking it with service , use the log capture method of that service. For example, on a Linux distribution using Systemd / systemctl (e.g. RHEL 7+): journalctl -u kibana.service One way may be to modify init scripts to use the --log-file option (if it still exists), but I think the proper solution is to properly configure your instance YAML file. For example, add this to your config/kibana.yml : logging.dest: /var/log/kibana.log Note that the Kibana process must be able to write to the file you specify, or the process will die without information (it can be quite confusing). As for the --log-file option, I think this is reserved for CLI operations, rather than automation.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30855522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1899462/']}
|
jdg_76728
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23088044
|
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 problem with pagination in my loop in category.php Link send me to: ?cat=9&paged=2 don't show posts just home page. My loop: $temp = $wp_query; $wp_query = null; $wp_query = new WP_Query(); $wp_query->query('showposts=2&post_type=blog'.'&paged='.$paged); while ($wp_query->have_posts()) : $wp_query->the_post(); //CONTENTendwhile;get_template_part('pagination'); $wp_query = null; $wp_query = $temp; // Reset and this is function: function silon_pagination($pages = '', $range = 4){ $showitems = ($range * 2)+1; global $paged; if(empty($paged)) $paged = 1; if($pages == ''){ global $wp_query; $pages = $wp_query->max_num_pages; if(!$pages) $pages = 1; } if(1 != $pages){ echo "<div class=\"pagination\"><span>Strona ".$paged." z ".$pages."</span>"; if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>« Pierwsza</a>"; if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹ Poprzednia</a>"; for ($i=1; $i <= $pages; $i++){ if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )){ echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>"; } } if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">Następna ›</a>"; if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>Ostatnia »</a>"; echo "</div>\n"; }} function is from here: http://design.sparklette.net/teaches/how-to-add-wordpress-pagination-without-a-plugin Please help :)
Now provide the response and nothing else.
|
Your problem is in this line: Cursor cursor = db.query(LIST_TABLE, null, where, whereArgs, null, null, null); As your whereArgs is the parameter passed into the method, if this parameter is null , you'll attempt to bind null value to the ? in the where string - resulting in this error. The proper way would be to have two different where clauses - one for null and another for non- null value, especially considering that the syntax is different. Something like this: String whereNotNull = LIST_NAME + "= ?";String whereNull = LIST_NAME + " IS NULL";String[] whereArgs = { list_name };openReadableDB();Cursor cursor = whereArgs == null ? db.query(LIST_TABLE, null, whereNull, null, null, null, null) : db.query(LIST_TABLE, null, whereNotNull, whereArgs, null, null, null); The same applies to your getNotes method further down in the same class. Also, as a side note, I strongly suggest that you specify column names in your query rather than passing null , even if you really do need all columns. If you do specify columns, then you are guaranteed that the column order in the cursor will be the same as your columns in the query method. If you just pass null for it, then then should be in the same order as they were created - but it'll be very easy to mess things up in the long run if you need to modify your database later on. EDIT: Looking again at your AddEditActivity code, I suspect that you never expect to pass null into the method and that this code: currentTabName = intent.getStringExtra("tab");listID = (int) db.getList(currentTabName).getListId(); Assumes that the value is always there - and is a non- null String . As you clearly are getting null , I suggest you check where this intent is launched and how the String extra is put into it. You may further want to do two things: Check that currentTabName is != null before passing it to getList - and deal with error condition if it is. Put the name of the extra parameter ( tab ) in this case into a static final String variable and reference it from there - this way you exclude the possibility of misspelling it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23088044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2953460/']}
|
jdg_76729
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
90658
|
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:
I'm working with 6 LEDs in series, which are rated at: 3V Typical / 3.2V Maximum 20mA. My power supply is: 19V 3A Maximum According to my calculations: I'd need a 50 ohm resistor at 3V I'd be in the negative at 3.2V. Because my target resistance with the LEDs alone would be below the maximum LED voltage specification, do I need any sort of resistor at all? Is this the appropriate use case for a 0 ohm resistor? I plugged in the array last night for around 20 seconds or so, and the wiring seemed to get rather hot which is a bit worrisome... The LEDs however, didn't appear to be brighter than when connecting one at the appropriate resistance.
Now provide the response and nothing else.
|
LEDs are diodes, so over the normal operating range the voltage is relatively stable for wide ranges in current. However, this also means that if you were to drive a LED with voltage, small changes in that voltage will cause large changes in the current. The characteristics are not definite enough to make this current predictable. LEDs therefore need to be driven with a controlled current, not with a low impedance supply. Your basic flaw is that you are trying to drive too many LEDs in series for the voltage you have. Get a higher voltage supply, lower voltage LEDs, or put fewer of them in each series string. With 5 LEDs in a series string, the nominal drop will be 15 V. That leaves 4 V for a resistor to drop, which is good since that will reduce current variations as the LED voltages vary. 4 V / 20 mA = 200 Ω, which is the size resistor you should use with 5 LEDs in series driven from a 19 V supply.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/90658', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/19522/']}
|
jdg_76730
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3483156
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having trouble representing a mobile number in one of my applications. I was wondering if there is an Integer class that will allow you to store such a number starting with 0417254482. Perhaps using a string be a more appropriate?At present when I'm trying to use represent a phone number with ints, doubles longs I seem to store random numbers and not the numbers I meant to store.
Now provide the response and nothing else.
|
Use String . Aside from anything else, you won't be able to store leading zeroes if you use integers. You definitely shouldn't use int (too small) float or double (too much risk of data loss - see below); long or BigInteger could be appropriate (aside from the leading zeroes problem), but frankly I'd go with String . That way you can also store whatever dashes or spaces the user has entered to make it easier to remember the number, if you want to. In terms of the "data loss" mentioned above for float and double - float definitely doesn't have enough precision; double could work if you're happy that you'll never need more than 16 digits (a couple fewer than you get with long ) but you would need to be very, very careful that anywhere you convert the value back from double to string , you got the exact value. Many formatting conversions will give you an approximation which may be accurate to, say, 10 significant digits - but you'd want an exact integer. Basically, using floating point for phone numbers is a fundamentally bad idea. If you have to use a fixed-width numeric type, use a long , but ideally, avoid it entirely.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3483156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/420344/']}
|
jdg_76731
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1766238
|
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:
The number $\pi$ is defined as the ratio between the circumeference and diameter of a circle. How do we know the value $\pi$ is correct for every circle? How do we truly know the value is the same for every circle? How do we know that $\pi = {C\over d}$ for any circle? Is there a proof that states the following: Given any circle we know that $\pi = {C\over d}$. Doesn't such a statement require a proof considering $\pi$ is used so widely on problems involved with circles, spheres, etc. How do we truly know that the value $\pi$ is correct for all circles?
Now provide the response and nothing else.
|
This is not a very rigorous proof, but it is how I was taught the fact that the circumference of a circle is proportional to its radius. Consider two concentric circles as in the diagram above. The radius of the smaller one is $r$, while that of the larger one, $R$; their circumferences are $c$ and $C$ respectively. We draw two lines through the center to meet each circle, forming two triangles as shown. The ratio of their sides $r/R = r/R$, and they have a common angle $\alpha$, so they are similar. Thus $k/K = r/R$. Also note that if $\beta$ denotes the full (360 degree) angle of a circle, then $\beta/\alpha \cdot k \approx c$ and $\beta/\alpha \cdot K \approx C$. We can say that $\frac{c}{C} \approx \frac{\beta/\alpha \cdot k}{\beta/\alpha \cdot K} = \frac{r}{R}$. As the angle $\alpha$ becomes smaller and smaller (tending towards zero, to make a limiting argument) the approximations $\beta/\alpha \cdot k \approx c$ and $\beta/\alpha \cdot K \approx C$ grow more accurate. In the limiting case -- and this is where the 'proof' is slightly nonrigorous -- we get that $\frac{c}{C} = \frac{r}{R}$. Thus $c/r = C/R$ or equivalently $c/(2r) = C/(2R)$: the circumference divided by the diameter is always a constant for any two circles since any two circles can be made concentric by a trivial translation. We call this magic constant $\pi$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1766238', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/265905/']}
|
jdg_76732
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11893134
|
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 came across this example on SO which gives a solution to create a unique index by ignoring nulls. However, I want to extend it and I am not able reach to a solution. I have a composite index for 3 columns of a table (there are other 10 columns in the table). These columns are not part of PK. Of these 3 columns, 2 will always hold some value and 3rd may be NULL. I have huge test data, and there are many inserts with 2 of the columns with same value and 3rd column NULL. These all inserts work well for PostgreSQL, however Oracle complains. For my test cases to work, I think the simplest solution that I think is to try a unique index for Oracle that would work as it works in PostgreSQL. Precisely: I want a construct of following kind, not sure how to combine col1 + col2 + col3 create unique index tbl_idx on tbl (nvl2(col3, col1 + col2, col1 + col2 + col3)) I am using liquibase. Index is created in following way - <changeSet dbms="postgresql,oracle" author="abc" id="222"> <createIndex indexName="Index_7" schemaName="ss" tableName="Users" unique="true"> <column name="idOrganization"/> <column name="strUsername"/> <column name="strNotDeleted"/> </createIndex></changeSet> I am using liquibase to create my test data, here are two insert statements <insert schemaName="ss" tableName="Users"> <column name="strUsername" value="user1" /> <column name="idUser" valueNumeric="20741" /> <column name="idOrganization" valueNumeric="4" /> <column name="strFirstName" value="user" /> <column name="strLastName" value="one" /> <column name="strEmail" value="[email protected]" /> <column name="strNotDeleted" /></insert><insert schemaName="ss" tableName="Users"> <column name="strUsername" value="user1" /> <column name="idUser" valueNumeric="20771" /> <column name="idOrganization" valueNumeric="4" /> <column name="strFirstName" value="user" /> <column name="strLastName" value="one" /> <column name="strEmail" value="[email protected]" /> <column name="strNotDeleted" /></insert> These 2 inserts work fine for PostgreSQL, however fail for Oracle with error "Index_7 constraint violation".
Now provide the response and nothing else.
|
If the goal is only to prevent duplicates where strNotDeleted is set to a non-NULL value, then you want a function-based index like this SQL> create table users( 2 idOrganization number, 3 strUsername varchar2(100), 4 strNotDeleted varchar2(3) 5 );Table created.SQL> create unique index idx_users 2 on users( (case when strNotDeleted is not null 3 then idOrganization 4 else null 5 end), 6 (case when strNotDeleted is not null 7 then strUsername 8 else null 9 end) );Index created. This allows the two rows you mention in your question to be inserted SQL> insert into users values( 4, 'user', null );1 row created.SQL> insert into users values( 4, 'user', null );1 row created. You can insert one row where the strNotNull column is set to a non-NULL value SQL> insert into users values( 4, 'user', 'Yes' );1 row created. But you then can't insert a second such row SQL> insert into users values( 4, 'user', 'Yes' );insert into users values( 4, 'user', 'Yes' )*ERROR at line 1:ORA-00001: unique constraint (SCOTT.IDX_USERS) violated Behind the scenes, an Oracle b*-tree index does not index completely NULL entries. The two CASE statements ensure that the index only has entries for idOrganization and strUsername if strNotDeleted is not NULL . If strNotDeleted is NULL , then both CASE statements evaluate to NULL and no entry is made in the index. Conceptually, it's similar to a partial index in other databases which allows you to specify a WHERE clause on your index so that you only index "interesting" rows.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11893134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1226605/']}
|
jdg_76733
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17402634
|
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 document click event how to return if target is button element $(document).click(function(e){ if(e.target.nodeName.toLowerCase() != 'button') Whether above code was correct ?
Now provide the response and nothing else.
|
You may do only $(document).click(function(e) { if ( $( e.currentTarget ).is( ":button" ) ) { // Do things }}); Why would you use :button instead of button ? Because that way you can detect if it's a <input type="button"> OR a <button> tag, aswell the other input types which render as buttons. If you're unsure about using this selector, check the :button selector jQuery docs.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17402634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1209050/']}
|
jdg_76734
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15411817
|
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 get my symfony2 app running on elastic beanstalk. I'm trying to get environment variables (RDS_USER, RDS_PASSWORD, etc...) in my parameters.yml in order to get the database credentials. The thing is symfony2 needs the environment variables to be prefixed by SYMFONY__ so I could I get these variables without prefixes ?
Now provide the response and nothing else.
|
You can load a php file as a resource: # app/config/config.ymlimports: - { resource: parameters.php } And from there it's easy: // app/config/parameters.php$container->setParameter('rds.user', getenv('RDS_USER'));// if set via apache SetEnv use://$container->setParameter('rds.user', apache_getenv('RDS_USER')); UPDATE :Since the original answer, a new solution was provided (thanks to @darragh-enright for pointing it out) using env-map feature of incenteev-parameters component in composer.json . "extra": { "incenteev-parameters": { "file": "app/config/parameters.yml", "env-map": { "database_host": "RDS_HOSTNAME", "database_port": "RDS_PORT", "database_name": "RDS_DB_NAME", "database_user": "RDS_USERNAME", "database_pass": "RDS_PASSWORD" } }} Any mapped parameter would be overwritten by value from environment variable. For more info on env-map see documentation .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15411817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448947/']}
|
jdg_76735
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3550
|
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 my attempts to understand just how computer algebra systems "do things", I tried to dig around a bit on Gröbner bases, which are described almost everywhere as "a generalization of the Euclidean algorithm and Gaussian elimination". I've tried to look for examples of Gröbner bases in action, but have been unable to find any (that can be easily understood). I could go ahead and just ask for an explanation with examples from people, but I'll go one step further. General plane conics can be represented by the Cartesian equation $$ax^2+2bxy+cy^2+dx+fy+g=0$$ One common problem in dealing with conics is finding out if two conics intersect, and if so, where the intersection point(s) are. Usually one can do all this by eliminating variables accordingly. How would, say, Buchberger's method, proceed on determining if two given conics intersect, and then find where they intersect?
Now provide the response and nothing else.
|
In order to find the solutions of the system of conics you mention, it suffices to give a procedure to find the projection of the simultaneous vanishing set of the two conics onto some axis, for instance, the $y$-axis: the coordinates of the projection onto the $y$-axis are the $y$-coordinates of the intersection points. Knowing them allows you to substitute back into the equations the values of $y$ and solve a system of equations in a single variable $x$, thus making the problem simpler. In terms of ideals, suppose that we can find a non-zero element $r$ in the ideal generated by the two conics, that depends only on a single variable, say $y$. This means that every solution of the system has $y$-coordinate satisfying the polynomial $r$. Thus we have severely limited the choices for the $y$-coordinates of the intersection (namely, they all have to satisfy the polynomial $r$) and, provided we can actually solve the polynomial $r$ in one variable, we can then substitute the various values of $y$ we found back into the initial equations and solve for $x$, again using our algorithm for solving polynomials in a single variable. So far, so good, I hope! The question is how to produce the element $r$. This is where Gröbner bases come in. In order to do the computation you ask, one would have to choose an appropriate monomial order. I will gloss over this, and simply "do the obvious". It is an exercise for you to figure out which order to use so that the computation I am going to make is actually a Gröbner bases computation. Scattered throughout the computation there will be also a couple of special cases that I will not deal with: again, you can treat those as exercises for you! First, I am going to choose a generic basis, so that the first conic has the form $$x^2 + \alpha x + \beta ,$$where $\alpha$ and $\beta$ are polynomials in $y$ only (I am trying to simplify the notation as much as possible; the only "assumption that I have made is that the coefficient of $x^2$ is non-zero, which can be arranged unless the "conic" is defined by a polynomial of degree at most one). In this basis, the second equation can be assumed to have no $x^2$ term (indeed, eliminating the $x^2$ term using the first equation would be the first step in any reasonable Gröbner basis computation in which the term $x^2$ is the highest term in sight). Thus I am going to write the second conic as $$\gamma x + \delta$$where, as before, $\gamma$ and $\delta$ are polynomials in $y$ only. Again, just to fix on a definite case, I am going to assume that the polynomial $\gamma$ is non-zero. (If $\gamma$ were zero, then we would have found a polynomial in the ideal generated by the two conics which only depends on $y$: this was our goal at the start anyway! Obviously, you should worry about the case $\gamma=\delta=0$, but I won't.) To compute a Gröbner basis, you would now compute S-polynomials: let's do it here as well. I am going to try to eliminate the $x^2$ term from the first equation, by using the second equation. This is easy: multiply the first equation by $\gamma$ and the second one by $x$ and take the difference: we are left with the equation$$(\alpha \gamma - \delta) x + \beta \gamma .$$Now we are going to eliminate the $x$ term from this last equation using again the second equation: multiply the second equation by $(\alpha \gamma - \delta)$, the last equation by $\gamma$ and subtract to obtain$$\delta^2 - \alpha \gamma \delta + \beta \gamma^2 .$$We found an expression independent of $x$!! We are done... provided this expression is not identically zero. You can figure out what this would mean and what happens in this case. Note also that the final expression is what we would have obtained if, at the very beginning, we had "solved" $x=-\frac{\delta}{\gamma}$ using the second equation, substituted in the first equation and cleared the denominators. I hope that this "hybrid" computation explains what is going on: Gröbner bases and Buchberger's algorithm are a systematic way of "solving" systems of equations. You do not have to do any thinking, once you set up the problem. But you need to set up the problem so that it computes what you want. In this case, you could have used several shortcuts to get to the answer, without following all the steps. In more complicated situations, Buchberger's algorithm might be the best way of keeping track of all the steps to be taken. Let me also comment that, except in the case in which you have a computer doing the computations for you, it is highly unlikely that Gröbner bases will help you with a specific question, unless you could have also found simple tricks to solve it right away.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3550', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/498/']}
|
jdg_76736
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4256493
|
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:
Find $\int \frac{dx}{1 +\cos{2x}}$ I did this integral with the method described here I have question with this step $$\int\frac{dx}{1+\cos2x}=\int \frac{1}{1+\cos2x}\frac{1-\cos2x}{1-\cos2x}\,dx$$ Here when $x=\pi k$ it divides $0$ how can you explain this step?
Now provide the response and nothing else.
|
I don't know whether or not you are interested in this, but you can avoid that step: \begin{align}\int\frac{\mathrm dx}{1+\cos(2x)}&=\int\frac{\mathrm dx}{1+\cos^2(x)-\sin^2(x)}\\&=\int\frac{\mathrm dx}{2\cos^2(x)}\\&=\frac12\int\sec^2(x)\,\mathrm dx\\&=\frac12\tan(x).\end{align} Anyway, whatever the method that you use, you can always check that the final answer works by differentiating it and checking that what you get is $\frac1{1+\cos(2x)}$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4256493', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/933947/']}
|
jdg_76737
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33434626
|
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 populated the recyclerView with image, title and checkbox.I have two problems. How to make the checkbox selected when the imageview or the whole recycler item is clicked. I have to go to next activity by getting all the checked items from the recyclerview. My layout : <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp"> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="150dp" android:layout_gravity="center_horizontal" android:contentDescription="Interests" android:scaleType="centerCrop" android:src="@drawable/ic_yash_dp" /> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_gravity="bottom" android:layout_margin="5dp" android:layout_marginTop="24dp" android:background="@drawable/rounded_corners" android:gravity="bottom" android:padding="5dp" android:text="GYM" android:textAlignment="center" android:textColor="@color/white" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/checkBox" android:layout_margin="2dp" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /></RelativeLayout> My adapter: @Overridepublic void onBindViewHolder(RecyclerViewHolder holder, int position) { final InterestBean model = arrayList.get(position); final int pos = position; RecyclerViewHolder mainHolder = (RecyclerViewHolder) holder;// holder Bitmap image = BitmapFactory.decodeResource(context.getResources(), model.getImage());// This will convert drawbale image into bitmap // setting title mainHolder.title.setText(model.getTitle()); mainHolder.imageview.setImageBitmap(image); mainHolder.checkBox.setChecked(arrayList.get(position).isSelected()); mainHolder.checkBox.setTag(arrayList.get(position)); mainHolder.checkBox.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CheckBox cb = (CheckBox) v; InterestBean contact = (InterestBean) cb.getTag(); contact.setIsSelected(cb.isChecked()); arrayList.get(pos).setIsSelected(cb.isChecked()); selectedItems.add(pos); Toast.makeText(v.getContext(), pos + cb.isChecked(), Toast.LENGTH_LONG).show(); } });}
Now provide the response and nothing else.
|
One simple solution is to create OnItemCheckLister , and implement it similar to following: public class MyAdapter extends RecyclerViewAdapter { interface OnItemCheckListener { void onItemCheck(Item item); void onItemUncheck(Item item); } ... @NonNull private OnItemCheckListener onItemClick; public MyAdapter (List<Item> items, @NonNull OnItemCheckListener onItemCheckListener) { this.items = items; this.onItemClick = onItemCheckListener; } ... @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { if (holder instanceof MyViewHolder) { final Item currentItem = items.get(position); ... ((MyViewHolder) holder).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MyViewHolder) holder).checkbox.setChecked( !((MyViewHolder) holder).checkbox.isChecked()); if (((MyViewHolder) holder).checkbox.isChecked()) { onItemClick.onItemCheck(currentItem); } else { onItemClick.onItemUncheck(currentItem); } } }); } } static class MyViewHolder extends RecyclerView.ViewHolder { CheckBox checkbox; View itemView; ... public MyViewHolder(View itemView) { super(itemView); this.itemView = itemView; checkbox = (CheckBox) itemView.findViewById(R.id.checkbox); checkbox.setClickable(false); ... } public void setOnClickListener(View.OnClickListener onClickListener) { itemView.setOnClickListener(onClickListener); } }} Then in the activity, we can do this: private List<Item> currentSelectedItems = new ArrayList<>(); ... myAdapter = new MyAdapter(items, new MyAdapter.OnItemCheckListener() { @Override public void onItemCheck(Item item) { currentSelectedItems.add(item); } @Override public void onItemUncheck(Item item) { currentSelectedItems.remove(item); } }); Then you can do stuff with currentSelectedItems . Note: Since this solution suppose for the whole Item to be pressed so the checkbox is set to be not clickable.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33434626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745242/']}
|
jdg_76738
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
209857
|
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 was discussing with someone ways to prevent data disclosure from a compromised admin account on a database server. The other person proposed encrypting the data at rest within the database. It sounds like a good idea, but I wasn't sure if that would protect the data in this scenario. My thinking is if the attacker has an admin account, they'll also have the ability to access the encryption key. In a typical configuration, would this be the case? Could the system be engineered so that it wouldn't, while still being practical to administer and use? I could see having the admin provide the key when they log in, but I am ignorant on the security implications of that... My threat model is as follows: A legitimate admin account's username and password is compromised. Our attacker uses that account to log in remotely and download the database. I understand MFA and other access controls would protect here, but assume they've failed or otherwise been circumvented. I'm merely curious of encryption's effect here. Now I realize this would definitely come down to implementation specific details, however I am not super familiar with database administration, so I'm struggling to provide a detailed setup for a hypothetical system.
Now provide the response and nothing else.
|
Yes, such a system exists; it's called Application-Level Encryption . Under that system the encryption keys (or at least the Key-Encrypting Key, or KEK) are only available to the application. Data is encrypted by the application before being stored in the database, and encrypted blobs are retrieved from the database to be decrypted by the application. The advantage of this is a sort of dual control - the DBAs, who can perform bulk actions against the entire database without much limitation - can only extract encrypted data. The application administrators, who hold the KEK, can decrypt anything in the database, but are limited to approved interfaces which may work piecemeal but not in bulk. It makes abuse of the decrypted data harder to perform and easier to detect. There are disadvantages as well, primarily the inability to index or search upon plaintext characteristics of the encrypted data in the database. Also, it requires the application and database be written to support it; unlike whole-disk or whole-database encryption it's not as easy as flipping a switch.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/209857', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/180252/']}
|
jdg_76739
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
419928
|
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:
I've started learning about transistors and was working on this circuit, and have fiddled around with the circuit simulator for a couple hours, but can't seem to find an efficient design for what I want. Because of the 20k resistor heavily limiting the current in the bottom transistor, I added a second transistor to "amplify" the current. Now, I'm trying to create a circuit where the LED will consume around 1-3 watts of power, while leaving the 20k ohm resistor as it is. Lastly, the resistors should consume less than 3 watt of power. To try to achieve this, I tried adding resistors at different places and editing their values, but I wasn't successful. Does anybody know how to make this possible? You can add or delete resistors and transistors as needed, however, the 20k resistor should remain where it is. Thanks for any help guys! Here's the link to the online circuit simulator: https://www.falstad.com/circuit/ EDIT: The voltage source can be anything from 10-20V. Whatever voltage works is fine!
Now provide the response and nothing else.
|
If the LED Vf is 2 V, and the source is 10 V, then between whatever resistors you use and the uppermost transistor, they will consume 4x as much power as the LED does. As a trivial solution to the problem as you have stated it, if you take your current design and split each 20-ohm resistor into two 10-ohm resistors in series, then you will have less than 3 W consumed by each resistor. Reducing the source voltage will reduce the overall power consumption of the circuit, and improve the efficiency, but might require re-adjusting your resistor values to keep the LED power as high as you want it. But really this is a horrifically inefficient way to power a 3 W LED. For a real-world design you should consider using a constant-current circuit based on switching power supply concepts. Or at least use a larger number (3 or 4) of smaller LEDs in series to improve the efficiency.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/419928', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/198186/']}
|
jdg_76740
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.