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
584988
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: If I nest DSC configurations in a single file like this, it works fine: Configuration Secondary { Param ($SomeParameter) Environment Test { Name = $SomeParameter Value = "12345" }}Configuration MyConfiguration { Node localhost { Secondary TheSecondary { SomeParameter = "TestEnvVar" } }}MyConfigurationStart-DscConfiguration .\MyConfiguration -Wait -Verbose I want to split my configuration in to two separate files. One will dot-source the other to include the configuration. Secondary.ps1: Configuration Secondary { Param ($SomeParameter) Environment Test { Name = $SomeParameter Value = "12345" }} Primary.ps1: . .\Secondary.ps1Configuration MyConfiguration { Node localhost { Secondary TheSecondary { SomeParameter = "TestEnvVar" } }}MyConfigurationStart-DscConfiguration .\MyConfiguration -Wait -Verbose For some reason this doesn't pick up the parameter passed in to the secondary configuration and so results in the error: Could not find mandatory property Name. Add this property and try again. + CategoryInfo : ObjectNotFound: (root/Microsoft/...gurationManager:String) [], CimException + FullyQualifiedErrorId : MI RESULT 6 + PSComputerName : localhost It seems very strange that it works when in the same file but not when dot-sourcing. I thought that dot-sourcing was basically the same as including code in the same file. What am I missing here? Now provide the response and nothing else.
If you want to reference a configuration from another configuration that is not defined in the same file, you need to use the composite resource pattern. In a module, you'll create a DscResources folder. In that folder, you'll create a module to hold your composite configurations. The composite configuration will be defined in a file with the extension .schema.psm1. The file will require a module manifest pointing to the schema.psm1 file as the root module. For more detail and an example, check out the PowerShell team blog - http://blogs.msdn.com/b/powershell/archive/2014/02/25/reusing-existing-configuration-scripts-in-powershell-desired-state-configuration.aspx
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/584988', 'https://serverfault.com', 'https://serverfault.com/users/41452/']}
jdg_374241
stackexchange
llm_judgeable_groundtruth_similarity
10057687
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 call a function in a remote process of an injected DLL that I've made. I have successfully injected my DLL with: CreateRemoteThread(pHandle, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("kernel32"), "LoadLibraryA"), pLibRemote, 0, NULL); The DllMain is executed and the DLL is running in a stand-by mode. What I would like to do is somehow call the remotely loaded DLL in order to do some work. I have tried exporting the function like this: extern "C" __declspec(dllexport) void MyFunc(void) and then executing the function like this: CreateRemoteThread(pHandle, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("mydll"), "MyFunc"), NULL, 0, NULL); but it results in a crash. How can I solve this? Now provide the response and nothing else.
Calling GetModuleHandle as you have will get the base of the DLL as it is mapped into your process (if at all). So what you need to do is first make sure to export the function in the DLL. You can do as you have done or create a .def file as shown here . Thereafter: In Theory Inject the DLL to the target process and get the base address it was loaded at Inject the DLL to the current process. Use GetProcAddress to find the offset between the exported function and the base of the DLL. Add this offset to the base address obtained from step 1. CreateRemoteThread at this location. In Practice When doing your DLL injection, it is possible for you to get the base that your DLL is loaded into the target. HMODULE hInjected;hThread = CreateRemoteThread( hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)( GetProcAddress( hMod, "LoadLibraryW" ) ), lpAddress, 0, NULL );// Locate address our payload was loadedif( hThread != 0 ) { WaitForSingleObject( hThread, INFINITE ); GetExitCodeThread( hThread, ( LPDWORD )&hInjected ); CloseHandle( hThread );} hInjected will be the base of the injected DLL. I then have another function: void* GetPayloadExportAddr( LPCWSTR lpPath, HMODULE hPayloadBase, LPCSTR lpFunctionName ) { // Load payload in our own virtual address space HMODULE hLoaded = LoadLibrary( lpPath ); if( hLoaded == NULL ) { return NULL; } else { void* lpFunc = GetProcAddress( hLoaded, lpFunctionName ); DWORD dwOffset = (char*)lpFunc - (char*)hLoaded; FreeLibrary( hLoaded ); return (DWORD)hPayloadBase + dwOffset; }} What this does is first load the payload into our own virtual address space. Afterwards, we can use GetProcAddress to get the address of the exported function. From this, we can get the offset of the function from the base of the DLL. Adding this offset to the hInjected we got earlier will tell us where the CreateRemoteThread call should be made. So you could make a call like so: BOOL InitPayload( HANDLE hProcess, LPCWSTR lpPath, HMODULE hPayloadBase, HWND hwndDlg ) { void* lpInit = GetPayloadExportAddr( lpPath, hPayloadBase, "Init" ); if( lpInit == NULL ) { return FALSE; } else { HANDLE hThread = CreateRemoteThread( hProcess, NULL, 0, lpInit, hwndDlg, 0, NULL ); if( hThread == NULL ) { return FALSE; } else { CloseHandle( hThread ); } } return TRUE;} This is all code that is ripped out of an old project I have . You're welcome to take the code and do whatever you want with it but I know if I were to rewrite the code now, I would do a lot of things differently.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10057687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/879598/']}
jdg_374242
stackexchange
llm_judgeable_groundtruth_similarity
31624649
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to have a system-wide oh-my-zsh setup, but I'm not sure what would be the "best" approach for this. It is not my intention to ask about personal preferences or the like, I'm just unsure whether the solutions below are: ln my local user configuration somewhere doesn't seem right, because adding an exploit to my local cfg and therefore gain root permissions would be very easy. Installing oh-my-zsh to /etc would be maybe also a security hole because I simply haven't written it by myself. Simply writing my own personal .zshrc would be the last approach I would like to try out because it’s very time-consuming. Any recommendations? Now provide the response and nothing else.
Fair Warning: this assumes a Debian style linux, but this should work on other forms as well. This also assumes you are starting from scratch. Part 1 , the install: You will need to install zsh system wide, and not just for one user. (you may have already done this but I'll include it just to be comprehensive) make sure you have installed zsh, simply: sudo apt-get install zsh Follow the oh-my-zsh install guide or you can either: use curl sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" use wget sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)" Part 2 , Setting up zsh when new users are added: You will need to make it so that new users default to zsh. In your /etc/adduser.conf file edit the line that says: DSHELL=/bin/sh to: DSHELL=/bin/zsh You should also change it for the /etc/default/useradd file, change the line: SHELL=/bin/sh to: SHELL=/bin/zsh Part 3 , set your custom theme. I have a custom theme file ( here ) that I wanted all users on the system to have. First, you should add the file to your .oh-my-zsh/themes folder: cp your_custom_style.zsh-theme ~/.oh-my-zsh/themes Next, edit your .zshrc file in your home directory, change the ZSH_THEME="default" to ZSH_THEME="your_custom_style" Then, reload your .zshrc file with: . ~/.zshrc Part 4 , setting up new user's home directories. We need to to place whatever files we want the new users to have in the /etc/skel directory, because this is what the system copies when it is creating new user's home directory. See this sys admin guide for details. Copy your user's files (you may need to sudo): cp -r .oh-my-zsh /etc/skel/cp .zshrc /etc/skel Now you will be able to add new users and they will have oh-my-zsh by default with whatever custom theme you want them to have. If you want to change all other existing user's shell to zsh, I would recommend reading this serverfault question .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31624649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5124117/']}
jdg_374243
stackexchange
llm_judgeable_groundtruth_similarity
5294470
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Update The accepted answer was good for last year but today I would use the package everyone else uses: https://github.com/mikeal/request Original I'm trying to grab google's logo and save it to my server with node.js. This is what I have right now and doesn't work: var options = { host: 'google.com', port: 80, path: '/images/logos/ps_logo2.png' }; var request = http.get(options); request.on('response', function (res) { res.on('data', function (chunk) { fs.writeFile(dir+'image.png', chunk, function (err) { if (err) throw err; console.log('It\'s saved!'); }); }); }); How can I get this working? Now provide the response and nothing else.
A few things happening here: I assume you required fs/http, and set the dir variable :) google.com redirects to www.google.com, so you're saving the redirect response's body, not the image the response is streamed. that means the 'data' event fires many times, not once. you have to save and join all the chunks together to get the full response body since you're getting binary data, you have to set the encoding accordingly on response and writeFile (default is utf8) This should work: var http = require('http') , fs = require('fs') , optionsoptions = { host: 'www.google.com' , port: 80 , path: '/images/logos/ps_logo2.png'}var request = http.get(options, function(res){ var imagedata = '' res.setEncoding('binary') res.on('data', function(chunk){ imagedata += chunk }) res.on('end', function(){ fs.writeFile('logo.png', imagedata, 'binary', function(err){ if (err) throw err console.log('File saved.') }) })})
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5294470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115608/']}
jdg_374244
stackexchange
llm_judgeable_groundtruth_similarity
16826364
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 achieve the following:I have an accordion that has a series of tabs within.Each tab has a series of inputsWhen the user changes an input, I want to display 3buttons on the accordion heading to Save, view the pending changes or cancel them.So far all this is working! Except for the view the pending changes.On click of the "view pending", I want to scan the tabs, find any inputs that have changed and show there values in a "dynamically" created div below the view button (like a tooltip - NOT as a normal div that is part of the body). My idea was to create a multi-dimensional array that will store the Tab name, the input name and its value, then loop through the array to build the html to show. I am stuck creating the multi-dimensional array and how to loop through it once its created. $('#showpending').click( function() { var a = $(this).siblings('div.accordion-body'); var b = $(this); if ($(a).find('input.sym-changed').length > 0) { var ma = {}; $(a).find('input.sym-changed').each( function() { var n=$(this).parent('div.tab-pane').attr('name');//--this to become h2 var m=$(this).attr('name');//this to be shown as a label var v=$(this).attr('value'); //this to be shown as text alert(n); alert(m); alert(v); //I am stuck here!!! ma.n.m = v; alert(ma.n.m); } ); //build a div based on the array / object 'ma' //show the div as tooltip for the button } else {alert('no inputs found');} }) Here is a jsFiddle that I setup. http://jsfiddle.net/J6ppR/2/ Now provide the response and nothing else.
If you can guarantee that the event should fire within a certain amount of time, then simply set a timeout. it('should emit an some_event', function(done){ this.timeout(1000); //timeout with an error if done() isn't called within one second myObj.on('some_event',function(){ // perform any other assertions you want here done(); }); // execute some code which should trigger 'some_event' on myObj}); If you can't guarantee when the event will fire, then it might not be a good candidate for unit testing.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16826364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/973870/']}
jdg_374245
stackexchange
llm_judgeable_groundtruth_similarity
18304722
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 find (but not draw!) contour lines for some data: from pprint import pprint import matplotlib.pyplot z = [[0.350087, 0.0590954, 0.002165], [0.144522, 0.885409, 0.378515], [0.027956, 0.777996, 0.602663], [0.138367, 0.182499, 0.460879], [0.357434, 0.297271, 0.587715]] cn = matplotlib.pyplot.contour(z) I know cn contains the contour lines I want, but I can't seem to get to them. I've tried several things: print dir(cn) pprint(cn.collections[0]) print dir(cn.collections[0]) pprint(cn.collections[0].figure) print dir(cn.collections[0].figure) to no avail. I know cn is a ContourSet , and cn.collections is an array of LineCollection s. I would think a LineCollection is an array of line segments, but I can't figure out how to extract those segments. My ultimate goal is to create a KML file that plots data on a world map, and the contours for that data as well. However, since some of my data points are close together, and others are far away, I need the actual polygons (linestrings) that make up the contours, not just a rasterized image of the contours. I'm somewhat surprised qhull doesn't do something like this. Using Mathematica's ListContourPlot and then exporting as SVG works, but I want to use something open source. I can't use the well-known CONREC algorithm because my data isn't on a mesh (there aren't always multiple y values for a given x value, and vice versa). The solution doesn't have to python, but does have to be open source and runnable on Linux. Now provide the response and nothing else.
You can get the vertices back by looping over collections and paths and using the iter_segments() method of matplotlib.path.Path . Here's a function that returns the vertices as a set of nested lists of contour lines, contour sections and arrays of x,y vertices: import numpy as npdef get_contour_verts(cn): contours = [] # for each contour line for cc in cn.collections: paths = [] # for each separate section of the contour line for pp in cc.get_paths(): xy = [] # for each segment of that section for vv in pp.iter_segments(): xy.append(vv[0]) paths.append(np.vstack(xy)) contours.append(paths) return contours Edit: It's also possible to compute the contours without plotting anything using the undocumented matplotlib._cntr C module: from matplotlib import pyplot as pltfrom matplotlib import _cntr as cntrz = np.array([[0.350087, 0.0590954, 0.002165], [0.144522, 0.885409, 0.378515], [0.027956, 0.777996, 0.602663], [0.138367, 0.182499, 0.460879], [0.357434, 0.297271, 0.587715]])x, y = np.mgrid[:z.shape[0], :z.shape[1]]c = cntr.Cntr(x, y, z)# trace a contour at z == 0.5res = c.trace(0.5)# result is a list of arrays of vertices and path codes# (see docs for matplotlib.path.Path)nseg = len(res) // 2segments, codes = res[:nseg], res[nseg:]fig, ax = plt.subplots(1, 1)img = ax.imshow(z.T, origin='lower')plt.colorbar(img)ax.hold(True)p = plt.Polygon(segments[0], fill=False, color='w')ax.add_artist(p)plt.show()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18304722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17394346/']}
jdg_374246
stackexchange
llm_judgeable_groundtruth_similarity
38133315
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 ul tag with display: flex . I need it ordered by column with flex-direction: column; , but it does not work. CSS for the container: #nav li.four_columns ul.sub-menu { width: 600px; display: flex; -webkit-flex-direction: column; flex-direction: column; justify-content: flex-start; align-items: flex-start; flex-flow: wrap;} CSS for the child: #nav li.four_columns ul.sub-menu li { flex-basis: 25%; /* white-space: nowrap; */ /* overflow: hidden; */ /* text-overflow: ellipsis; */ /* border-bottom: none; */} Now provide the response and nothing else.
Here is the source of your problem: flex-flow: wrap This is a shorthand property for flex-direction and/or flex-wrap . The initial values of this property are row nowrap . You have only declared the flex-wrap component: wrap . This means that the flex-direction component remains the default value: row . Hence, your flex items are aligning horizontally in a row that wraps. As a solution, either specify both components: flex-flow: column wrap OR, since you already have flex-direction: column in the rule, remove flex-flow and use: flex-wrap: wrap Also important : If you want flex items to wrap in column-direction, you need to define a height on the container. Without a fixed height, the flex items don't know where to wrap and they'll stay in a single column, expanding the container as necessary. Reference: 5.3. Flex Direction and Wrap: the flex-flow shorthand
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38133315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2904701/']}
jdg_374247
stackexchange
llm_judgeable_groundtruth_similarity
1240498
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems to me that anytime I come across internal calls or types, it's like I hit a road block. Even if they are accessible in code like open-source, it still feels they are not usable parts of the API code itself. i.e. it's as if they are discouraged to be modified. Should one keep oneself from using the internal keyword unless it's absolutely necessary? I am asking this for an open-source API. But still not everyone will want to change the API, but mostly use it to write their own code for the app itself. Now provide the response and nothing else.
There is nothing wrong with having an internal type in your DLL that is not a part of your public API. In fact, if you have anything other than a trivial DLL is more likely a sign of bad design if you don't have an internal type (or at least a non-public type) Why? Public APIs are a way of exposing the parts of your object model you want a consumer to use. Having an API of entirely public types means that you want the consumer to see literally everything in your DLL. Think of the versioning issues that come along with that stance. Changing literally anything in your object model is a breaking change. Having internal types allows you great flexibility in your model while avoiding breaking changes to your consumers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1240498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51816/']}
jdg_374248
stackexchange
llm_judgeable_groundtruth_similarity
60088889
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Permanent deletion of an experiment isn't documented anywhere. I'm using Mlflow w/ backend postgres db Here's what I've run: client = MlflowClient(tracking_uri=server)client.delete_experiment(1) This deletes the the experiment, but when I run a new experiment with the same name as the one I just deleted, it will return this error: mlflow.exceptions.MlflowException: Cannot set a deleted experiment 'cross-sell' as the active experiment. You can restore the experiment, or permanently delete the experiment to create a new one. I cannot find anywhere in the documentation that shows how to permanently delete everything. Now provide the response and nothing else.
Unfortunately it seems there is no way to do this via the UI or CLI at the moment :-/ The way to do it depends on the type of backend file store that you are using. Filestore : If you are using the filesystem as a storage mechanism (the default) then it is easy. The 'deleted' experiments are moved to a .trash folder. You just need to clear that out: rm -rf mlruns/.trash/* As of the current version of the documentation (1.7.2), they remark: It is recommended to use a cron job or an alternate workflow mechanism to clear .trash folder. SQL Database: This is more tricky, as there are dependencies that need to be deleted. I am using MySQL, and these commands work for me: USE mlflow_db; # the name of your databaseDELETE FROM experiment_tags WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage="deleted");DELETE FROM latest_metrics WHERE run_uuid=ANY( SELECT run_uuid FROM runs WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage="deleted" ));DELETE FROM metrics WHERE run_uuid=ANY( SELECT run_uuid FROM runs WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage="deleted" ));DELETE FROM tags WHERE run_uuid=ANY( SELECT run_uuid FROM runs WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage="deleted" ));DELETE FROM runs WHERE experiment_id=ANY( SELECT experiment_id FROM experiments where lifecycle_stage="deleted");DELETE FROM experiments where lifecycle_stage="deleted";
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/60088889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5378132/']}
jdg_374249
stackexchange
llm_judgeable_groundtruth_similarity
15357450
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose you have the following html select statement <select><option value="Newest">Newest</option><option value="Best Sellers">Best Sellers</option><option value="Alphabetical">Alphabetical</option></select> Now I want to run a php if elseif statement that says, if (option value = newest) {// Run this}elseif ( option value = best sellers ) {// Run this} etc. But I don't know what to put inside the if elseif statement. In other words instead of 'option value = newest' (which I know is incorrect), what can I put there so that if newest is selected it will execute the if statement, or if best sellers is selected it will execute the elseif statement? Now provide the response and nothing else.
Give name to your select. <select name="selectedValue"><option value="Newest">Newest</option><option value="Best Sellers">Best Sellers</option><option value="Alphabetical">Alphabetical</option></select> in your PHP, you will do: $_POST['selectedValue']; if I were you, I would prefer a switch-case incase, there are more than 2 conditions. Example: switch($_POST['selectedValue']){case 'Newest': // do Something for Newestbreak;case 'Best Sellers': // do Something for Best sellerbreak;case 'Alphabetical': // do Something for Alphabeticalbreak;default: // Something went wrong or form has been tampered.}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15357450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2126745/']}
jdg_374250
stackexchange
llm_judgeable_groundtruth_similarity
14895016
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hope any angularjs gurus can help me with this.Here is my angularjs code $scope.$on('$routeChangeStart', function(event, next, current) { if ($scope.myForm.$dirty) { if(!confirm("Unsaved, do u want to continue?")) { event.preventDefault(); } } }); It alerts in browser back button click when data is dirty, but on clicking cancel or ok it still completes the route change.Seems like event.preventDefault() is not working.Can any one point out what may be wrong Now provide the response and nothing else.
I had lots of trouble finding this one, but instead of the "$routeChangeStart" event, you can listen to the "$locationChangeStart" event, for which you can prevent default: $scope.$on("$locationChangeStart", function(event, next, current) { if (!confirm("You have unsaved changes, continue navigating to " + next + " ?")) { event.preventDefault(); }}); You could also always prevent default, store "next", and display a clean JS modal and decide asynchronously. $locationChangeStart is currently undocumented but referenced here : https://github.com/angular/angular.js/issues/2109
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14895016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1426157/']}
jdg_374251
stackexchange
llm_judgeable_groundtruth_similarity
11970293
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 use bundling to combine & minify some CSS files. In my Global.aspx.cs Application_Start I have the following: var jsBundle = new Bundle("~/JSBundle", new JsMinify()); jsBundle.AddDirectory("~/Scripts/", "*.js", false); jsBundle.AddFile("~/Scripts/KendoUI/jquery.min.js"); jsBundle.AddFile("~/Scripts/KendoUI/kendo.web.min.js"); BundleTable.Bundles.Add(jsBundle); var cssBundle = new Bundle("~/CSSBundle", new CssMinify()); cssBundle.AddDirectory("~/Content/", "*.css", false); cssBundle.AddDirectory("~/Content/themes/base/", "*.css", false); cssBundle.AddFile("~/Styles/KendoUI/kendo.common.min.css"); cssBundle.AddFile("~/Styles/KendoUI/kendo.default.min.css"); BundleTable.Bundles.Add(cssBundle); And in my .cshtml file I have the following: <link href="/CSSBundle" rel="stylesheet" type="text/css" /><script src="/JSBundle" type="text/javascript"></script> However, when I view the source of my bundles CSS file, it has the following: /* Minification failed. Returning unminified contents.(40,1): run-time error CSS1019: Unexpected token, found '@import'(40,9): run-time error CSS1019: Unexpected token, found '"jquery.ui.base.css"' .... lots more Any ideas on how to resolve this? I did narrow it down to the following line: cssBundle.AddDirectory("~/Content/themes/base/", "*.css", false); If I only have that line of code I get the same errors. Now provide the response and nothing else.
There are a few issues here: The css issue is due to including the jquery.ui.all.css, as the default minifier doesn't support following imports, and this is not what you want to do anyways as it would double include all of the jquery ui css files. So what you want to do instead is not use *.css, and instead explicitly list what jquery ui files you want to include: bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( "~/Content/themes/base/jquery.ui.core.css", "~/Content/themes/base/jquery.ui.resizable.css", "~/Content/themes/base/jquery.ui.selectable.css", "~/Content/themes/base/jquery.ui.accordion.css", "~/Content/themes/base/jquery.ui.autocomplete.css", "~/Content/themes/base/jquery.ui.button.css", "~/Content/themes/base/jquery.ui.dialog.css", "~/Content/themes/base/jquery.ui.slider.css", "~/Content/themes/base/jquery.ui.tabs.css", "~/Content/themes/base/jquery.ui.datepicker.css", "~/Content/themes/base/jquery.ui.progressbar.css", "~/Content/themes/base/jquery.ui.theme.css")); Secondly you want to be using the Script/Styles.Render methods rather than explicitly referencing the bundles url as you are doing, as the helpers will automatically not bundle/minify and render individual references to each script/style asset when in debug mode, and also append a fingerprint for the bundle contents into the url so browser caching will work propertly. @Scripts.Render("~/JSBundle") and @Styles.Render("~/CSSBundle") You can also use StyleBundle/ScriptBundle which is just syntaxtic sugar for not having to pass in new Css/JsMinify. You can also check out this tutorial for more info: Bundling Tutorial
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11970293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127853/']}
jdg_374252
stackexchange
llm_judgeable_groundtruth_similarity
219056
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: (This is a re-post of 1 ) In the paper "On the realizability of singular cohomology groups" by Kan and Whitehead, it is shown that there is no space $X$ and integer $n\geq 1$ such that $H^{n−1}(X)=0$ and $H^n(X)=\mathbb{Q}$ (cohomology with integral coefficients). At the very end of the article there is a remark where it is stated that, at the time of writing (around 1960, I suppose), it was not known whether $\mathbb{Q}$ could be a (integral) singular cohomology group at all. My question is: is this still not known? Now provide the response and nothing else.
This may depend on your axioms, see S. Shelah "The consistency of Ext(G,Z)=Q", Israel J. Math. 39 (1981), no. 1-2, 74–82. There it is shown that it is consistent with the generalised continuum hypothesis that there exists a group $G$ having $Ext(G, \mathbb{Z})=\mathbb{Q}$. Then a Moore space $M(G,n-1)$ has the required property.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/219056', 'https://mathoverflow.net', 'https://mathoverflow.net/users/49520/']}
jdg_374253
stackexchange
llm_judgeable_groundtruth_similarity
7649752
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This isn't a big issue for me (as far as I'm aware), it's more of something that's interested me. But what is the main difference, if any, of using is_numeric over preg_match (or vice versa) to validate user input values. Example One: <?php $id = $_GET['id']; if (!preg_match('/^[0-9]*$/', $id)) { // Error } else { // Continue }?> Example Two: <?php $id = $_GET['id']; if (!is_numeric($id)) { // Error } else { // Continue }?> I assume both do exactly the same but is there any specific differences which could cause problems later somehow? Is there a "best way" or something I'm not seeing which makes them different. Now provide the response and nothing else.
is_numeric() tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation. The preg_match() example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence. Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended. [EDIT] As per your comment, a better regular expression might look like this: /^[1-9][0-9]*$/ This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue. You're not worried about negatives, so that's not an issue. You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so: /^[1-9][0-9]{0,15}$/ This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces. Hope that helps.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7649752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/584711/']}
jdg_374254
stackexchange
llm_judgeable_groundtruth_similarity
34061781
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 working on my final project for my intro to java class and i am having a hard time understanding the errors in my project and why it will not run if you could tell me why i would greatly appreciate it public static void main(String[] args) {Scanner scanner1;int dice, dice2;int pScore, cScore = 0;int pTotalScore = 0;int cTotalScore = 0;final int maxScore = 750;String input = "R";String input2 = "R";char repeat;Random randomNumbers = new Random();System.out.println("Welcome to Our version of the dice game Pig");System.out.println("Here are the instructions");System.out.println("On a turn, the player or computer rolls the die repeatedly");System.out.println("Until either a 1,7,12, or 17 is rolled");System.out.println("or the player or computer holds");System.out.println("If a 1,7,12, or 17 is rolled, that player's turn ends");System.out.println("and no points are earned");System.out.println("If the player chooses to hold, all of the points rolled during");System.out.println("that turn are added to his or her score.");System.out.println("First player to 750 points or more WINS!");System.out.print("\nPlease enter your name: ");scanner1 = new Scanner(System.in);String pName = scanner1.nextLine();System.out.print("\nI Hope You have fun," + pName);do { // run at least once. Start of loop dice = randomNumbers.nextInt(6) + 1; System.out.println(); System.out.printf("%s you rolled a %d %n", pName, dice); if (dice == 1 || dice == 7 || dice == 12 || dice == 17) // if these numbers, end { pScore = 0; System.out.println("Turn over."); System.out.println(" " + pName + " total is " + pScore + " "); break; } else { // else ask for re-roll pScore = dice; pTotalScore += pScore; System.out.print(+pScore + " Your turn total is " + pTotalScore + " "); System.out.print("Enter (R) to roll or (H)to hold: "); input = scanner1.nextLine(); repeat = input.charAt(0); } if (repeat != 'R') { // if something other than R, end break; }} while (pTotalScore < 750 || cTotalScore < 750); // allow repeat so long as scores are less than 750 if (repeat == 'H') { System.out.println("Turn over."); System.out.print("Current score: " + pname + " has " + pTotalScore); System.out.println("The Computer has " + cTotalScore); break; } while (input.equalsIgnoreCase("R")); if (pTotalScore >= maxScore) { System.out.println("Your total Score is " + totalScore); System.out.println(+pname + "WINS!"); break; } System.out.println(); System.out.println("It is the Computer's turn."); do { dice2 = randomNumbers.nextInt(6) + 1; System.out.println("The Computer rolled: " + dice2); if (dice2 == 1 || dice2 == 7 || dice2 == 12 || dice2 == 17) { cScore = 0; System.out.print("Turn over"); System.out.println("The Computer total is " + cTotalScore); break; } else { cScore = dice2; cTotalScore += cScore; System.out.print("The Computer's total is " + cTotalScore + " "); System.out.print("Enter (r) to Roll or (H)to Hold: "); input = keyboard.nextLine(); repeat = input.charAt(0); } if (repeat == 'H') { System.out.println("Turn over"); System.out.print("Current score:" + pName + " has " + pTotalScore); System.out.println(", The Computer has " + cTotalScore); break; } } while (input2.equalsIgnoreCase("R")); if (cTotalScore >= maxScore) { System.out.println("The Computer's score is " + cTotalScore + "\n"); System.out.println("The Computer wins!!!!"); System.out.printl("Run The uprisng has begun!!!!!!"); break; } Final3.java:112: error: reached end of file while parsing } ^ 1 error now the problem is i get the error basically means im missing a } but i cant see where it would be nd no matter where i put it it still says Final3.java:112: error: reached end of file while parsing } ^ 1 error Now provide the response and nothing else.
Ask yourself the question: which day should be parsed with the String "201510" ? A LocalDate needs a day but since there is no day in the date to parse, an instance of LocalDate can't be constructed. If you just want to parse a year and a month, you can use the YearMonth object instead: YearMonth localDate = YearMonth.parse(date, formatter); However, if you really want to have a LocalDate to be parsed from this String, you can build your own DateTimeFormatter so that it uses the first day of the month as default value: DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("yyyyMM") .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) .toFormatter();LocalDate localDate = LocalDate.parse(date, formatter);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34061781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4489072/']}
jdg_374255
stackexchange
llm_judgeable_groundtruth_similarity
4300240
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 simple rake task, stored in lib/tasks/items_spider.rake runs just fine in development. All it does is call spider! on the Item model. namespace :items do desc "Spider the web for data, hoorah" task :spider => :environment do Item.spider! endend I have the :environment task as a dependency, so everything works just fine. However, when I add RAILS_ENV=production , I hit errors, both on my local server and the production server: $ rake items:spider RAILS_ENV=production --trace(in /home/matchu/Websites/my-rails-app)** Invoke items:spider (first_time)** Invoke environment (first_time)** Execute environment** Execute items:spiderrake aborted!uninitialized constant Object::Item/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rake-0.8.7/lib/rake.rb:2503:in `const_missing'/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rspec-core-2.0.0.beta.22/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rspec-expectations-2.0.0.beta.22/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'/home/matchu/Websites/openneo-impress-items/lib/tasks/items_spider.rake:4:in `block (2 levels) in <top (required)>'/home/matchu/.rvm/gems/ruby-1.9.2-preview3@rails3/gems/rake-0.8.7/lib/rake.rb:636:in `call'[...trace of how rake gets to my task...] This just seems odd to me. Apparently the models have not been loaded correctly. I'm on Rails 3.0.3, though development on this app started back when Rails 3 was in beta. How can I go about debugging this issue? Thanks! Now provide the response and nothing else.
Contrary to running your application in production, a Rake task does not eager load your entire code base. You can see it in the source : module Rails class Application module Finisher # ... initializer :eager_load! do if config.cache_classes && !$rails_rake_task ActiveSupport.run_load_hooks(:before_eager_load, self) eager_load! end end # ... end endend So only if $rails_rake_task is false , will the application be eager-loaded in production. And $rails_rake_task is set to true in the :environment Rake task. The easiest workaround is to simply require the model that you need. However, if you really need all of your application to be loaded in the Rake task, it is quite simple to load it: Rails.application.eager_load! The reason all of this work in development is because Rails autoloads your models in development mode. This also works from within a Rake task.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4300240', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107415/']}
jdg_374256
stackexchange
llm_judgeable_groundtruth_similarity
93454
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: Base Data : I have ~1,000 people marked with assessments: '1,' [good] '2,' [middle] or '3' [bad] -- these are the values I'm trying to predict for people in the future. In addition to that, I have some demographic information: gender (categorical: M / F), age (numerical: 17-80), and race (categorical: black / caucasian / latino). I mainly have four questions: I was initially trying to run the dataset described above as a multiple regression analysis. But I recently learned that since my dependent is an ordered factor and not a continuous variable, I should use ordinal logistic regression for something like this. I was initially using something like mod <- lm(assessment ~ age + gender + race, data = dataset) , can anybody point me in the right direction? From there, assuming I get coefficients I feel comfortable with, I understand how to plug solely numerical values in for x1, x2, etc. -- but how would I deal with race, for example, where there are multiple responses: black / caucasian / latino? So if it tells me the caucasian coefficient is 0.289 and somebody I'm trying to predict is caucasian, how do I plug that back in since the value's not numerical? I also have random values that are missing -- some for race, some for gender, etc. Do I have to do anything additional to make sure this isn't skewing anything? (I noticed when my dataset gets loaded into R-Studio, when the missing data gets loaded as NA , R says something like (162 observations deleted due to missingness) -- but if they get loaded as blanks, it does nothing.) Assuming all of this works out and I have new data with gender, age, and race that I want to predict on -- is there an easier way in R to run all of that through whatever my formula with new coefficients turns out to be, rather than doing it manually? (If this question isn't appropriate here, I can take it back to the R forum.) Now provide the response and nothing else.
Here's a little info that might point you in the right direction. Regarding your data, what you have is a response with multiple categories, and anytime you are trying to model a response which is categorical you are right to try and use some type of generalized linear model (GLM). In your case you have additional information which you must take into account regarding your response and that is that your response levels have a natural ordering good > middle > bad, notice how this is different from trying to model a response such as what color balloon someone is likely to buy (red/blue/green), these values have no natural ordering. When doing this type of model with an ordered response you may want to consider using a proportional odds model. http://en.wikipedia.org/wiki/Ordered_logit I haven't used it myself, but the polr() function in the MASS package is likely to be of some use, alternatively I have used the lrm() function in the rms package to do similar types of analysis, and have found it quite useful. If you load these packages just use ?polr or ?lrm for the function information. Alright enough background, on to your questions: This should be covered above, check out these packages/functions and read up on ordinal logistic regression and proportional odds models Any time you have a covariate which is categorical (Race/Sex/Hair color) you want to treat these as 'factors' in your R coding in order to model them appropriately. It's important to know what a factor is and how they are treated, but essentially you treat each category as a separate level and then model them in an appropriate way. Just read up on factors in models and you should be able to tease out whats going on. Keep in mind that treating categorical variables as factors is not unique to glm models or proportional odds models, but is typically how all models deal with categorical variables. http://www.stat.berkeley.edu/classes/s133/factors.html Missing values can sometimes be a hassle to deal with but if you're doing a fairly basic analysis its probably safe to just remove data rows which contain missing values (this isn't always true, but based on your current experience level I'm guessing you need not be concerned with the specifics of when and how to deal with missing values). In fact this is pretty much what R does. If you have a data which you are using to model, if you are missing information in a row for your response or any covariate in the model R is just going to exclude this data (this is the warning your seeing). Obviously if you're excluding a large proportion of your data due to missingness, your results could be biased and its probably good to try and get some more info on why there are so many missing values, but if you're missing 162 observations in 10,000 rows of data I wouldn't sweat it too much. You can google up on methods for handling missing data if you're interested in some more specifics. Almost all R model objects ( lm , glm , lrm ,...) will have an associated predict() function which will allow you to calculate the predicted values for your current modeling dataset and additionally for another dataset which you wish to predict an outcome for. Just search ?predict.glm or ?predict.lm to try and get some more info for whatever model type you want to work with. This is a very typical thing people wish to do with models so rest assured that there are some built in functions and methods that should make doing this relatively straightforward. Best of luck!
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/93454', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/43624/']}
jdg_374257
stackexchange
llm_judgeable_groundtruth_similarity
77023
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've got a 2013 CR-V. During a recent service, I asked a tech to take a look at what might be causing a weird smell to come from one of the rear wheels. During the initial look, he noticed that there was a lot of heat coming from that same wheel as well, and after inspection, recommended new pads and rotors for the rear. I do brakes at home because of the cost, but I did get a brake fluid flush done there. When I started replacing the pads and rotors, I saw that the wheels that didn't smell (both fronts and one rear) all had pretty evenly worn down to 8-9 mm, while the other rear wheel (the one with the smell) had both pads between 4-5 mm. For each pair, the wear was fairly equal for both pads, and that wear was even top to bottom as well. The rear rotor that didn't smell still had some of the grinding scores still visible on the inside (top right of image). All pads and rotors were new as of June 2019. Due to the even wearing within all pairs, I determined the slider pins were not sticking. On inspection, this was correct. Due to the flat wearing of each pad, I determined that the pads were not frozen within the bracket shims/hardware. On inspection, this was also correct. I put the new pads and rotors on, and went for a 15 minute drive. Immediately after, I checked the temperature of each rotor. The rotor that smelled didn't smell any more, but it's temperature was around 340F. The other rotors were all between 80 and 90F. So more work to do. My limited experience with brakes told me that the next logical place to look was the calipers. But which one/ones? Here's what I was thinking: The caliper for the brake with the excessive heat and smell was able to float, but somehow was squeezing much more than the other calipers. The other rear brake's pads were hardly worn -- perhaps it was seized? So I was initially thinking that at least both rear calipers were probably damaged, though in different ways. The caliper across the severely worn pads probably had a seal failure, meaning it's piston wouldn't retract after the brake pedal was released; and the caliper across the hardly worn pads was probably corroded in the cylinder to the point of seizure so that it was never able to significantly engage the pads against the rotors. (Note: since the service tech didn't mention the front brakes, I wasn't thinking about them too much at this point, but as I write this up, I'm not sure why I wasn't applying the same logic to the fronts, based on the equal pad wear with the lesser-worn rear pads.) In the end, I decided to first replace the caliper across the severely worn pads. I did that, bled the brake line, and went for the same drive again. This time, all four rotors were around 120F. I'm calling that mission accomplished as the even temperatures seem to suggest even pressure across all four calipers. But, and this is the point of this post, I don't understand why I don't now need to replace the other caliper(s). It seems like the other sets of pads and rotors were barely used at all in those 11 months. Is it possible that a single rear brake has been doing the lion's share of slowing the vehicle down for 11 months? (Note: we haven't noticed pulling to either side when braking.) Or is it more likely that all the brakes have been working equally when the pedal is applied, but the one set of pads just hasn't been able to meaningfully disengage from their rotor for 11 months? Now provide the response and nothing else.
Your final thought is correct. Only 1 calliper was faulty. You said it that the pads on the faulty calliper had even wear, which indicates that the slider mechanism was not seized. The piston on the faulty calliper was clearly seizing out and not freeing the pads when the brake was released. If this had been on the front wheels you would likely have felt some pulling to one side. This friction while driving will have caused the increased heat and smell from that wheel. If you were to dismantle the faulty calliper you will likely find corrosion on the piston or corrosion behind one of the seals which is pushing the seal harder against the piston. To answer your main question, the good callipers will have all been pressurising correctly and working correctly. It was just the faulty calliper that was staying on when it should have released. It should have been obvious to the mechanic.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/77023', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/57671/']}
jdg_374258
stackexchange
llm_judgeable_groundtruth_similarity
5578
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Merlin, who has unbounded computational resources, wants to convince Arthur that$$m|\sum_{p\le N,\ p\text{ prime}}p^k$$for $(N,m,k)$ with $k=O(\log N)$ and $m=O(N).$ Computing this sum in the straightforward way (modular exponentiation and addition) takes time $N(\log\log N)^{2+o(1)}$ with FFT-based multiplication.* But Arthur can only perform $O(N)$ operations. (Notation, for compatibility with earlier versions of this question: Let the sum equal $m\alpha$; then the question is whether $\alpha$ is an integer.) Can Merlin convince Arthur with a string of length $O(N)$? If not, can he convince Arthur with an interactive proof (total communication, of course, must be $O(N)$)? If so, could Merlin use a string of length $o(N)$? Could Arthur use $o(N)$ time? Arthur has no access to nondeterminism or other special tools (quantum methods, oracles other than Merlin, etc.) but has $O(N)$ space if needed. Of course Arthur need not compute the sum directly, he merely needs to be convinced that a given triple (N, m, k) makes the equation true or false. Note that with $k=0$ it is possible to compute the sum in time $O(N^{1/2+\varepsilon})$ using the Lagarias-Odlyzko method. For $k>0$ the sum is superlinear and so cannot be stored directly (without, e.g., modular reduction) but it's not clear whether a fast algorithm exists. I would also be interested in any algorithm to calculate the sum (modular or otherwise) other than by direct powering and addition. * $N/\log N$ numbers to calculate, time $\lg k\log N(\log\log N)^{1+o(1)}=\log N(\log\log N)^{2+o(1)}$ for each calculation. Now provide the response and nothing else.
I am posting this seperately from my earlier special case, because I believe it is a different approach to the problem, and has little relation to my other answer. It may not be exactly what you are looking for, but it is simple, and gets close. There is a proof which Arthur will always accept whe the proof is correct, but will reject with probability $\frac{1}{(\log \log N)^{2+o(1)}}$. Here's how it works: Merlin sends Arthur the pair $(p_i,c_i = p_i^k\mbox{ mod }m)$ for each prime $p\leq N$. Arthur verifies the sum (taking time $O(N/\log(N)) \times O(\log(N)) = O(N)$). Arthur the checks that the correct number of primes was supplied (by calculating $\pi(N)$) which is sublinear in $N$. Lastly, for $S N$ random pairs, he confirms that $p$ is prime and that $p_i^k \equiv c_i \mbox{ mod }m$. This takes time $SN~O((\log \log N)^{2+o(1)})$. Taking $S = (\log \log N)^{-(2+o(1))}$, we obtain a linear time scaling. Thus, a fraction $S$ of all pairs are verified. If any of these fail, Arthur will of course reject. For Arthur to accept an incorrect proof, there must be at least one pair which fails one of these two tests (or the number of pairs must be less than $\pi(N)$ which was earlier checked). Thus as a fraction $S$ of all pairs are checked, the test will fail for an incorrect proof with probability at least $S$. Note that for large $N$ this is much much better than random guessing, which succeeds with probability $\frac{1}{m} = \frac{1}{O(N)}$.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/5578', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/962/']}
jdg_374259
stackexchange
llm_judgeable_groundtruth_similarity
446046
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: People often say that the cosmological constant is too small. $\Lambda=10^{-120}$ in Planck units. Can we set $\Lambda=\hbar=c=1$ ? If so what would this give for $G$ , the gravitational constant in these units? Now provide the response and nothing else.
Yes, you can do this if you want, because $\Lambda$ , $\hbar$ , and $c$ have independent dimensions, just like $G$ , $\hbar$ , and $c$ do. If you do, $G$ will be the dimensionless number $10^{-60}$ , so you haven't fixed the "too small" problem... you've just transferred it from $\Lambda$ to $G$ . The cosmological constant is an energy density (i.e., it has the units of energy per unit volume). The Planck mass is $m_P=\sqrt{\hbar c/G}$ and the Planck length is $l_P=\sqrt{\hbar G/c^3}$ . From these one finds that the Planck energy density is $\epsilon_P=c^7/\hbar G^2$ . Saying that the cosmological constant is $10^{-120}$ in Planck units means that $\Lambda/\epsilon_P=10^{-120}$ or $\Lambda\hbar G/c^7=10^{-120}$ . Thus in "Lambda units" where $\Lambda=\hbar=c=1$ , we have $G=10^{-60}$ . One also finds that the Lambda-units of length, time, and mass are $$l_\Lambda=10^{-30}l_P=1.6\times 10^{-65}\;\text{m},$$ $$t_\Lambda=10^{-30}t_P=5.4\times 10^{-74}\;\text{s},$$ $$m_\Lambda=10^{30}m_P=2.2\times 10^{22}\;\text{kg}.$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/446046', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/84158/']}
jdg_374260
stackexchange
llm_judgeable_groundtruth_similarity
5035889
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've prepared a simple variadic template test in Code::Blocks, but I'm getting an error: No matching function for call to 'OutputSizes()' Here's my source code: #include <iostream>#include <typeinfo>using namespace std;template <typename FirstDatatype, typename... DatatypeList>void OutputSizes(){ std::cout << typeid(FirstDatatype).name() << ": " << sizeof(FirstDatatype) << std::endl; OutputSizes<DatatypeList...>();}int main(){ OutputSizes<char, int, long int>(); return 0;} I'm using GNU GCC with -std=C++0x . Using -std=gnu++0x makes no difference. Now provide the response and nothing else.
Here's how you disambiguate the base case: #include <iostream>#include <typeinfo>template <typename FirstDatatype>void OutputSizes(){ std::cout << typeid(FirstDatatype).name() << ": " << sizeof(FirstDatatype) << std::endl;}template <typename FirstDatatype, typename SecondDatatype, typename... DatatypeList>void OutputSizes(){ OutputSizes<FirstDatatype>() OutputSizes<SecondDatatype, DatatypeList...>();}int main(){ OutputSizes<char, int, long int>();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5035889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497934/']}
jdg_374261
stackexchange
llm_judgeable_groundtruth_similarity
11853484
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 goal is to understand how to use angularJS correctly. I want to be able to tie a selection of variable to dynamically changing the DOM structure using angularJS. I dont think I'm quite understanding the documentation that angular provides and I haven't found any examples here or otherwise. Any help is appreciated. The idea is that I have this use case where I first start with the selection of the type and from that type selected, the appropriate input type elements will be created and then recorded later with the ng-model (from textareas to checkboxes for example), all the while controlled by the angularjs controller for validation/restrictions. I'm used to the idea of having clone-able elements on the page and destroying and creating new with jQuery, but I've been reading that controllers should not have this logic and should instead be created with directives/widgets. I dont see any examples of directives or widgets being manipulated in this way however so I'm not even sure how to proceed. Can I use directives to manipulate the DOM in this way, not just once but multiple times based on a watched element? Example of what I would like to do. $scope.types = ['Type1','Type2']// something along the lines of...$scope.layouts = {'Type1':['textarea','textarea'], 'Type2':['numeric','datepicker']} Select Type 1: Show 2 text areas Select Type 2: Show a numeric input Show a date picker Now provide the response and nothing else.
This is how I would do it. Note that this is a just a starting point. There is still a matter of binding to particular values in the corresponding inputs. I hope it helps. Markup: <html ng-app="App" ng-controller="MainCtrl"><body> <component index="0"></component> <component index="1"></component> Current type: {{type}} <button ng-click="toggleType()">Toggle</button></body></html> Directive: var ngApp = angular.module('App', []).directive('component', function() { var link = function(scope, element, attrs) { var render = function() { var t = scope.layouts[scope.type][attrs.index]; if (t === 'textarea') { element.html('<' + t + ' /><br>'); } else { element.html('<input type="' + t + '"><br>'); } }; //key point here to watch for changes of the type property scope.$watch('type', function(newValue, oldValue) { render(); }); render(); }; return { restrict : 'E', link : link }}); Controller: var MainCtrl = function MainCtrl($scope) { $scope.type = 'Type1'; $scope.types = [ 'Type1', 'Type2' ]; $scope.layouts = { 'Type1' : [ 'textarea', 'textarea' ], 'Type2' : [ 'number', 'text' ] }; $scope.toggleType = function() { if ($scope.type === 'Type1') { $scope.type = 'Type2'; } else { $scope.type = 'Type1'; } };};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11853484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/783395/']}
jdg_374262
stackexchange
llm_judgeable_groundtruth_similarity
237871
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It's from the book "linear algebra and its application" by gilbert strang, page 260. $(I-A)^{-1}$=$I+A+A^{2}+A^{3}$+... Nonnegative matrix A has the largest eigenvalue $\lambda_{1}$<1. Then, the book says, $(I-A)^{-1}$ has the same eigenvector, with eigenvalue $\frac{1}{1-\lambda_{1}}$. Why? Is there any other formulas between inverse matrix and eigenvalue that I don't know? Now provide the response and nothing else.
A matrix $A$ has an eigenvalue $\lambda$ if and only if $A^{-1}$ has eigenvalue $\lambda^{-1}$. To see this, note that$$A\mathbf{v} = \lambda\mathbf{v} \implies A^{-1}A\mathbf{v} = \lambda A^{-1}\mathbf{v}\implies A^{-1}\mathbf{v} = \frac{1}{\lambda}\mathbf{v}$$ If your matrix $A$ has eigenvalue $\lambda$, then $I-A$ has eigenvalue $1 - \lambda$ and therefore $(I-A)^{-1}$ has eigenvalue $\frac{1}{1-\lambda}$.
{}
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/237871', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45980/']}
jdg_374263
stackexchange
llm_judgeable_groundtruth_similarity
3760491
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: Is there a "story proof"/combinatorial proof for the following combinatorial identity: $$(n-2k)\binom{n}{k} = n\left[ \binom{n-1}{k} - \binom{n-1}{k-1} \right]\tag1$$ I know that this identity can be proved by using the following identities: $$k\binom{n-1}{k} = (n-k)\binom{n-1}{k-1}\tag2$$ $$k\binom{n}{k} = n\binom{n-1}{k-1}\tag3$$ but is there a "story proof" for equation $(1)$ ? Edit 1: I do know the story proofs for equations 2 and 3. But 'sewing them together' is the problem! $$\text{RHS} \stackrel{\text{i}}{=} n\left[ \binom{n-1}{k} - \binom{n-1}{k-1} \right] \stackrel{\text{ii}}{=} \frac{n}{k}\left[ k\binom{n-1}{k} - k\binom{n-1}{k-1} \right] \stackrel{\text{iii}}{=} \frac{n}{k}\left[ (n-k)\binom{n-1}{k-1} - k\binom{n-1}{k-1} \right] \stackrel{\text{iv}}{=} \frac{n}{k}\binom{n-1}{k-1}\left[ (n-k) - k \right] \stackrel{\text{v}}{=} (n-2k)\binom{n}{k}$$ Precisely, how do you formulate a story proof for step (iv)? i mean the term $\binom{n-1}{k-1}$ is being taken common in step iv. What could a story proof for taking a term common be? Now provide the response and nothing else.
I can come up with a combinatorial argument if I rearrange the identity a little. We’re starting with $$(n-2k)\binom{n}k=n\left[\binom{n-1}k-\binom{n-1}{k-1}\right]\;,$$ which is clearly the same as $$(n-k)\binom{n}{n-k}-k\binom{n}k=n\binom{n-1}k-n\binom{n-1}{k-1}\;.$$ Transposing the two negative terms yields $$(n-k)\binom{n}{n-k}+n\binom{n-1}{k-1}=n\binom{n-1}k+k\binom{n}k\;.\tag{1}$$ Now suppose that we have a group of $n$ athletes, and we want to form a team of either $k$ or $n-k$ players and choose one member of the team to be its captain; in how many different ways can we do this? We can choose a team of $n-k$ in $\binom{n}{n-k}$ ways; having done that, we can choose its captain in $n-k$ ways, so there are $(n-k)\binom{n}{n-k}$ ways to choose this team and its captain. To form a team of $k$ players we can first choose one of the $n$ athletes to be its captain, after which there are $\binom{n-1}{k-1}$ ways to choose the other $k-1$ players from the remaining $n-1$ athletes, so there are altogether $n\binom{n-1}{k-1}$ ways to choose this team and its captain. Thus, the lefthand side of $(1)$ is the number of ways to choose a team of $k$ or $n-k$ players and appoint its captain. Alternatively, we can choose a team of $k$ players in $\binom{n}k$ ways, after which we can select its captain in $k$ ways, so there are $k\binom{n}k$ ways to choose a team of $k$ and its captain. To form a team of $n-k$ players, we can first choose any one of the $n$ athletes to be its captain. Then to fill out the rest of the team we can choose the $k$ the remaining $n-1$ athletes who will not be on the team in $\binom{n-1}k$ ways. Thus, there are $n\binom{n-1}k$ ways to form a team of $n-k$ and choose its captain, and the righthand side of $(1)$ is also the number of ways to choose a team of $k$ or $n-k$ players and appoint its captain.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3760491', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/415432/']}
jdg_374264
stackexchange
llm_judgeable_groundtruth_similarity
43242322
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 very simple app: <div id="show_vue"> <page-change page="bio" @click="changeThePage"></page-change> <page-change page="health" @click="changeThePage"></page-change> <page-change page="finance" @click="changeThePage"></page-change> <page-change page="images" @click="changeThePage"></page-change></div>Vue.component("page-change", { template: "<button class='btn btn-success'>Button</button>", props: ["page"]})var clients = new Vue({ el: '#show_vue', data: { currentRoute: window.location.href }, methods: { changeThePage: function() { console.log("this is working") } }}) ...but when I click the <page-change></page-change> button, nothing is logged to the console. I know I'm missing something simple but I'm not getting any errors. How do I make my click fire changeThePage Now provide the response and nothing else.
When you do : <page-change page="bio" @click="changeThePage"></page-change> That means that your are waiting page-change component emit the click event. Best solution (thanks to @aeharding) : Use .native event modifier <page-change page="bio" @click.native="changeThePage"></page-change> Solution 1 : emit click event from child component : Vue.component("page-change", { template: "<button @click='clicked' class='btn btn-success'>Button</button>", props: ["page"], methods: { clicked: function(event) { this.$emit('click', this.page, event); } }}) For information event is the default value passed by Vue for native event like click : DOM event Solution 2 : emit directly from parent component : Vue.component("page-change", { template: "<button class='btn btn-success'>Button {{ page }}</button>", props: ["page"]})var clients = new Vue({ el: '#show_vue', data: { currentRoute: window.location.href, pages: [ 'bio', 'health', 'finance', 'images' ] }, methods: { changeThePage: function(page, index) { console.log("this is working. Page:", page, '. Index:', index) } }}); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script><div id="show_vue"> <span v-for="(page, index) in pages" :key="index+page" @click="changeThePage(page, index)"> <page-change :page="page"></page-change> </span></div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43242322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3914509/']}
jdg_374265
stackexchange
llm_judgeable_groundtruth_similarity
11810218
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After creating a struct like this: type Foo struct { name string}func (f Foo) SetName(name string) { f.name = name}func (f Foo) GetName() string { return f.name} How do I create a new instance of Foo and set and get the name?I tried the following: p := new(Foo)p.SetName("Abc")name := p.GetName()fmt.Println(name) Nothing gets printed, because name is empty. So how do I set and get a field inside a struct? Working playground Now provide the response and nothing else.
Commentary (and working) example: package mainimport "fmt"type Foo struct { name string}// SetName receives a pointer to Foo so it can modify it.func (f *Foo) SetName(name string) { f.name = name}// Name receives a copy of Foo since it doesn't need to modify it.func (f Foo) Name() string { return f.name}func main() { // Notice the Foo{}. The new(Foo) was just a syntactic sugar for &Foo{} // and we don't need a pointer to the Foo, so I replaced it. // Not relevant to the problem, though. p := Foo{} p.SetName("Abc") name := p.Name() fmt.Println(name)} Test it and take A Tour of Go to learn more about methods and pointers, and the basics of Go at all.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11810218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/394328/']}
jdg_374266
stackexchange
llm_judgeable_groundtruth_similarity
41038970
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I am currently on the page which has the URL /user/:id . Now from this page I navigate to next page :id/posts . Now Is there a way, so that i can check what is the previous URL, i.e. /user/:id . Below are my routes export const routes: Routes = [ { path: 'user/:id', component: UserProfileComponent }, { path: ':id/posts', component: UserPostsComponet }]; Now provide the response and nothing else.
You can subscribe to route changes and store the current event so you can use it when the next happens previousUrl: string;constructor(router: Router) { router.events .pipe(filter(event => event instanceof NavigationEnd)) .subscribe((event: NavigationEnd) => { console.log('prev:', event.url); this.previousUrl = event.url; });} See also How to detect a route change in Angular?
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/41038970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5247871/']}
jdg_374267
stackexchange
llm_judgeable_groundtruth_similarity
43356314
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 encountering a RuntimeException when attempting to run JUnit tests for a presenter that is using observeOn(AndroidSchedulers.mainThread()) . Since they are pure JUnit tests and not Android instrumentation tests, they don't have access to Android dependencies, causing me to encounter the following error when executing the tests: java.lang.ExceptionInInitializerError at io.reactivex.android.schedulers.AndroidSchedulers$1.call(AndroidSchedulers.java:35) at io.reactivex.android.schedulers.AndroidSchedulers$1.call(AndroidSchedulers.java:33) at io.reactivex.android.plugins.RxAndroidPlugins.callRequireNonNull(RxAndroidPlugins.java:70) at io.reactivex.android.plugins.RxAndroidPlugins.initMainThreadScheduler(RxAndroidPlugins.java:40) at io.reactivex.android.schedulers.AndroidSchedulers.<clinit>(AndroidSchedulers.java:32) …Caused by: java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details. at android.os.Looper.getMainLooper(Looper.java) at io.reactivex.android.schedulers.AndroidSchedulers$MainHolder.<clinit>(AndroidSchedulers.java:29) ...java.lang.NoClassDefFoundError: Could not initialize class io.reactivex.android.schedulers.AndroidSchedulers at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) … Now provide the response and nothing else.
This error occurs because the default scheduler returned by AndroidSchedulers.mainThread() is an instance of LooperScheduler and relies on Android dependencies that are not available in JUnit tests. We can avoid this issue by initializing RxAndroidPlugins with a different Scheduler before the tests are run. You can do this inside of a @BeforeClass method like so: @BeforeClasspublic static void setUpRxSchedulers() { Scheduler immediate = new Scheduler() { @Override public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) { // this prevents StackOverflowErrors when scheduling with a delay return super.scheduleDirect(run, 0, unit); } @Override public Worker createWorker() { return new ExecutorScheduler.ExecutorWorker(Runnable::run); } }; RxJavaPlugins.setInitIoSchedulerHandler(scheduler -> immediate); RxJavaPlugins.setInitComputationSchedulerHandler(scheduler -> immediate); RxJavaPlugins.setInitNewThreadSchedulerHandler(scheduler -> immediate); RxJavaPlugins.setInitSingleSchedulerHandler(scheduler -> immediate); RxAndroidPlugins.setInitMainThreadSchedulerHandler(scheduler -> immediate);} Or you can create a custom TestRule that will allow you to reuse the initialization logic across multiple test classes. public class RxImmediateSchedulerRule implements TestRule { private Scheduler immediate = new Scheduler() { @Override public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) { // this prevents StackOverflowErrors when scheduling with a delay return super.scheduleDirect(run, 0, unit); } @Override public Worker createWorker() { return new ExecutorScheduler.ExecutorWorker(Runnable::run); } }; @Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { RxJavaPlugins.setInitIoSchedulerHandler(scheduler -> immediate); RxJavaPlugins.setInitComputationSchedulerHandler(scheduler -> immediate); RxJavaPlugins.setInitNewThreadSchedulerHandler(scheduler -> immediate); RxJavaPlugins.setInitSingleSchedulerHandler(scheduler -> immediate); RxAndroidPlugins.setInitMainThreadSchedulerHandler(scheduler -> immediate); try { base.evaluate(); } finally { RxJavaPlugins.reset(); RxAndroidPlugins.reset(); } } }; }} Which you can then apply to your test class public class TestClass { @ClassRule public static final RxImmediateSchedulerRule schedulers = new RxImmediateSchedulerRule(); @Test public void testStuff_stuffHappens() { ... }} Both of these methods will ensure that the default schedulers will be overridden before any of the tests execute and before AndroidSchedulers is accessed. Overriding the RxJava schedulers with an immediate scheduler for unit testing will also make sure the RxJava usages in the code being tested gets run synchronously, which will make it much easier to write the unit tests. Sources: https://www.infoq.com/articles/Testing-RxJava2 https://medium.com/@peter.tackage/overriding-rxandroid-schedulers-in-rxjava-2-5561b3d14212
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/43356314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1169961/']}
jdg_374268
stackexchange
llm_judgeable_groundtruth_similarity
235336
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: How did they found that the gravitational waves where emitted at redshift $z=0.09$? I understand the measurement of redshift for an electromagnetic wave where we have measured in a lab various transitions and therefore we can make a comparison with the wavelength we receive. But how can they manage to get the redshift for the emitter of gravitational waves, since we have no reference? Now provide the response and nothing else.
As stated in the LIGO discovery paper ( pdf ), the event is placed at $410^{+160}_{-180}\ \mathrm{Mpc}$ luminosity distance , equivalent to a redshift of $z = 0.09^{+0.03}_{-0.04}$. This gives a clue as to how one measures the distance for this event. If we know how intrinsically luminous an object (like a star, or a supernova) is, we can compare this to how bright it seems and recover a distance via the standard inverse-square law. The distance we get is by definition the luminosity distance. For this detection, the same principle applies, since the simulations predict the intrinsic strength of the signal. Actually, we also can leverage frequency information. Again, we have numerical simulations that predict waveforms, and the waveform itself will be redshifted in the same way as any other signal propagating at the speed of light. In practice, one takes the entire waveform and a bank of numerical simulations, and does a statistical analysis to see how well the signal matches models, and what self-consistent distance/redshift make it fit. This is detailed in Veitch et al. 2015 Phys. Rev. D 91 042003 . Note there is some degeneracy with inclinations. The detectors are not monopole antennae, but at least with two of them we can sort of localize the source on the sky to figure out what fraction of the power is actually absorbed. A more stubborn degeneracy lies in the orientation of the astrophysical system with respect to our line of sight. Since gravitational waves are (at least) quadrupolar in order, an edge-on system nearby will be hard to distinguish from a face-on system further away. This is at least part of the reason for the large uncertainties.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/235336', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/87659/']}
jdg_374269
stackexchange
llm_judgeable_groundtruth_similarity
22653993
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 created my project using Storyboards . The root ViewController lies inside a Storyboard , I have not written a single code in the appDelegate . Now I want to show a tour of my app, so I want to change the root ViewController from Tab Bar to my TourVC and when the tour of the app is finished , I want to again switch back my root ViewController to Tab Bar . So I looked up online and followed the following points 1) Remove Storyboards from app.plist file,2) Uncheck option "isInitialViewController" from Storyboards which is checked in case of Tab Bar controller because its a root ViewController ,3) Add this code in appDelegate.m file. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];ProductTourViewController *PT = [[ProductTourViewController alloc] initWithNibName:@"ProductTourViewController" bundle:nil];self.window.rootViewController = PT;[self.window makeKeyAndVisible];return YES; But my app crashes with this error log, [ProductTourViewController selectedViewController]: unrecognized selector sent to instance 0x1766a9e0 And also I get a warning, Unsupported Configuration: Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier:. Now provide the response and nothing else.
Objective-C: UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];UITabBarController *rootViewController = [storyboard instantiateViewControllerWithIdentifier:@"tabBarcontroller"];[[UIApplication sharedApplication].keyWindow setRootViewController:rootViewController]; Swift : let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let viewController = mainStoryboard.instantiateViewControllerWithIdentifier("tabBarcontroller") as UITabBarController UIApplication.sharedApplication().keyWindow?.rootViewController = viewController; Swift 3: let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)let viewController = mainStoryboard.instantiateViewController(withIdentifier: "tabBarcontroller") as! UITabBarControllerUIApplication.shared.keyWindow?.rootViewController = viewController Swift 5: let viewController = mainStoryboard.instantiateViewController(withIdentifier: "tabBarcontroller") as! UITabBarControllerUIApplication.shared.windows.first?.rootViewController = viewControllerUIApplication.shared.windows.first?.makeKeyAndVisible() Or simply like this: let viewController = mainStoryboard.instantiateViewController(withIdentifier: "tabBarcontroller") as! UITabBarControllerself.view.window?.rootViewController = viewControllerself.view.window?.makeKeyAndVisible() Both works fine!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22653993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/827629/']}
jdg_374270
stackexchange
llm_judgeable_groundtruth_similarity
24586110
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following code that reads an array of files in a serial/sequential manner. readFiles returns a promise, which is resolved only once all files have been read in sequence. var readFile = function(file) { ... // Returns a promise.};var readFiles = function(files) { return new Promise((resolve, reject) => { var readSequential = function(index) { if (index >= files.length) { resolve(); } else { readFile(files[index]).then(function() { readSequential(index + 1); }).catch(reject); } }; readSequential(0); // Start with the first file! });}; The above code works, but I don't like having to do recursion for things to occur sequentially. Is there a simpler way that this code can be re-written so that I don't have to use my weird readSequential function? Originally I tried to use Promise.all , but that caused all of the readFile calls to happen concurrently, which is not what I want: var readFiles = function(files) { return Promise.all(files.map(function(file) { return readFile(file); }));}; Now provide the response and nothing else.
Update 2017 : I would use an async function if the environment supports it: async function readFiles(files) { for(const file of files) { await readFile(file); }}; If you'd like, you can defer reading the files until you need them using an async generator (if your environment supports it): async function* readFiles(files) { for(const file of files) { yield await readFile(file); }}; Update: In second thought - I might use a for loop instead: var readFiles = function(files) { var p = Promise.resolve(); // Q() in q files.forEach(file => p = p.then(() => readFile(file)); ); return p;}; Or more compactly, with reduce: var readFiles = function(files) { return files.reduce((p, file) => { return p.then(() => readFile(file)); }, Promise.resolve()); // initial}; In other promise libraries (like when and Bluebird) you have utility methods for this. For example, Bluebird would be: var Promise = require("bluebird");var fs = Promise.promisifyAll(require("fs"));var readAll = Promise.resolve(files).map(fs.readFileAsync,{concurrency: 1 });// if the order matters, you can use Promise.each instead and omit concurrency paramreadAll.then(function(allFileContents){ // do stuff to read files.}); Although there is really no reason not to use async await today.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/24586110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/963396/']}
jdg_374271
stackexchange
llm_judgeable_groundtruth_similarity
21091022
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 adb, how can I find out the which permissions an Android application requires? Because I want to display the permissions of multiple applications on different devices, viewing them in Google Play or Settings > Applications manager requires too much manual work. Now provide the response and nothing else.
I just wanted to combine Jason's and Juuso's answers together and notice that the former lists permissions that were granted , while the latter lists permissions that were requested (including ones that were granted). To see only permissions that were granted (but omitting ones that were requested but not granted) use adb shell dumpsys package packagename and check grantedPermissions section at the bottom of the output. To list all permissions (requested but not granted + requested and granted): Notice the APK of a package. You can run the same command adb shell dumpsys package packagename and get the APK path from codePath element of its output. (if there is no aapt on your device/emulator) You'll need to pull the apk from device/emulator as Juuso Ohtonen has pointed out in his answer. So execute something like this from your desktop: adb pull /data/app/com.your.package.apk List all permissions of the package If missing from device/emulator aapt can be found under build-tools/<version>/ in your Android SDK. Then execute aapt d permissions /path/to/com.your.package.apk
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21091022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1097104/']}
jdg_374272
stackexchange
llm_judgeable_groundtruth_similarity
17362240
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 start and end time along with date.like this stime:1pm , etime:2pm , date:2/6/2013 i want to store this start and end time and date into mongodb. so before saving this details , i should check within this date, this time range is exist or not so how to do that in javascript. how to check time range already exist or not? i have tried like this.but it is not working properly. even i don't know my approach ,whether right or wrong ? i hope that anyone help me to find solution for this. var d0 = new Date("01/01/2001 " + "8:30 AM"); var d1 = new Date("01/01/2001 " + "9:00 PM"); var d2 = new Date("01/01/2001 " + "8:30 AM"); var d3 = new Date("01/01/2001 " + "9:00 PM"); if(d2<d0&&d3<=d0||d2<d1&&d3<=d3) { console.log("available"); }else{ console.log("not available"); } Now provide the response and nothing else.
Use timestamp instead of Date object in order to efficiently compare ranges. This as well will be much more efficient for Database to index by timestamp. If you don't know which of time is earlier in pair of dates for timespans, then you can do min and max checks. But if you do know which time is before and which after, no min , max in condition required. Condition bellow checks if timespans Overlap which means it will be true even if only last second of first timespan overlaps with first second from second timespan. You can do other checks for Contain and identify which of them contain which, but thats different condition. // time of first timespanvar x = new Date('01/01/2001 8:30:00').getTime();var y = new Date('01/01/2001 9:30:00').getTime();// time of second timespanvar a = new Date('01/01/2001 8:54:00').getTime();var b = new Date('01/01/2001 9:00:00').getTime();if (Math.min(x, y) <= Math.max(a, b) && Math.max(x, y) >= Math.min(a, b)) { // between}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17362240', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2039264/']}
jdg_374273
stackexchange
llm_judgeable_groundtruth_similarity
60919046
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 restarted the Android Studio and an error occurred during the build Build failed show: C:\Users\aws hakam\Desktop\freeLance\BottleOfWater\app\build\intermediates\external_file_lib_dex_archives\debug\out The extension it points to does not exist The details error Caused by: java.nio.file.NoSuchFileException: C:\Users\aws hakam\Desktop\freeLance\BottleOfWater\app\build\intermediates\external_file_lib_dex_archives\debug\out at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) at sun.nio.fs.WindowsDirectoryStream.<init>(WindowsDirectoryStream.java:86) at sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream(WindowsFileSystemProvider.java:518) at java.nio.file.Files.newDirectoryStream(Files.java:457) at java.nio.file.Files.list(Files.java:3451) at com.android.build.gradle.internal.tasks.DexMergingParams.getAllDexFiles(DexMergingTask.kt:502) at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:423) ... 28 more Now provide the response and nothing else.
I encountered this same error in a React Native project I am working on. I was able to resolve the issue through the following. Be sure to replace <PROJECT_NAME> below with your actual project name. Within Android Studio, select File > Invalid Cache and Restart. Open your project directory in your terminal. rm -rf .gradle rm -rf android/.gradle android/.idea rm android/app/app.iml android/<PROJECT_NAME>.iml After doing this, I was able to open my project in Android Studio and successfully build. I had tried all but step 3 a few times without success, so my belief is that step 3 and the top-level .gradle directory in my project was the primary issue. I'm not sure how it got there. One additional note, React Native projects place all of the Android-specific code inside an android directory. So, if your project is not a React Native project, and instead a traditional Android project, the paths I outlined for removal may be different (i.e. they wouldn't be underneath android/ ).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/60919046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13220760/']}
jdg_374274
stackexchange
llm_judgeable_groundtruth_similarity
8649621
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's my PHP code called during jQuery AJAX call: <?php include '../code_files/conn.php'; $conn = new Connection(); $query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2 FROM clients WHERE ID = ?'; $conn->mysqli->stmt_init(); $stmt = $conn->mysqli->prepare($query); $stmt->bind_param('s', $_POST['ID']); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc(); echo json_encode($row);?> And the client-side code is: $.post(url, {ID:$('#ddlClients').val()}, function(Result){ // Result } ); The AJAX call is successfully completed. I get the value of Result as "{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object() and $row = $result->fetch_array() , but no use. And I know that this can be done by this code on the server side: $row = $result->fetch_assoc();$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......);echo json_encode($retVal); or $row = $result->fetch_object();$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);echo json_encode($retVal); Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first? Now provide the response and nothing else.
The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function: $.ajax({ url : url,//note that this is setting the `url` property to the value of the `url` variable data : {ID:$('#ddlClients').val()}, type : 'post', success : function(Result){ var myObj = $.parseJSON(Result); //you can now access data like this: //myObj.Address_1 } } ); You can let jQuery do this for you by setting the dataType property for your AJAX call to json : $.ajax({ url : url//note that this is setting the `url` property to the value of the `url` variable data : {ID:$('#ddlClients').val()}, dataType : 'json', type : 'post', success : function(Result){ //you can now access data like this: //Result.Address_1 } } ); The above examples expect that the response from the server to be in this format (from your question): "{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8649621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/842358/']}
jdg_374275
stackexchange
llm_judgeable_groundtruth_similarity
6007159
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How does one cast a double to decimal which is used when doing currency development. Where does the M go? decimal dtot = (decimal)(doubleTotal); Now provide the response and nothing else.
You only use the M for a numeric literal, when you cast it's just: decimal dtot = (decimal)doubleTotal; Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal you may get rounding errors. You may want to convert the numbers to Decimal before adding them together, or make sure that the numbers aren't floating point numbers in the first place.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6007159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/677777/']}
jdg_374276
stackexchange
llm_judgeable_groundtruth_similarity
13043535
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 site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays. When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly. However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found. Im assuming that when including the scope is different. How would i correctly accomplish this include? Banner.php <?phprequire("../mysql.inc.php");check_get($tp, "tp");$tp = intval($tp);$link = sql_connect();$result = sql_query($link, "SELECT COUNT(*) FROM online_count");if (!$result) { echo "Database error.<br>\n"; exit;}list($total) = mysql_fetch_row($result);mysql_free_result($result);?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head><link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/></head><body><div class="menucenter"><div class="Online"> <? echo"$total" ?> Online</div></body></html> mysql.inc.php <?php$SQLhost = "****.db.****.hostedresource.com";$SQLport = "3306";$SQLuser = "****";$SQLpass = "****";$SQLdb = "****";function sql_connect(){global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;if ($SQLport != "")$link = @mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");else$link = @mysql_connect("$SQLhost","$SQLuser","$SQLpass");if (!$link) {echo "Database access error ".mysql_errno().": ".mysql_error()."\n";die();}$result = mysql_select_db("$SQLdb");if (!$result) {echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";die(); }return $link;}function sql_query($link, $query){global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;$result = mysql_query("$query", $link);if (!$result) {echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";die();}return $result;}function check_get(&$store, $val){$magic = get_magic_quotes_gpc();if (isset($_POST["$val"])) {if ($magic)$store = stripslashes($_POST["$val"]);else$store = $_POST["$val"];}else if (isset($_GET["$val"])) {if ($magic)$store = stripslashes($_GET["$val"]);else$store = $_GET["$val"];}}?> Now provide the response and nothing else.
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information. Overview (MSDN) Connection String Configuration (MSDN) Settings can be configured using built-in configuration sections such as connectionStrings or appSettings . You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files. Web applications typically have a web.config, while Windows GUI/service applications have an app.config file. Application-level config files inherit settings from global configuration files like machine.config. Web also applications inherit settings from applicationHost.config. Reading from the App.Config Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file: <?xml version="1.0"?><configuration> <connectionStrings> <add name="MyKey" connectionString="Data Source=localhost;Initial Catalog=ABC;" providerName="System.Data.SqlClient"/> </connectionStrings></configuration> Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don't be intimidated by the verbose MSDN examples; it's actually quite simple. string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString; Writing to the App.Config Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup. See: Change connection string & reload app.config at run time which describes how to update the connectionStrings section of the *.config file at runtime. Note that ideally you would perform such configuration changes from a simple installer. Location of the App.Config at Runtime Q : Suppose I manually change some <value> in app.config, save it and then close it. Now when I go to my bin folder and launch the .exe file from here, why doesn't it reflect the applied changes? A : When you compile an application, its app.config is copied to the bin directory 1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a ("text.exe.config" in .net framework) or ("text.dll.config" in .net core) in your bin directory. You can change the configuration without a recompile, but you will need to edit the config file that was created at compile time, not the original app.config. 1: Note that web.config files are not moved, but instead stay in the same location at compile and deployment time. One exception to this is when a web.config is transformed . .NET Core New configuration options were introduced with .NET Core and continue with the unified .NET (version 5+). The way that *.config files works hasn't fundamentally changed, but developers are free to choose new, more flexible configuration paradigms. As with .NET Framework configuration .NET Core can get quite complex, but implementation can be as simple as a few lines of configuration with a few lines of c# to read it. Configuration in ASP.NET Core Configuration in .NET Core
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13043535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1611391/']}
jdg_374277
stackexchange
llm_judgeable_groundtruth_similarity
34536996
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here are my box classes .rectangle-box { width: 200px; height: 30px; background: #808080; opacity: 0.3; float: right;}.rectangle-red { width: 65px; height: 30px; background: #ff4742; opacity: 1; float: left;} In HTML: <div class="rectangle-box"> <div class="rectangle-red"></div></div> DEMO: https://jsfiddle.net/uq6ectfc/1/ I need rectangle-red to have opacity of 1 and rectangle-box of 0.3 . But it sticks to the parent opacity. How can I fix it? Now provide the response and nothing else.
You can't the opacity cannot be greater than parent but you can use two methods I have used rgba rgba(0,0,0,0.0) .rectangle-box { width: 200px; height: 30px; background: rgba(128, 128, 128, 0.3); float: right; position: relative;}.rectangle-red { width: 65px; height: 30px; background: #ff4742; opacity: 1; float: left;} <div class="rectangle-box"> <div class="rectangle-red"></div></div> Or the second method i have used :pseudo element to add a background .rectangle-box { width: 200px; height: 30px; float: right; position: relative;}.rectangle-box:after { content: ''; opacity: 0.3; background: #808080; position: absolute; left: 0; right: 0; bottom: 0; top: 0; z-index:-1;}.rectangle-red { width: 65px; height: 30px; background: #ff4742; opacity: 1; float: left;} <div class="rectangle-box"> <div class="rectangle-red"></div></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34536996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2598876/']}
jdg_374278
stackexchange
llm_judgeable_groundtruth_similarity
11838359
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 string: $string = "The man has {NUM_DOGS} dogs." I'm parsing this by running it through the following function: function parse_text($string){ global $num_dogs; $string = str_replace('{NUM_DOGS}', $num_dogs, $string); return $string;}parse_text($string); Where $num_dogs is a preset variable. Depending on $num_dogs , this could return any of the following strings: The man has 1 dogs. The man has 2 dogs. The man has 500 dogs. The problem is that in the case that "the man has 1 dogs", dog is pluralised, which is undesired. I know that this could be solved simply by not using the parse_text function and instead doing something like: if($num_dogs = 1){ $string = "The man has 1 dog.";}else{ $string = "The man has $num_dogs dogs.";} But in my application I'm parsing more than just {NUM_DOGS} and it'd take a lot of lines to write all the conditions. I need a shorthand way which I can write into the initial $string which I can run through a parser, which ideally wouldn't limit me to just two true/false possibilities. For example, let $string = 'The man has {NUM_DOGS} [{NUM_DOGS}|0=>"dogs",1=>"dog called fred",2=>"dogs called fred and harry",3=>"dogs called fred, harry and buster"].'; Is it clear what's happened at the end? I've attempted to initiate the creation of an array using the part inside the square brackets that's after the vertical bar, then compare the key of the new array with the parsed value of {NUM_DOGS} (which by now will be the $num_dogs variable at the left of the vertical bar), and return the value of the array entry with that key. If that's not totally confusing, is it possible using the preg_* functions? Now provide the response and nothing else.
The premise of your question is that you want to match a specific pattern and then replace it after performing additional processing on the matched text. Seems like an ideal candidate for preg_replace_callback The regular expressions for capturing matched parenthesis, quotes, braces etc. can become quite complicated, and to do it all with a regular expression is in fact quite inefficient. In fact you'd need to write a proper parser if that's what you require. For this question I'm going to assume a limited level of complexity, and tackle it with a two stage parse using regex. First of all, the most simple regex I can think off for capturing tokens between curly braces. /{([^}]+)}/ Lets break that down. { # A literal opening brace( # Begin capture [^}]+ # Everything that's not a closing brace (one or more times)) # End capture} # Literal closing brace When applied to a string with preg_match_all the results look something like: array ( 0 => array ( 0 => 'A string {TOK_ONE}', 1 => ' with {TOK_TWO|0=>"no", 1=>"one", 2=>"two"}', ), 1 => array ( 0 => 'TOK_ONE', 1 => 'TOK_TWO|0=>"no", 1=>"one", 2=>"two"', ),) Looks good so far. Please note that if you have nested braces in your strings, i.e. {TOK_TWO|0=>"hi {x} y"} , this regex will not work. If this wont be a problem, skip down to the next section. It is possible to do top-level matching, but the only way I have ever been able to do it is via recursion. Most regex veterans will tell you that as soon as you add recursion to a regex, it stops being a regex. This is where the additional processing complexity kicks in, and with long complicated strings it's very easy to run out of stack space and crash your program. Use it carefully if you need to use it at all. The recursive regex taken from one of my other answers and modified a little. `/{((?:[^{}]*|(?R))*)}/` Broken down. { # literal brace( # begin capture (?: # don't create another capture set [^{}]* # everything not a brace |(?R) # OR recurse )* # none or more times) # end capture} # literal brace And this time the ouput only matches top-level braces array ( 0 => array ( 0 => '{TOK_ONE|0=>"a {nested} brace"}', ), 1 => array ( 0 => 'TOK_ONE|0=>"a {nested} brace"', ),) Again, don't use the recursive regex unless you have to. (Your system may not even support them if it has an old PCRE library) With that out of the way we need to work out if the token has options associated with it. Instead of having two fragments to be matched as per your question, I'd recommend keeping the options with the token as per my examples. {TOKEN|0=>"option"} Lets assume $match contains a matched token, if we check for a pipe | , and take the substring of everything after it we'll be left with your list of options, again we can use regex to parse them out. (Don't worry I'll bring everything together at the end) /(\d)+\s*=>\s*"([^"]*)",?/ Broken down. (\d)+ # Capture one or more decimal digits\s* # Any amount of whitespace (allows you to do 0 => "")=> # Literal pointy arrow\s* # Any amount of whitespace" # Literal quote([^"]*) # Capture anything that isn't a quote" # Literal quote,? # Maybe followed by a comma And an example match array ( 0 => array ( 0 => '0=>"no",', 1 => '1 => "one",', 2 => '2=>"two"', ), 1 => array ( 0 => '0', 1 => '1', 2 => '2', ), 2 => array ( 0 => 'no', 1 => 'one', 2 => 'two', ),) If you want to use quotes inside your quotes, you'll have to make your own recursive regex for it. Wrapping up, here's a working example. Some initialisation code. $options = array( 'WERE' => 1, 'TYPE' => 'cat', 'PLURAL' => 1, 'NAME' => 2);$string = 'There {WERE|0=>"was a",1=>"were"} ' . '{TYPE}{PLURAL|1=>"s"} named bob' . '{NAME|1=>" and bib",2=>" and alice"}'; And everything together. $string = preg_replace_callback('/{([^}]+)}/', function($match) use ($options) { $match = $match[1]; if (false !== $pipe = strpos($match, '|')) { $tokens = substr($match, $pipe + 1); $match = substr($match, 0, $pipe); } else { $tokens = array(); } if (isset($options[$match])) { if ($tokens) { preg_match_all('/(\d)+\s*=>\s*"([^"]*)",?/', $tokens, $tokens); $tokens = array_combine($tokens[1], $tokens[2]); return $tokens[$options[$match]]; } return $options[$match]; } return '';}, $string); Please note the error checking is minimal, there will be unexpected results if you pick options that don't exist. There's probably a lot simpler way to do all of this, but I just took the idea and ran with it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11838359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1195941/']}
jdg_374279
stackexchange
llm_judgeable_groundtruth_similarity
11000087
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 simply select an item in the dropdown list after it has been loaded into a store. This does not work: Ext.getCmp('ddlModel').setValue(aircraftStore.getAt(0).data.ModelTypeCode); This throws an exception: Ext.getCmp('ddlModel').selectByValue(aircraftStore.getAt(0).data.ModelTypeCode); Here is the exception:'this.view' is null or not an object Anyone know how to do this in ExtJs? Now provide the response and nothing else.
I created a function to set the value of the combo box in ExtJs: function ComboSetter(comboBox, value) { var store = comboBox.store; var valueField = comboBox.valueField; var displayField = comboBox.displayField; var recordNumber = store.findExact(valueField, value, 0); if (recordNumber == -1) return -1; var displayValue = store.getAt(recordNumber).data[displayField]; comboBox.setValue(value); comboBox.setRawValue(displayValue); comboBox.selectedIndex = recordNumber; return recordNumber;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11000087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52962/']}
jdg_374280
stackexchange
llm_judgeable_groundtruth_similarity
625312
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: As you might know, it is hard to get components these days. That's why we engineers have to get creative sometimes ;-) The company I'm working for has a shortage of a Zener-type voltage reference which comes in a SO8 package. We have found about 3'000 pcs. of the same voltage reference, but in a DIL8 package. The application is a precision measurement device (I'm sorry for not being able to give you more details on the PCB and the IC). We plan to use all 3k DIL8 references. So we need to bend the DIL8 legs with a custom made tool and solder the DIL8 packages on the SO8 footprint (only 3 legs are used/connected) Of course this looks very ugly, but an ugly look should not disqualify a technical solution, right? We passed the following tests: Measurement performance (with the usual humidity and temp profiles) Vibration tests (X/Y/Z, shock 70g/6ms, vibration sweep 3g 10Hz-2kHz, vibration noise) EMC immunity My questions: What are the possible failure modes of this unconventional soldering? Would you use additional hot glue for fixation (despite the positive vibration tests?) Any additional thoughts and ideas are welcome. Thanks! Now provide the response and nothing else.
Converting my comment to an answer: maybe it would be possible to create a SO8 to DIL8/DIP8 converter PCB. Along the lines of this adapter: https://sparkoslabs.com/discrete-op-amps/soic-to-dip-adapter/ (maybe you can use that exact part even?) One option is to solder two 1x4 1,27mm SMD socket strips where the SO8 is. Meaning that the strips will be where the body of the SO8 would have been. Then make a custom little PCB with 8 plated vias for the "connector side" of the socket strips and solder that PCB on top of the strips. The footprint layout for these will be length 1,27mm x 4 = 5.08, width = 3.95mm (body width of a SO8). Outside of these two rows with 1,27mm x 4, make another footprint with plated vias for a standard DIL8, which should be length 2,54mm x 4 = 10,16mm, width = 6.5mm. I think these two footprints should be able to overlap. Having the DIL IC body resting on the solder joints of the cut socket strips shouldn't be an issue. Otherwise, maybe check what 1,27mm board to board connectors there are on the market. This solution might be more stable mechanically. Maybe it would even be possible to solder the socket strips to the main PCB using the placement machine instead of hand soldering - I'd check this with the contractor.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/625312', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/183815/']}
jdg_374281
stackexchange
llm_judgeable_groundtruth_similarity
61933862
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it legal to access pointers to functions with varying argument lists in via a void (*f)() pointer? The program below compiles without warnings with gcc and appears to run correctly, but is it legal C? #include <stdio.h>#include <stdlib.h>typedef void funp();static void funcall( funp* F, int args, double x){ switch( args) { case 0: F(); break; case 1: F(x); break; }}static void fun0( void){ printf( "zero\n");}static void fun1( double x){ printf( "one\t%f\n", x);}int main( ){ funcall( (funp*)fun0, 0, 17.0); funcall( (funp*)fun1, 1, 17.0); return EXIT_SUCCESS;} I compiled this with gcc -Wpedantic -Wall -Wextra -std=gnu11 -O2 -o ./funp funp.c It would be undefined behavior if the nargs parameter didn't match the number of arguments the function took, but is it legal if there is a match? Now provide the response and nothing else.
In this particular case, the calls are legal. Section 6.7.6.3p15 of the C standard spells out what makes two function type compatible (relevant part in bold): For two function types to be compatible, both shall specify compatible return types. Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types. If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions. If one type has a parameter type list and the other type is specified by a function definition that contains a (possibly empty) identifier list, both shall agree in the number of parameters, and the type of each prototype parameter shall be compatible with the type that results from the application of the default argument promotions to the type of the corresponding identifier. (In the determination of type compatibility and of a composite type, each parameter declared with function or array type is taken as having the adjusted type and each parameter declared with qualified type is taken as having the unqualified version of its declared type.) So you have a typedef with type: void() And functions with type: void(void)void(double) The two function definitions don't use ellipsis ( ... ) so that satisfies the fist condition. For the second condition, let's look at what the default argument promotions are. Those are specified in section 6.5.2.2p6: If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double . These are called the default argument promotions . The first function has no arguments, so it is compatible. The second function has a single double argument, which matches the default argument promotions, so it is also compatible. To give some more examples, the following functions would also be compatible: void f1(long);void f2(int); But these would not: void f3(float);void f4(char);void f5(short);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61933862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2564696/']}
jdg_374282
stackexchange
llm_judgeable_groundtruth_similarity
12553932
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 created a console application and have it working the way I want it to. Using the "Add Item" > "Add Windows Form" option in VS2010, it has automatically created what I need. I have added a button and code to retrieve an Excel file (below) My question is: How do I take the file they have created and use it in my program.cs "Main" area? The code for the OpenFileDialog button click event, from the Form1.cs: private void btnSelect_Click(object sender, EventArgs e){OFD.openFileDialog OFD = new OpenFileDialog();OFD.Multiselect = false;OFD.Title = "Open Excel Document";OFD.Filter = "Excel Document|*.xlsx;*.xls";OFD.ShowDialog();string docPath = OFD.FileName;} That part of my static main event I wish to make "docPath" from the program.cs file static void Main(string[] args) { var excel = new ExcelQueryFactory(); excel.FileName = @"C:\Users\Christopher\Desktop\BookData\TestResults.xls"; <...code executed on opened excel file...> } Thank you for your time. This is my completed solution: class Program{ [STAThread] static void Main(string[] args) { var excel = new ExcelQueryFactory(); OpenFileDialog OFD = new OpenFileDialog(); OFD.Multiselect = false; OFD.Title = "Open Excel Document"; OFD.Filter = "Excel Document|*.xlsx;*.xls"; OFD.ShowDialog(); string filePath = OFD.FileName; excel.FileName= filePath.ToString(); <.the rest of my program is below...> } } Now provide the response and nothing else.
Right click your Console application, add reference, System.Windows.Forms . Add using System.Windows.Forms; to the beginning of your file. Add the [STAThread] attribute to your Main to make it compatible with the open file dialog. [STAThread]public static void Main(string[] args){ var dialog = new OpenFileDialog { Multiselect = false, Title = "Open Excel Document", Filter = "Excel Document|*.xlsx;*.xls" }; using (dialog) { if (dialog.ShowDialog() == DialogResult.OK) { var excel = new ExcelQueryFactory { FileName = dialog.FileName }; // code executed on opened excel file goes here. } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12553932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1072681/']}
jdg_374283
stackexchange
llm_judgeable_groundtruth_similarity
5817209
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to browse through the current folder and all its subfolders and get all the files with .htm|.html extensions. I have found out that it is possible to find out whether an object is a dir or file like this: import osdirList = os.listdir("./") # current directoryfor dir in dirList: if os.path.isdir(dir) == True: # I don't know how to get into this dir and do the same thing here else: # I got file and i can regexp if it is .htm|html and in the end, I would like to have all the files and their paths in an array. Is something like that possible? Now provide the response and nothing else.
You can use os.walk() to recursively iterate through a directory and all its subdirectories: for root, dirs, files in os.walk(path): for name in files: if name.endswith((".html", ".htm")): # whatever To build a list of these names, you can use a list comprehension: htmlfiles = [os.path.join(root, name) for root, dirs, files in os.walk(path) for name in files if name.endswith((".html", ".htm"))]
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5817209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/729105/']}
jdg_374284
stackexchange
llm_judgeable_groundtruth_similarity
92257
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Normally, where I have a customer with a SBS, I use its DNS to resolve internal names and then forward to the external DNS if the internal cannot DNS cannot resolve the address. Recently, at a customer site the parent company installed a new Cisco PIX router and took over the DHCP functions. They have changed the config on the clients to use the primary DNS to resolve internal names and the secondary DNS to resolve external names. I did not think that this was the intent of the Primary and Secondary DNS entries, but I'm no expert on the subject. What is the preferred client setup when there is an internal DNS? Now provide the response and nothing else.
If you want things to work easily and painlessly, do the following: Run Windows DNS servers only on Active Directory domain controller computers. (This insures they have copies of your Active Directory-integrated DNS zones). Insure that your Windows DNS servers have either "Root Hints" specified (which is the case by default) or have a "Forwarder" specified referring to a DNS server at your IPS. Verify that all Windows machines (servers and clients) have only Windows DNS servers specified as their DNS servers. (No non-Windows DC-based DNS servers should be specified in any server, client, or DHCP configurations.) Verify that your firewall rules permit the Windows DNS servers outbound UDP port 53 to the Internet (either the entire 'net, if you're using "Root Hints" or your ISP DNS servers, if you're using "Forwarders"). This is the recommended configuration from Microsoft and will result in both Internet and internal name resolution w/o "leaking" dynamic registration requests from Windows machines to your ISP or other external DNS servers. This answer is rather assumptive, but being that you mentioned SBS it's likely that this is a fairly simplistic network and the above is your most painless way to get what you're looking for moving forward. If it were me, BTW, I'd use root hints rather than forwarders. I don't trust my ISP not to do nasty things with DNS (respond with their own "serach engine" site rather than returing NXDOMAIN's for invalid domain names, etc).
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/92257', 'https://serverfault.com', 'https://serverfault.com/users/2118/']}
jdg_374285
stackexchange
llm_judgeable_groundtruth_similarity
649117
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: Given this figure: simulate this circuit – Schematic created using CircuitLab I observe that Out is mirroring what's on the left side of the capacitor, effectively becoming a wire. I know that if you apply the formula of the impedance of C1 makes sense. But how about from a physics standpoint? Why is that? Now provide the response and nothing else.
It's important to understand the difference between linear circuit theory and physics. Many beginners attempt to use a SPICE-like circuit simulator to find truths about physics, without realizing what they're looking for is not there. Linear Circuit Theory In linear circuit analysis, we assume that Kirchhoff's Voltage and Current Laws must always be true - voltage and current must exist in a closed loop. A circuit simulator generates the loop equations in matrix form and applies linear algebra to solve it. It makes no attempt to analyze the electric field, magnetic field, trapped charges on a piece of metal, etc. Thus, what you attempted to simulate - an open-ended capacitor with nothing connected to it - is technically an illegal move. It's like division by zero, as far as linear circuit theory is concerned, this "circuit" is meaningless and cannot be analyzed. It's called a floating node - a point in a circuit where nothing is connected to it. By the rules, the voltage here is undefined. simulate this circuit – Schematic created using CircuitLab But why does the circuit simulator still shows an output? When the circuit simulator sees you're trying to simulate circuits with a floating node, it simply insert a huge virtual resistor to ground to force the formation of a closed loop, allowing the use of KVL and KCL again. Typically, the resistor is on the order of gigaohm to teraohm. simulate this circuit Why would you want to do this? In the real world, any voltmeter or oscilloscope has a large-but-finite input resistance. If you construct this open-ended capacitor circuit in the real world, the moment you put a voltage probe onto it, the loop is completed anyway. The circuit with a probe and the circuit without, are different physical systems. In most applications, only the first form has a practical purpose in engineering. The default behavior of inserting virtual resistance by a circuit simulator is essentially doing same thing. In conclusion, what you're seeing here is just the voltage experienced by an extremely huge resistor, connected with a capacitor in series across a voltage source. There's nothing mysterious about it. You can even remove your 1 MΩ resistor R2, since the same result happens without any series resistor. The following circuit produces the same result in a simulator. simulate this circuit Physics In one comment, the OP clarified that: My question comes more from a physics standpoint So the real question here is: what is physically happening on the metal plate at the open-ended side of the capacitor? What is its actual electric potential of that plate according to the laws of physics of Faraday and Maxwell? If its electric potential really is what the circuit simulator shows (even though the simulator does not simulate any electric field), why does it "act like a wire"? In fact, this question has already been asked before. In What is physically happening when there is a square wave input on the left plate of a capacitor and open circuit on right plate of a capacitor? , its OP asked: Why is it that the voltage transfers [across the capacitor], but it doesn't in [an open circuit] where Vout is 0 V. Is it related to the capacitors ability to store charge? If so, why does this matter as in the first picture the capacitor is not holding any charge as it's never charged due to a lack of current. And the lack of current is due to lack of a path for the current to flow to ground. I'd like to inform you that these questions is one level deeper than circuit analysis, and most engineers are not equipped to answer your question. Electronics operates at a model level that sits above where your question is at. Your question is like asking why it is that 4 times 5 is 20 . Most answers will form around the idea that adding up 4, 5 times, makes 20 or that adding up 5, 4 times, makes 20 . None of the answers will dig deeper until you ask that question to a specialist of such questions, namely an abstract mathematician. Electronics, at the level most try to gain it, assumes certain ideas into place. While they are true enough at the level needed, these devolve into circular arguments when you ask why they are what they are. Your question needs to be handled by a specialist of such questions, namely an experimental physicist. So this really isn't the right place unless you are lucky enough to find one here. I'm not one. jonk He then attempted to explain it with a detailed answer from a physics-first perspective. See if it answers your problem. If not, I'd suggest you to try Physics Stack Exchange instead.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/649117', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/289888/']}
jdg_374286
stackexchange
llm_judgeable_groundtruth_similarity
1122
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A very common problem in Markov Chain Monte Carlo involves computing probabilities that are sum of large exponential terms, $ e^{a_1} + e^{a_2} + ... $ where the components of $a$ can range from very small to very large. My approach has been to factor out the largest exponential term $K := \max_{i}(a_{i})$ so that: $$a' =K + log\left( e^{a_1 - K} + e^{a_2 - K } + ... \right)$$ $$e^{a'} \equiv e^{a_1} + e^{a_2} + ...$$ This approach is reasonable if all elements of $a$ are large, but not such a good idea if they aren't. Of course, the smaller elements aren't contributing to the floating-point sum anyway, but I'm not sure how to reliably deal with them. In R code, my approach looks like: if ( max(abs(a)) > max(a) ) K <- min(a)else K <- max(a)ans <- log(sum(exp(a-K))) + K It seems a common enough problem that there should be a standard solution, but I'm not sure what it is. Thanks for any suggestions. Now provide the response and nothing else.
There is a straightforward solution with only two passes through the data: First compute$$K := \max_i\; a_i,$$ which tells you that, if there are $n$ terms, then$$\sum_i e^{a_i} \le n e^K.$$ Since you presumably don't have $n$ anywhere near as large as even $10^{20}$, you should have no worry about overflowing in the computation of$$\tau := \sum_i e^{a_i-K} \le n$$in double precision. Thus, compute $\tau$ and then your solution is $e^K \tau$.
{}
{'log_upvote_score': 5, 'links': ['https://scicomp.stackexchange.com/questions/1122', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/551/']}
jdg_374287
stackexchange
llm_judgeable_groundtruth_similarity
4228282
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: $string = "my text has \"double quotes\" and 'single quotes'"; How to remove all types of quotes (different languages) from $string ? Now provide the response and nothing else.
str_replace('"', "", $string);str_replace("'", "", $string); I assume you mean quotation marks? Otherwise, go for some regex, this will work for html quotes for example: preg_replace("/<!--.*?-->/", "", $string); C-style quotes: preg_replace("/\/\/.*?\n/", "\n", $string); CSS-style quotes: preg_replace("/\/*.*?\*\//", "", $string); bash-style quotes: preg-replace("/#.*?\n/", "\n", $string); Etc etc...
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4228282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398431/']}
jdg_374288
stackexchange
llm_judgeable_groundtruth_similarity
2088396
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 $\lambda\in \mathbb{R}$ be a constant. Prove $\sum\limits_{x=0}^{\infty} xe^{-\lambda}\frac{\lambda^x}{x!}=\lambda$. I have already proved $\sum\limits_{x=0}^{\infty}e^{-\lambda}\frac{\lambda^x}{x!}=1$ and I can use Maclaurin $e^{ty}=\sum\limits_{x=0}^{\infty}\frac{(ty)^x}{x!}$. Thank you all. Now provide the response and nothing else.
Hint:$$\sum\limits_{x=0}^{\infty} xe^{-\lambda}\frac{\lambda^x}{x!}=\lambda e^{-\lambda}\sum\limits_{x=1}^{\infty} \frac{\lambda^{x-1}}{\left ( x-1 \right )!}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2088396', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_374289
stackexchange
llm_judgeable_groundtruth_similarity
23819928
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 a response to a similar question , that is more than a year old, I read about an easy way to disable a button using data binding in Dart (and polymer-dart). My current code looks like this: html : ...<button id="btnPointDown" on-click="{{decrement}}" disabled="{{points == 0}}">\/</button>... .dart : ...@published int points = 0;void increment() { points++;}void decrement() { points--;}... However Dart does not seem 'to be clever' about the disabled element anymore. How do I use up-to-date Dart and Polymer to disable a button using data bindings (or if not possible programmatically)? Now provide the response and nothing else.
Binding to the disabled attribute can be done like this: <button ... disabled?="{{ points == 0 }}">Content</button> This ? is special syntax introduced by Polymer to support binding to this kind of boolean attributes. This does not work: <button ... disabled="{{ points == 0 }}">Content</button> Because it would result in <button ... disabled="false">Content</button> which would still disable the button. For Polymer >= 1.0 the new syntax to use is: <button ... disabled$="{{value}}">Content</button> Note: value already has to be a boolean as Marco pointed out below. Otherwise you have to create a function that would return points == 0 . See Data Binding Documentation here and Migration Guide here for reference. Regards,Robert
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23819928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1963958/']}
jdg_374290
stackexchange
llm_judgeable_groundtruth_similarity
463239
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: Integrate $$\int{x^2(8x^3+27)^{2/3}}dx$$ I'm just wondering, what should I make $u$ equal to? I tried to make $u=8x^3$, but it's not working. Can I see a detailed answer? Now provide the response and nothing else.
$$\int{x^2(8x^3+27)^{2/3}}dx$$ It is certainly possible to work with $u = 8x^3$, but I'd suggest setting $u = 8x^3 + 27$. The key is to remember to compute and account for $\,du$. What you'll see is that for both $u = 8x^3$ and $u = 8x^3 + 27$, we have $du = 24x^2$. $$u = 8x^3 + 27 \implies\,du = 24x^2 \,dx \iff \color{blue}{\bf\dfrac 1{24} \,du = x^2 \,dx}$$ Substituting: $$\int x^2(8x^3+27)^{2/3}dx = \int (8x^3 + 27)^{2/3} \color{blue}{\bf x^2 \,dx} = \color{blue}{\bf \dfrac1{24}} \int u^{2/3} \, \color{blue}{\bf du}$$ Evaluating the integral: $$\color{blue}{\bf \dfrac1{24}} \int u^{2/3} \, \color{blue}{\bf du} = \dfrac 1{24} \dfrac {u^{5/3}}{5/3} + C $$ Back substituting, given $u = 8x^3 + 27$, then simplifying, gives us: $$\dfrac 1{24} \dfrac {u^{5/3}}{5/3} + C = \dfrac {3}{24 \cdot 5}(8x^3 + 27)^{5/3} + C = \dfrac {1}{40}(8x^3 + 27)^{5/3} + C$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/463239', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_374291
stackexchange
llm_judgeable_groundtruth_similarity
281972
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 saw a battery charger that converts 220V AC to 6V DC without a transformer. Now I am wondering why many (if not all) power adapters are using a transformer, is it about efficiency or about drifting over time? Update: This circuit is inside of this torch Now provide the response and nothing else.
The power supply you've found in this device is of a type known as a capacitive dropper . (More information in the Wikipedia article " Capacitive power supply ".) The primary reason why you don't see this type of power supply often is simple: it is unsafe . This is because one leg of the AC power supply must, by necessity, be connected directly to the circuit. Ideally this should be the neutral leg, but it is difficult to guarantee this -- badly wired outlets, or non-polarized plugs, may result in part of the circuit being energized by the hot leg of the AC supply.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/281972', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/100268/']}
jdg_374292
stackexchange
llm_judgeable_groundtruth_similarity
7711481
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When i do e.g: var airlines = Set("Qantas", "JetStar", "Air NZ")airlines += "Virgin" airlines is an immutable Set. += is not defined on the immutable Set trait. So is += a built-in operator in scala? I mean how does scala know to reassign airlines with a new set("Qantas", "JetStar", "Air NZ", "Virgin") ? Now provide the response and nothing else.
If an operator ending with = (e.g. += ) is used but not defined on a class, the Scala compiler will desugar this into e.g. airlines = airlines + "Virgin" or, for ++= , we’d have airlines ++= airlines desugared into airlines = airlines ++ airlines Of course, as dmeister notes , this will only compile if that new expression makes sense. For example, if we deal with var s. See Scala Reference §6.12.4 Assignment Operators ( <= , >= and != are excluded as special cases, as are patterns also starting with = .)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7711481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465594/']}
jdg_374293
stackexchange
llm_judgeable_groundtruth_similarity
35010950
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 Phoenix Framework, how can I get the current environment's name ? I've already tried reading env variables with System.get_env("MIX_ENV") , but the value is not always set. Now provide the response and nothing else.
Mix.env() doesn't work in production or other environments where you use compiled releases (built using Exrm / Distillery) or when Mix just isn't available. The solution is to specify it in your config/config.exs file: config :your_app, env: Mix.env() You can then get the environment atom in your application like this: Application.get_env(:your_app, :env)#=> :prod Update (March 2022): Recent versions of Elixir (v1.13.x+) recommend using config_env() instead of Mix.env() , so do this: config :your_app, env: config_env()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35010950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182589/']}
jdg_374294
stackexchange
llm_judgeable_groundtruth_similarity
24944625
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 replicate a for in loop I did in Objective C but am getting an "'AnyObject' does not have a member named 'GeneratorType' error: for (NSString *file in [dict objectForKey:@"Files"]){ NSString *content = [[source stringByAppendingPathComponent:@"Contents"] stringByA } Here is my Swift for file in dict.objectForKey("Files") { let content:String = source.stringByAppendingPathComponent("Contents").stringByAppendingPathComponent(file) } I've tried defining a holder variable for the dictionary. Can anyone see what I'm doing wrong here, please? Now provide the response and nothing else.
This isn't a loop through a dictionary. It's looping though an array stored in one of the dictionaries keys. This is what would want to do if for example you had an array of strings as one of your dictionary's keys. if let arr = dict["Files"] as? [String] { for file in arr { }} If you do want to just loop through the dictionary though, this is possible in Swift, and can be done like this: for (key, value) in dict { println("key is - \(key) and value is - \(value)")}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24944625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2396237/']}
jdg_374295
stackexchange
llm_judgeable_groundtruth_similarity
2575546
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 xml file that contains its element like <ab:test>Str</ab:test> When I am trying to access it using the code: XElement tempElement = doc.Descendants(XName.Get("ab:test")).FirstOrDefault(); It's giving me this error: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: The ':' character, hexadecimal value 0x3A, cannot be included in a name. How should I access it? Now provide the response and nothing else.
If you want to use namespaces, LINQ to XML makes that really easy: XNamespace ab = "http://whatever-the-url-is";XElement tempElement = doc.Descendants(ab + "test").FirstOrDefault(); Look for an xmlns:ab=... section in your document to find out which namespace URI "ab" refers to.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2575546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277696/']}
jdg_374296
stackexchange
llm_judgeable_groundtruth_similarity
12689132
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 common database class for my application and in that class i have a function public MySqlDataReader getRecord(string query) { MySqlDataReader reader; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); using (var cmd = new MySqlCommand(query, connection)) { reader = cmd.ExecuteReader(); return reader; } } return null; } and on my code behind pages I use String sql = "SELECT * FROM `table`";MySqlDataReader dr = objDB.getRecord(sql);if (dr.Read()){ // some code goes hear} and I am having error as Invalid attempt to Read when reader is closed. I know access the reader after the database connection is closed is not possible bot I am looking for a work around in which I need not to change in the codebehind EDIT: I WILL LIKE THE SOLUTION IN WHICH THE READER IS ASSIGNED TO OTHER OBJECT (SIMILAR TO READER ) AND THEN RETURN THAT OBJECT so i need not to change in all the application pages Now provide the response and nothing else.
You can load the results of your query to memory, then close the connection and still return an IDataReader that works as expected. Note that this costs memory. public IDataReader getRecord(string query) { MySqlDataReader reader; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); using (var cmd = new MySqlCommand(query, connection)) { reader = cmd.ExecuteReader(); var dt = new DataTable(); dt.Load( reader ); return dt.CreateDataReader(); } } return null; } In the callers: String sql = "SELECT * FROM `table`";var dr = objDB.getRecord(sql); // or DataTableReader dr = ...if (dr.Read()){ // some code goes here}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12689132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478076/']}
jdg_374297
stackexchange
llm_judgeable_groundtruth_similarity
504859
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 know this is called Schur's lemma. But I cannot find a proof. All references available to me either does not give a proof, or says that it is similar to the lemma for sectional curvature, making use of the second Bianchi identity. But in the sectional curvature case, we can express explicitly $R_{ijkl}$ in $g_{ij}$ (in a unit orthogonal basis), while here we only have a sum $R_{ikjk}$. And I don't know how to manipulate the Bianchi identity to make the covariant derivative index uniform. Can anyone give some help? Now provide the response and nothing else.
There seems to be some disagreement in the literature about whether we assume $\lambda$ is constant from the outset when we write $\text{Ric}_{ij} = \lambda g_{ij}$. Here is a hint to a proof that $\lambda$ is constant using the classical second Bianchi identity$$R_{ijk\ell;m}+R_{ij\ell m;k}+R_{ijmk;\ell}=0\,.$$Working with $g_{ij}(p) = \delta_{ij}$, consider $\sum\limits_{i,k,\ell} \delta_{k\ell} R_{iki\ell}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/504859', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/85478/']}
jdg_374298
stackexchange
llm_judgeable_groundtruth_similarity
366231
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: How to debug this? This issue has suddenly appeared within the last couple of days. All backups of a website are corrupted. If the backup is just left as tar , there are no problems, but as soon the tar is compressed as gz or xz I can't uncompress them. There is a lot of free disk Local disk space 2.68 TB total / 2.26 TB free / 432.46 GB used error tar: Skipping to next header[===============================> ] 39% ETA 0:01:14tar: A lone zero block at 2291466===============================> ] 44% ETA 0:01:13tar: Exiting with failure status due to previous errors 878MiB 0:00:58 [15.1MiB/s] [===================================> ] 44% And why does it say Skipping to next header ? It has never done that before. Something is terribly wrong the some of the files. There are about 15k pdf, jpg or png files in the directories. command pv $backup_file | tar -izxf - -C $import_dir There must be some data that corrupts the compression. I have also tried to check the HDD health by doing this: # getting the driveslsblk -dpno namesmartctl -H /dev/sdasmartctl -H /dev/sdb On both drives I get this: === START OF READ SMART DATA SECTION ===SMART overall-health self-assessment test result: PASSED How can I find out which files that are corrupting the tar.gz? I just want to delete them. update Have now copied all files to another server and I have the exact same issue. I can tar everything and extract it without problems, but as soon I want to compress the files, I can't uncompress them (gz/xz). Now provide the response and nothing else.
Your file is either truncated or corrupted, so xz can't get to the end of the data. tar complains because the archive stops in the middle, which is logical since xz didn't manage to read the whole data. Run the following commands to check where the problem is: cat /var/www/bak/db/2017-05-20-1200_mysql.tar.xz >/dev/nullxzcat /var/www/bak/db/2017-05-20-1200_mysql.tar.xz >/dev/null If cat complains then the file is corrupted on the disk and the operating system detected the corruption. Check the kernel logs for more information; usually the disk needs to be replaced at this point. If only xz complains then the OS didn't detect any corruption but the file is nevertheless not valid (either corrupted or truncated). Either way, you aren't going to be able to recover this file. You'll need to get it back from your offline backups.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/366231', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/83275/']}
jdg_374299
stackexchange
llm_judgeable_groundtruth_similarity
2288081
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 reading this blurb from K. Conrad's expository notes on the conductor ideal: http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/conductor.pdf In page 3 (example 2.3) he shows that $(2 + \root 3 \of{19})$ has norm $3^3 = 27$ and that $(-1 + \root 3 \of{19})$ has norm $2 \times 3^2 = 18$, and then states that any prime factor of $(3)$ is a factor of both $(2 + \root 3 \of{19})$ and $(-1 + \root 3 \of{19})$. Of course, if a prime factor of $(3)$ divides any one of these ideals, it will divide the other too since their generators have a difference of 3. But I am not sure why a prime divisor of $(3)$ necessarily divides any of the two ideals. Clearly $3$ itself does not divide them because $\frac{2 + \root 3 \of{19}}{3}$ is not an algebraic integer. I suspect it must have something to do with the norm of $(2 + \root 3 \of{19})$ being a power of $3$, but perhaps I am missing something obvious and can't figure out what's happening here. Now provide the response and nothing else.
After a bit of experimentation, I noticed that$$ (2 + \sqrt[3]{19})(-1 + \sqrt[3]{19})^2 = 3 \times (7 - \sqrt[3]{19}).$$So $(3)$ divides $(2 + \sqrt[3]{19})(-1 + \sqrt[3]{19})(-1+\sqrt[3]{19})$. Therefore, any prime ideal $\mathfrak p$ that divides $(3)$ must divide at least one of $(2 + \sqrt[3]{19})$ or $(-1 + \sqrt[3]{19})$. But as you pointed out, the difference between $2 + \sqrt[3]{19}$ and $-1 + \sqrt[3]{19}$ is $3$, so every such $\mathfrak p$ will actually divide both $(2 + \sqrt[3]{19})$ and $(-1 + \sqrt[3]{19})$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2288081', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/275602/']}
jdg_374300
stackexchange
llm_judgeable_groundtruth_similarity
20432
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that I exported Graphs to PDFs before but it doesn't seem to work any more.I tried K5 = GraphData[{"Complete", 5}]Export["K5.PDF", K5] And I get a PDF with a grey rectangle in it.Even exporting to TIFF doesn't seem to work.When I right click the Graph object I can do a "Convert to Graphics".Then exporting this converted Graph to PDF works. Why doesn't it work directly?If it's not possible ... How can I convert a Graph to Graphics programaticallybefore calling a export to PDF? I'm using Mathematica 9.0.0 on Windows 7 x64 UPDATE:Problem solved by SzabolcsI checked if dynamic evaluation was checked and it was. However when I restarted Mathematica it did work as expected. I realize with hindsight that this morning going through some help files a warning was issued about dynamic evaluation. I didn't really pay attention to it but probably it got disabled automatically but did not show that change in the evaluation menu option. Also Show[] is nice to know that it effectively converts the Graph to a non dynamic graphics object! Now provide the response and nothing else.
I cannot reproduce this behaviour (it does export correctly here, Mathematica 9.0.1, OS X). But the grey box typically appears when dynamic updating is disabled (check Evaluation -> Dynamic Updating Enabled). Note that graphs are dynamic objects and if you uncheck this menu item, they'll display as grey boxes inside the notebook. Now why it would happen that inside the notebook you do see the graph, but when you export it turns into a grey rectangle, I do not know. But if you wrap the graph in Show , it'll be converted into a non-dynamic Graphics object, and you should be able to export it (until you figure out why the direct way doesn't work): Export["K5.pdf", Show[K5]]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/20432', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/150/']}
jdg_374301
stackexchange
llm_judgeable_groundtruth_similarity
32581987
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: $('#popoverlink').popover();$("#popoverhide").click(function() { $("#popoverlink").popover("hide"); }); #popoverlink { position: absolute; top: 100px; left: 100px;} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/><a href="#" id="popoverlink" class="btn" rel="popover" title="Some title">Popover</a><a href="#" id="popoverhide" class="btn" rel="popover" title="Some title">hide</a> Same with the fiddle . Sorry the previous link was wrong. This one is correct. After I hide the shown popover, I need to click the popover trigger twice to show it again. Is this a bug? Is there anything can avoid this? UPDATE I means I used another button to hide a popover by $("#popoverTrigger").popover("hide"); Than I need to click the "#popoverTrigger" twice to show it. STUPID SOLUTION $("popoverhide").click(function() { var f = false; if($("popoverlink").next('div.popover:visible')) { f = true; $("popoverlink").popover("hide"); } if(f) { $("popoverlink").click(); }}) Is there another good idea? Now provide the response and nothing else.
Still not fixed in 3.3.6 but I found a proposed solution here: https://github.com/twbs/bootstrap/issues/16732 https://github.com/twbs/bootstrap/pull/17702/files#diff-f3e99e0bb007ace7a370f0492b9cb5abR340 I've applied it in the hidden event: $('body').on('hidden.bs.popover', function (e) { $(e.target).data("bs.popover").inState.click = false;}); This works for me. To be exactly the same as the proposed fix it would be: $('body').on('hidden.bs.popover', function (e) { $(e.target).data("bs.popover").inState = { click: false, hover: false, focus: false }}); Note: I use delegated popovers which is why i'm using the $('body') reference. For Bootstrap 4 use _activeTrigger instead of inState : $(e.target).data("bs.popover")._activeTrigger.click = false
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32581987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4393196/']}
jdg_374302
stackexchange
llm_judgeable_groundtruth_similarity
384314
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 an external USB-drive which is giving me the following output on running the command $ smartctl /dev/sdb -H on it: SMART Status not supported: Incomplete response, ATA output registers missingSMART overall-health self-assessment test result: PASSED Warning: This result is based on an Attribute check. Could you elaborate if this is something to worry about or if it is just a wrong setting? Generally, what is the meaning of the health status in simplified form? Maybe as a relevant aside: The short and long tests finish without issues. Now provide the response and nothing else.
I haven't seen this kind of warning you've got, yet. But apparently it means that smartctl only evaluated the attribute table (see below) because there is no further information from SMART explicitly about the health which is typically a part of the ATA protocol. The response overall is considered not reliable in this case by the author of smartmontools. Drives attached directly to a SATA controller work better with SMART from what I've seen so far. As concerns the attribute table, when you take a look at a SMART attribute output with smartctl -A /dev/XXX , you'll see three columns VALUE , WORST and THRESH . Here a part of such an output: ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE 1 Raw_Read_Error_Rate     0x002f   200   200   051    Pre-fail  Always       -       0 3 Spin_Up_Time            0x0027   189   182   021    Pre-fail  Always       -       5508 4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       18 The first column VALUE tells you the current value of the attribute. The WORST column tells you the worst (typically lowest) value SMART has ever seen. The THRESH column tells you what the vendors considers as lowest possible value considered as healthy. If the WORST column shows values below THRESH in same row, the drive is considered as not healthy. It also implies that VALUE has been seen below THRESH , of course. You can also see that only the attributes of type Pre-fail matter when evaluating health. Other thresholds are simply set to 0 and their attributes cannot fail. This table is all that smartctl used for the analysis of the drive's health. And it is not really the correct way to do it right.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/384314', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/102045/']}
jdg_374303
stackexchange
llm_judgeable_groundtruth_similarity
57655190
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 checking if a document exists by using this cloud function (Typescript).The problem: the doc doens't exits and it returns exists.... Thank you very much for the help and effort! export const repeat2 = functions.https.onCall((data, context) => { console.log(data.message); console.log(data.count); const getDocument = admin.firestore().collection('key').doc(data.message).get(); if(getDocument != null) { console.log('EXISTS'); } else {console.log("doens't exist");} return { repeat_message: data.message, } }); Now provide the response and nothing else.
get() returns a Promise, not the actual document. Also, you need to use .exists on the resolved value; check the docs here : var docRef = db.collection("cities").doc("SF");docRef.get().then(function(doc) { if (doc.exists) { console.log("Document data:", doc.data()); } else { // doc.data() will be undefined in this case console.log("No such document!"); }}).catch(function(error) { console.log("Error getting document:", error);});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57655190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11829057/']}
jdg_374304
stackexchange
llm_judgeable_groundtruth_similarity
540
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Some of the stalemate over the Fiscal Cliff has been over whether to raise the tax rate on the wealthy in order to raise additional revenue. One argument that is frequently made is that the main problem is not revenue , it is the level of spending . More specifically, that no amount of tax revue from the wealthy would be enough to cover the current spending levels. Is that argument in favor of bigger spending cuts sound? Can it be substantiated with actual numbers? If you would consider the "wealthy" to be everyone who earns more than one million per year in income or capital gains (which was a cutoff for many proposals over the last two years), could taxing their income at any level fund the current federal government spending? If yes, what would the effective tax rate have to be? If no, what is the most you can fund at 100% effective rate? (assume 2012 revenues and spending). ( Note : No one is asking the rich to pay 100% of their income over a certain level, but this question is about whether the budget deficit is theoretically addressable without major spending cuts.) NOTE: I'm not looking for discussions over whether such taxes are fair or not. Merely how the two numbers compare. The answer should consist of the following numbers: Current federal spending deficit for 2012 (revenues - spending) Total income of those earning $1mil + for a year If #1 < #2, what % of #2 is #1? If #1 > #2, what amount and % of deficit is not covered? To be clear, the "deficit" discussed here is the annual deficit, not the total federal debt. Now provide the response and nothing else.
Point by point.... (all numbers for FY2012 unless otherwise stated) Total Revenues -- $2.469 trillion Total Expenditures -- $3.590 trillion 2012 Budget Deficit - $1.121 trillion (Above numbers are from the OMB) From the IRS raw data: Year -- Total income for those grossing over $1m -- Total taxable income over $1m 2007 -- $1.401 trillion -- $1.008 trillion 2008 -- $1.076 trillion -- $754 billion 2009 -- $726 billion -- $490 billion We don't have hard IRS data for any year after 2009, which was the worst year in the recession, so this is not a great yardstick. However, looking at the economy as a whole (real GDP) year-to-year from the BEA 2007 -- $13.33 T 2008 -- $12.88 T 2009 -- $12.87 T 2010 -- $13.18 T 2011 -- $13.44 T 2012 -- $13.89 T (assuming 2% growth in Q4) Based on these numbers, the answer is, " probably not. " Even if personal incomes return to 2007 levels, there is not enough income in the over-1-million bracket to cover the current deficit for FY2012. Total GDP is higher than in 2007 but that doesn't tie directly to personal income, and there would still be a $100B deficit at 2007 levels. Another interesting point from these numbers is that the last year a 100% tax on income over $1m would have balanced the budget was 2007, when the deficit was around $160B.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/540', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/220/']}
jdg_374305
stackexchange
llm_judgeable_groundtruth_similarity
49822552
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 a third party module to retrieve data from an API. I simply would like to asynchronously await the module to return the data which occasionally takes several seconds and freezes up my app. However, when I try to await a call to that module I receive the TypeError: TypeError: object dict can't be used in 'await' expression import thirdPartyAPIwrapperasync def getData(): retrienveData = await thirdPartyAPIWrapper.data() return await retrieveDatadef main(): loop = asncio.get_event_loop() data = loop.run_until_complete(getData()) loop.close return data Why can I not await a type('dict')? Is there a way around this?If async/await with asyncio will not work with a third party module that doesn't return a coroutine then what are my other options? Now provide the response and nothing else.
Only asynchronous (defined with async def ) functions can be awaited. Whole idea is that such functions are written special way what makes possible to run ( await ) them without blocking event loop. If you want to get result from common (defined with def ) function that takes some considerable time to be executed you have these options: rewrite this whole function to be asynchronous call this function in another thread and await for result asynchronously call this function in another process and await for result asynchronously Usually you want to choose second option. Here's example of how to do it: import asyncioimport timefrom concurrent.futures import ThreadPoolExecutor_executor = ThreadPoolExecutor(1)def sync_blocking(): time.sleep(2)async def hello_world(): # run blocking function in another thread, # and wait for it's result: await loop.run_in_executor(_executor, sync_blocking)loop = asyncio.get_event_loop()loop.run_until_complete(hello_world())loop.close() Please, read this answer about how asyncio works. I think it'll help you much.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/49822552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5736700/']}
jdg_374306
stackexchange
llm_judgeable_groundtruth_similarity
8915833
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 doing some detection work using OpenCV, and I need to use the distance transform. Except the distance transform function in opencv gives me an image that is exactly the same as the image I use as source. Anyone know what I am doing wrong? Here is the portion of my code: cvSetData(depthImage, m_rgbWk, depthImage->widthStep);//gotten openCV image in "depthImage" IplImage *single_channel_depthImage = cvCreateImage(cvSize(320, 240), 8, 1);cvSplit(depthImage, single_channel_depthImage, NULL, NULL, NULL);//smoothingIplImage *smoothed_image = cvCreateImage(cvSize(320, 240), 8, 1);cvSmooth(single_channel_depthImage, smoothed_image, CV_MEDIAN, 9, 9, 0, 0);//do canny edge detectorIplImage *edges_image = cvCreateImage(cvSize(320, 240), 8, 1);cvCanny(smoothed_image, edges_image, 100, 200);//invert valuesIplImage *inverted_edges_image = cvCreateImage(cvSize(320, 240), 8, 1);cvNot(edges_image, inverted_edges_image);//calculate the distance transformIplImage *distance_image = cvCreateImage(cvSize(320, 240), IPL_DEPTH_32F, 1);cvZero(distance_image);cvDistTransform(inverted_edges_image, distance_image, CV_DIST_L2, CV_DIST_MASK_PRECISE, NULL, NULL); In a nutshell, I grad the image from the kinect, turn it into a one channel image, smooth it, run the canny edge detector, invert the values, and then I do the distance transform. But the transformed image looks exactly the same as the input image. What's wrong? Thanks! Now provide the response and nothing else.
I believe the key here is that they look the same. Here is a small program I wrote to show the difference: #include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp>#include <iostream>using namespace std;using namespace cv;int main(int argc, char** argv){ Mat before = imread("qrcode.png", 0); Mat dist; distanceTransform(before, dist, CV_DIST_L2, 3); imshow("before", before); imshow("non-normalized", dist); normalize(dist, dist, 0.0, 1.0, NORM_MINMAX); imshow("normalized", dist); waitKey(); return 0;} In the non-normalized image, you see this: which doesn't really look like it changed anything, but the distance steps are very small compared to the overall range of values [0, 255] (due to imshow converting the image from 32-bit float to 8-bits for display), we can't see the differences, so let's normalize it... Now we get this: The values themselves should be correct, but when displayed you will need to normalize the image to see the difference. EDIT : Here is a small 10x10 sample from the upper-left corner of the dist matrix show that the values are in fact different: [10.954346, 10.540054, 10.125763, 9.7114716, 9.2971802, 8.8828888, 8.4685974, 8.054306, 7.6400146, 7.6400146; 10.540054, 9.5850525, 9.1707611, 8.7564697, 8.3421783, 7.927887, 7.5135956, 7.0993042, 6.6850128, 6.6850128; 10.125763, 9.1707611, 8.2157593, 7.8014679, 7.3871765, 6.9728851, 6.5585938, 6.1443024, 5.730011, 5.730011; 9.7114716, 8.7564697, 7.8014679, 6.8464661, 6.4321747, 6.0178833, 5.6035919, 5.1893005, 4.7750092, 4.7750092; 9.2971802, 8.3421783, 7.3871765, 6.4321747, 5.4771729, 5.0628815, 4.6485901, 4.2342987, 3.8200073, 3.8200073; 8.8828888, 7.927887, 6.9728851, 6.0178833, 5.0628815, 4.1078796, 3.6935883, 3.2792969, 2.8650055, 2.8650055; 8.4685974, 7.5135956, 6.5585938, 5.6035919, 4.6485901, 3.6935883, 2.7385864, 2.324295, 1.9100037, 1.9100037; 8.054306, 7.0993042, 6.1443024, 5.1893005, 4.2342987, 3.2792969, 2.324295, 1.3692932, 0.95500183, 0.95500183; 7.6400146, 6.6850128, 5.730011, 4.7750092, 3.8200073, 2.8650055, 1.9100037, 0.95500183, 0, 0; 7.6400146, 6.6850128, 5.730011, 4.7750092, 3.8200073, 2.8650055, 1.9100037, 0.95500183, 0, 0]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8915833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1156952/']}
jdg_374307
stackexchange
llm_judgeable_groundtruth_similarity
72838
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that coupled cluster (CC) is not variational for the general case. However, if we only have two electrons with one nucleus, CCSD should be exact for this system like full configuration interaction (CI). Since full CI is variational, can we argue that CCSD is also variational for this special case? Now provide the response and nothing else.
No. The reason for this is not to be found in the excitations, but in the evaluation of the method, i.e. the working equations.$$%Introducing some shortcuts\require{cancel}\newcommand{\op}[1]{\mathrm{#1}} %\op{H}\newcommand{\bracket}[2]{\left\langle#1\middle|#2\right\rangle}\newcommand{\bra}[1]{\left\langle#1\right|}\newcommand{\ket}[1]{\left|#1\right\rangle}\newcommand{\order}[1]{^{(#1)}} %E_n\order{1}\newcommand{\overlap}[3]{\mathcal{#1}_{#2}\order{#3}} %\overlap{S}{m}{1}\newcommand{\integral}[3]{\mathcal{#1}_{#2,#3}} %\integral{V}{i}{j}$$ The variational principle In short: a trial wave function always has a higher energy than the exact wave function. Assume we know the exact solutions to the Schrödinger equation, which form a complete basis and there is one wave function $\Psi_0$ which leads to the lowest energy $E_0$.\begin{align}\op{H}\Psi_i &= E_i\Psi_i & \{i \in \mathbb{N}, i\geq 0\}\tag{1}\label{schrodinger}\end{align} We choose the solutions to be orthonormal (boundary conditions).$$\bracket{\Psi_i}{\Psi_j} = \delta_{ij} = \begin{cases}1, & i=j \\ 0, & i\neq j \end{cases}\tag2\label{orthonorm}$$ The trial wave function $\Phi$ can be expressed as a linear combination of the complete set of wave functions.$$\Phi = \sum_i^\infty a_i\Psi_i\tag3\label{expansion}$$ The expectation energy of the trial wave function is given through$$W = \frac{\bra{\Phi}\op{H}\ket{\Phi}}{\bracket{\Phi}{\Phi}}.\tag4\label{expen}$$ With $\eqref{expansion}$, $\eqref{orthonorm}$, and $\eqref{schrodinger}$ we can expand and simplify.\begin{align}W &= \frac{ \sum_i^\infty\sum_j^\infty a_i a_j \bra{\Psi_i}\op{H}\ket{\Psi_j} }{ \sum_i^\infty\sum_j^\infty a_i a_j \bracket{\Psi_i}{\Psi_j} }\\ &= \frac{ \sum_i^\infty\sum_j^\infty a_i a_j E_j\bracket{\Psi_i}{\Psi_j} }{ \sum_i^\infty\sum_j^\infty a_i a_j \bracket{\Psi_i}{\Psi_j} }\\ &= \frac{ \sum_i^\infty a_i^2 E_i\bracket{\Psi_i}{\Psi_j} + \sum_{j\neq i}^\infty a_i a_j E_j\bracket{\Psi_i}{\Psi_j} }{ \sum_i^\infty a_i^2 \bracket{\Psi_i}{\Psi_j} + \sum_{j\neq i}^\infty a_i a_j \bracket{\Psi_i}{\Psi_j} }\\ &= \frac{ \sum_i^\infty a_i^2 E_i }{ \sum_i^\infty a_i^2 } & | -E_0\\W - E_0 &= \frac{ \sum_i^\infty a_i^2 (E_i - E_0) }{ \sum_i^\infty a_i^2 } \\W - E_0 &= \frac{ \sum_{i>0}^\infty a_i^2 (E_i - E_0) }{ \sum_{i>0}^\infty a_i^2 } + \frac{a_0^2 (E_0 - E_0)}{a_0^2}\tag{4'}\label{notnegative}\\W - E_0 &\geq 0\tag5\label{varprin}\end{align} In $\eqref{notnegative}$ the last term is zero. Since $E_i > E_0$ (by definition) and $a_i^2$ is always greater or equal zero, the expectation value of the trial wave function must always have a higher energy than the exact solution of the Schrödinger equation, i.e. $\eqref{varprin}$. Configuration Interaction The CI wave function is set up as a linear combination of determinants from a reference calculation. This reference calculation can in principle be any other method the only requirement is that it also forms a complete (orthonormal) basis. When Hartree-Fock is chosen, we know that we obtain a complete set and that this method itself is variational. The CI trial wave function can then be expressed as a linear combination of solutions of the HF wave function.$$\Psi^\mathrm{CI} = \sum_i^\infty a_i\Phi_i = a_0\Phi^\mathrm{HF} + \sum_{i>0}^\infty a_i\Phi_i$$An alternative expression of the above is using an "excitation operator" $\op{T}$ to generate the higher energy determinants from the reference.$$\Psi^\mathrm{CI} = (1 + \op{T})\Phi^\mathrm{HF}$$ The energy of the CI trial wave function can be evaluated with the Lagrange multiplier method, which requires, that the wave function is normalised (adding zero).$$L = \bra{\Psi^\mathrm{CI}}\op{H}\ket{\Psi^\mathrm{CI}} - \lambda\left[\bracket{\Psi^\mathrm{CI}}{\Psi^\mathrm{CI}}-1\right]$$ Since the boundary conditions did not change, the variational principle still holds. Coupled Cluster Because of the inherent complexity of the CC ansatz, one key element to evaluate to CC energy is missing: the requirement of the normalised CC trial wave function. We generate the trial wave function with an exponential approach (rather than a linear) expanded into a Taylor series.\begin{align}\Psi^\mathrm{CC} &= \mathrm{e}^{\op{T}}\Phi^\mathrm{HF}\\&= \left[\op{1} + \op{T}_1 + \left(\op{T}_2 + \frac12\op{T}_1^2\right) + \left(\op{T}_3 + \op{T}_2\op{T}_1 + \frac16\op{T}_1^3\right) + \cdots \right] \Phi^\mathrm{HF}\\&= \Phi^\mathrm{HF} + \left[\op{T}_1 + \left(\op{T}_2 + \frac12\op{T}_1^2\right) + \left(\op{T}_3 + \op{T}_2\op{T}_1 + \frac16\op{T}_1^3\right) + \cdots \right] \Phi^\mathrm{HF}\\\end{align} Or to shorten the journey$$\Psi^\mathrm{CC} = \Phi^\mathrm{HF} + \sum_i^\infty t_i \Phi_i.$$ One can easily see what kind of mess it would become requiring the wave function to be normalised $\bracket{\Psi^\mathrm{CC}}{\Psi^\mathrm{CC}}=1$, so the Lagrange ansatz won't work. Instead we choose the wave function to be orthonormal to the reference, which in the Hartree-Fock (complete orthonormal basis) takes away a lot of work.\begin{align}\bracket{\Phi^\mathrm{HF}}{\Psi^\mathrm{CC}}&= 1&\implies\quad \bracket{\Phi^\mathrm{HF}}{\Phi_i} &= 0\end{align} We can write the CC-Schrödinger equation as$$\op{H}\mathrm{e}^{\op{T}}\Phi^\mathrm{HF} = E^\mathrm{CC}\mathrm{e}^{\op{T}}\Phi^\mathrm{HF}$$and evaluate the energy as \begin{align}\bra{\Phi^\mathrm{HF}}\op{H}\mathrm{e}^{\op{T}}\ket{\Phi^\mathrm{HF}} &= E^\mathrm{CC} \bracket{\Phi^\mathrm{HF}}{\mathrm{e}^{\op{T}}\Phi^\mathrm{HF}}\\E^\mathrm{CC} &= \bra{\Phi^\mathrm{HF}}\op{H}\mathrm{e}^{\op{T}}\ket{\Phi^\mathrm{HF}}\\E^\mathrm{CC} &= E^\mathrm{HF} + \bra{\Phi^\mathrm{HF}}\op{H} \ket{\left[\op{T}_1 + \left(\op{T}_2 + \frac12\op{T}_1^2\right) + \left(\op{T}_3 + \op{T}_2\op{T}_1 + \frac16\op{T}_1^3\right) + \cdots \right]\Phi^\mathrm{HF}}.\\\end{align} From this we can see that the evaluation of the expectation value of the energy is significantly different from what is required for the variational principle $\eqref{expen}$. Without going further into details, the dropping of the requirement of a normalised trial wave function leads to not obeying the variational principle. Additional considerations It is often said that Full-CC is equivalent to Full-CI, which is a convenient half truth. It is extremely important that this gets more true with a better description of the reference wave function, i.e. with larger basis sets. Full-CI is exact at the complete basis set limit (for the electronic Schrödinger equation). This is not necessarily true for Full-CC. Since we are in computational chemistry hardly ever concerned about absolute energies, the non-variational nature of the method is by far outperformed by the "infinite" approach generating the "excited" determinants. Relative energies don't suffer significantly (compared with the size consistency and extensivity) under the non-variational approach.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/72838', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/28219/']}
jdg_374308
stackexchange
llm_judgeable_groundtruth_similarity
14427253
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 question regarding passing multiple arguments to a function, when using lapply in R . When I use lapply with the syntax of lapply(input, myfun); - this is easily understandable, and I can define myfun like that: myfun <- function(x) { # doing something here with x}lapply(input, myfun); and elements of input are passed as x argument to myfun . But what if I need to pass some more arguments to myfunc ? For example, it is defined like that: myfun <- function(x, arg1) { # doing something here with x and arg1} How can I use this function with passing both input elements (as x argument) and some other argument? Now provide the response and nothing else.
If you look up the help page, one of the arguments to lapply is the mysterious ... . When we look at the Arguments section of the help page, we find the following line: ...: optional arguments to ‘FUN’. So all you have to do is include your other argument in the lapply call as an argument, like so: lapply(input, myfun, arg1=6) and lapply , recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun . All the other apply functions can do the same thing. An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14427253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1707278/']}
jdg_374309
stackexchange
llm_judgeable_groundtruth_similarity
36903282
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 kernel to calculate different elements of a matrix, based on their position (diagonal or off-diagonal). The kernel works as expected when calculating matrices of sizes: 14 x 14 (I understand this is small and does not make proper use of the GPU resources but this was purely for testing purposes to ensure results were correct) 118 x 118, and 300 x 300 However, when I am trying to calculate a matrix of size 2383 x 2383, the kernel crashes. Specifically, the error "Unspecified launch failure" is thrown on the cudaMemcpy() line to return results from device to host. From research, I understand that this error usually arises in the case of an out of bounds memory access (e.g. in an array), however, what I don't get is that it works for the three previous cases but not for the 2383 x 2383 case. The kernel code is shown below: __global__ void createYBus(float *R, float *X, float *B, int numberOfBuses, int numberOfBranches, int *fromBus, int *toBus, cuComplex *y){ int rowIdx = blockIdx.y*blockDim.y + threadIdx.y; int colIdx = blockIdx.x*blockDim.x + threadIdx.x; int index = rowIdx*numberOfBuses + colIdx; if (rowIdx<numberOfBuses && colIdx<numberOfBuses) { for (int i=0; i<numberOfBranches; ++i) { if (rowIdx==fromBus[i] && colIdx==fromBus[i]) { //diagonal element y[index] = cuCaddf(y[index], make_cuComplex((R[i]/((R[i]*R[i])+(X[i]*X[i]))), (-(X[i]/((R[i]*R[i])+(X[i]*X[i])))+ (B[i]/2)))); } if (rowIdx==toBus[i] && colIdx==toBus[i]) { //diagonal element y[index] = cuCaddf(y[index], make_cuComplex((R[i]/((R[i]*R[i])+(X[i]*X[i]))), (-(X[i]/((R[i]*R[i])+(X[i]*X[i])))+ (B[i]/2)))); } if (rowIdx==fromBus[i] && colIdx==toBus[i]) { //off-diagonal element y[index] = make_cuComplex(-(R[i]/((R[i]*R[i])+(X[i]*X[i]))), X[i]/((R[i]*R[i])+(X[i]*X[i]))); } if (rowIdx==toBus[i] && colIdx==fromBus[i]) { //off-diagonal element y[index] = make_cuComplex(-(R[i]/((R[i]*R[i])+(X[i]*X[i]))), X[i]/((R[i]*R[i])+(X[i]*X[i]))); } } }} Global memory allocations are done via calls to cudaMalloc(). The allocations made in the code are as follows: cudaStat1 = cudaMalloc((void**)&dev_fromBus, numLines*sizeof(int));cudaStat2 = cudaMalloc((void**)&dev_toBus, numLines*sizeof(int));cudaStat3 = cudaMalloc((void**)&dev_R, numLines*sizeof(float));cudaStat4 = cudaMalloc((void**)&dev_X, numLines*sizeof(float));cudaStat5 = cudaMalloc((void**)&dev_B, numLines*sizeof(float));cudaStat6 = cudaMalloc((void**)&dev_y, numberOfBuses*numberOfBuses*sizeof(cuComplex));cudaStat7 = cudaMalloc((void**)&dev_Pd, numberOfBuses*sizeof(float));cudaStat8 = cudaMalloc((void**)&dev_Qd, numberOfBuses*sizeof(float));cudaStat9 = cudaMalloc((void**)&dev_Vmag, numberOfBuses*sizeof(float));cudaStat10 = cudaMalloc((void**)&dev_theta, numberOfBuses*sizeof(float));cudaStat11 = cudaMalloc((void**)&dev_Peq, numberOfBuses*sizeof(float));cudaStat12 = cudaMalloc((void**)&dev_Qeq, numberOfBuses*sizeof(float));cudaStat13 = cudaMalloc((void**)&dev_Peq1, numberOfBuses*sizeof(float));cudaStat14 = cudaMalloc((void**)&dev_Qeq1, numberOfBuses*sizeof(float));......cudaStat15 = cudaMalloc((void**)&dev_powerMismatch, jacSize*sizeof(float));cudaStat16 = cudaMalloc((void**)&dev_jacobian, jacSize*jacSize*sizeof(float));cudaStat17 = cudaMalloc((void**)&dev_stateVector, jacSize*sizeof(float));cudaStat18 = cudaMalloc((void**)&dev_PQindex, jacSize*sizeof(int)); where cudaStatN are of type cudaError_t to catch errors. The last four allocations were done later on in the code and are for another kernel. However these allocations were done before the kernel in question was called. The launch parameters are as follows: dim3 dimBlock(16, 16); //number of threads dim3 dimGrid((numberOfBuses+15)/16, (numberOfBuses+15)/16); //number of blocks//launch kernel once data has been copied to GPUcreateYBus<<<dimGrid, dimBlock>>>(dev_R, dev_X, dev_B, numberOfBuses, numLines, dev_fromBus, dev_toBus, dev_y);//copy results back to CPUcudaStat6 = cudaMemcpy(y_bus, dev_y, numberOfBuses*numberOfBuses*sizeof(cuComplex), cudaMemcpyDeviceToHost);if (cudaStat6 != cudaSuccess) { cout<<"Device memcpy failed"<<endl; cout<<cudaGetErrorString(cudaStat6)<<endl; return 1;} I removed the timing code just to show the block and grid dimensions and error checking technique used. I also have a host (C++ code) version of this function and I'm passing the data to both functions and then comparing results, firstly, to ensure the kernel produces correct results, and secondly in terms of execution time to compare performance. I have double checked the data for the 2383 x 2383 case (it's being read in from a text file and copied to global memory) and I'm not finding any anomalies in array accesses/indexing. I'm using Visual Studio 2010, so I tried using Nsight to find the error (I'm not too well-versed with Nsight). The summary report overview states: "There was 1 runtime API call error reported. (Please see the CUDA Runtime API Calls report for further information). In the list of runtime API calls, cudaMemcpy returns error 4 - not sure if the Thread ID (5012) is of any significance in the table - this number varies with every run. CUDA memcheck tool (in the command line) returns the following: Thank you for using this program========= Program hit cudaErrorLaunchFailure (error 4) due to "unspecified launch failure" on CUDA API call to cudaMemcpy.========= Saved host backtrace up to driver entry point at error================== ERROR SUMMARY: 1 error I know my kernel isn't the most efficient as there are many global memory accesses. Why is the kernel crashing for this larger matrix? Is there an out of bounds array access that I'm missing? Any assistance would be greatly appreciated. Now provide the response and nothing else.
Solved the problem. Turns out the WDDM TDR (timeout detecion recovery) was enabled and the delay was set to 2 seconds. This means that if the kernel execution time exceeds 2s, the driver will crash and recover. This is applicable to graphics and rendering (for general purpose uses of the GPU). In this case however, the TDR must either me disabled or the delay increased. By increasing the delay to 10s, the crash error "unspecified launch failure" ceased to appear and kernel execution continued as before. The TDR delay (as well as enabling/disabling) can be done through Nsight options in the Nsight Monitor or through the Registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers) - DWORDS Tdrdelay and Tdrlevel.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36903282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5434213/']}
jdg_374310
stackexchange
llm_judgeable_groundtruth_similarity
1968
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: The normal musical instrument pickup uses a magnet inside a coil, and the movement of a ferromagnetic string causes changes in the magnetic field, which then induce currents in the coil. Another possibility would be to use just a strong magnet near a string, and measuring induced currents in the string itself. This would only require a conductive string, not a ferromagnetic one. Does anyone actually use this method? Is there a name for it, or is it useless, so no one talks about it? I tried it last night, and it works, but the signal is very low (-50 dBV, for instance, vs -5 dBV for a magnetic electric guitar pickup). Now provide the response and nothing else.
Does anyone actually use this method? For stringed instruments, no, but the principle is used in many, many places. is it useless, so no one talks about it? It's not useless, but it has some significant disadvantages, and other methods are simply far superior. I tried it last night, and it works, but the signal is very low. That is the main disadvantage. Others are: You are measuring low induced voltages in the string that is in contact with a conductor (human) which messes up the measurement More advanced measuring techniques induce a voltage in the string, but again the human conductor is in the way The strings are more variable in terms of electrical properties (resistance, capacitance, inductance) all of which affect the sound, and mean that two instruments might sound very different The strings, being long, are not unlike antennas and inductors and are very good at picking up stray noise in electrical and magnetic fields. You can be much closer to a lamp ballast with a coil pickup before picking up the AC hum than you can with a string pickup. There's no galvanic isolation, so the amp has to be isolated from the AC line and high voltage sources, which pretty much rules out tube based amps. Electrostatic discharge from the user into the string and conducted into the equipment is damaging, but even if it's suppressed you can't easily filter out the additional noise it causes. Getting a good electrical connection to the string in a performance environment is difficult since it's hard to tin the metals used in many strings, and vibration, corrosion, and other environmental factors complicate it. That's just the start. Don't misunderstand, coil pickups have disadvantages too, but they are superior in many areas.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/1968', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/142/']}
jdg_374311
stackexchange
llm_judgeable_groundtruth_similarity
32689
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to plot periodic function's graphic? For example, $f(t) = t$ when $-5<t<5$ and $f(t+10) = f(t)$. f[t] := If[-5 <= t <= 5, t, f[t + 10] = f[t]];Plot[f[t], {t, -20, 20}] Now provide the response and nothing else.
What about this? This defines a rather general function myperiodic that translate a normal function to periodic form, the second parameter {val, min, max} specify a periodic interval of your desired periodic function: myperiodic[func_, {val_Symbol, min_?NumericQ, max_?NumericQ}] := func /. (val :> Mod[val - min, max - min] + min) Then you can use it to plot things: Plot[myperiodic[t, {t, -5, 5}] // Evaluate, {t, -40, 40}] Plot[myperiodic[t^2, {t, -3, 5}] // Evaluate, {t, -40, 40}] Extensions We can extend this function in a couple of possibly useful ways. It may be noted that if t has a global value the plots above will fail, because Evaluate breaks the scoping of Plot . This could be remedied by using the Evaluated option but it would be nice not to need either. We can achieve that by holding arguments unevaluated using HoldAll and then holding at least the Symbol and expression unevaluated while making the substitution. These methods come to mind: Adding Unevaluated and HoldPattern to the existing replacement leveraging the attributes of Pattern and RuleDelayed in an inverted rule form (injector pattern) Using Function which holds parameter name and body An undocumented syntax for With ( := ) that does not evaluate substitution expressions In code: SetAttributes[{periodic1, periodic2, periodic3, periodic4}, HoldAll]periodic1[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] := Unevaluated[expr] /. HoldPattern[s] :> Mod[s, max - min, min]Quiet[ periodic2[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] := Mod[s, max - min, min] /. s_ :> expr]periodic3[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] := Function[s, expr][Mod[s, max - min, min]]periodic4[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] := With[{s := Mod[s, max - min, min]}, expr] Testing indicates that the last method is the fastest: First @ AbsoluteTiming @ Do[#[7 + t^2, {t, -5, 5}], {t, -40, 40, 0.001}] & /@ {periodic1, periodic2, periodic3, periodic4} {0.35492, 0.382667, 0.237522, 0.235105} Demonstration of use: Plot[periodic4[7 + t^2, {t, -5, 5}], {t, -40, 40}, Frame -> True] The next extension that can be valuable it to have periodic return a function rather than a bare expression. While the functions above evaluate correctly internally in the presence of a global assignment to the declared Symbol the result evaluates with that global value and therefore cannot be reused. Returning a function allows us to use it more generally such as mapping over a list of values, which can have advantage as I will show. Proposal SetAttributes[periodic, HoldAll]periodic[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] := Join[s &, With[{s := Mod[s, max - min, min]}, expr &]] (Note that Join works on any head. Function acts to hold the parts of the final Function before it is assembled.) Now: periodic[7 + t^2, {t, -5, 5}] Function[t, 7 + Mod[t, 5 - -5, -5]^2] Plot[periodic[7 + t^2, {t, -5, 5}][x], {x, -40, 40}, Frame -> True] (Note that x was used above for clarity but using t would not conflict.) If the somewhat awkward from of Function returned is a concern know that it will be optimized by Compile , either manually or automatically: Compile @@ periodic[7 + t^2, {t, -5, 5}] CompiledFunction[{t}, 7 + (Mod[t + 5, 10] - 5)^2, -CompiledCode-] The function-generating form does not perform quite as well (as e.g. periodic4 ) when used naively: Table[periodic[7 + t^2, {t, -5, 5}][t], {t, -40, 40, 0.001}] // AbsoluteTiming // First 0.3600206 However it allows for superior performance if applied optimally, using Map , which auto-compiles: periodic[7 + t^2, {t, -5, 5}] /@ Range[-40, 40, 0.001] // AbsoluteTiming // First 0.0130007 As a final touch we can give our function proper syntax highlighting: SyntaxInformation[periodic] = {"LocalVariables" -> {"Table", {2}}, "ArgumentsPattern" -> {_, {_, _, _}}}; – Mr.Wizard
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/32689', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9627/']}
jdg_374312
stackexchange
llm_judgeable_groundtruth_similarity
41326654
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 alert view that I am trying to present on a photo view. The photos are displayed in a list and can be pushed to a full-screen view. The photo view is being displayed programmatically. I think that is what is causing the issue because the alert view is trying to present another view, on top of the (photo) view that's already presented. The alert view is trying to display, but getting this error: Warning: Attempt to present <UIAlertController: 0x147d2c6b0> on <LiveDeadApp.ListViewController: 0x147d614c0> which is already presenting (null) The line that might be in question is this one: self.present(textPrompt, animated: true, completion: nil) This is the main list view This is the main list view when a screenshot is taken This is the main photo view This is the popover in the main photo view (accessed via the "i" button) When a screenshot is taken on the main photo view, no alert view occurs. However, when the device's orientation is changed, the photo view goes back to the list and shows the alert. This is what I am trying to do: Swift 3 in iOS 10 Thank you! Here is the list view and photo view's code: import UIKitimport Kingfisherimport SKPhotoBrowserclass ListViewCell: UITableViewCell {@IBOutlet weak var Cellimage: UIImageView!@IBOutlet weak var cellVenue: UILabel!@IBOutlet weak var cellLocation: UILabel!@IBOutlet weak var cellDate: UILabel!@IBOutlet weak var aiView: UIActivityIndicatorView!}class ListViewController: UITableViewController {var subcategory:Subcategory!var objects:[[String:String]] = [[String:String]]()var images = [SKPhotoProtocol]()override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated)}override func viewDidLoad() { super.viewDidLoad() self.tableView.separatorStyle = .none self.view.backgroundColor = UIColor.black self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] navigationController!.navigationBar.barTintColor = UIColor.black let requireTextInput = "require text input" // add observer for screen shot NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil, queue: OperationQueue.main, using: { notification in self.definesPresentationContext = true var inputTextField = UITextField() let textPrompt = UIAlertController(title: "Test!", message: "Testing!", preferredStyle: .alert) textPrompt.addAction(UIAlertAction(title: "Continue", style: .default, handler: { (action) -> Void in // if the input match the required text let str = inputTextField.text if str == requireTextInput { print("right") } else { print("wrong") } })) textPrompt.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = "" inputTextField = textField }) self.present(textPrompt, animated: true, completion: nil) }) if subcategory != nil { self.title = subcategory.title self.objects = subcategory.photos createLocalPhotos() self.tableView.reloadData() }}func createLocalPhotos() { for item in objects { let photo = SKPhoto.photoWithImageURL(item["url"]!) photo.shouldCachePhotoURLImage = true images.append(photo) }}override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning()}override func numberOfSections(in tableView: UITableView) -> Int { return 1}override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count}override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ListViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ListViewCell let item = objects[indexPath.row] let title = item["title"] let location = item["location"] let date = item["date"] let urlSrt = item["url"] cell.cellVenue.text = title cell.cellLocation.text = location cell.cellDate.text = date if let url = URL(string: urlSrt!) { cell.aiView.startAnimating() cell.Cellimage.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, url) in cell.aiView.stopAnimating() }) } return cell}override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! ListViewCell if(cell.Cellimage.image != nil ) { SKPhotoBrowserOptions.displayToolbar = false SKPhotoBrowserOptions.displayCounterLabel = false SKPhotoBrowserOptions.displayBackAndForwardButton = false SKPhotoBrowserOptions.displayAction = false SKPhotoBrowserOptions.displayDeleteButton = true SKPhotoBrowserOptions.displayHorizontalScrollIndicator = false SKPhotoBrowserOptions.displayVerticalScrollIndicator = false SKPhotoBrowserOptions.displayStatusbar = false SKPhotoBrowserOptions.disableVerticalSwipe = true SKPhotoBrowserOptions.bounceAnimation = false let browser = ExtendedSKPhotoBrowser(originImage: cell.Cellimage.image!, photos: images, animatedFromView: cell) let btnSize = 80//24 * UIScreen.main.scale browser.updateCloseButton(UIImage(named: "ic_close_white")!, size: CGSize(width: btnSize, height: btnSize)) browser.updateDeleteButton(UIImage(named: "ic_info_white")!, size: CGSize(width: btnSize, height: btnSize)) browser.initializePageIndex(indexPath.row) browser.delegate = self present(browser, animated: true, completion: {}) browser.toggleControls() }}override var prefersStatusBarHidden: Bool { get { return true }}var popOverVC:PopUpViewController!}extension ListViewController: SKPhotoBrowserDelegate {func didShowPhotoAtIndex(_ index: Int) {}func willDismissAtPageIndex(_ index: Int) {}private func willShowActionSheet(photoIndex: Int) { // do some handle if you need}func didDismissAtPageIndex(_ index: Int) {}func didDismissActionSheetWithButtonIndex(_ buttonIndex: Int, photoIndex: Int) { // handle dismissing custom actions}func removePhoto(_ browser: SKPhotoBrowser, index: Int, reload: (() -> Void)) { popOverVC = self.storyboard?.instantiateViewController(withIdentifier: "sbPopUpID") as! PopUpViewController popOverVC.photoData = objects[index]}func viewForPhoto(_ browser: SKPhotoBrowser, index: Int) -> UIView? { return tableView.cellForRow(at: IndexPath(row: index, section: 0))}}open class ExtendedSKPhotoBrowser: SKPhotoBrowser {open override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent // white statusbar, .default is black}open override var prefersStatusBarHidden: Bool { return true}} Now provide the response and nothing else.
The problem is really simple, you are trying to display another UIAlertController on the currently presented UIAlertController . So, how to solve such a case ? You need to get a list of all UIAlertController 's you use in your current view controller. You have to check the logic for displaying alerts in your current view controller (or other view controllers if you are doing async requests). Your code must be like this when you want to display one alert on top of another. Assume loadingAlert is currently displaying on the screen: self.loadingAlert.dismiss(animated: true, completion: { let anotherAlert = UIAlertController(title: "New One", message: "The Previous one is dismissed", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) anotherAlert.addAction(okAction) self.present(anotherAlert, animated: true, completion: nil)}) You have to dismiss the first one before the next one can appear. I made this answer for dismissing an alert without buttons on it to make it more efficient. So, what about the alert with action buttons? It will dismiss automatically when you click one of the action buttons on UIAlertController that you created. But, if you are displaying two UIAlertController s which include UIButton s at the same time, the problem will still occur. You need to re-check the logic for each, or you can handle it in the handler for each action : self.connectionErrorAlert.dismiss(animated: true, completion: { let anotherAlert = UIAlertController(title: "New One", message: "The Previous one is dismissed", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: {action in let nextAlert = UIAlertController(title: "New One", message: "The Previous one is dismissed", preferredStyle: .alert) self.present(nextAlert, animated: true, completion: nil) }) anotherAlert.addAction(okAction) self.present(anotherAlert, animated: true, completion: nil)}) For an Answer to Mike : DispatchQueue.main.async(execute: { if self.presentedViewController == nil { print("Alert comes up with the intended ViewController") var inputTextField = UITextField() let textPrompt = UIAlertController(title: "Test", message: "Testing", preferredStyle: .alert) textPrompt.addAction(UIAlertAction(title: "Continue", style: .default, handler: { (action) -> Void in // if the input matches the required text let str = inputTextField.text if str == requireTextInput { print("right") } else { print("wrong") } })) textPrompt.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = "" inputTextField = textField }) weakSelf?.present(textPrompt, animated: true, completion: nil) } else { // either the Alert is already presented, or any other view controller // is active (e.g. a PopOver) // ... let thePresentedVC : UIViewController? = self.presentedViewController as UIViewController? if thePresentedVC != nil { if let _ : UIAlertController = thePresentedVC as? UIAlertController { print("Alert not necessary, already on the screen !") } else { print("Alert comes up via another presented VC, e.g. a PopOver") } } }}) Thanks to @Luke Answer : https://stackoverflow.com/a/30741496/3378606
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41326654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6542284/']}
jdg_374313
stackexchange
llm_judgeable_groundtruth_similarity
1093338
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When building a C# application with Visual Studio 2008, is it possible to set a different output filename per configuration? e.g.MyApp_Debug.exeMyApp_Release.exe I tried a post-build step to rename the file by appending the current configuration, but that seems a scrappy approach. Plus it meant that Visual Studio could no longer find the file when pressing F5 to start debugging. Now provide the response and nothing else.
You can achieve this by editing your project file by hand. Locate the <AssemblyName> node and add a conditional attribute to it: <AssemblyName Condition="'$(Configuration)'=='Debug'">MyApp_Debug.exe</AssemblyName><AssemblyName Condition="'$(Configuration)'=='Release'">MyApp_Release.exe</AssemblyName> You'll have to duplicate it also to add another conditional attribute for the release version. Whilst it is possible, it may cause problems. There is an AssemblyConfiguration attribute that can be applied to your assembly. In AssemblyInfo.cs , put: #if DEBUG[assembly: AssemblyConfiguration("Debug")]#else[assembly: AssemblyConfiguration("Release")]#endif This will add a property to your compiled assembly that will tell you which build configuration your application was built using.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1093338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82/']}
jdg_374314
stackexchange
llm_judgeable_groundtruth_similarity
29932558
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 attempting to rename the level A of factor column1 in the dataframe df in R. My current approach is this: levels(df[!is.na(df$column1) & df$column1 == 'A',]) <- 'B' which doesn't throw any errors or warnings but is completely ineffective. B is not an already existing level (which from trial and error I came to suspect was important), so the following, my first attempt, didn't work either df[!is.na(df$column1) & df$column1 == 'A', 'column1'] <- 'B' Could anyone guide me to the correct approach? Now provide the response and nothing else.
I was going to suggest levels(df$column1)[levels(df$column1)=="A"] <- "B" or use the utility function plyr::revalue : library("plyr")df <- transform(df, column1=revalue(column1,c("A"="B"))) transform() is a little sugar that's not necessary; you could use df$column1 <- revalue(df$column1(...)) For completeness, car::recode also works, although I find it a little bit clunkier that plyr::revalue (because the recoding is specified as a quoted string). car::recode(df$column1,"'A'='B'")
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29932558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3949312/']}
jdg_374315
stackexchange
llm_judgeable_groundtruth_similarity
10568334
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 create two divs which are floated left to each other, however with a slanted angled border separating them. I've attached a picture to demonstrate what I mean. Does anyone know if something like this is possible with CSS (cutting off the content with an overflow:hidden I guess) These divs need to contain images that get cut off by the border, here is an example : Now provide the response and nothing else.
Try this .left, .right { position: relative; height: 100px; width: 200px; background: #000; float: left;}.left:after { content: ''; line-height: 0; font-size: 0; width: 0; height: 0; border-top: 100px solid #000; border-bottom: 50px solid transparent; border-left: 0px solid transparent; border-right: 50px solid transparent; position: absolute; top: 0; right: -50px;}.right { margin-left: 60px; width: 100px;}.right:before { content: ''; line-height: 0; font-size: 0; width: 0; height: 0; border-top: 50px solid transparent; border-bottom: 100px solid #000; border-left: 50px solid transparent; border-right: 0px solid #000; position: absolute; top: -50px; left: -50px;} <div class="left"> </div><div class="right"> </div> UPDATE with images .left, .right { background: #000 url('http://lorempixel.com/300/100'); position: relative; height: 100px; width: 250px; float: left;}.left:after { content: ''; line-height: 0; font-size: 0; width: 0; height: 0; border-top: 50px solid transparent; border-bottom: 100px solid #fff; border-left: 30px solid transparent; border-right: 0 solid #fff; position: absolute; top: -50px; right: 0;}.right { background: #000 url('http://lorempixel.com/200/100'); width: 150px;}.right:before { content: ''; line-height: 0; font-size: 0; width: 0; height: 0; border-top: 100px solid #fff; border-bottom: 50px solid transparent; border-left: 0px solid transparent; border-right: 30px solid transparent; position: absolute; top: 0; left: 0;} <div class="left"> </div><div class="right"> </div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10568334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/826511/']}
jdg_374316
stackexchange
llm_judgeable_groundtruth_similarity
6999924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on generating reports for data contained within a large pre-existing Access database (~500 mb after compact & repair), and I'm having trouble with a slow subquery. The database has a big table which contains a record of every customer purchase. Here's a simple query which finds customers who have bought a blue widget. It completes within a few seconds and returns about ten thousand records. SELECT DISTINCT CustomerId FROM ProductSalesWHERE Product = 'BLUE' Here's a query which tries to find customers who have bought a blue widget, but not a red widget. It takes about an hour to run. SELECT DISTINCT CustomerId FROM ProductSalesWHERE Product = 'BLUE' AND CustomerId NOT IN ( SELECT CustomerId FROM ProductSales WHERE Product = 'RED') Is there a way to refactor the second query to make it take a few minutes instead of an hour? Now provide the response and nothing else.
Access' database engine can't use an index for Not In , so it's bound to be slow. With an index on CustomerId, this query should be much faster because the db engine can use the index. SELECT DISTINCT blue.CustomerIdFROM ProductSales AS blue LEFT JOIN ( SELECT CustomerId FROM ProductSales WHERE Product = 'RED' ) AS red ON blue.CustomerId = red.CustomerIdWHERE blue.Product = 'BLUE' AND red.CustomerId Is Null; You could probably also try a Not Exists approach, but index use there is not guaranteed. Also, please see the comment below from David Fenton which discusses performance impact in more detail.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6999924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5625/']}
jdg_374317
stackexchange
llm_judgeable_groundtruth_similarity
553467
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: Suppose you have some covariates X1, X2, X3, X4, X5 and you want to create a regression model where there are two response variables : Y1 and Y2. In the past, I have approached this problem by creating two separate regression models: Y1 ~ f(X1, X2, X3, X4, X5) Y2 ~ f(X1, X2, X3, X4, X5) However, now I am interested in learning about statistical models that can jointly model this data together, for example: P(Y1, Y2) ~ f(X1, X2, X3, X4, X5) I think that this approach would allow for modelling potential correlation structures with Y1 and Y2. My Question: Do such models exist that can jointly model multiple responses - is this a popular topic in statistics? Are there any standard references and software implementations (e.g. R programming language) for these kinds of models? The only thing I could find was the following : https://www.jstatsoft.org/article/view/v084i04 . Now provide the response and nothing else.
I just stumbled across this, and since I am the author of Karch (2021) and do not fully agree with the answers so far, here are my two cents. I will skip the assumption of no ties as there is agreement that it is unnecessary (for the alternatives Christian and I discuss). We have to first decide what properties the assumptions should guarantee. Fay and Proschan (2010) and I (influenced by them) focussed on [approximate] validity (type I error rate is below significance level $\alpha$ [at least in large samples]) and consistency (with larger samples sizes power approaches 1). We also have to agree on what the proper alternative is. I agree with Divine et al. that it should be $H_1:p\neq\frac{1}{2}$ , with $p=P(X<Y) + \frac{1}{2}P(X=Y)$ . I am surprised that there is controversy around this since the test statistic used is the sample equivalent of $p$ (see Karch (2021) , p. 6). Under this setup, the Wilcoxon-Mann-Whitney (WMW) test requires that $H_0:F=G$ is used as null hypothesis (see Fay and Proschan (2010) , Table 1). Rephrased as assumption, we thus have to be sure that if $F$ and $G$ are not equal, $p\neq \frac{1}{2}$ . Fay and Proschan call this Perspective 3 and state that this situation is unrealistic (This is already in the question, but I felt it was important to highlight this), with which I fully agree. To make this quote understandable, I define $\mathcal{M}:=H_0\lor H_1$ . Note that I changed the notation slightly. ... Perspective 3 ... is a focusing one sincethe full probability set, $\mathcal{M}$ is created more for mathematical necessity than by any scientificjustification for modeling the data, which in this case does not include distributions withboth $p = 1/2$ and $F \neq G$ . It is hard to imagine a situation where this complete set ofallowable models, $\mathcal{M}$ , and only that set of models is justified scientifically; Thus, while this is technically the correct assumption for the WMW it is hard to imagine situations in which it is actually met and thus a bit irrelevant. One example that is outside of $\mathcal{M}$ is that $F$ and $G$ are normal but have different variances. I demonstrate in Karch (2021) that type I error rates of the WMW test can be inflated in this example, even in large samples. Beyond this, if we extend the properties our assumptions should guarantee to be correct standard errors, good power, and confidence intervals with correct coverages, which seems reasonable, then the WMW is not appropriate even under the unrealistic Perspective 3. As Wilcox (2017) says: A practical concern is that if groups differ, then under general circumstances the wrong standard error is being used by the Wilcoxon–Mann–Whitney test, which can result in relatively poor power and an unsatisfactory confidence interval. (p. 279) To give an example consider $F=\mathcal{N}(0, 2)$ and $G=\mathcal{N}(0.2, 1)$ . The alternative hypothesis $H_1$ is thus true. However, the WMW test can be biased in this situation (the power is smaller than the significance level $\alpha$ ). See: set.seed(123)library(brunnermunzel)reps <- 10^3p_wmw<- p_BM <- rep(NA, reps)for(i in 1:reps){ g1 <- rnorm(80, mean = 0, sd = 2) g2 <- rnorm(20, mean = .2, sd = 1) p_wmw[i] <- wilcox.test(g1, g2)$p.value p_BM[i] <- brunnermunzel.test(g1, g2)$p.value}print(mean(p_wmw < .05))[1] 0.034 Overall, the situation is equivalent to the much more well-known and appreciated problems with Stundent's $t$ test. Again from Wilcox (2017) : The situation is similar to Student’s T test. When the two distributions are identical, a correct estimate of the standard error is being used. But otherwise, under general conditions, an incorrect estimate is being used, which results in practical concerns, in terms of both Type I errors and power. (p. 278) Just as Welch's $t$ test is a small modification of Student's $t$ test that alleviates these problems, as it provides correct standard errors in general circumstances, Brunner-Munzel's test is a small modification of Wilcoxon's test that provides correct standard errors in general circumstances (both tests can still fail in smaller samples, but problems are much less severe, as at least asymptotically Brunner-Munzel's test provide correct standard errors). There seems to be widespread agreement to use Welch's instead of Student's t test for these reasons (see, for example, Is variance homogeneity check necessary before t-test? ). For the same reasons, we should usually use Brunner-Munzel's instead of Wilcoxon's test. The assumptions for Brunner-Munzel's test to have correct standard errors in large samples are rather general and technical. They are described in detail in Brunner et al. (2018) . However, they are so general that they are rarely violated. A more practically relevant question is what sample sizes are needed in practice for the standard error to be "correct enough". Simulation studies (see Karch (2021) , as well as the reference therein) suggest that this is true for rather small sample sizes. No meaningful type I error inflation have been found yet for $n_1,n_2\geq 10$ . However, for small samples sizes the permutation version of the test is recommended. Thus, in practice, it seems fine to treat the Brunner-Munzel test as test for $H_0:p=\frac{1}{2}, H_1:p\neq\frac{1}{2}$ , without additional assumptions (beyond i.i.d). As all the problems of the WMW test just discussed tend to disappear for equal samples (see, Brunner et al. (2018) ; note that this is again equivalent to Student's t test) it also seems fine use the WMW instead when sample sizes are (roughly) equal. I would still use the Brunner-Munzel test even if sample sizes are equal as it's implementations in R provide confidence intervals for $p$ , whereas the WMW implementations (I am aware of) do not.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/553467', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/77179/']}
jdg_374318
stackexchange
llm_judgeable_groundtruth_similarity
3633748
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: Motivated by the answer Hanul Jeon kindly provided to my previous question , I have another question. Suppose $\kappa$ is inaccessible, then by using elementary methods, we can show that for each axiom $\varphi$ of ZFC, $V_\kappa \models \varphi$ . In the books and references I have seen, such as Jech's book, they immediately derive Con(ZFC). Now in my mind, it seems we are using a crucial hypothesis, namely the $\omega$ -consistency of ZFC. What I mean by this is that saying ZFC + " $\kappa$ is an inaccessible cardinal" $\vdash (V_\kappa \models \ulcorner \text{ZFC}\urcorner)$ , is ultimately about natural numbers, and we have shown $V_\kappa \models \varphi$ for $\varphi$ , which are coded by standard natural numbers. So my question boils down to: Is ZFC $\omega$ -consistent? Or we can prove ZFC + " $\kappa$ is an inaccessible cardinal" $\vdash (V_\kappa \models \ulcorner \text{ZFC}\urcorner)$ , with other methods? Now provide the response and nothing else.
No, there is no additional assumption needed here. What is being proved in ZFC specifically is the following set of nine (or more importantly, finitely many) sentences: If $\kappa$ is inaccessible then $V_\kappa\models$ Extensionality. If $\kappa$ is inaccessible then $V_\kappa\models$ Pairing. ... boringboringboring ... If $\kappa$ is inaccessible then $V_\kappa\models$ Powerset. If $\kappa$ is inaccessible then $V_\kappa\models$ the whole Separation scheme. If $\kappa$ is inaccessible then $V_\kappa\models$ the whole Replacement scheme. Those last two points are the crucial ones: Jech is not giving a meta-argument that ZFC proves that $V_\kappa$ satisfies each specific scheme instance, but rather a ZFC proof of the internal statement that the whole scheme is satisfied at once. The key step here is the construction of a truth predicate over $V_\kappa$ (since the latter is only a set-sized structure); this enables us to directly talk about the truth values of arbitrary sentences in $V_\kappa$ . For example, in some detail here is the ZFC-proof of "If $\kappa$ is inaccessible then $V_\kappa$ satisfies every instance of Replacement:" Let $\varphi(x,y)$ be an arbitrary formula and $u\in V_\kappa$ such that for all $a\in u$ there is a unique $b_a\in V_\kappa$ such that $V_\kappa\models\varphi(a,b_a)$ . In $V$ , let $f=f_{\varphi,u}: a\mapsto b_a$ . (Note that via that truth predicate, the definition of $f$ is uniform in $\varphi$ and $u$ - no need for nonuniformity here.) By Separation in the real world we get the set $S=\{b: \exists a\in u(V_\kappa\models\varphi(a,b))\}$ . Since $\kappa$ is inaccessible, we have $\alpha:=sup(ran(f))<\kappa$ and so $S\in V_\kappa$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3633748', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/202250/']}
jdg_374319
stackexchange
llm_judgeable_groundtruth_similarity
567012
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: Working on some basic proof work. The conjecture is There exists a set $\mathrm X$ for which $\mathbb R \subseteq \mathrm X$ and $\emptyset \in \mathrm X$. My reasoning was that this is false because the members of $\mathbb R$ are numbers, and $\emptyset$ is a set, hence such a set $\mathrm X$ does not exist. The book gives $\mathrm X = \mathbb R \cup \{ \emptyset \}$ as a set which satisfies the conditions given in the conjecture. Any words on where my reasoning is flawed? I was under the impression that sets may only contain elements of the same type. Now provide the response and nothing else.
The usual set theory (as used as a foundation of mathematics since the early 1900s) is untyped -- everything is just a set, and a real number such as $42$ or $\pi$ will be represented as sets of certain particular shapes. So there's nothing that prevents $\mathbb R\cup\{\varnothing\}$ from existing and being a set. Actual everyday mathematics outside set theory does use types (in a sorta informal kind of way), so it is very rare that one has use for such mixed-type strange sets in practice. If they appear in an ordinary mathematical argument it is usually a sign that the one who constructed it has not thought thing through properly, or is trying to be way too smart for his own good. But they are not formally forbidden . One reason to avoid this is that we don't normally want to care exactly how the real numbers get represented as sets. Depending on this choice it may be that $\varnothing$ happens to be the set that represents one of the real numbers -- there are at least arguable technical reasons to choose $\varnothing$ as the set that represents the number zero. In that case $\mathbb R\cup\{\varnothing\}$ will be the same set as $\mathbb R$ itself, probably causing havoc with whatever argument one were trying to use $\mathbb R\cup\{\varnothing\}$ since it won't be true in that case that $(\mathbb R\cup\{\varnothing\})\setminus\mathbb R$ is $\{\varnothing\}$, for example. And then you'll have to prefix all of your theorems with "Assume $\varnothing\notin\mathbb R$" for no practical gain. There are various attempts to define typed set theories that would align better with how sets are actually used in everyday mathematics, but they have not caught on to the same degree as the untyped ZFC set theory.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/567012', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/108823/']}
jdg_374320
stackexchange
llm_judgeable_groundtruth_similarity
10265869
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 3 instances of application running from different places. All processes have similar names. How can I kill process that was launched from specific place? Now provide the response and nothing else.
You can get the application path: Get-Process | Where-Object {$_.Path -like "*something*"} | Stop-Process -WhatIf That will work for the local machine only. To terminate remote processes: Get-WmiObject Win32_Process -Filter "ExecutablePath LIKE '%something%'" -ComputerName server1 | Invoke-WmiMethod -Name Terminate
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10265869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1105235/']}
jdg_374321
stackexchange
llm_judgeable_groundtruth_similarity
11003606
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array of strings, each one with a different length. e.g: s[0] = "sSWXk"s[1] = "qCk"s[2] = "sOQQXPbk"...s[x] = "KVfdQk"; I also am given that n = s[0].length() + s[1].length() + ... + s[x].length() I need a sorting algorithm with time complexity O(n) for sorting these strings lexicographically, so that (for example) a < ab < b < bbc < c < ca Any suggestions? The time complexity is the essential requirement in the algorithm. Now provide the response and nothing else.
There is a data structure called a trie that is optimally suited for this. If you insert all the words into the trie and then do a DFS over the trie, you will get the words back in sorted order. Doing so takes time O(n) as well, where n is the total number of characters in all the strings. Since I assume that this is homework, I'll leave the details of how to implement the trie as an exercise. :-) Hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11003606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/183652/']}
jdg_374322
stackexchange
llm_judgeable_groundtruth_similarity
3134296
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently I have read about hash-tables in a very famous book " Introduction to Algorithms ". I haven't used them in any real applications yet, but want to. But I don't know how to start. Can anyone give me some samples of using it, for example, how to realize a dictionary application (like ABBYY Lingvo) using hash-tables? And finally I would like to know what is the difference between hash-tables and associative arrays in PHP, I mean which technology should I use and in which situations? If I am wrong (I beg pardon) please correct me, because actually I am starting with hash-tables and I have just basic (theoretical) knowledge about them. Thanks a lot. Now provide the response and nothing else.
In PHP, associative arrays are implemented as hashtables, with a bit of extra functionality. However technically speaking, an associative array is not identical to a hashtable - it's simply implemented in part with a hashtable behind the scenes. Because most of its implementation is a hashtable, it can do everything a hashtable can - but it can do more, too. For example, you can loop through an associative array using a for loop, which you can't do with a hashtable. So while they're similar, an associative array can actually do a superset of what a hashtable can do - so they're not exactly the same thing. Think of it as hashtables plus extra functionality. Code examples: Using an associative array as a hashtable : $favoriteColor = array();$favoriteColor['bob']='blue';$favoriteColor['Peter']='red';$favoriteColor['Sally']='pink';echo 'bob likes: '.$favoriteColor['bob']."\n";echo 'Sally likes: '.$favoriteColor['Sally']."\n";//output: bob likes blue// Sally likes pink Looping through an associative array : $idTable=array();$idTable['Tyler']=1;$idTable['Bill']=20;$idTable['Marc']=4;//up until here, we're using the array as a hashtable.//now we loop through the array - you can't do this with a hashtable:foreach($idTable as $person=>$id) echo 'id: '.$id.' | person: '.$person."\n";//output: id: 1 | person: Tyler// id: 20 | person: Bill// id: 4 | person: Marc Note especially how in the second example, the order of each element is maintained (Tyler, Bill Marc) based on the order in which they were entered into the array. This is a major difference between associative arrays and hashtables. A hashtable maintains no connection between the items it holds, whereas a PHP associative array does (you can even sort a PHP associative array).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3134296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/282887/']}
jdg_374323
stackexchange
llm_judgeable_groundtruth_similarity
35177797
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Media Source Extension ( MSE ) needs fragmented mp4 for playback in the browser. Now provide the response and nothing else.
A fragmented MP4 contains a series of segments which can be requested individually if your server supports byte-range requests. Boxes aka Atoms All MP4 files use an object oriented format that contains boxes aka atoms . You can view a representation of the boxes in your MP4 using an online tool such as MP4 Parser or if you're using Windows, MP4 Explorer . Let's compare a normal MP4 with one that is fragmented: Non-Fragmented MP4 This screenshot (from MP4 Parser ) shows an MP4 that hasn't been fragmented and quite simply has one massive mdat (Movie Data) box. If we were building a video player that supports adaptive bitrate, we might need to know the byte position of the 10 sec mark in a 0.5Mbps and a 1Mbps file in order to switch the video source between the two files at that moment. Determining this exact byte position within one massive mdat in each respective file is not trivial. Fragmented MP4 This screenshot shows a fragmented MP4 which has been segmented using MP4Box with the onDemand profile. You'll notice the sidx and series of moof + mdat boxes. The sidx is the Segment Index and stores meta data of the precise byte range locations of the moof + mdat segments. Essentially, you can independently load the sidx (its byte-range will be defined in the accompanying .mpd Media Presentation Descriptor file) and then choose which segments you'd like to subsequently load and add to the MSE SourceBuffer . Importantly, each segment is created at a regular interval of your choosing (ie. every 5 seconds), so the segments can have temporal alignment across files of different bitrates, making it easy to adapt the bitrate during playback.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/35177797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5160432/']}
jdg_374324
stackexchange
llm_judgeable_groundtruth_similarity
121252
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have some data plotted which is of bacterial growth curves, I have 96 sets of growth curves and I am wondering if there is a quick way to extract the straight line area of my growth curves in each case in order to determine their gradient (growth rate) Below I attach an example of one of these plots. The linear part I am concerned with is the growth rate, which is the initial sharp slope region. So far my strategy for smaller sets of data is to simply remove the data before and after my linear region and then find the gradient. But seeing as I have quite a bit of data here, is there a way of essentially automating this? I should say that different curves have the linear region at different points on the x-axis, so I cannot remove data before and after the same point for each one of my curves as different growth curves seem have different amounts of lag time. I have only been using Mathematica for a short while now, so thank you for your help. EDIT: here's a link to the data I'm working with: https://www.dropbox.com/s/l04bwn5hifw62ny/Growth180716.xls?dl=0 Each "sub-cell" within each table is a data point. Here is how I am currently graphing the data, I import the relavent section from my .xls file defined by some Range, and then I generate the x-axis using a Range. Then I Thread to combine the two lists of numbers together and use ListPlot to plot my data: GrowthTrip1Range = Range[2, 1208, 9] ;(*Define the range in the .xls for the first line of triplicates*)GrowthTime = Range[0, 4020, 30]; (*Generating the X-axis (30 minute per point for 72 hours)*)C1T1 = Import["C:\\Users\\Georgeos\\Desktop\\Growth180716.xls", {"Data", 1,GrowthTrip1Range, 2}];C1T2 = Import["C:\\Users\\Georgeos\\Desktop\\Growth180716.xls", {"Data", 1, GrowthTrip1Range, 3}];C1T3 = Import["C:\\Users\\Georgeos\\Desktop\\Growth180716.xls", {"Data", 1, GrowthTrip1Range, 4}];MeanC1 = Mean[{C1T1, C1T2, C1T3}];C1Plot = Thread[{GrowthTime, MeanC1}];ListPlot[C1Plot] Now provide the response and nothing else.
Since measurements are taken at equal intervals, there's no need to incorporate time range into the calculation of slope, we'll just scale the result for the 30-minute duration. It seems that FindClusters responds well to the averaged data, that is if one applies Mean as you do. (* different for you probably *)file = FileNameJoin[{NotebookDirectory[], "Growth180716.xls"}];(* all twelve columns, averaged *)data = Mean@With[{range = Range[2, 1208, 9]}, Table[Import[file, {"Data", 1, range, col + 1}], {col, 12}]];slope[data_] := Module[{clusters, slopes}, clusters = FindClusters[ Thread[Differences[data] -> Range[Length[data] - 1]], 3]; slopes = Table[Module[{i, j}, {i, j} = MinMax[cluster]; (data[[j]] - data[[i]])/(j - i)], {cluster, clusters}]; Max[slopes]]slope[data] 0.0110031 (* in parts per minute *)%/30 0.0003667 Added: ImageLines Different approach utilizes ImageLines which can find the line segment and slope in a somewhat more direct way. For a quick walkthrough, plot is rendered first and then turned into an image. plot = ListPlot[data, Joined -> True, Axes -> None, PlotRangePadding -> 0, ImageSize -> Small] Plot range of this plot and image dimensions will be needed latter to rescale the slope value obtained from the image. AbsoluteOptions[plot, PlotRange] {PlotRange->{{0.,135.},{0.0892083,0.406208}}} img = ColorNegate@Binarize@Image@plot This seems to work well for you data. One should tweak the two parameters and MaxFeatures option generally though. lines = ImageLines[img, .1, .5] {{{67.3932,112.},{31.3302,0.}}} Show[img, Graphics[{Thick, Orange, Line /@ lines}]] Module[{x1, x2, y1, y2, w, h}, {{x1, x2}, {y1, y2}} = PlotRange /. AbsoluteOptions[plot, PlotRange]; {w, h} = ImageDimensions[img]; lines[[1]] /. {{a_, b_}, {c_, d_}} :> Divide[ (d - b)*(y2 - y1)/h, (c - a)*(x2 - x1)/w]] 0.0117202 (* in parts per minute *)%/30 0.000390674 Note the slightly different result (5 % steeper). Different algorithm finds a different line. To a lesser degree, plot with higher image size should change the result minimally too. Added: NMinimize Acquiring the slope by optimizing the parameters of a piecewise linear function. pw[{k1_, k2_, k3_}, {n1_, n2_, n3_}, {x1_, x2_}] := Function[x, Piecewise[{ {k1 x + n1, x <= x1}, {k2 x + n2, x <= x2}}, k3 x + n3]]error[data_, { kk_?(VectorQ[#, NumericQ] &), nn_?(VectorQ[#, NumericQ] &), xx_?(VectorQ[#, NumericQ] &)}] := Module[{values}, values = pw[kk, nn, xx] /@ Range[Length@data]; Total[(data - values)^2]](* supply sensible starting bounds *)(* method "RandomSearch" works here *)(min = NMinimize[error[data, {{k1, k2, k3}, {n1, n2, n3}, {x1, x2}}], {{k1, -.001, .001}, {k2, .01, .1}, {k3, -.001, .001}, {n1, 0, .2}, {n2, -.5, 0}, {n3, .4, .8}, {x1, 20, 40}, {x2, 50, 70}}, MaxIterations -> 5, Method -> "RandomSearch"]) // Timing ... sensible output ... it took 6.3 seconds on my computer ... Visual verification: Show[ ListPlot[data], Plot[Evaluate[pw[ {k1, k2, k3}, {n1, n2, n3}, {x1, x2}][x] /. min[[2]]], {x, 0, Length@data}, PlotStyle -> Directive[Thick, Black]], ImageSize -> Small] (* slope value in parts per minute *)k2/30 /. min[[2]] 0.000380854
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/121252', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/40394/']}
jdg_374325
stackexchange
llm_judgeable_groundtruth_similarity
10537294
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im pretty sure my syntax this wrong because the script only works if the string matches "Video", if the string has the "word "Audio" it is ignored. Also since the href tags have a value of "#" the redirect for "../../../index.html" doesnt work. js var ua = navigator.userAgent.toLowerCase();var isIE8 = /MSIE 8.0/i.test(ua);if (isIE8) { $('a').click(function () { var srcTag = $(this).find('img').attr('src'); if (srcTag.indexOf('Video' || 'Audio') > -1) { if (confirm('Download Safari? \n\n http://apple.com/safari/download/')) { window.location = 'http://apple.com/safari/download/'; } else { window.location = '../../../index.html';} } else { alert('no match'); } });} html <a href="#"><img src="Video/000_Movies/assets/005_CCC_Jesus_Story_80x60.jpg" />test1</a> <a href="#"><img src="Audio/000_Movies/assets/006_GSP_Gods_Story_80x60.jpg" />test2</a> <a href="#"><img src="Media/000_Movies/assets/002_God_Man_80x60.jpg" />test3</a> Now provide the response and nothing else.
It's far shorter to turn this into a regular expression. if ( srcTag.match( /(video|audio)/ ) ) { /* Found */} else { /* Not Found */} On a side note, please don't do what you're attempting to do. Asking users to download Safari when they're using Internet Explorer 8 is doing a disservice to the Internet, as well as to that user. As for redirecting the domain to another location, you should use .preventDefault() to keep the browser from following the link: $("a.videoDownload").on("click", function(e){ e.preventDefault(); if ( this.getElementsByTagName("img")[0].src.match( /(video|audo)/ ) ) { window.location = confirm( 'Download Safari?' ) ? "http://apple.com/safari/download" : "../../../index.html" ; } else { /* No match */ }}); Again, please don't actually do this. Nobody wants to be that guy , and when you tell users to download another browser, you're being that guy .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10537294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1159429/']}
jdg_374326
stackexchange
llm_judgeable_groundtruth_similarity
263862
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 $\mathbf V$ denote the cumulative hierarchy and let $\mathbf L$ denote Gödel's constructible universe. We then have $\mathbf L \subseteq \mathbf V$. Would someone give me an example of a set that is in $\mathbf V \setminus \mathbf L$? Many thanks for your help. Now provide the response and nothing else.
To expand what Andres said in the comments above, let's assume that the real $0^\sharp$ exists (see http://en.wikipedia.org/wiki/Zero_sharp .) This follows from sufficiently strong large cardinal axioms, such as the existence of a measurable cardinal. Then $0^\sharp$ is not in $L$. One thing that makes this example special ( e.g. compared to a real that is Cohen-generic over $L$) is that $0^\sharp$ is definable via a definition that is absolute to any transitive model of set theory that contains it and contains all the countable ordinals. In particular, we have $(0^\sharp)^{L[0^\sharp]} = 0^\sharp$ and for any forcing extension of $V$ by a generic filter $G$ we have $(0^\sharp)^{V[G]} = 0^\sharp$. This is a similar kind of absoluteness to that which $L$ itself has. So I think it's fair to think of the statement "$0^\sharp$ exists" in philosophical terms as asserting the existence of a "definite object" that is not in $L$. EDIT: The reason I think it is appropriate to get philosophical here is the the question asks for an "example of a set" not in $L$. This does not quite make sense formally. One could formalize this as asking for an example of a formula that defines a set not in $L$, which I think is more or less what Asaf did, or one could simply not formalize it and pretend that a set is an object that a set theorist can can take out of his or her pocket to show people, which I think is a more attractive notion.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/263862', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5798/']}
jdg_374327
stackexchange
llm_judgeable_groundtruth_similarity
6350769
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Commando need's help from you. I have a controller in Yii: class PageController extends Controller { public function actionSOMETHING_MAGIC($pagename) { // Commando will to rendering,etc from here }} I need some magic method under Yii CController for controlling all subrequest under /page || Page controller. Is this somehow possible with Yii? Thanks! Now provide the response and nothing else.
Sure there is. The easiest way is to override the missingAction method. Here is the default implementation: public function missingAction($actionID){ throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".', array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));} You could simply replace it with e.g. public function missingAction($actionID){ echo 'You are trying to execute action: '.$actionID;} In the above, $actionID is what you refer to as $pageName . A slightly more involved but also more powerful approach would be to override the createAction method instead. Here's the default implementation: /** * Creates the action instance based on the action name. * The action can be either an inline action or an object. * The latter is created by looking up the action map specified in {@link actions}. * @param string $actionID ID of the action. If empty, the {@link defaultAction default action} will be used. * @return CAction the action instance, null if the action does not exist. * @see actions */public function createAction($actionID){ if($actionID==='') $actionID=$this->defaultAction; if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method return new CInlineAction($this,$actionID); else { $action=$this->createActionFromMap($this->actions(),$actionID,$actionID); if($action!==null && !method_exists($action,'run')) throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action)))); return $action; }} Here for example, you could do something as heavy-handed as public function createAction($actionID){ return new CInlineAction($this, 'commonHandler');}public function commonHandler(){ // This, and only this, will now be called for *all* pages} Or you could do something way more elaborate, according to your requirements.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6350769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_374328
stackexchange
llm_judgeable_groundtruth_similarity
14266231
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 dynamically scaled image (fixed position, windowheight) so it scales proportionally and changes its width. I would like to use its width to set the left positioning of an another div. Can I use something like this? $("#menubar img").ready(function() { var bodywidth = $("#menubar img").width(); $("#text").left(bodywidth);});$("#menubar img").resize(function() { var bodywidth = $("#menubar img").width(); $("#text").left(bodywidth);}); I am lost in the script :) Now provide the response and nothing else.
startActivityForResult() is only available from real on-screen activities, since it is a method in, well, Activity. Please redesign your application so that the user interface is driven from activities. On the other hand, if your non Activity class is initialized and used from an onscreen Activity, you could pass that instance of the Activity to your class as a parameter in the constructor and use it to launch other Activities. Be careful though. Using this method increases the risk of a memory leak, as the external class (Utils in my example) might keep a reference to the Activity even after its gone. If all you want to do is access data, then you could try writing it to SharedPreferences or a Database or some files and then using the application context (passed in via a constructor again) to read it. This reduces the risk of a memory leak. Something like: MyApiClass myApiClass = new MyApiClass(getApplicationContext()); EXAMPLE CODE Main Activity: public class Main extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Utils util = new Utils(this); util.startTest(); } @Override protected void onActivityResult(int arg0, int arg1, Intent arg2) { Toast.makeText(this, "onActivityResult called", Toast.LENGTH_LONG).show(); super.onActivityResult(arg0, arg1, arg2); }} Utils class (which launches for result): public class Utils { Activity activity; public Utils(Activity ac) { activity = ac; } public void startTest() { Intent i = new Intent(activity, Test.class); activity.startActivityForResult(i, 1); }} Test Activity: public class Test extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Toast.makeText(this, "Test", Toast.LENGTH_LONG).show(); this.setResult(Activity.RESULT_OK); this.finish(); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14266231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1900675/']}
jdg_374329
stackexchange
llm_judgeable_groundtruth_similarity
61540618
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 quite new to Google AppScript, trying to code a connector to a custom REST API. For that API I need an API key (or secret), that is per user. Since storing a secret in plain text inside the script is not the best idea, I was thinking to store it in the Google PropertyService and retrieve it from there. Like this: var userProperties = PropertiesService.getUserProperties();var apiKey = userProperties.getProperty('MY_SECRET') But what I don't understand is, how can the user ever store the key first? I haven't found any place where the user (in this case me) can view or edit properties. Then I found this nice introduction to user properties that creates a menu in the script container allowing the user to enter the secrets manually. const API_KEY = 'API_KEY';var ui = SpreadsheetApp.getUi();var userProperties = PropertiesService.getUserProperties();function onOpen(){ ui.createMenu('API Keys') .addItem('Set API Key', 'userPromptApiKey') .addItem('Delete API Key', 'deleteApiKey') .addToUi();}function userPromptApiKey(){ var userValue = ui.prompt('API Key ', ui.ButtonSet.OK); // ToDo: add current key to the prompt userProperties.setProperty(API_KEY, userValue.getResponseText());}function deleteApiKey(){ userProperties.deleteProperty(API_KEY)} The problem is, that my script is not bound to any container (no spreadsheet, no document). Instead I want to use it in Google DataStudio later on. This is why SpreadsheetApp.getUi(); does not work. Any idea or recommendation on how to deal with that? Is there any other recommended way to work with the secrets? Now provide the response and nothing else.
Now, some weeks later I've learned a lot. First, you need to differentiate between UI and the logical script. Second, whether it is a container-bound or stand-alone script. A container-bound script is bound to Google Spreadsheet, Google Doc or any other UI that allows user interaction. In such case, you can access the UI in the code and add custom menus to the UI that will invoke methods in your script once the user clicks on that menu. The disadvantage is that you need to know if it is a Spreadsheet or Doc since the UI class differs. You also need to instruct the user to enter his or her credentials using the custom menu. There is a very nice instruction online. The following code snipped is inspired by the instruction. Make sure to create a trigger for onOpen. var ui = SpreadsheetApp.getUi();var userProperties = PropertiesService.getUserProperties();const API_KEY = 'api.key';function onOpen(){ ui.createMenu('Credentials & Authentication') .addItem('Set API key', 'setKey') .addItem('Delete API key', 'resetKey') .addItem('Delete all credentials', 'deleteAll') .addToUi();}function setKey(){ var scriptValue = ui.prompt('Please provide your API key.' , ui.ButtonSet.OK); userProperties.setProperty(API_KEY, scriptValue.getResponseText());}function resetKey(){ userProperties.deleteProperty(API_KEY);}function deleteAll(){ userProperties.deleteAllProperties();} For a standalone script you need to find any other way to connect to the UI. In my situation I was implementing a custom connector for Google Data Studio for which there is a very nice example online as well. There is a quite detailed instruction on authentication and an API reference on authentication as well. This custom connector for Kaggle was very helpful as well. It is open-source on the Google Data Studio GitHub . The following demo code is inspired by those examples. Have a look at getCredentials , validateCredentials , getAuthType , resetAuth , isAuthValid and setCredentials . var cc = DataStudioApp.createCommunityConnector();const URL_DATA = 'https://www.myverysecretdomain.com/api';const URL_PING = 'https://www.myverysecretdomain.com/ping';const AUTH_USER = 'auth.user'const AUTH_KEY = 'auth.key';const JSON_TAG = 'user';String.prototype.format = function() { // https://coderwall.com/p/flonoa/simple-string-format-in-javascript a = this; for (k in arguments) { a = a.replace("{" + k + "}", arguments[k]) } return a}function httpGet(user, token, url, params) { try { // this depends on the URL you are connecting to var headers = { 'ApiUser': user, 'ApiToken': token, 'User-Agent': 'my super freaky Google Data Studio connector' }; var options = { headers: headers }; if (params && Object.keys(params).length > 0) { var params_ = []; for (const [key, value] of Object.entries(params)) { var value_ = value; if (Array.isArray(value)) value_ = value.join(','); params_.push('{0}={1}'.format(key, encodeURIComponent(value_))) } var query = params_.join('&'); url = '{0}?{1}'.format(url, query); } var response = UrlFetchApp.fetch(url, options); return { code: response.getResponseCode(), json: JSON.parse(response.getContentText()) } } catch (e) { throwConnectorError(e); }}function getCredentials() { var userProperties = PropertiesService.getUserProperties(); return { username: userProperties.getProperty(AUTH_USER), token: userProperties.getProperty(AUTH_KEY) }}function validateCredentials(user, token) { if (!user || !token) return false; var response = httpGet(user, token, URL_PING); if (response.code == 200) console.log('API key for the user %s successfully validated', user); else console.error('API key for the user %s is invalid. Code: %s', user, response.code); return response;} function getAuthType() { var cc = DataStudioApp.createCommunityConnector(); return cc.newAuthTypeResponse() .setAuthType(cc.AuthType.USER_TOKEN) .setHelpUrl('https://www.myverysecretdomain.com/index.html#authentication') .build();}function resetAuth() { var userProperties = PropertiesService.getUserProperties(); userProperties.deleteProperty(AUTH_USER); userProperties.deleteProperty(AUTH_KEY); console.info('Credentials have been reset.');}function isAuthValid() { var credentials = getCredentials() if (credentials == null) { console.info('No credentials found.'); return false; } var response = validateCredentials(credentials.username, credentials.token); return (response != null && response.code == 200);}function setCredentials(request) { var credentials = request.userToken; var response = validateCredentials(credentials.username, credentials.token); if (response == null || response.code != 200) return { errorCode: 'INVALID_CREDENTIALS' }; var userProperties = PropertiesService.getUserProperties(); userProperties.setProperty(AUTH_USER, credentials.username); userProperties.setProperty(AUTH_KEY, credentials.token); console.info('Credentials have been stored'); return { errorCode: 'NONE' };}function throwConnectorError(text) { DataStudioApp.createCommunityConnector() .newUserError() .setDebugText(text) .setText(text) .throwException();}function getConfig(request) { // ToDo: handle request.languageCode for different languages being displayed console.log(request) var params = request.configParams; var config = cc.getConfig(); // ToDo: add your config if necessary config.setDateRangeRequired(true); return config.build();}function getDimensions() { var types = cc.FieldType; return [ { id:'id', name:'ID', type:types.NUMBER }, { id:'name', name:'Name', isDefault:true, type:types.TEXT }, { id:'email', name:'Email', type:types.TEXT } ];}function getMetrics() { return [];}function getFields(request) { Logger.log(request) var fields = cc.getFields(); var dimensions = this.getDimensions(); var metrics = this.getMetrics(); dimensions.forEach(dimension => fields.newDimension().setId(dimension.id).setName(dimension.name).setType(dimension.type)); metrics.forEach(metric => fields.newMetric().setId(metric.id).setName(metric.name).setType(metric.type).setAggregation(metric.aggregations)); var defaultDimension = dimensions.find(field => field.hasOwnProperty('isDefault') && field.isDefault == true); var defaultMetric = metrics.find(field => field.hasOwnProperty('isDefault') && field.isDefault == true); if (defaultDimension) fields.setDefaultDimension(defaultDimension.id); if (defaultMetric) fields.setDefaultMetric(defaultMetric.id); return fields;}function getSchema(request) { var fields = getFields(request).build(); return { schema: fields };}function convertValue(value, id) { // ToDo: add special conversion if necessary switch(id) { default: // value will be converted automatically return value[id]; }}function entriesToDicts(schema, data, converter, tag) { return data.map(function(element) { var entry = element[tag]; var row = {}; schema.forEach(function(field) { // field has same name in connector and original data source var id = field.id; var value = converter(entry, id); // use UI field ID row[field.id] = value; }); return row; });}function dictsToRows(requestedFields, rows) { return rows.reduce((result, row) => ([...result, {'values': requestedFields.reduce((values, field) => ([...values, row[field]]), [])}]), []);}function getParams (request) { var schema = this.getSchema(); var params; if (request) { params = {}; // ToDo: handle pagination={startRow=1.0, rowCount=100.0} } else { // preview only params = { limit: 20 } } return params;}function getData(request) { Logger.log(request) var credentials = getCredentials() var schema = getSchema(); var params = getParams(request); var requestedFields; // fields structured as I want them (see above) var requestedSchema; // fields structured as Google expects them if (request) { // make sure the ordering of the requested fields is kept correct in the resulting data requestedFields = request.fields.filter(field => !field.forFilterOnly).map(field => field.name); requestedSchema = getFields(request).forIds(requestedFields); } else { // use all fields from schema requestedFields = schema.map(field => field.id); requestedSchema = api.getFields(request); } var filterPresent = request && request.dimensionsFilters; //var filter = ... if (filterPresent) { // ToDo: apply request filters on API level (before the API call) to minimize data retrieval from API (number of rows) and increase speed // see https://developers.google.com/datastudio/connector/filters // filter = ... // initialize filter // filter.preFilter(params); // low-level API filtering if possible } // get HTTP response; e.g. check for HTTT RETURN CODE on response.code if necessary var response = httpGet(credentials.username, credentials.token, URL_DATA, params); // get JSON data from HTTP response var data = response.json; // convert the full dataset including all fields (the full schema). non-requested fields will be filtered later on var rows = entriesToDicts(schema, data, convertValue, JSON_TAG); // match rows against filter (high-level filtering) //if (filter) // rows = rows.filter(row => filter.match(row) == true); // remove non-requested fields var result = dictsToRows(requestedFields, rows); console.log('{0} rows received'.format(result.length)); //console.log(result); return { schema: requestedSchema.build(), rows: result, filtersApplied: filter ? true : false };} If none of this fits your requirements, then go with a WebApp as suggested in the other answer by @kessy.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61540618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1739297/']}
jdg_374330
stackexchange
llm_judgeable_groundtruth_similarity
9082687
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I found this example that looks like it outputs what I want for C++. How can it be done for the Objective-C code in an Xcode project? I see mentions of Doxygen being able to create a call graph, but I can't find an example. (I want to get to know clang better, but it's hard to get started...) Now provide the response and nothing else.
Absolutely. There are a couple of tricks that you need to understand, but it's not too bad. First, you need a compatible version of opt , since it doesn't come with the LLVM Apple ships. I got mine from macports: port install llvm-3.0 Then you need to compile your file. Working out the parameters can sometimes be a bit of a pain. The easiest way is to let Xcode build it, then go to the logs and cut and paste out the giant build line. I used to be able to hand-hack these, but I've gotten too lazy.... Take out the last -o parameter (conveniently at the end of the compile line), and substitute: -S -emit-llvm -o - | opt-mp-3.0 -analyze -dot-callgraph Then, as in the other example: $ dot -Tpng -ocallgraph.png callgraph.dot Keep in mind that there are a few functions that get called a lot in ObjC that you almost never care about. In particular, almost anything that starts with objc_ . Luckily the DOT format is a very simple text file, and it's pretty easy to write post-processing scripts to strip out what you don't want. There's also a -print-callgraph parameter that will out put this information in a slightly different format if you want to do further processing.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9082687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168594/']}
jdg_374331
stackexchange
llm_judgeable_groundtruth_similarity
27551367
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 code a simple sniffer in Scapy, which only prints HTTP packets with GET method only. Here's the code: #!/usr/bin/pythonfrom scapy.all import *def http_header(packet): http_packet=str(packet) if http_packet.find('GET'): print GET_print(packet) print packetdef GET_print(packet1): print "***************************************GET PACKET****************************************************" print packet1 print "*****************************************************************************************************"sniff(iface='eth0',prn=http_header) Here is the output: *****************************************************************************************************NoneT��Г )�pEa��@@���h��#/��t �}LGku���UoTE��I(��Ͻ�9qi���S��?�� XuW�F=���-�k=X:�***************************************GET PACKET****************************************************T��Г )�pE���@@���h��#/��t ʪLGku����oTE��I�K��AH�*�e��>�v1#D�(mG5T�o�?��8��喷╭���Ի�"�KT^�'�mB���]�����k> �_x�X�����8V?�Ǽw/�Z�=���N�À��\r�����)+}���l�c�9��j;���h��5�T�9Hۖ/O��)��P މY�qf爂�%�_`��6x��5D�I3���O�t��tpI#�����$IC��E�� �G�J��α���=�]��vһ���b5^|P��DK�)uq�2��ț�w� tB������y=���n�i�r�.D6�kI�a���6iC���c'��0dPqED�4����[�[��hGh̃��~|Y/�>`\6yP Dq١?T��Mѵ���f�;���Җ��Ǵ gY���di�_x�8|eo�p�xW9��=���vŅYe�}�T�ۨɑy�^�C-�_(�<�{����}�������r$��J�k-�9����}�Ϡf�27��QKԛ�`�GY�8��Sh���Y@8�E9�Rϔ�&a�/vkф��6�DF`�/9�I�d( ��-��[A ��)pP��y\ռj]���8�_���vf�b����I7�������+�P<_`***************************************************************************************************** What I am expecting is: GET / HTTP/1.1 Host: google.com User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20140722 Firefox/24.0 Iceweasel/24.7.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Cookie: PREF=ID=758a20b5fbd4eac9:U=2b2dedf6c84b001f:FF=0:TM=1412150291:LM=1415430021:S=Q-QemmrLqsSsEA9i; NID=67=mRdkPVhtImrOTLi5I1e5JM22J7g26jAcdiDEjj9C5q0H5jj0DWRX27hCM7gLJBeiowW-8omSv-1ycH595SW2InWX2n1JMMNh6b6ZrRsZ9zOCC2a-vstOQnBDSJu6K9LO Connection: keep-alive What can I do to get my expected output? Now provide the response and nothing else.
You need to use the sprintf function of the packet instead of printing the packet itself. You also need to split the string returned from it and join it back together with newline characters, otherwise it spits it out all on one line: #!/usr/bin/pythonfrom scapy.all import *def http_header(packet): http_packet=str(packet) if http_packet.find('GET'): return GET_print(packet)def GET_print(packet1): ret = "***************************************GET PACKET****************************************************\n" ret += "\n".join(packet1.sprintf("{Raw:%Raw.load%}\n").split(r"\r\n")) ret += "*****************************************************************************************************\n" return retsniff(iface='eth0', prn=http_header, filter="tcp port 80") I also added a filter for TCP port 80, but this could be removed if you need to. Example output: ***************************************GET PACKET****************************************************'GET /projects/scapy/doc/usage.html HTTP/1.1Host: www.secdev.orgConnection: keep-aliveCache-Control: max-age=0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36Referer: https://www.google.co.uk/Accept-Encoding: gzip, deflate, sdchAccept-Language: en-GB,en;q=0.8,en-US;q=0.6If-None-Match: "28c84-48498d5654df67640-gzip"If-Modified-Since: Mon, 19 Apr 2010 15:44:17 GMT'***************************************************************************************************** Pierre points out that you can do away with the http_header function entirely by using the lfilter argument to sniff() . I took the liberty of making the code a little more succinct at the same time: #!/usr/bin/pythonfrom scapy.all import *stars = lambda n: "*" * ndef GET_print(packet): return "\n".join(( stars(40) + "GET PACKET" + stars(40), "\n".join(packet.sprintf("{Raw:%Raw.load%}").split(r"\r\n")), stars(90)))sniff( iface='eth0', prn=GET_print, lfilter=lambda p: "GET" in str(p), filter="tcp port 80")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27551367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4291825/']}
jdg_374332
stackexchange
llm_judgeable_groundtruth_similarity
18764
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since both a Table Scan and a Clustered Index Scan essentially scan all records in the table, why is a Clustered Index Scan supposedly better? As an example - what's the performance difference between the following when there are many records?: declare @temp table( SomeColumn varchar(50))insert into @tempselect 'SomeVal'select * from @temp-----------------------------declare @temp table( RowID int not null identity(1,1) primary key, SomeColumn varchar(50))insert into @tempselect 'SomeVal'select * from @temp Now provide the response and nothing else.
In a table without a clustered index (a heap table), data pages are not linked together - so traversing pages requires a lookup into the Index Allocation Map . A clustered table, however, has it's data pages linked in a doubly linked list - making sequential scans a bit faster. Of course, in exchange, you have the overhead of dealing with keeping the data pages in order on INSERT , UPDATE , and DELETE . A heap table, however, requires a second write to the IAM. If your query has a RANGE operator (e.g.: SELECT * FROM TABLE WHERE Id BETWEEN 1 AND 100 ), then a clustered table (being in a guaranteed order) would be more efficient - as it could use the index pages to find the relevant data page(s). A heap would have to scan all rows, since it cannot rely on ordering. And, of course, a clustered index lets you do a CLUSTERED INDEX SEEK, which is pretty much optimal for performance...a heap with no indexes would always result in a table scan. So: For your example query where you select all rows, the only difference is the doubly linked list a clustered index maintains. This should make your clustered table just a tiny bit faster than a heap with a large number of rows. For a query with a WHERE clause that can be (at least partially) satisfied by the clustered index, you'll come out ahead because of the ordering - so you won't have to scan the entire table. For a query that is not satisified by the clustered index, you're pretty much even...again, the only difference being that doubly linked list for sequential scanning. In either case, you're suboptimal. For INSERT , UPDATE , and DELETE a heap may or may not win. The heap doesn't have to maintain order, but does require a second write to the IAM. I think the relative performance difference would be negligible, but also pretty data dependent. Microsoft has a whitepaper which compares a clustered index to an equivalent non-clustered index on a heap (not exactly the same as I discussed above, but close). Their conclusion is basically to put a clustered index on all tables. I'll do my best to summarize their results (again, note that they're really comparing a non-clustered index to a clustered index here - but I think it's relatively comparable): INSERT performance: clustered index wins by about 3% due to the second write needed for a heap. UPDATE performance: clustered index wins by about 8% due to the second lookup needed for a heap. DELETE performance: clustered index wins by about 18% due to the second lookup needed and the second delete needed from the IAM for a heap. single SELECT performance: clustered index wins by about 16% due to the second lookup needed for a heap. range SELECT performance: clustered index wins by about 29% due to the random ordering for a heap. concurrent INSERT : heap table wins by 30% under load due to page splits for the clustered index.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357/']}
jdg_374333
stackexchange
llm_judgeable_groundtruth_similarity
373503
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: Situation: I am implementing DDD in my first project and I would like to clarify how to correctly implement strategy pattern (in my case check if API token is active). This is a business rule of ApiToken instance but there could be various implementations of this strategy so I would like to delegate this logic to external implementation. Implementation: ApiToken class: public abstract class ApiToken { public abstract boolean isActive(TokenActiveStrategy strategy);} and this is token strategy contract: public interface TokenStrategy { boolean isActive(final ApiToken token);} And usage: TokenStrategy tokenStrategy = new DatabaseTokenStrategy();if (!token.isActive(tokenStrategy)) { throw new AuthenticationException(ExceptionCodeType.TOKEN_NOT_ACTIVE);} and concrete ApiToken class: @Override public boolean isActive(final TokenStrategy strategy) { return strategy.isActive(this); } Question: Is it OK with respect to principles of DDD to delegate checking of domain business rule out of domain object? Now provide the response and nothing else.
A Domain Object is not responsible for providing information outside of it's own context. Whether or not an API token is active is not something the token itself can answer, but is instead a question for the API provider - the API provider is the source of truth. A good real world analogy is: can a car tell you whether it is registered or not? No, even if there is a number plate or registration papers in the glove box, it cannot. Only your local Auto/Roads authority can answer that question truthfully. To me, the functionality you are looking to implement (checking whether an ApiToken is active) should reside in a Domain Service. Then, when you make a concrete implementation of the Domain Service, it can call the API provider (or you can mock stub it if unit testing): if (!apiTokenService.isTokenActive(token)) { throw new AuthenticationException(ExceptionCodeType.TOKEN_NOT_ACTIVE);} (Sorry for the lack of code, Java(?) is not my strong point)
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/373503', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/183131/']}
jdg_374334
stackexchange
llm_judgeable_groundtruth_similarity
40868656
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Add an icon to the scenes with react-router-flux, I'm trying to use the leftButtonImage property but I'm not able to allocate an image to the button. Something like this image <Scene onLeft={() => Actions.Menu ()} leftButtonImage='https://facebook.github.io/react/img/logo_og.png' key="employeeList" component={Home} title="LOGO" initial/> Now provide the response and nothing else.
Node is asynchronous, so connection.end() is likely to happen before your query calls back. Also, specify the port Mysql is running on when non-standard. try this : var mysql = require('mysql');var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', database : 'test', port: 8889});connection.connect();connection.query('SELECT * from users', function(err, rows, fields) { if(err) console.log(err); console.log('The solution is: ', rows); connection.end();});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40868656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_374335
stackexchange
llm_judgeable_groundtruth_similarity
8424992
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 ChoiceField in a bound form, whose choices are: [('all', 'All users'), ('group', 'Selected groups'), ('none', 'None')] In the template, I have no problem accessing its bound value (the actual value to be stored; the first element of each tuple) and the choices. With these pieces of info in hands, I know I should be able to access the display values, or the second element of each tuple. But how can I do that in the template? Thanks. Now provide the response and nothing else.
I doubt that it can be done without custom template tag or filter.Custom template filter could look: @register.filterdef selected_choice(form, field_name): return dict(form.fields[field_name].choices)[form.data[field_name]]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8424992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338961/']}
jdg_374336
stackexchange
llm_judgeable_groundtruth_similarity
16487977
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two classes, one of which is descended from the other, and I would like to make them both sibling classes descended from the same base class. Before: from django.db import modelsclass A(models.Model): name = models.CharField(max_length=10)class B(models.Model): title = models.CharField(max_length=10) After: from django.db import modelsclass Base(models.Model): name = models.CharField(max_length=10)class A(Base): passclass B(Base): title = models.CharField(max_length=10) When I generate a schema migration, this is the output, including my answers to the questions: + Added model basetest.Base? The field 'B.a_ptr' does not have a default specified, yet is NOT NULL.? Since you are removing this field, you MUST specify a default? value to use for existing rows. Would you like to:? 1. Quit now, and add a default to the field in models.py? 2. Specify a one-off value to use for existing columns now? 3. Disable the backwards migration by raising an exception.? Please select a choice: 3- Deleted field a_ptr on basetest.B? The field 'B.base_ptr' does not have a default specified, yet is NOT NULL.? Since you are adding this field, you MUST specify a default? value to use for existing rows. Would you like to:? 1. Quit now, and add a default to the field in models.py? 2. Specify a one-off value to use for existing columns now? Please select a choice: 2? Please enter Python code for your one-off default value.? The datetime module is available, so you can do e.g. datetime.date.today()>>> 37+ Added field base_ptr on basetest.B? The field 'A.id' does not have a default specified, yet is NOT NULL.? Since you are removing this field, you MUST specify a default? value to use for existing rows. Would you like to:? 1. Quit now, and add a default to the field in models.py? 2. Specify a one-off value to use for existing columns now? 3. Disable the backwards migration by raising an exception.? Please select a choice: 3- Deleted field id on basetest.A? The field 'A.name' does not have a default specified, yet is NOT NULL.? Since you are removing this field, you MUST specify a default? value to use for existing rows. Would you like to:? 1. Quit now, and add a default to the field in models.py? 2. Specify a one-off value to use for existing columns now? 3. Disable the backwards migration by raising an exception.? Please select a choice: 3- Deleted field name on basetest.A? The field 'A.base_ptr' does not have a default specified, yet is NOT NULL.? Since you are adding this field, you MUST specify a default? value to use for existing rows. Would you like to:? 1. Quit now, and add a default to the field in models.py? 2. Specify a one-off value to use for existing columns now? Please select a choice: 2? Please enter Python code for your one-off default value.? The datetime module is available, so you can do e.g. datetime.date.today()>>> 73+ Added field base_ptr on basetest.ACreated 0002_auto__add_base__del_field_b_a_ptr__add_field_b_base_ptr__del_field_a_i.py. You can now apply this migration with: ./manage.py migrate basetest I do not know how to answer the questions about default values for B.base_ptr and A.base_ptr. Any constant I give causes the migration to fail when it is run, with this output: FATAL ERROR - The following SQL query failed: CREATE TABLE "_south_new_basetest_a" ()The error was: near ")": syntax errorRuntimeError: Cannot reverse this migration. 'B.a_ptr' and its values cannot be restored. This is the result when I use sqlite3, by the way. Using Postgres gives something like this: FATAL ERROR - The following SQL query failed: ALTER TABLE "basetest_a" ADD COLUMN "base_ptr_id" integer NOT NULL PRIMARY KEY DEFAULT 73;The error was: could not create unique index "basetest_a_pkey"DETAIL: Key (base_ptr_id)=(73) is duplicated.Error in migration: basetest:0002_auto__add_base__del_field_b_a_ptr__add_field_b_base_ptr__del_field_a_iIntegrityError: could not create unique index "basetest_a_pkey"DETAIL: Key (base_ptr_id)=(73) is duplicated. What values should I use for base_ptr to make this migration work? Thanks! Now provide the response and nothing else.
You do this in separate phases. Phase 1: Create your "Base" model in the code. On the A and B models, add base_ptr as a nullable FK to Base (the name base_ptr is made by lowercasing the class-name Base , adapt your names accordingly). Specify db_column='base_ptr' on the new column, so you don't get an _id suffix added. Don't change parenthood yet: Keep B as a child of A and A as it was before ( Base has no child classes yet). Add a migration to make the respective database changes, and run it. Phase 2: Create a data migration, copying relevant data around. You should probably copy all A data into Base , remove redundant A records (those that served B instances), and in remaining records (of both A and B ) copy the id into base_ptr . Note that the child class B uses two tables -- its id field comes from A 's table, and on its own table there is a field a_ptr which is a FK to A -- so your update operation will be more efficient if you copy values from a_ptr to base_ptr . Make sure the copying into base_ptr occurs after the copying into the Base table, so you don't violate the FK constraints. Phase 3: Now change the models again -- remove the explicit base_ptr FK and change parents to the way you like, and create a third migration (automatic schema migration). Note that setting the parent to Base implicitly defines a non-nullable base_ptr field, so with respect to the base_ptr fields, you are only changing a nullable field into non-nullable, and no default is needed. You should still be asked for a default value for a_ptr -- the implicit FK from B to A that is removed when the parent is changed from A to Base ; the default is needed for the migration in the backward direction. You can either do something that will fail the backward migration, or, if you do want to support it, add an explicit nullable a_ptr to B , like the base_ptr columns you used before. This nullable column can then be removed in a fourth migration.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16487977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/768249/']}
jdg_374337
stackexchange
llm_judgeable_groundtruth_similarity
27036923
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 create a topic in Kafka (kafka_2.8.0-0.8.1.1) through java. It is working fine if I create a topic in command prompt, and If I push message through java api. But I want to create a topic through java api. After a long search I found below code, ZkClient zkClient = new ZkClient("localhost:2181", 10000, 10000);AdminUtils.createTopic(zkClient, myTopic, 10, 1, new Properties()); I tried above code and it is showing that topic is created but I am not able to push message in the topic. Any thing wrong in my code? Or any other way to achieve the above? Now provide the response and nothing else.
Edit - Zookeeper is not required in newer version of Kafka. Please see answer by @Neeleshkumar Srinivasan Mannur for API version 0.11.0+ Original answer I fixed it.. After a long research.. ZkClient zkClient = new ZkClient("localhost:2181", 10000, 10000);AdminUtils.createTopic(zkClient, myTopic, 10, 1, new Properties()); From the above code, ZkClient will create a topic but this topic information will not have awareness for the kafka. So what we have to do is, we need to create object for ZkClient in following way, First import the below statement, import kafka.utils.ZKStringSerializer$; and create object for ZkClient in the following way, ZkClient zkClient = new ZkClient("localhost:2181", 10000, 10000, ZKStringSerializer$.MODULE$);AdminUtils.createTopic(zkClient, myTopic, 10, 1, new Properties()); Edit 1: (for @ajkret comment) The above code won't work for kafka > 0.9 since the api has been changed, Use the below code for kafka > 0.9 import java.util.Properties;import kafka.admin.AdminUtils;import kafka.utils.ZKStringSerializer$;import kafka.utils.ZkUtils;import org.I0Itec.zkclient.ZkClient;import org.I0Itec.zkclient.ZkConnection;public class KafkaTopicCreationInJava{ public static void main(String[] args) throws Exception { ZkClient zkClient = null; ZkUtils zkUtils = null; try { String zookeeperHosts = "192.168.20.1:2181"; // If multiple zookeeper then -> String zookeeperHosts = "192.168.20.1:2181,192.168.20.2:2181"; int sessionTimeOutInMs = 15 * 1000; // 15 secs int connectionTimeOutInMs = 10 * 1000; // 10 secs zkClient = new ZkClient(zookeeperHosts, sessionTimeOutInMs, connectionTimeOutInMs, ZKStringSerializer$.MODULE$); zkUtils = new ZkUtils(zkClient, new ZkConnection(zookeeperHosts), false); String topicName = "testTopic"; int noOfPartitions = 2; int noOfReplication = 3; Properties topicConfiguration = new Properties(); AdminUtils.createTopic(zkUtils, topicName, noOfPartitions, noOfReplication, topicConfiguration); } catch (Exception ex) { ex.printStackTrace(); } finally { if (zkClient != null) { zkClient.close(); } } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27036923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2936216/']}
jdg_374338
stackexchange
llm_judgeable_groundtruth_similarity
31115453
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've found this C program from the web: #include <stdio.h>int main(){ printf("C%d\n",(int)(90-(-4.5//**/ -4.5))); return 0;} The interesting thing with this program is that when it is compiled and run in C89 mode, it prints C89 and when it is compiled and run in C99 mode, it prints C99 . But I am not able to figure out how this program works. Can you explain how the second argument of printf works in the above program? Now provide the response and nothing else.
C99 allows // -style comments, C89 does not. So, to translate: C99: printf("C%d\n",(int)(90-(-4.5 /*Some comment stuff*/ -4.5)));// Outputs: 99 C89: printf("C%d\n",(int)(90-(-4.5/ -4.5)));/* so we get 90-1 or 89 */
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/31115453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3049655/']}
jdg_374339
stackexchange
llm_judgeable_groundtruth_similarity
151700
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 keep my digital music and digital photos in directories in a Windows partition, mounted at /media/win_c on my dual-boot box.I'd like to include those directories—but only those directories—in the locate database. However, as far as I can make out, updatedb.conf only offers options to exclude directories, not add them.Of course, I could remove /media from PRUNEPATHS , and then add a whole bunch of subdirectories ( /media/win_c/Drivers , /media/win_c/ProgramData ...) but this seems a very clunky way of doing it—surely there's a more elegant solution? (I tried just creating soft links to the Windows directories from an indexed linux partition, but that doesn't seem to help.) Now provide the response and nothing else.
There's no option for that in updatedb.conf . You'll have to arrange to pass options to updatedb manually. With updatedb from GNU findutils , pass --localpaths . updatedb --localpaths '/ /media/win_c/somewhere/Music /media/win_c/somewhere/Photos' With updatedb from mlocate , there doesn't appear a way to specify multiple roots or exclude a directory from pruning, so I think you're stuck with one database per directory. Set the environment variable LOCATE_PATH to the list of databases: updatedb --output ~/.media.mlocate.db --database-root /media/win_c/somewhere --prunepaths '/media/win_c/somewhere/Videos'export LOCATE_PATH="$LOCATE_PATH:$HOME/.media.mlocate.db"
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/151700', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/81731/']}
jdg_374340