text
stringlengths
64
81.1k
meta
dict
Q: Find element in array that matches selection and write to that row of the array The good news is I'm to the very last part of this project, the bad news is i can't figure it out. My program consist of two forms. The first form is only relevant at this moment because it is where I originally load the text file into a dictionary. class SharedMethods { public static void LoadDictionary(Dictionary<string, string> vendorPhones) { string currentLine; string[] fields = new string[2]; StreamReader vendorReader = new StreamReader("Vendor.txt"); while (vendorReader.EndOfStream == false) { currentLine = vendorReader.ReadLine(); fields = currentLine.Split(','); vendorPhones.Add(fields[1], fields[6]); string[] name = { fields[1] }; string[] phone = { fields[6] }; } vendorReader.Close(); } } Now the second form is what is important. This form is opened from the first form and allows the user to select a name from a combobox, and the phone number that belongs to that name is displayed in a text box. The user can then type in the text box to overwrite that name and click save to save it to a text file. My problem is I can't figure out how to get the writing function to find the selected name in the text and then write over the current phone element in that row. Here is my code for this form: public partial class UpdateVendor : Form { public UpdateVendor() { InitializeComponent(); } public Dictionary<string, string> vendorPhones = new Dictionary<string, string>(); private void UpdateVendor_Load(object sender, EventArgs e) { SharedMethods.LoadDictionary(vendorPhones); foreach (string name in vendorPhones.Keys) { cboVendors.Items.Add(name); } } private void cboVendors_SelectedIndexChanged(object sender, EventArgs e) { string selectedName = cboVendors.SelectedItem.ToString(); string phone = vendorPhones[selectedName]; txtPhone.Text = phone.ToString(); } private void btnSave_Click(object sender, EventArgs e) { //SharedMethods.LoadDictionary(vendorPhones); //string selectedName = cboVendors.SelectedItem.ToString(); //string newPhone; //newPhone = txtPhone.Text; //using (var sw = new StreamWriter("Vendors.txt")) //{ //} // I've tried a lot of things but can't get any to work. } Sorry if the code makes you cringe in disgust. I'm just learning code and I'm ecstatic that it works half the time. To add, here is how the program looks when running: Second form running A: The problem here is that, because you are not capturing all the data when reading the file in the first place, you will have to be a little tricky about writing it back so that you don't lose any data. What we can do is re-read the entire file back into an array, then search each line in the array for the one that contains our vendor and original phone number. When we find that line, update the phone number part to the new number. Then, write all the lines back to the file again Here's one way to do it: private void btnSave_Click(object sender, EventArgs e) { // Grab the selected vendor name string selectedName = cboVendors.SelectedItem.ToString(); // Grab the original phone number for this vendor string originalPhone = vendorPhones[selectedName]; // Read all the file lines into an array: var fileLines = File.ReadAllLines("Vendor.txt"); // Now we iterate over the file lines one by one, looking for a match for (int i = 0; i < fileLines.Length; i++) { // Break the line into parts to see if this line is the one we need to update string[] lineParts = fileLines[i].Split(','); string name = lineParts[1]; string phone = lineParts[6]; // Compare this line's name and phone with our originals if (name == selectedName && phone == originalPhone) { // It's a match, so we will update the phone number part of this line lineParts[6] = txtPhone.Text; // And then we join the parts back together and assign it to the line again fileLines[i] = string.Join(",", lineParts); // Now we can break out of the loop since we updated our vendor info break; } } // Finally, we can write all the lines back to the file File.WriteAllLines("Vendor.txt", fileLines); // May not be necessary, but if you're not reading back from the file right away // then update the dictionary with the new phone number for this vendor vendorPhones[selectedName] = txtPhone.Text; } Ideally, however, you would capture ALL the data when you read the file, and for each line in the file you would create a new Vendor object that had properties representing each comma-separated value. Then, these Vendor objects could be stored in a List<Vendor>. Now you have a collection of strongly typed objects that you can display and manipulate, and when you're all done you can just write them all back to the file in a similar manner. But that wasn't your question, and it sounds like you may not be quite there yet...
{ "pile_set_name": "StackExchange" }
Q: Run After Submit Script when approve button is clicked Netsuite When approve button is clicked on journal entry, this reversal should be auto approved. This script is running when i am clicking edit and then saving. I want this to run when just approve button is clicked without editing. How can i do that? function JEReversalAfterSubmit(type){ if (type == 'approve') { var filters2 = new Array(); filters2[0] = new nlobjSearchFilter( 'tranid', null, 'is', 'JV267'); var columns2 = new Array(); columns2[0] = new nlobjSearchColumn( 'internalid' ); var searchresults2 = nlapiSearchRecord( 'journalentry', null, filters2, columns2 ); for ( var j = 0; searchresults2 != null && j < searchresults2.length; j++ ) { var searchresult2 = searchresults2[ j ]; var reversalJEID = searchresult2.getValue( 'internalid' ); nlapiLogExecution('debug','reversalJEID',reversalJEID); } nlapiLogExecution('DEBUG','34','34'); var params = new Array(); params['type'] = 'approve'; nlapiSetRedirectURL('RECORD','journalentry',reversalJEID, 'false',params); } } } } A: How is the approve button created? If it is created via workflow, you can use a custom workflow action script for this instead of an User Event script.
{ "pile_set_name": "StackExchange" }
Q: How Can Telecommunication System Know Which Part Is Signal and Which Is Noise? When signal is received how can receiver know which part of received signal is signal and which part is noise?? A: To elaborate on MM's answer just a little bit. Unless the receiver has some sort of expectation of the nature of the signal there is no way to tell. With an expectation (for instance a pure tone), only a best estimation can be made with the rest assumed to be noise. With something like serial communication a voltage past a threshold is considered a "1" and no (or low) voltage is considered a "0". In noisy channels, parity bits (or error correcting codes) are used to ensure "what was sent". There are many possibilities, but the receiver has to know the nature of is being sent, which seems to be the answer you are fishing for.
{ "pile_set_name": "StackExchange" }
Q: Is AllowZeroLength for Number column in Access? I would like to know that Can we create the column to allow null values even if it has default value as 0 in MS Access? A: Of course you can. If it is not a required entry -- that is, the Required property is set to No -- it will allow null. It will be up to you or the user to clear the 0 where you want a null.
{ "pile_set_name": "StackExchange" }
Q: can't get simple twitter bootstrap modal dialog to popup I'm trying to get a modal dialog to show by clicking a button. I'm trying to use bootstrap. My button isn't styled properly (it should be blue, but it's just a link), and the modal dialog doesn't appear when clicking the link. The screen does turn gray when I click the button. The sample code for the modal came from the boot strap website. I'm loading all resources from CDN. This doesn't seem like it would be difficult. http://jschr.github.io/bootstrap-modal/bs3.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen"> </head> <body> <!-- Button to trigger modal --> <a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a> <!-- Modal --> <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Modal header</h3> </div> <div class="modal-body"> <p>One fine body…</p> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> <button class="btn btn-primary">Save changes</button> </div> </div> </body> </html> A: button default type=> btn-default <a href="#myModal" role="button" class="btn btn-default" data-toggle="modal">Launch demo modal</a> forgetting to put 2 divs 'modal-dialog' and 'modal-content' <div class="modal-dialog"> <div class="modal-content"> remove hide from div 'myModal' <div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> http://jsfiddle.net/32fWL/1/
{ "pile_set_name": "StackExchange" }
Q: Importing Python files in Aws Lambda causes error I'm currently in a school course where we have to do a software project for some client. Our project is a helper bot powered by Amazon Lex service and Amazon's Lambda function. Our issue is that for some reason the Lambda function does not have same kind of syntax for importing files that other Python 3.6 programs have. This causes problems because TravisCI won't build properly due to the different syntax and errors caused by it. In the Lambda function the import needs to looks like this: from custom_python_file import CustomClass But in TravisCI, and I believe every in also everyother other platform it needs to be typed like this: from .custom_python_file import CustomClass We tried to do some workarounds, but none did work. Any help? A: In Python . is used for relative imports. It simply means that it is importing from the same package. Refer this tutorial and this question for the same.
{ "pile_set_name": "StackExchange" }
Q: ld: library not found for -lcrt0.o on OSX 10.6 with gcc/clang -static flag When I try to build the following program: #include <stdio.h> int main(void) { printf("hello world\n"); return 0; } On OS X 10.6.4, with the following flags: gcc -static -o blah blah.c It returns this: ld: library not found for -lcrt0.o collect2: ld returned 1 exit status Has anyone else encountered this, or is it something that noone else has been affected with yet? Any fixes? Thanks A: This won’t work. From the man page for gcc: This option will not work on Mac OS X unless all libraries (including libgcc.a) have also been compiled with -static. Since neither a static version of libSystem.dylib nor crt0.o are provided, this option is not useful to most people.
{ "pile_set_name": "StackExchange" }
Q: Multiple Upload Bootstrap I am attempting to use bootstrap to upload multiple files from User. I can see that if i select more than one file it does indeed upload but I am looking for a way for the user to be able to hit the choose files button more than once to attach more files. Has anyone had any luck using this with bootstrap? <div class="form-group"> <label class="col-sm-3 control-label"> Attachment(s) (Attach multiple files.) </label> <div class="col-sm-9"> <span class="btn btn-default btn-file"> <input id="input-2" name="input2[]" type="file" class="file" multiple data-show-upload="false" data-show-caption="true"> </span> </div> </div> Here is my FIDDLE A: If you want to upload a multiple files just put "multiple" inside the input file tag like this. < input type="file" name="img" multiple> <input id="input-2" name="input2[]" type="file" class="file" data-show-upload="false" data-show-caption="true" multiple>
{ "pile_set_name": "StackExchange" }
Q: How to use replaceAll() method in StringBuffer? I need to replace multiple words in a string buffer. So I am looking for a replaceAll method in StringBuffer. So do we have it in StringBuffer? String method: str2 = str1.replaceAll(regex, substr); // (This is String method, I need like this in StringBuffer) A: There is no such method on StringBuffer. Perhaps the following will help: StringBuffer str1 = new StringBuffer("whatever"); // to get a String result: String str2 = str1.toString().replaceAll(regex, substr); // to get a StringBuffer result: StringBuffer str3 = new StringBuffer(str2);
{ "pile_set_name": "StackExchange" }
Q: How can I style an Android Switch? The switch widget introduced in API 14 is styled by default with holo theme. I want to style it slightly different, changing its colors and shape a bit for branding reasons. How does one go about this? I know it must be possible, as ive seen the difference between default ICS and Samsung's touchwiz theme I assume I'll need some state drawables, and I've seen a few styles in http://developer.android.com/reference/android/R.styleable.html with Switch_thumb and Switch_track that look like what I might be after. I just don't know how to go about using them. I'm using ActionbarSherlock if that makes a difference. Only devices running API v14 or above will be able to use a switch at all, of course. A: You can define the drawables that are used for the background, and the switcher part like this: <Switch android:layout_width="wrap_content" android:layout_height="wrap_content" android:thumb="@drawable/switch_thumb" android:track="@drawable/switch_bg" /> Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" /> <item android:state_pressed="true" android:drawable="@drawable/switch_thumb_pressed_holo_light" /> <item android:state_checked="true" android:drawable="@drawable/switch_thumb_activated_holo_light" /> <item android:drawable="@drawable/switch_thumb_holo_light" /> </selector> This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider: The deactivated version (xhdpi version that Android is using) The pressed slider: The activated slider (on state): The default version (off state): There are also three different states for the background that are defined in the following selector: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" /> <item android:state_focused="true" android:drawable="@drawable/switch_bg_focused_holo_dark" /> <item android:drawable="@drawable/switch_bg_holo_dark" /> </selector> The deactivated version: The focused version: And the default version: To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style. A: It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio A good description of all the tools are at AndroidOnRocks.com (site offline now) However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick A: You can customize material styles by setting different color properties. For example custom application theme <style name="CustomAppTheme" parent="Theme.AppCompat"> <item name="android:textColorPrimaryDisableOnly">#00838f</item> <item name="colorAccent">#e91e63</item> </style> Custom switch theme <style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch"> <item name="android:textColorPrimaryDisableOnly">#b71c1c</item> <item name="android:colorControlActivated">#1b5e20</item> <item name="android:colorForeground">#f57f17</item> <item name="android:textAppearance">@style/TextAppearance.AppCompat</item> </style> You can customize switch track and switch thumb like below image by defining xml drawables. For more information http://www.zoftino.com/android-switch-button-and-custom-switch-examples
{ "pile_set_name": "StackExchange" }
Q: What does it mean by saying someone is "effectively risk averse/loving"? Recently I am reading a paper by Ortner & Chassang (2018) on corruption control. It is a nice paper to read, and the idea is kinda cool. The game is as follows. There are 3 players, a principle, a monitor, and an agent. The agent can choose to engage crime, and the principle offers a wage structure to the monitor in order to deter crime (for details, please refer to the paper if you are interested). One of the results says that, when the monitor's private cost of misreporting is strictly concave (convex) over the support, the agent is effectively risk-loving (risk-averse). However, I do not quite understand the concept of being "effectively risk averse/loving" that they mentioned. I never saw this before. What does it mean? Does it simply mean that it is beneficial for the agent to be risk-loving? Thanks for your clarification in advance. Please kindly provide some reference if there is any. A: "Effectively" has two definitions: 1: in such a manner as to achieve a desired result. 2: actually but not officially or explicitly. O+C are using the second definition here. This is because the risk averse/loving behaviour that is being exhibited does not come from the concavity of the agent's utility function, but instead indirectly, from the concavity of the c.d.f of the random cost $\eta$ that the monitor will have to pay if they misreport information. So the agents are not "officially" risk averse/loving but as a result of the concavity/convexity of the monitor's cost cdf they will behave as a risk averse/loving agent would when the cdf is linear. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: What's the exact relationship between the scale $Q$ at which parameters are probed and the "fake parameter" $\mu$? It is well known that couplings change depending on the scale $Q$ at they are measured. This effect is experimentally well documented: From a theoretical point of view, the running $\alpha_S(\mu)$ can be calculated using the renormalized group equations. However, it is regularly argued that the parameter $\mu$ appears here is a "fake parameter", has no meaning and can always be chosen at will. In particular, it is argued that we can use the fact that "physical observables must be independent of the fake parameter $\mu$ to figure out how the lagrangian parameters $m$ and $g$ must change with $\mu$." The renormalized group equations that we find this way are then regularly used to calculate the running of parameters like $\alpha_S$: How does this fit together? In particular, what's the exact relationship between the measured energy dependence of parameters and the running of parameters with the fake parameter $\mu$? Or formulated differently, if the renormalization group equations encode the dependence on the "fake parameter" $\mu$, which equations describe the dependence on the physical energy scale $Q$? (I'm aware that there are lots of related questions, but none of them seemed to answer this question unambiguously.) A: if the renormalization group equations encode the dependence on the "fake parameter" $\mu$, which equations describe the dependence on the physical energy scale Q? Let's look at a (oversimplified) case of running (where Q is the measurable probing energy (momentum) in a realistic scattering process), $$ g(Q) = g_{\mu} + ln(\frac{Q}{\mu}), $$ which is the solution to the differential equation $$ \frac{dg}{d(lnQ)} = 1, $$ with the initial condition $$ g|_{Q=\mu} = g_{\mu}. $$ Equivalently, the above logarithmic $g(Q)$ can be viewed as the solution to a different differential equation (the garden variety renormalization group equation) $$ \frac{dg}{d(ln\mu)} = -1, $$ with the initial condition $$ g|_{\mu=Q} = g_{\mu}. $$ The first differential equation (of $\frac{dg}{d(lnQ)}$) interprets the running as "g running with the probing/scattering energy (momentum) Q" and the second differential equation (of $\frac{dg}{d(ln\mu)}$, beta function in the usual parlance) interprets the running as "g running with renormalization scale $\mu$". Most text books take the second view, while I prefer the first. Nonetheless, they depict the same underlying physics. The parameter $\mu$ is "fake" in the sense that, you can fix the solution of the differential equation of $\frac{dg}{d(lnQ)}$ with the initial condition set at $\mu'$, rather than at $\mu$, $$ g(Q) = g_{\mu'} + ln(\frac{Q}{\mu'}), $$ where $$ g|_{Q=\mu'} = g_{\mu'} = g_{\mu} + ln(\frac{\mu'}{\mu}). $$ In other words, the "fake parameter" $\mu$ is merely an arbitrary anchor point to frame the initial condition. Nothing more, nothing less!
{ "pile_set_name": "StackExchange" }
Q: 2D Array of objects with virtual child methods -> "vtable referenced from" error In my header for the Tile class, I defined a pure virtual method with no definition in the implementation: virtual void setVals(int ID) = 0; The two classes which inherit Tile (Terrain and Actor) both overwrite the setVals method with the implementations: void Terrain::setVals(int ID){ switch(ID){ case 1 : GFX_ = '.'; name_ = "Grass"; desc_ = "Some grass"; break; default: GFX_ = '?'; name_ = "Error"; desc_ = "Error"; Tile::isPassable_ = false; break; } } and void Tile::setVals(int ID){ switch(ID){ case 1 : GFX_ = '?'; name_ = "Nothing"; desc_ = "You shouldn't be seeing this"; break; case 0 : GFX_ = '@'; name_ = "Player"; desc_ = "The Player"; break; default: GFX_ = '?'; name_ = "Error"; desc_ = "Error"; Tile::isPassable_ = false; break; } } respectively. An 2D array of each of these child classes is initialized in the Map class: Terrain terrain_[HEIGHT][WIDTH]; Actor actors_[HEIGHT][WIDTH]; (where HEIGHT and WIDTH are constant ints). But when the program runs, the program returns a runtime error reading "'vtable for Actor', referenced from:". Am I making a mistake in how I'm initializing these methods or objects? A: You said that your base class is Tile, and has the following pure virtual method virtual void setVals(int ID) = 0; But yet you went on to define it? void Tile::setVals(int ID){ switch(ID){ case 1 : GFX_ = '?'; name_ = "Nothing"; desc_ = "You shouldn't be seeing this"; break; case 0 : GFX_ = '@'; name_ = "Player"; desc_ = "The Player"; break; default: GFX_ = '?'; name_ = "Error"; desc_ = "Error"; Tile::isPassable_ = false; break; } } You need to implement Actor::setVals if that is a derived class from Tile
{ "pile_set_name": "StackExchange" }
Q: Trying to build a button to expand a list in a list I'm trying to build in a button to expand a list in a list of div elements. $('.expandAllfixVersionList').click(function () { $('.fixVersionList').find('.issue').animate({height: $('.fixVersionList').children('.version')[0].scrollHeight}, 500); $('.fixVersionList').find('.issue').animate({'overflow': 'visible'}, 500); }); Here I got the problem that he shows the first fixVersionListElement correct and all folowing get the same height, even if they got more or less Issues in them. So they might get cut off or be way to big. Can I make this in a way that he addresses the animation dynamic to the correct height? The structure of the HTML is like this: <div class="content"> <div class="fixVersionList">...</div> ... <div class="fixVersionList"> <ul class="issue"> <li> </li> </ul> <ul class="issue">...</ul> ... </div> </div> A: Hi I recreated your existing code, please let me know if this helps you $('.expandAllfixVersionList').click(function () { $('.fixVersionList').each(function( index, value ) { $(value).find('.issue').animate({height: $(value).children()[0].scrollHeight}, 500); $(value).find('.issue').animate({'overflow': 'visible'}, 500); }); }); .issue{ height:0px; overflow:hidden; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <button class="expandAllfixVersionList">asads</button> <div class="content"> <div class="fixVersionList"> <ul class="issue"> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> <ul class="issue"> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> <ul class="issue"> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> </div> <div class="fixVersionList"> <ul class="issue"> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> <ul class="issue"> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> <ul class="issue"> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Sublime Text 3 Stop Auto-Complete From Committing on 'Space' In Sublime Text 3, is there any way to stop the Auto-Complete from committing when pressing space? I see the "auto_complete_commit_on_tab": false option in the settings, but nothing to stop pressing the space key from committing the selected entry. Perhaps I can make use of some combination of the "auto_complete_selector" or "auto_complete_triggers" settings? Any help will be greatly appreciated. Update To recreate, open a new buffer and verify that the syntax is set to Plain Text. Write Blah Test Stuff More Text Now press ctrl+space (or whatever you have the hotkey set to) to open the Completions List. Use the arrow keys to navigate to one of the choices and press space. This will automatically select the highlighted choice as if you had pressed enter (or tab if you have "auto_complete_commit_on_tab" set to true). I want to stop Sublime Text from assuming that space means I want to select the highlighted completion. A: I was asking this question because I was developing an auto-complete package (Gherkin Auto-Complete Plus) for Cucumber's Gherkin language. Because the language uses human readable text, the commit on spaces made it practically useless. Because I wanted to display the auto-complete results while typing (like you'd see in an IDE), I manage the displaying of said results in my package. The solution was hacky, but it works. I got the idea from the SublimeCodeIntel package. The implementation can be seen in gherkin_event_listener.py First, I defined a _show_auto_complete method on my GherkinEventListener class. def _show_auto_complete(self, view): def _show_auto_complete(): view.run_command('auto_complete', { 'disable_auto_insert': True, 'api_completions_only': True, 'next_completion_if_showing': False, 'auto_complete_commit_on_tab': True, }) # Have to set a timeout for some reason sublime.set_timeout(_show_auto_complete, 0) Note that a timeout must be set, even if it's 0. Then in the on_modified method of the GherkinEventListener, I did this: view.settings().set('auto_complete', False) pos = view_sel[0].end() next_char = view.substr(sublime.Region(pos - 1, pos)) if next_char in (' ', '\n'): view.run_command('hide_auto_complete') return view.run_command('hide_auto_complete') self._show_auto_complete(view) self._fill_completions(view, pos) Note that you must fill the completions after calling _show_auto_complete, otherwise it will be set to false when filling and they won't display.
{ "pile_set_name": "StackExchange" }
Q: How to open link that is inside div using jQuery? I have the following div: <div class="panel-heading"> <h3 class="panel-title"><a href="#">Test Title</a> <small>Aug 24, 2013</small></h3> </div> I want to make it so that when the user clicks on .panel-heading (any part of that div), it will open up what was linked to Test Title. In this case, it should open #. How do I do this using jQuery? A: $('.panel-heading').click(function(){ window.location.href = $(this).find('a').attr('href'); }); Demo
{ "pile_set_name": "StackExchange" }
Q: Calculating logs and fractional exponents by hand In view of what we can compute by hand, on a piece of paper, without having to use a computer or a calculator, how far can we go with the evaluation of $\log$-functions and fractional powers? More concretely, are there practical methods, that work in general well enough, for computing the followings? $\log(x)$ (natural log used here) for $x\in ]0,\infty[$ (e.g take $x=3,$ which has a natural log of $\approx 1.09$) $x^{\alpha},$ ($x$ being any real number) for $\alpha$ not being a natural number. So e.g. $\alpha=1/2,1/3,\cdots$ It would be neat to learn about possible ways of maybe first simplifying these calculations, translating them into more feasible calculations (by hand), and then take it from there. Or if direct methods exist that work for certain values or powers. This surely begs the question, how people used to do these calculations before computers were around. A: The well known series $$\log(1+x) = \sum_{k=1}^{\infty}(-1)^{k+1}\frac{x^k}{k}$$ converges for $-1< x\leq 1$, so it cannot be used to calculate $\log(3)$ with directly. However, it is possible to extend the radius of convergence using a conformal mapping. If we put $y = \frac{1+x}{1-x}$, then we have: $$\log(y) = \log(1+x) - \log(1-x) = 2\sum_{k=0}^{\infty}\frac{x^{2k+1}}{2k+1}$$ Since $x = \frac{y-1}{y+1}$, this means that $$\log(y) = 2\sum_{k=0}^{\infty}\frac{1}{2k+1}\left(\frac{y-1}{y+1}\right)^{2k+1}$$ and this converges for all positive y. So, you can directly insert $y = 3$ in this series and compute $\log(3)$ quite accurately using only a few terms: $$\log(3) =1 + \frac{1}{3\times 4} + \frac{1}{5\times 16} + \frac{1}{7\times 64} + \frac{1}{9\times 256} + \frac{1}{11\times 1024} +\cdots$$ So, with 6 terms we get 5 significant figures. But for larger $y$ the series will converge more slowly, it's then more convenient to use the above series to construct a series for $\log(y+1) -\log(y) = \log\left(1+\frac{1}{y}\right)$: $$\log(1+y) = \log(y)+ 2\sum_{k=0}^{\infty}\frac{1}{2k+1}\left(\frac{1}{1+2y}\right)^{2k+1}$$ The series now converges faster when computing $\log(n)$ for $n$ larger than 2, but you then need to know $\log(n-1)$. However, it is then possible to compute several logarithms simultaneously in terms of only fast converging series. E.g. to compute $\log(2)$, $\log(3)$ and $\log(5)$ simultaneously, we can use $2^4 = 16 = 15+1 = 3\times 5 +1$, $3^4 = 81 = 80+1 = 2^4\times 5 +1$, and $5^2 = 24+1 = 3\times 2^3+1$, this yields: $$ \begin{split} &4\log(2) - \log(3) - \log(5) &= 2\sum_{k=0}^{\infty}\frac{1}{2k+1}\left(\frac{1}{31}\right)^{2k+1}\\ &4\log(3) - 4\log(2) - \log(5) &= 2\sum_{k=0}^{\infty}\frac{1}{2k+1}\left(\frac{1}{161}\right)^{2k+1}\\ &2\log(5) - 3\log(2) - \log(3) & = 2\sum_{k=0}^{\infty}\frac{1}{2k+1}\left(\frac{1}{49}\right)^{2k+1} \end{split} $$ So, you can then solve for the 3 logarithms using these 3 equations involving fast converging series. A: My favorite way of calculating the natural logarithm: $$\ln(x)\approx-\gamma+\sum_{n=1}^x\frac1n$$ Where $\gamma$ is the Euler-Mascheroni constant. Not only is this easy, but it works quite well for something like $x>10$. If you need to calculate other bases, like $\log_b(x)$, use $\log_b(x)=\frac{\ln(x)}{\ln(b)}$. If you are not satisfied with the result because $x$ is small, try $\ln(x)=\frac1k\ln(x^k)$ to make the approximation better. A: Before computers were available log tables were used to compute logs and fractional exponents. You say "by hand" but I'm assuming that reasonably sized pre-computed tables are allowed. The method for estimating the log of an arbitrary number is as follows: For example to compute $y=ln(14623)$ the first step is to find $log_{10}(14623)$. $log_{10}(14623)= log_{10}(14.623 \times 10^3)= log_{10}(14.623)+3 $ The log tables are written for base 10 and a reasonable sized one can have results for $log_{10}(a)$ for all $a$ between 1 and 100. We want to find $log_{10}(14.623)+3$. Round it to two significant figures of accuracy and find $log_{10}(15)+3$. Now we just look up $log_{10}(15)$ in the table which is $1.176$, therefore $log_{10}(14.623)+3 \approx 1.176+3=4.176$. But we wanted the natural log so we use the change of base rule. $ln(x)=\frac{log_{10}(x)}{log_{10}(e)}$. We know in advance that $log_{10}(e)=0.434$, therefore $ln(14623)=\frac{4.176}{0.434}=9.616$ The method for computing exponents uses the above method. To find $y=x^a$ first take the log of both sides $log_{10}(y)=log_{10}(x^a)=alog_{10}(x)$ With the log tables we can find $log_{10}(x)$ With a table for exponents it is simple to estimate $y=10^{alog_{10}(x)}$
{ "pile_set_name": "StackExchange" }
Q: Count number of occurences for each unique value Let's say I have: v = rep(c(1,2, 2, 2), 25) Now, I want to count the number of times each unique value appears. unique(v) returns what the unique values are, but not how many they are. > unique(v) [1] 1 2 I want something that gives me length(v[v==1]) [1] 25 length(v[v==2]) [1] 75 but as a more general one-liner :) Something close (but not quite) like this: #<doesn't work right> length(v[v==unique(v)]) A: Perhaps table is what you are after? dummyData = rep(c(1,2, 2, 2), 25) table(dummyData) # dummyData # 1 2 # 25 75 ## or another presentation of the same data as.data.frame(table(dummyData)) # dummyData Freq # 1 1 25 # 2 2 75 A: If you have multiple factors (= a multi-dimensional data frame), you can use the dplyr package to count unique values in each combination of factors: library("dplyr") data %>% group_by(factor1, factor2) %>% summarize(count=n()) It uses the pipe operator %>% to chain method calls on the data frame data. A: It is a one-line approach by using aggregate. > aggregate(data.frame(count = v), list(value = v), length) value count 1 1 25 2 2 75
{ "pile_set_name": "StackExchange" }
Q: How to handle incoming call events in Android Does anybody know if there is any event to handle incoming calls? I'm developing an app that streams audio from the microphone and I would like to have a listener that stops the recording, etc when there is an incoming call, and that restarts the process when the telephone call is over. A: You can create a BroadcastReceiver and listen for the TelephonyManager#ACTION_PHONE_STATE_CHANGED action.
{ "pile_set_name": "StackExchange" }
Q: Rails: HTTP Get request from Callback Method (in model) I want to create a callback in my User model. after a user is created, a callback is initiated to run get_followers to get that users twitter followers (via full contact API). This is all a bit new to me... Is this the correct approach putting the request in a callback or should it be in the controller somewhere? And then how do I make the request to the endpoint in rails, and where should I be processing the data that is returned? EDIT... Is something like this okay? User.rb require 'open-uri' require 'json' class Customer < ActiveRecord::Base after_create :get_twitter private def get_twitter source = "url-to-parse.com" @data = JSON.parse(JSON.load(source)) end A: A few things to consider: The callback will run for every Customer that is created, not just those created in the controller. That may or may not be desirable, depending on your specific needs. For example, you will need to handle this in your tests by mocking out the external API call. Errors could occur in the callback if the service is down, or if a bad response is returned. You have to decide how to handle those errors. You should consider having the code in the callback run in a background process rather than in the web request, if it is not required to run immediately. That way errors in the callback will not produce a 500 page, and will improve performance since the response can be returned without waiting for the callback to complete. In such a case the rest of the application must be able to handle a user for whom the callback has not yet completed.
{ "pile_set_name": "StackExchange" }
Q: AspNetCore.SignalR SendAsync not firing inside OnConnectedAsync I am having an issue where I would like to send an event to the frontend whenever somebody is connected to the hub, but the notification is not being received on the front end. I think I may be confused between calling methods directly from the hub vs. utilizing the IHubContext. I was not able to find much information related to these versions, so your help will be greatly appreciated! Package versions: Server side (.Net Core 2.2): Microsoft.AspNetCore.SignalR (1.1.0) Client side (React): @aspnet/signalr:1.1.0 So this is my example Hub: public class MyHub: Hub<IMyHub> { public override async Task OnConnectedAsync() { // This newMessage call is what is not being received on the front end await Clients.All.SendAsync("newMessage", "test"); // This console.WriteLine does print when I bring up the component in the front end. Console.WriteLine("Test"); await base.OnConnectedAsync(); } public Task SendNewMessage(string message) { return Clients.All.SendAsync("newMessage", message); } } Now the working call I have so far is in a service, but that is sending "newMessage" like so: public class MessageService: IMessageService { private readonly IHubContext<MyHub> _myHubContext; public MessageService(IHubContext<MyHub> myHubContext) { _myHubContext = myHubContext; } public async Task SendMessage(string message) { // I noticed tis calls SendAsync from the hub context, // instead of the SendMessage method on the hub, so maybe // the onConnectedAsync needs to be called from the context somehow also? await _myHubContext.Clients.All.SendAsync("newMessage", message); } } So the above service method call works and will contact the front end, this is an example of my front end connection in a react component: const signalR = require('@aspnet/signalr'); class MessageComponent extends React.Component { connection: any = null; componentDidMount() { this.connection = new signalR.HubConnectionBuilder() .withUrl('http://localhost:9900/myHub') .build(); this.connection.on('newMessage', (message: string) => { // This works when called from the service IHubContext // but not OnConncectedAsync in MyHub console.log(message); }); this.connection.start(); } componentWillUnmount() { this.connection.stop(); } render() { ... } } A: This is because you are using a Strongly Typed Hub (https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.2#strongly-typed-hubs). I assume you defined SendAsync on your IMyHub interface and so the server is sending a message with method = SendAsync, arguments = "newMessage", "test". If you removed your IMyHub type then this will work as expected.
{ "pile_set_name": "StackExchange" }
Q: PL/SQL Pragma incorrectly violated My package header code looks like this: CREATE OR REPLACE PACKAGE INST_PKG IS ... FUNCTION Check_View ( view_name_ IN VARCHAR2 ) RETURN BOOLEAN; PRAGMA restrict_references (Check_View, WNDS); ... END INST_PKG; And the body of the function is defined as follows: CREATE OR REPLACE PACKAGE BODY INST_PKG IS .... FUNCTION View_Exist ( view_name_ IN VARCHAR2 ) RETURN BOOLEAN IS ck_ NUMBER := 0; CURSOR check_view IS SELECT 1 FROM user_views uv WHERE uv.view_name = upper(view_name_); BEGIN OPEN check_view; FETCH check_view INTO ck_; IF check_view%FOUND THEN CLOSE check_view; RETURN true; ELSE CLOSE check_view; RETURN false; END IF; END View_Exist; .... END INST_PKG; I get an error message which reads as follows, when I try to compile the package body: Compilation errors for PACKAGE BODY INST_PKG Error: PLS-00452: Subprogram 'VIEW_EXIST' violates its associated pragma Line: 684 Text: FUNCTION View_Exist ( Clearly, my pragma of "Write No Database State" is not violated, as there are no DML statements in the function. Has anyone seen such behaviour before? Of course, I could drop the Pragma reference, but that would kind of defeat the purpose. Worthy of note: My database has been exported from an Oracle 10g instance, and has been re-imported to 12c. (This is an upgrade test, as you might imagine). Hence I get the above error on Oracle 12c. I have tried to drop and re-create the package, but that doesn't seem to change things. I have a feeling that there may be a library reference somewhere that has been imported in error, because when I drop the package, the same error comes up in another package, which contains a function of the same name. But when I re-create the INST_PKG, the second package compiles fine, almost as though the problem in the first package is masking it from being flagged in the second. A: It emerges from the link you showed, that the issue is a result of a bug in USER_VIEWS (Oracle forgot to associate PRAGMA restrict_references with NO_ROOT_SW_FOR_LOCAL). In this case you can be certain that your function doesn't violate WNDS assertion (doesn't write to the database), therefore just use TRUST option to disable assertions validation during compilation: PRAGMA restrict_references (Check_View, WNDS, TRUST);
{ "pile_set_name": "StackExchange" }
Q: Can I both use T-test and non-parametric T-test for the same data? For example, I want to do test on each variable independently. Some variables are normally distributed, some are log-normally distributed, some just can't be transform to normal distribution (not even by Box-Cox, etc.). Because for each condition, T-test, T-test after log transformation, non-parametric T-test gain highest power than the other two methods. Can I simply use different method for different situation because of high power? I guess the answer is No because of increment of Type I error. But I just cannot understand how does this increase Type I error. Isn't it true that we should use right test (the test that makes right assumption)? To make question more clear. Suppose I have a metabolomics data set, which contains two group, group health (size:15) and group ill (size:15). Columns are 1000 metabolites. So data set is 30*1000. I am trying to figure out which metabolites may be influenced by the treatment. First I do univariate analysis, t-test on each metabolite (More suggestion on statistical methods for omics data analysis is more than welcomed). We don't know about the distribution of each metabolite. So we can only make assumption of normality based on the data we have. So what I try to do here is for each metabolite, if the metabolite is normally distributed , then use t-test; if the metabolites can be transform to normal distribution, after transformation use t-test. Otherwise use non-parametric method for comparing two group means (non-parametric t-test is not a good word). My question is that, can I do so? Thank you! What I am doing is not trying to use the statistical test which gives the smallest p-value for each variable. I believe this is not correct. A: If you choose between tests on the basis of $p$ value then you will inflate your type I error rate, so that you're not conducting your tests at the advertized significance level. [This does increase power, of course, as it does any time you inflate the type I error rate.] How does this occur? Note if the null hypothesis is true* and you have a continuously distributed test statistic, the p-value for a test will be a random uniform. Now if you're generating multiple test statistics they won't be independent, but they will be different (they're not perfectly dependent). As a result, in some situations one test will lead to a smaller p-value, and in other cases another will, and so on. So while each test may have a uniform p-value when the null is true, (and so an $\alpha$ chance of being smaller than $\alpha$), the smallest of several statistics will be more likely to be below $\alpha$. * at the least, lets assume that the distributions under the null are identical, and the individual nulls+associated assumptions are at least approximately true If you're choosing between tests based on some test of normality or even some more visual assessment you actually end up with a very similar issue; the distribution of the p-values of the test you ultimately do is not uniform under the null hypothesis
{ "pile_set_name": "StackExchange" }
Q: llvm's cmake integration I'm currently building a compiler/interpreter in C/C++. When I noticed LLVM I thought it would fit greatly to what I needed and so I'm trying to integrate LLVM in my existing build system (I use CMake). I read this bout integration of LLVM in CMake. I copy and pasted the example CMakeLists.txt, changed the LLVM_ROOT to ~/.llvm/ (that's where I downloaded and build LLVM and clang) and it says it isn't a valid LLVM-install. Best result I could achieve was the error message "Can't find LLVMConfig" by changing LLVM_ROOT to ~/.llvm/llvm. My ~/.llvm/ folder looks like this: ~/.llvm/llvm # this folder contains source files ~/.llvm/build # this folder contains object, executable and library files I downloaded LLVM and clang via SVN. I did not build it with CMake. Is it just me or is something wrong with the CMakeLists.txt? A: This CMake documentation page got rotted, but setting up CMake for LLVM developing isn't different from any other project. If your headers/libs are installed into non-standard prefix, there is no way for CMake to guess it. You need to set CMAKE_PREFIX_PATH to the LLVM installation prefix or CMAKE_MODULE_PATH to prefix/share/llvm/cmake to make it work. And yes, use the second code snippet from documentation (under Alternativaly, you can utilize CMake’s find_package functionality. line).
{ "pile_set_name": "StackExchange" }
Q: Inserting a picture in a title page I am trying to insert a picture in the first page of my report but it is becoming on a separate page or else it comes above the title. I want it to be between author and date: \begin{document} \title{bb} \author{bb} \date {bb} \begin{figure}[] \centering \includegraphics[width=3in]{figure1} \end{figure} \maketitle \end{document} I tried doing as shown below but I got an error with \titlehead: \titlehead{\centering\includegraphics[width=3in]{figure1}} A: It's most easy with the titling package and its maketitlehookxcommands that allow for inserting supplementary material for the \maketitle command. Here is an example: \documentclass[11pt,a4paper,twoside]{report} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[osf]{garamondx} \usepackage[showframe, nomarginpar]{geometry} \usepackage{graphicx} \pagestyle{plain} \usepackage{titling} \title{About Piero di Cosimo} \author{The author} \setlength\droptitle {-38.5mm} \pretitle{\begin{center}\Huge\itshape\bfseries} \posttitle{\end{center}\vskip2cm} \preauthor{\begin{center}\LARGE} \postauthor{\end{center}\vfill} \renewcommand{\maketitlehooka}{% \noindent\includegraphics[width=\linewidth]{Piero_di_Cosimo_1}\par\vskip 3cm}% \begin{document} \maketitle \end{document} ! A: There is no requirement that \includegraphics is in a figure environment, which is for including floating objects (including pictures) with their caption. For your problem, use the titling package that allows customizing the \maketitle command adding items where needed. \documentclass{article} \usepackage{graphicx} \usepackage{titling} % set up \maketitle to accept a new item \predate{\begin{center}\placetitlepicture\large} \postdate{\par\end{center}} % commands for including the picture \newcommand{\titlepicture}[2][]{% \renewcommand\placetitlepicture{% \includegraphics[#1]{#2}\par\medskip }% } \newcommand{\placetitlepicture}{} % initialization \begin{document} \title{A very important paper} \author{A. Uthor} \date{38 July 2014} \titlepicture[width=3in]{example-image} \maketitle \end{document} So long as you have \titlepicture before \maketitle you'll get the picture where you want it. Not specifying \titlepicture will do nothing different from the usual \maketitle.
{ "pile_set_name": "StackExchange" }
Q: Calling SignalR from API at another project - No error nor notification I have a WebSite integrated with SignalR. It functions well, and it has a button which sends popup notification to all clients who are online. It works well when I click on the button. My API is in another project but in the same Solution. I want to send the above notification by calling from the API side. Basically, a mobile app will send a request to API and then API will send a notification to all online web clients. Below code runs and not gives the notification nor any error. Is this fundamentally correct? Appreciate your help API code (at WebAPI project) [HttpGet] public IEnumerable<string> WatchMe(int record_id) { GMapChatHub sendmsg = new GMapChatHub(); sendmsg.sendHelpMessage(record_id.ToString()); return "Done"; } C# code (at Web project) namespace GMapChat { public class GMapChatHub : Hub { public void sendHelpMessage(string token) { var context = GlobalHost.ConnectionManager.GetHubContext<GMapChatHub>(); context.Clients.All.helpMessageReceived(token, "Test help message"); } } } Home.aspx file (at Web project) var chat = $.connection.gMapChatHub; $(document).ready(function () { chat.client.helpMessageReceived = function (token,msg) { console.log("helpMessageReceived: " + msg); $('#helpMessageBody').html(msg) $('#helpModal').modal('toggle'); }; } A: You can not call that hub directly. Firs you need to install the .net client for SignalR from nuget. Then you need to initialize it like this : [HttpGet] public IEnumerable<string> WatchMe(int record_id) { using (var hubConnection = new HubConnection("your local host address")) { IHubProxy proxy= hubConnection.CreateHubProxy("GMapChatHub"); await hubConnection.Start(); proxy.Invoke("sendHelpMessage",record_id.ToString()); // invoke server method } // return sth. IEnumerable<string> } And opening a new connection per request may not be good idea you may make it per session (if you use) or static or time fashioned.
{ "pile_set_name": "StackExchange" }
Q: How to programmatically check if a certificate has been revoked? I'm working on an xcode automated build system. When performing some pre-build validation I would like to check if the specified certificate file has been revoked. I understand that security verify-cert verifies other cert properties but not revokation. How can I check for revokation? I'm writing the build system in Ruby but am really open to ideas in any language. I read this answer (Openssl - How to check if a certificate is revoked or not) but the link towards the bottom (Does OpenSSL automatically handle CRLs (Certificate Revocation Lists) now?) gets into material that's a bit too involved for my purposes (a user uploading a revoked cert is a far out edge case). Is there a simpler / ruby oriented method for checking for revokation? Thanks in advance! A: Checking if a certificate is revoked can be a complex process. First you have to look for a CDP or OCSP AIA, then make a request, parse the response, and check that the response is signed against by a CA that is authorized to respond for the certificate in question. If it is a CRL you then need to see if the serial number of the certificate you're checking is present in the list. If it is OCSP then you need to see if you've received a "good" response (as opposed to unknown, revoked, or any of the various OCSP responder errors like unauthorized). Additionally you may want to verify that the certificate is within its validity period and chains to a trusted root. Finally, you should do revocation checks against every intermediate as well and check the certificate's fingerprint against the explicit blacklists that Mozilla/Apple/Google/Microsoft maintain. I'm unaware of any Ruby libraries that automate the revocation checking process for you (eventually I hope to add it to r509), but given your more specific use case here's some untested code that should point you in the right direction. require 'r509' require 'net/http' cert = R509::Cert.load_from_file("some_iphone_cert.pem") crl_uri = cert.crl_distribution_points.crl.uris[0] crl = Net::HTTP.get_response(URI(crl_uri)) # you may need to follow redirects here, but let's assume you got the CRL. # Also note that the Apple WWDRCA CRL is like 28MB so you may want to cache this damned thing. OCSP would be nicer but it's a bit trickier to validate. parsed_crl = R509::CRL::SignedList.new(crl) if not parsed_crl.verify(cert.public_key) raise StandardError, "Invalid CRL for certificate" end if parsed_crl.revoked?(cert.serial) puts 'revoked' end Unfortunately, due to the enormous size (~680k entries) of the Apple WWDRCA CRL this check can be quite slow with r509's current hash map model. If you're interested in going down the OCSP path I can write up how to generate OCSP requests/parse responses in Ruby as well. Edit: It appears the iPhone developer certificates I have do not contain an embedded OCSP AIA so the only option for revocation checking will be via CRL distribution point as presented above. Edit2: Oh why not, let's do an OCSP check in Ruby! For this we'll need the certificate and its issuing certificate. You can't use a WWDRCA certificate for this so just grab one from your favorite website. I'm using my own website. require 'net/http' require 'r509' cert = R509::Cert.load_from_file("my_website.pem") # get the first OCSP AIA URI. There can be more than one # (degenerate example!) ocsp_uri = cert.aia.ocsp.uris[0] issuer = R509::Cert.load_from_file("my_issuer.pem") cert_id = OpenSSL::OCSP::CertificateId.new(cert.cert,issuer.cert) request = OpenSSL::OCSP::Request.new request.add_certid(cert_id) # we're going to make a GET request per RFC 5019. You can also POST the # binary DER encoded version if you're more of an RFC 2560 partisan request_uri = URI(ocsp_uri+"/"+URI.encode_www_form_component(req_pem.strip) http_response = Net::HTTP.get_response(request_uri) if http_response.code != "200" raise StandardError, "Invalid response code from OCSP responder" end response = OpenSSL::OCSP::Response.new(http_response.body) if response.status != 0 raise StandardError, "Not a successful status" end if response.basic[0][0].serial != cert.serial raise StandardError, "Not the same serial" end if response.basic[0][1] != 0 # 0 is good, 1 is revoked, 2 is unknown. raise StandardError, "Not a good status" end current_time = Time.now if response.basic[0][4] > current_time or response.basic[0][5] < current_time raise StandardError, "The response is not within its validity window" end # we also need to verify that the OCSP response is signed by # a certificate that is allowed and chains up to a trusted root. # To do this you'll need to build an OpenSSL::X509::Store object # that contains the certificate you're checking + intermediates + root. store = OpenSSL::X509::Store.new store.add_cert(cert.cert) store.add_cert(issuer.cert) #assuming issuer is a trusted root here, but in reality you'll need at least one more certificate if response.basic.verify([],store) != true raise StandardError, "Certificate verification error" end The example code above neglects to handle many possible edge cases, so it should be considered a starting point only. Good luck!
{ "pile_set_name": "StackExchange" }
Q: Finding recurrence when Master Theorem fails Following method is explained by my senior. I want to know whether I can use it in all cases or not. When I solve it manually, I come to same answer. $T(n)= 4T(n/2) + \frac{n^2}{\lg n}$ In above recurrence master theorem fails. But he gave me this solution, when for $T(n) = aT(n/b) + \Theta(n^d \lg^kn)$ if $d = \log_b a$ if $k\geq0$ then $T(n)=\Theta(n^d \lg^{k+1})$ if $k=-1$ then $T(n)=\Theta(n^d\lg\lg n)$ if $k<-1$ then $T(n)=\Theta(n^{\log_ba})$ using above formulae, the recurrence is solved to $\Theta(n^2\lg\lg n)$. When I solved manually, I come up with same answer. If it is some standard method, what it is called ? A: OK, try Akra-Bazzi (even if Raphael thinks it doesn't apply...) $$ T(n) = 4 T(n / 2) + n^2 / \lg n $$ We have $g(n) = n^2 / \ln n = O(n^2)$, check. We have that there is a single $a_1 = 4$, $b_1 = 1 / 2$, which checks out. Assuming that the $n / 2$ is really $\lfloor n / 2 \rfloor$ and/or $\lceil n / 2 \rceil$, the implied $h_i(n)$ also check out. So we need: $$ a_1 b_1^p = 4 \cdot (1 / 2)^p = 1 $$ Thus $p = 2$, and: $$ T(n) = \Theta\left(n^2 \left( 1 + \int_2^n \frac{u^2 du}{u^3 \ln u} \right) \right) = \Theta\left(n^2 \left( 1 + \int_2^n \frac{du}{u \ln u} \right) \right) = \Theta(n^2 \ln \ln n) $$ (The integral as given with lower limit 1 diverges, but the lower limit should be the $n_0$ for which the recurrence starts being valid, the difference will usually just be a constant, so using 1 or $n_0$ won't make a difference; check the original paper.) [I've taken the liberty to add this to the Akra-Bazzi examples in the reference question, thanks!]
{ "pile_set_name": "StackExchange" }
Q: python cannot insert string in table I did a coding for dynamic updating table. it gave me output,but i can only insert Integers not strings it gives me "operational error" if i enter strings,I tried altering the table field datatype, but still it accepts integers only,I think it needs a change within the program.Please help: Here's my code: import MySQLdb class data: def __init__(self): self.file123 = raw_input("Enter film: ") self.title_ = raw_input("Enter title: ") self.year = raw_input("Enter year: ") self.director = raw_input("Enter director: ") a=data() db = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="mysql", # your password db="sakila") # name of the data base cursor = db.cursor() query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director) cursor.execute(query) db.commit() db.close() what should i change so that it accepts both integers and strings as input?please help error : Enter film: 123 Enter title: adarsh Enter year: 1234 Enter director: 132 **error** Traceback (most recent call last): File "C:\Python27\maybe1.py", line 22, in <module> cursor.execute(query) File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute self.errorhandler(self, exc, value) File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (1054, "Unknown column 'adarsh' in 'field list'") Datatypes: file123 int(11),title_ varchar(50),year int(11),director varchar(12) A: i think you need to add '%s' for the string and %s to the integers query = "INSERT INTO films (file123, title_, year, director) VALUES ('%s', '%s', %s, '%s')" % (a.file123, a.title_, a.year, a.director) or query = "INSERT INTO films (file123, title_, year, director) VALUES (?,?,?,?)" curs.excute(query,[a.file123, a.title_, a.year, a.director]) Explanation what wrong with your code: self.file123 = raw_input("Enter film: ") self.title_ = raw_input("Enter title: ") self.year = raw_input("Enter year: ") self.director = raw_input("Enter director: ") raw_input("Enter film: ") always a string . so you need to convert each variable to appropriate type eg :file123 to int; year to int now query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director) print query it gives INSERT INTO films (file123, title_, year, director) VALUES (123, adars, 200, sundar) but right format should be INSERT INTO films (file123, title_, year, director) VALUES (123, 'adars', 200, 'sundar') this happens due to %s directly put values as string without quotes so instead of %s use ?
{ "pile_set_name": "StackExchange" }
Q: Get a single character from hex expression? I have a hex value stored in a register such as this one: mov ax,1234h I need to compare each character (1,2,3,4) with a decimal value, ideally I would loop through the characters/numbers in the register but I don't know how to point to each one or if it's even possible. How can this be done? A: given a number such as 1234h divide it by 16, get the remainder, this is your first righ-most number if the result of the division is not zero then repeat using the result of the division as your number. this is the well known base conversion algorithm. you can look it up on wikipedia. http://en.wikipedia.org/wiki/Hexadecimal
{ "pile_set_name": "StackExchange" }
Q: Do you have to ban cellphones and paper to be PCI compliant? Today I heard of a call centre that you are not allowed to bring cellphones into or take paper out of. This is allegedly to be PCI complaint. Is this true? What is the reasoning? This seems like overkill. They said it's to protect credit card information but usually customer service reps (e.g. ones at Starbucks) don't have to do this. A: Short version: The PCI-DSS does not explicitly call out the steps you describe. However, those are common sense steps that are reasonably encompassed by several PCI-DSS requirements. They are not at all uncommon and I have seen them as requirements to non-PCI-DSS contractual agreements by third parties in a card processing environment. Long version: Technically, the PCI-DSS only prescribes security for "system components," not people: The PCI DSS security requirements apply to all system components included in or connected to the cardholder data environment. That said, an awful lot of the DSS touches on policies which impact things other than system components. The following requirements could be reasonably interpreted as being addressed by the two measures (prohibition of uncontrolled data/camera devices in the CDE, control over use of paper in the CDE) you describe: 7.3 Ensure that security policies and operational procedures for restricting access to cardholder data are documented, in use, and known to all affected parties. While 7.3 doesn't say how restrictions should be implemented, it says you should have restrictions around access as part of your policy. Control of phone/camera and paper in the CDE is a reasonable restriction. 9.5 Physically secure all media: Verify that procedures for protecting cardholder data include controls for physically securing all media (including but not limited to computers, removable electronic media, paper receipts, paper reports, and faxes). Keeping paper from leaving the CDE is a form of securing paper media, and keeping cell phones/cameras from entering is control of 'removable electronic media'. 12.3 Develop usage policies for critical technologies and define proper use of these technologies. (... tablets, removable electronic media, e-mail usage and Internet usage.) You'll also note that call centers often disallow access to Internet and email, for the same reason - they're methods that employees could use to get card numbers out of the environment. These requirements are not 'overkill', they're pretty standard. They can cause "real" problems (e.g., not just inconveniencing humans) - for example, how do you email password reset links to call center employees who don't have access to email? How do you verify identity by callback or set up multifactor authentication without soft tokens if there are no personal smartphones? But they do provide a real security value. Which is why you will see these requirements as part of PCI-DSS driven policy and as part of contractual agreements.
{ "pile_set_name": "StackExchange" }
Q: Show that $(1 – \cos θ – \sin θ )^2 – 2(1 – \sin θ )(1 – \cos θ ) = 0$. Show that $(1 – \cos θ – \sin θ )^2 – 2(1 – \sin θ )(1 – \cos θ ) = 0$. What kind of formulas should I use? A: Observe \begin{align} (1-\cos\theta-\sin\theta)^2 & =(1-\cos\theta)^2-2(1-\cos\theta)\sin\theta+\sin^2\theta \\ & = 1 - 2\cos\theta+\color{red}{\cos^2\theta}-2(1-\cos\theta)\sin\theta+\color{red}{\sin^2\theta} \\ & = 1+\color{red}{1}-2\cos\theta -2(1-\cos\theta)\sin\theta\\ & =2(1-\cos\theta)-2(1-\cos\theta)\sin\theta\\ & =2(1-\cos\theta)(1-\sin\theta) \end{align}
{ "pile_set_name": "StackExchange" }
Q: MySQL Join returns more than expected This is a problem that keep me 2 days of sleep. I have 2 tables views id | postid | date | count ================================= 13 | 8 | 2016-07-16 | 38 16 | 8 | 2016-07-17 | 35 15 | 9 | 2016-07-16 | 7 17 | 9 | 2016-07-17 | 32 14 | 12 | 2016-07-16 | 17 18 | 12 | 2016-07-17 | 13 visitors id | postid | date | ip ================================= 13 | 8 | 2016-07-16 | 127.0.0.1 17 | 8 | 2016-07-17 | 127.0.0.1 18 | 8 | 2016-07-17 | 127.0.0.1 16 | 9 | 2016-07-16 | 127.0.0.1 19 | 9 | 2016-07-17 | 127.0.0.1 14 | 12 | 2016-07-16 | 127.0.0.1 15 | 12 | 2016-07-16 | 127.0.0.1 20 | 12 | 2016-07-17 | 127.0.0.1 21 | 12 | 2016-07-17 | 127.0.0.1 And the following query $query = $wpdb->get_results(" SELECT SUM(a.count) AS countviews, COUNT(b.ip) AS countvisitors, a.postid FROM views a RIGHT JOIN visitors b ON a.postid=b.postid AND a.date=b.date WHERE a.date BETWEEN DATE_SUB('2016-07-17', INTERVAL 3 DAY) AND '2016-07-17' GROUP BY a.postid ORDER BY countviews DESC "); When i print_r the output i'll see the following result Array ( [0] => stdClass Object ( [countviews] => 108 [countvisitors] => 3 [postid] => 8 ) [1] => stdClass Object ( [countviews] => 60 [countvisitors] => 4 [postid] => 12 ) [2] => stdClass Object ( [countviews] => 39 [countvisitors] => 2 [postid] => 9 ) ) Only the [countviews] result is higher then expacted. I 'm going to count and see that the countviews from postid 8 must not be '108' but '73'. The stranger thing about it is that the last count of postid 8 is '35'. '108' minus '35' = '73'. So the views tables are count double? RIGHT JOIN, LEFT JOIN and INNER JOIN gives all the same result. A: You cannot make a join here if you want to count. The relation you made is creating multiples of the view table in case there are multiple days in your search parameters for the same postid. You can avoid that by using subqueries: SELECT SUM(a.count) AS countviews, (SELECT COUNT(b.ip) FROM visitors i WHERE b.date BETWEEN DATE_SUB("2016-07-17", INTERVAL 3 DAY) AND "2016-07-17" AND i.postid = a.postid) AS countvisitors, a.postid FROM views a WHERE a.date BETWEEN DATE_SUB('2016-07-17', INTERVAL 3 DAY) AND '2016-07-17' GROUP BY a.postid ORDER BY countviews DESC Hope I got it right. Let me know if this helps :)
{ "pile_set_name": "StackExchange" }
Q: iOS - The best way to measure distance I'm currently working on a project where I need the user to tell where (on the real world map) to build a wall. Question: What (in your opinion) is the most accurate way for the user to show(/tell) where to place the wall? Idea 1 I have thought about drawing on a map, But that wouldn't be so accurate. Idea 2 Another thing that I have thought of is, that the user should place their phone on the beginning and the end of the wall. And in that way the app could use CLLocationManager to print the locations on the map, and also measure the distance between the two ends. This is the code that I tried my thought with, but it wasn't really that accurate at all. let locationManager = CLLocationManager() var location1: CLLocation = CLLocation() var location2: CLLocation = CLLocation() override func viewDidLoad() { super.viewDidLoad() setup() } func setup() { resett.isHidden = true // Ask for Authorisation from the User. self.locationManager.requestAlwaysAuthorization() // For use in foreground self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation locationManager.activityType = .fitness locationManager.startUpdatingLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue:CLLocationCoordinate2D = manager.location!.coordinate currentCord.text = "\(locValue.latitude) \(locValue.longitude)" } func measure(cord1: CLLocation, cord2: CLLocation) -> Float { let distanceInMeters = cord1.distance(from: cord2) //result is in meters return Float(distanceInMeters) } func calculateCoordinates(status: Int) { let coordinate = calculate() if status == 1 { location2 = coordinate let measured = measure(cord1: location1, cord2: location2) print("\(measured) m") displayLabel.text = "\(measured)m" resett.isHidden = false } else { location1 = coordinate } } func calculate() -> CLLocation { let locValue:CLLocationCoordinate2D = locationManager.location!.coordinate let coordinate = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude) return coordinate } @IBAction func FirstAction(_ sender: Any) { button1.setTitle("Klar", for: .normal) calculateCoordinates(status: 0) } @IBAction func SecondAction(_ sender: Any) { button2.setTitle("Klar", for: .normal) calculateCoordinates(status: 1) } Thanks in advance! A: Assuming you mean a real-world "wall", with order of dimension of centimeters to a few meters, the location of the iPhone GPS is really not adapt for these kind of measurments, being the typical minimum error on good covered areas 5 meters. If asking explicitely the geocoordinates (with very high accuracy) is not feasable: I'd rather ask the user explicitly the dimensions and then maybe dragging the object (wall) on the map, zooming as much as possible while approaching the possible final position. PS: there are anyway many optimizations that are possible to be made to increase the accuracy of the CLLocationManager, first of all filtering away results with low accuracy and manually away the one with big horizzontal accuracy issues after receiving it.
{ "pile_set_name": "StackExchange" }
Q: pass to a function an object which is an instance of a subclass of the type accepted by the function is there any way who let the code below works? public function my_function(My_Class $arg){ .... } public class My_Sub_Class extends My_Class { ... } //NOW $my_object = new My_Sub_Class(); my_function($my_object); I've Edited some write errors A: public class My_Sub_Class extends My_Class() { } should be public class My_Sub_Class extends My_Class { } Also, I'm not sure what $my_object = new My_Sub_Class(){ .... } is supposed to be. A My_Sub_Class is not a function! Fixing these errors, adding a definition of My_Class to your testcase, and removing the public prefixes (because your example had no surrounding class definition), I end up with the following, which works just fine: <?php class My_Class {} class My_Sub_Class extends My_Class {} function my_function(My_Class $arg){ echo "my_function"; } $my_object = new My_Sub_Class(); my_function($my_object); ?> Take a look at the extends keyword in the PHP manual. In fact, take a look at every feature you use in the manual, if you can't get something to "work".
{ "pile_set_name": "StackExchange" }
Q: 指定したファイルパスが存在するか確かめたい ~/Desktop/animals/cat.txt が存在するかコマンドで確かめたい。 存在したら Found 存在しなかったら Not found を出力したいです A: ソース [ -e ~/Desktop/animals/cat.txt ] && echo Found || echo Not found 出力 Not found オプション -e ファイルかディレクトリが実在するか判定 -f ファイルが実在するか判定 -d ディレクトリが実在するか判定 -x 実行可能ファイルが実在するか判定 -r 読み込み可能か判定 -w 書き込み可能か判定 この書き方は 短絡評価 といいます
{ "pile_set_name": "StackExchange" }
Q: How to change the starting order number for Commerce 2? I want to change the initial order number for my new Commerce store to 777 instead of 1. For Drupal 7, there is an explanation here, but I know the Commerce architecture has changed a lot. I'm using Drupal 8.4 and Commerce 2.1. The basic approach described is to use a sql query to adjust AUTO_INCREMENT for the order table-- is that still the recommended approach in Commerce 2? A: I used the command in the given explanation on my commerce 2 projects and it worked without any problems. So I am pretty sure you can't do anything wrong with this command.
{ "pile_set_name": "StackExchange" }
Q: Php замена последней буквы Помогите с заменом последней буквы в зависимости от буквы.Тоесть есть имя Рома увидел букву а и поменял на е,или к примеру ещё Роман тоесть конец согласный и добавляет букву у с результатом Роману A: Вот то, что вам нужно: http://morpher.ru/php/ http://namecaselib.com/ru/
{ "pile_set_name": "StackExchange" }
Q: Import entities from local storage when using ASP.NET WebApi OData not loading extra metadata When I try to save imported entities from local storage it thrown exception here. var extraMetadata = aspect.extraMetadata; var uri = extraMetadata.uri || extraMetadata.id; if (core.stringStartsWith(uri, baseUri)) { uri = routePrefix + uri.substring(baseUri.length); } request.requestUri = uri; if (extraMetadata.etag) { request.headers["If-Match"] = extraMetadata.etag; } But if I get data from OData service directly it is saving correctly. Anything I am missing when importing data from local storage. I tried this solution but it didn't help me. A: This is a bug we are tracking (#2574). I was hoping we'd fix it for v.1.4.12 but it looks like it will have to wait a cycle. There is no good workaround. You can try to remember the extraMetadata yourself (in some sideband storage) and re-attach it when you re-import. Not fun I know. Sorry.
{ "pile_set_name": "StackExchange" }
Q: Compare DNS on two different nameservers I am working on switching the nameserves of my domain to a new DNS service. What is the best tool to compare the new settings with the existing DNS setup. I have tried to use dig with and without @nameserver to allow me to make sure that the DNS records match between the old and the new provider. No success so far. Any ideas ? A: I answer that old question, I was confronted with this problem and I solved it this way: For a single domain: diff <(sort -u <(dig +nottlid +noall +answer @ns.myfirstserver.com example.com ANY) ) <(sort -u <(dig +nottlid +noall +answer @ns.mysecondserver.com example.com ANY) ) For multiple domains or subdomains: Create a text file with 1 domain by line (by example: alldomains.txt) The command line: diff <(sort -u <(for host in $(cat alldomains.txt); do dig +nottlid +noall +answer @ns.myfirstserver.com $host ANY; done) ) <(sort -u <(for host in $(cat alldomains.txt); do dig +nottlid +noall +answer @ns.mysecondserver.com $host ANY; done) ) Comments: diff: compare files line by line sort: sort lines of text files -u: make sure that there is only unique line dig: DNS lookup utility +nottlid: do not display the TTL when printing the record +noall: clear all display flags answer: display the authority section of a reply. @ns.server.com: name or IP address of the name server to query ANY: indicates what type of query is required (ANY, A, MX, SIG, etc.) You can redirect to a file by adding > myresult.txt at end. I hope this can help someone.
{ "pile_set_name": "StackExchange" }
Q: Soql in Vf page using sForce.connection I am trying to soql in VF page. But I am not getting an result. I have verified my code. <apex:page > <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="/soap/ajax/33.0/connection.js" type="text/javascript"></script> <script src="/soap/ajax/33.0/apex.js" type="text/javascript"></script> <script type="text/javascript"> function soqlQuery(){ try{ var result = sforce.connection.query("SELECT Id, Name from Account",{ onSuccess : function(result){ alert('I am in 2'); }, onFailure : function(error){ } }); }catch(e){ alert(e); } } window.onload=function(){ soqlQuery(); } </script> </apex:page> Can anyone check and let me know what i am missing out here. A: To get the list of records from result You need result.getArray("records") to get the records complete code <apex:page > <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="/soap/ajax/33.0/connection.js" type="text/javascript"></script> <script src="/soap/ajax/33.0/apex.js" type="text/javascript"></script> <script type="text/javascript"> function soqlQuery(){ try{ sforce.connection.sessionId = '{!$Api.Session_ID}'; var result = sforce.connection.query("SELECT Id, Name from Account",{ onSuccess : function(result){ alert('I am in 2'); var records = result.getArray("records"); console.log('==========records======='+records); }, onFailure : function(error){ } }); }catch(e){ alert(e); } } window.onload=function(){ soqlQuery(); } </script> </apex:page> and check browser console..
{ "pile_set_name": "StackExchange" }
Q: Angular router appends component data instead of replacing the component First of all i tried with this answers but not found my solution: Similar question Let me expalin how i implemented: I have two components forgot-password & new-password When the user submit forgot password form he will get a email verification link. when user clicks that email link it will go to forgot-password.ts file and then in ngOnInit ajax call will go. From ajax response if success data it will redirect to the new-password or it will throw the error in frogot password page itself My issue: when I try to navigate to new-password from forgot-password ts file after ajax response using the external link (Gmail link) ; it appends component data instead of replacing the forgot with new component. My app.moduel.ts: import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserAnimationsModule, }) And this my route code forgot-password.ts : if(result.data == "failure") { // failure no data } else { // success data this._router.navigate(['new-password']); } NOTE When I comment these BrowserAnimationsModule in my app.module.ts the routing is working fine.But I need thisBrowserAnimationsModule.! what is the alternate solution. If not form external link(Gmail) the routing is working fine. A: Update to lastest version of Angular Also, try : if(result.data == "failure") { // failure no data } else { // success data this.zone.run(() =>{ this._router.navigate(['new-password']); }); }
{ "pile_set_name": "StackExchange" }
Q: Does Komodo Edit list variables? I'm using Komodo Edit as an IDE for PERL. Is there a way to show all the declared variables on the side panel? I know it keeps track of it since there is a red wiggly line if I use a variable that has not been previously declared - would be nice if there was a list somewhere. Plugins would be cool too but I can't seem to find any. thanks in advance! Ahdee A: No, that is not possible in Komodo Edit. See the comparrisson page for the additional features the IDE has that Edit doesn't have. The one you want here is called Code Browser. In Komodo IDE however, it is: It is called Code Explorer and you can move it between the left and right panel. You get it by clicking the button which is blue in my screenshot abouve the Text-2.txt file tab, as it starts out being on the right. Note that it does not recognize methods introduced by Moo(se) or variables that are imported through use.
{ "pile_set_name": "StackExchange" }
Q: Como colocar logo na sidebar ou navbar dependendo do tamanho da tela? Gostaria de colocar um Logo (Brand) na sidebar ao invés da navbar para telas maiores e, quando reduzir a proporção da tela (dispositivos móveis e tablets e smarts), o logo deve ir para a navbar usando Media Queries do Bootstrap 3. A: O Bootstrap trás uma série de utilitários responsivos para ajudar a lidar com cenários desse género. Estes utilitários são classes de CSS que visam manipular a apresentação dos elementos com base na tela do dispositivo onde o website se encontra a ser visualizado: Responsive utilities ┌───────────────┬─────────────────────────────────────────────────────────────────────┐ │ │ Dispositivos (pixeis) │ │ ├───────────────┬────────────────┬─────────────────┬──────────────────┤ │ CSS Class │ Extra small │ Small │ Medium │ Large │ │ │ Phones (<768) │ Tablets (≥768) │ Desktops (≥992) │ Desktops (≥1200) │ ├───────────────┼───────────────┼────────────────┼─────────────────┼──────────────────┤ │ .visible-xs-* │ Visivel | Escondido | Escondido | Escondido | ├───────────────┼───────────────┼────────────────┼─────────────────┼──────────────────┤ │ .visible-sm-* │ Escondido │ Visivel │ Escondido │ Escondido │ ├───────────────┼───────────────┼────────────────┼─────────────────┼──────────────────┤ │ .visible-md-* │ Escondido │ Escondido │ Visivel │ Escondido │ ├───────────────┼───────────────┼────────────────┼─────────────────┼──────────────────┤ │ .visible-lg-* │ Escondido │ Escondido │ Escondido │ Visivel │ ├───────────────┼───────────────┼────────────────┼─────────────────┼──────────────────┤ │ .hidden-xs │ Escondido │ Visivel │ Visivel │ Visivel │ ├───────────────┼───────────────┼────────────────┼─────────────────┼──────────────────┤ │ .hidden-sm │ Visivel │ Escondido │ Visivel │ Visivel │ ├───────────────┼───────────────┼────────────────┼─────────────────┼──────────────────┤ │ .hidden-md │ Visivel │ Visivel │ Escondido │ Visivel │ ├───────────────┼───────────────┼────────────────┼─────────────────┼──────────────────┤ │ .hidden-lg │ Visivel │ Visivel │ Visivel │ Escondido │ └───────────────┴───────────────┴────────────────┴─────────────────┴──────────────────┘ Solução Para o teu caso, a solução passa por ter a Brand nos dois locais desejados, aplicando na mesma as classes de CSS em cima apresentadas para que ou apareça na NavBar ou apareça na SideBar consoante o pretendido: Ver exemplo no JSFiddle onde podes arrastar a largura da janela de preview para visualizares a Brand a aparecer ou esconder mediante a largura da tela: NavBar Esconder em ecrãs Desktops (≥1200) pixeis largura: <a class="navbar-brand hidden-lg" href="#">Project name</a> SideBar Esconder em ecrãs Phones (<768), Tablets (≥768) e Desktops (≥992) pixeis largura: <a class="hidden-sm hidden-xs hidden-md" href="#">Project name</a> HTML para demonstração <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand hidden-lg" href="#">Project name</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-sm-8"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras euismod hendrerit mauris, eget dictum turpis pulvinar semper. Etiam finibus tortor nec mi sodales malesuada. Vestibulum sed dolor id lorem viverra dignissim. Nullam hendrerit nunc vel quam dignissim interdum ut vel nulla. Maecenas nec venenatis nibh, et vehicula odio. Nullam gravida nulla a suscipit aliquam. Vivamus porta est dolor, id tristique massa ultrices ac. Morbi aliquam risus in risus sollicitudin dapibus. Vivamus malesuada interdum neque, aliquet elementum quam porta non. Aenean ac mauris tempus, vestibulum neque id, imperdiet erat. Aliquam et nunc nec nibh convallis tempus vitae at ex. Aenean quis odio nec augue dapibus vulputate non vel lacus. </div> <div class="col-sm-4"> <a class="hidden-sm hidden-xs hidden-md" href="#">Project name</a> </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: HTML5 input date type is not storing in a consistent format I am having an issue when using the HTML5 input fields with type set to "date". My test page is as follows: <!DOCTYPE html> <html> <head> <script> function testDate() { window.alert("Date: " + document.getElementById("date").valueAsDate.toJSON()); } </script> </head> <body> <form> <label for="date">Date</label> <input id="date" type="date" onchange="testDate()" required /> </form> </body> </html> If I load this page in Opera, I am presented with a 'date picker'. If I select the 10th of August 2016, I am presented with a popup window which exhibits the correct behavior i.e. it displays the following: "Date: 2016-06-10T00:00:00.000Z" If I load the page in Firefox, I do not get any kind of 'date picker' and it will let me enter any value I want. I have tried the following input: 10/08/2016 10-08-2016 2016-08-10 In all cases I get the following logged to the console: TypeError: document.getElementById(...).valueAsDate is undefined In my real code, I simply want to allow a user to select a date, convert it to a JSON date, and then send it over an XMLHttpRequest, but I can't seem to find any consistency in the date format. Can someone assist? A: Currently it is too soon for using the fields if you are not creating the browser-specific web application. As you can see here - Firefox, Safari and Internet Explorer has no support for this kind of input fields. You can try to use the pattern attribute which can be used for a simple validation of the user input. It has a better support, but still it is not perfect. You can also try to use one of these vanillaJS datepicker implementations.
{ "pile_set_name": "StackExchange" }
Q: Buggy fade in/out code in JavaScript/CSS I'm not the most proficient in coding and have been stuck at trying to get this function working right for days and hope that someone could help me... The idea is for the red div to show by default and the blue/yellow divs to be called upon by pressing the 'fade 1' and 'fade 2' buttons. When either of the buttons are pressed the red div is hidden and wont be called for. The current code bugs up when the buttons are pressed continuously, they either wont show, the fade effect wont work or the red div appears. Thanks! <!DOCTYPE html> <html> <head> <style type="text/css"> .myBtn { width:80px; } #myImg0 { -webkit-transition: opacity 0.5s ease-in; -moz-transition: opacity 0.5s ease-in; -o-transition: opacity 0.5s ease-in; position:absolute; background-color:red; width: 100px; height: 100px; } #myImg1 { -webkit-transition: opacity 0.5s ease-in; -moz-transition: opacity 0.5s ease-in; -o-transition: opacity 0.5s ease-in; position:absolute; background-color:blue; width: 100px; height: 100px; } #myImg2 { -webkit-transition: opacity 0.5s ease-in; -moz-transition: opacity 0.5s ease-in; -o-transition: opacity 0.5s ease-in; position:absolute; background-color:yellow; width: 100px; height: 100px; } #myImg1.fade-out { opacity:0; } #myImg1.fade-in { opacity:1; } #myImg2.fade-out { opacity:0; } #myImg2.fade-in { opacity:1; } .hide {display: none;} </style> <script type="text/javascript"> function fade1(btnElement) { if (btnElement.value === "Fade Out") { document.getElementById("myImg0").className = "fade-out"; document.getElementById("myImg2").className = "fade-out"; btnElement.value = "Fade In"; } else { document.getElementById("myImg1").className = "fade-in"; btnElement.value = "Fade Out"; } } function fade2(btnElement) { if (btnElement.value === "Fade Out") { document.getElementById("myImg0").className = "fade-out"; document.getElementById("myImg1").className = "fade-out"; btnElement.value = "Fade In"; } else { document.getElementById("myImg2").className = "fade-in"; btnElement.value = "Fade Out"; } } </script> </head> <body> <input class="myBtn" type="button" value="Fade 1" onclick="fade1(myImg1);" /> <input class="myBtn" type="button" value="Fade 2" onclick="fade2(myImg2);" /> <div id="myImg0" ></div> <div id="myImg1" class="hide" ></div> <div id="myImg2" class="hide" ></div> </body> </html> A: You could use jquery like this- jsFiddle $(document).ready(function () { $(".fade1").click(function () { $("#myImg1").fadeToggle(); $("#myImg2").fadeOut(); }); }); $(document).ready(function () { $(".fade2").click(function () { $("#myImg2").fadeToggle(); $("#myImg1").fadeOut(); }); });
{ "pile_set_name": "StackExchange" }
Q: Django, how to use 'group by' and 'max' to get complete row in queryset and display related items in template I have a model like this: models.py class Talk_comment(models.Model): user = models.ForeignKey(User_info, null=True) talk = models.ForeignKey(Talk) comment = models.CharField(max_length=500) class Talk(models.Model): user = models.ForeignKey(User_info, null=True) title = models.CharField(max_length=150) slug = models.SlugField(max_length=50) My DB looks like this for Talk_comment: id | user_id | talk_id | comment 1 10 45 first comment 2 5 45 second comment 3 5 45 third comment 4 10 45 fourth comment Now I want to get rows with maximum id for a user(max 'id', group by 'user_id'). In this case I want rows with id '3' and '4'. To get this I have following code in my view. views.py qs = Talk_comment.objects.values('user').annotate(Max('id')) Now in my template I want the following: How to get this?? Please help template.html {% for x in qs %} <li> {{ x.comment }} in talk {{ x.talk.title }} </li> {% endfor %} A: I have found the solution for this, new querysets in views.py will be as follows: id_list = Talk_comment.objects.filter(user=user_info_obj).values('user','talk').annotate(Max('id')).values('id__max') qs = Talk_comment.objects.filter(pk__in=id_list)
{ "pile_set_name": "StackExchange" }
Q: Two navbars below the other one with bootstrap I'm starting with Bootstrap and have a small problem with the navbar-element. I need to declare a container with the width of 1024px and have to add two navbars. On at the top and the other one below it. Both navbars need a distance from the right div of 0px. (Stackoverflow doesn't want to let me post pictures, but I think it's much more easier if you can see what I mean: http://www.abload.de/img/asdjraik.png) As you can see the first navbar is working correctly, but now I need another one below it. Padding from the container under it should be exactly 5px. My problem is, that the other navbar gains the same padding from the top as the first navbar. I can't get it below the other one. When I define the following classes for this problem another one comes up: .small-margin { margin-top: 20px; } .big-margin { margin-top: 110px; } My HTML looks like this: <div class="navbar small-margin"> <div class="navbar-inner"> <div class="pull-right"> <ul class="nav"> <li><a href="#">link 1</a></li> <li><a href="#">link 2</a></li> </ul> </div> </div> </div> <div class="clear"></div> <div class="navbar big-margin"> <div class="navbar-inner"> <div class="pull-right"> <ul class="nav"> <li><a href="#">another link 1</a></li> <li><a href="#">another link 2</a></li> </ul> </div> </div> </div> The second navbar appears on the left side of the first navbar and not below it. I tried a lot of CSS-fixes. Anyone have a idea how to get the 2nd navbar below the first? Thanks in advance! A: I've tried your code and it's works I also tried adding it into 1024px container .container{ max-width: 1024px; } this is the result Your css code must be conflicted with the bootstrap. maybe you could try wrapping each navbar with .row. I believe that this solution is surely make all navbar separated. <div class="row-fluid"> <div class="span12"> ... navbar 1 ... </div> </div> <div class="row-fluid"> <div class="span12"> ... navbar 2 ... </div> </div>
{ "pile_set_name": "StackExchange" }
Q: A nicer way to write a CHECK CONSTRAINT that checks that exactly one value is not null Imagine that I have a table with integer columns Col1, Col2, Col3, Col4. Each column is nullable and a valid row must contain a value in exactly 1 columns (i.e. all nulls is invalid and more than 1 column is also invalid). At the moment I have a check constraint like this ALTER TABLE [dbo].[MyTable] WITH CHECK ADD CONSTRAINT [CK_ReportTemplateAttributes] CHECK (( [Col1] IS NOT NULL AND [Col2] IS NULL AND [Col3] IS NULL AND [Col4] IS NULL OR [Col1] IS NULL AND [Col2] IS NOT NULL AND [Col3] IS NULL AND [Col4] IS NULL OR [Col1] IS NULL AND [Col2] IS NULL AND [Col3] IS NOT NULL AND [Col4] IS NULL OR [Col1] IS NULL AND [Col2] IS NULL AND [Col3] IS NULL AND [Col4] IS NOT NULL )); GO; It works but it strikes me that there might be a more elegant way to achieve the same result (for example this questioner wants to check that at least 1 field is not null and the COALESCE keyword works well in that case). A: To riff on the other answer here, I think this is a little more self-documenting: ALTER TABLE [dbo].[MyTable] WITH CHECK ADD CONSTRAINT [CK_ReportTemplateAttributes] CHECK (1 = CASE when [Col1] IS NULL THEN 0 ELSE 1 END + CASE when [Col2] IS NULL THEN 0 ELSE 1 END + CASE when [Col3] IS NULL THEN 0 ELSE 1 END + CASE when [Col4] IS NULL THEN 0 ELSE 1 END ) ; It also has the benefit of avoiding the bug where you alter the constraint to take another column into consideration but forget to update the "3" to "[number of columns in constraint] - 1". A: The most concise way I can think of at the moment is. ALTER TABLE [dbo].[MyTable] WITH CHECK ADD CONSTRAINT [CK_ReportTemplateAttributes] CHECK (3 = ISNULL([Col1] - [Col1],1) + ISNULL([Col2] - [Col2],1) + ISNULL([Col3] - [Col3],1) + ISNULL([Col4] - [Col4],1)) ;
{ "pile_set_name": "StackExchange" }
Q: Getting device ID to show Admob Interstitial Ads I have previously used Admob, but only to display Banner Ads. Now on my latest App I'd like to use Interstitial Ads, but I have some doubts about it. According to the documentation, in order to request for a new Ad, I need to do something like this: AdRequest adRequest = new AdRequest.Builder() .addTestDevice("Device_ID") .build(); The problem is that I don't know how to get the device ID programatically, since I guess it's a different one on each device. What I've done so far to dislpay Interstitial test ads on my device is calling the .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) method. So it's pretty much working fine on my device. The main problem is that I want to be able to display interstitial ads on multiple devices, but I sincerely don't know how to get the ID programatically to get it to work in any device. Thanks in advance! A: Here is what I usually use on my apps : public static String getMD5(String inputText){ String md5 = ""; try{ MessageDigest digester = MessageDigest.getInstance("MD5"); digester.update(inputText.getBytes()); md5 = new BigInteger(1, digester.digest()).toString(16); } catch(Exception e){} return md5; } public String getDeviceId(){ String androidID = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID); String deviceID = getMD5(androidID).toUpperCase(); return deviceID; }
{ "pile_set_name": "StackExchange" }
Q: Command-line to switch between profiles in gnome-terminal I created a new profile for gnome-terminal and I can switch between "Implicit" profile and the new created profile as you can see in the below image: Now I wonder how can I switch between profiles using a command-line/script or maybe using a shortcut for this. Note: Solutions like: gnome-terminal --tab-with-profile=Implicit && exit are excluded because I prefer not to close and open another terminal or get another terminal window in this process of changing the profile. A: To switch to the "implicit" profile: xdotool key Alt+t p Return To switch to the second profile: xdotool key Alt+t p Down Return xdotool is not installed by default in Ubuntu, so it must to be installed first. Of course, for these commands can be added custom keyboard shortcuts. A: A lot of great answers already but I wanted to add one more variation using xdotool that does not require the menu bar to be visible... The key combo shift+F10 will open a pop-up menu (the equivalent of right-clicking on terminal) and from there the profile can be changed. e.g. xdotool key shift+F10 r 3 to get to the third profile I've also found that this method does not require setting a delay for xdotool (which I found necessary for the menu bar method) so it's therefore a little faster. I tend to change profiles a lot so I wrap this into a function: function chp(){ xdotool key --clearmodifiers Shift+F10 r $1 } so I can just call chp N to switch to the Nth profile. Some more tips and idiosyncrasies of my setup: By adding a chp command to my .bashrc I can force new tabs to always switch to the default profile I color code my ssh sessions based on host but I don't like my ssh alias to open new tabs or windows AND I want the profile to change back to the default when I exit ssh. My solution: alias somehost="chp 2; ssh user@somehost; chp 1" I give xdotool the flag --clearmodifiers so that if I happen to be holding a modifier key (when opening a tab/window, exiting ssh, etc.), it won't interfere with xdotool. I prepend my profile names with numbers so that if I add a new one, it doesn't shift all the others due to the alphabetizing of the profile menu A: There is no shortcut that allows you to change the profile within the terminal (without navigating the menus as you said in comments), without the use of the GUI. Quoting the manual (stable, development 3.9): You can change the profile in your current Terminal tab or window by selecting a profile from Terminal ▸ Change Profile. (You can propose this as suggestion in the bug tracker)
{ "pile_set_name": "StackExchange" }
Q: Javascript Objects and jQuery I'm not sure what the best way to approach this is. I have a control that I want to be able to open and persist some data or change it on the fly. function TaskControl(params) { this.params = params; this.openTaskControl = function () { alert("openTaskControl"); } $("#button").click(function () { this.openTaskControl(); }); } The problem I'm having is that trying to call openTaskControl throws an error because this apparently refers to the HTML element and not the TaskControl. How do I call this function from inside the click function? A: function TaskControl(params) { this.params = params; var that = this; this.openTaskControl = function () { alert("openTaskControl"); } $("#button").click(function () { that.openTaskControl(); }); } A: The inner scope will refer to a different this object. Use variables instead: function TaskControl(params) { var paramsSave = params; var openTaskControl = function () { alert("openTaskControl"); } $("#button").click(function () { openTaskControl(); }); }
{ "pile_set_name": "StackExchange" }
Q: limits of diamond anvils for high pressure research in this wikipedia article regarding diamond anvils, it mentions that the pressure peaks roughly at 300 GPa. My question is why is this so? is the diamond crystal structure collapsing if higher pressures are applied (like 500-600 Gpa, where metallic hydrogen is expected to form? and if such collapse happens, what sort of phase does the diamond collapses into? A: The compressive strength of a perfect diamond cristal is in the range of 220–470 GPa, depending on the direction you compress. (X. Luo et al, J. Phys. Chem. C 2010, 114, 17851–17853; DOI: 10.1021/jp102037j) To cite this article’s introduction: Usually, diamond is used under nonhydrostatic conditions, such as a diamond indenter in the nanoindentation test and as diamond tips of the diamond anvil cell (DAC) in ultrahigh-pressure research. Therefore, theoretical investigations into the mechanical properties of diamond under nonhydrostatic conditions should be important. […] In experimental work, the compressive strength of diamond can be roughly obtained from the strength of DAC. And the conclusion: From the mechanism under compressive deformation of diamond, we can estimate that the limit strength of DAC should be about 470 GPa.
{ "pile_set_name": "StackExchange" }
Q: objects unable to change its own member's values I have created object type a which has member x and y, also some functions changing the members' value. I have seen the members been changed in debugger. But none of the members are changed. Can you explain? Is there any difference in behaviour of x and y? one is local variable and the other is a parameter. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <div id="debug"></div> <script src="Scripts/jquery-2.0.0.min.js"></script> <script> function a(y) { var x = 0; return { x: x, y: y, getX: getX, getY: getY, processX: processX, processY: processY, } function getX() { return x; } function getY() { return y; } function processX() { this.x = 1; } function processY() { this.y = 100; } } $(function () { var objs = []; for (var i = 0; i < 3; i++) { objs[i] = a(i); } objs[0].processX(); objs[1].processY(); objs.forEach(function (o) { $("#debug").append($("<p>").text(o.x + " " + o.y)); $("#debug").append($("<p>").text(o.getX() + " " + o.getY())); //result: //1 0 //0 0 //0 100 //0 1 //0 2 //0 2 }); }); </script> </body> </html> Strangely if i write a function to access the members, the correct values can be obtained. why??? A: You have to explicitly involve this when you want to modify object properties: function getX() { return this.x; } function getY() { return this.y; } function processX() { this.x = 1; } function processY() { this.y = 100; } In your original code, references to "x" and "y" inside those four functions would be resolved to the local variables "x" and "y" inside the outer function (the function called "a"). That "a" function includes a parameter called "y" and a var declaration for "x".
{ "pile_set_name": "StackExchange" }
Q: How does Weasley's Wizard Wheezes stay in business? We know Fred and George's shop is immensely popular with wizard kids. However, a large majority, about 97%, go to a boarding school year round. I could understand if they had a shop in Hogsmeade, but it is in Diagon Alley. I also know they have a delivery service, but is it really enough to keep them in business? A: The twins have a line of Defense Against the Dark Arts products that provided quite a bit of business for them during the events of book 6: "Giving him the tour? Come through the back, Harry, that's were we're making the real money....."We've just developed this more serious line", said Fred. "Funny how it happened...you wouldn't believe how many people, even people who work at the Ministry, can't do a decent Shield Charm", said George.... "The Ministry bought five hundred for all its support staff. And we're still getting massive orders. So we've expanded into a range of Shield Cloaks, Shield Gloves.." As to the effectiveness, it is likely that the magic is fairly good, as Hermione proclaims about another of their (the twins) magical products: "You know, said Hermione, looking up at Harry, "that really is extraordinary magic!" Additionally, to the point about student orders, they have mail order and their Skiving Snackboxes, Love Potions, and other products are things that students may be more inclined to send away for than purchase with parents in tow. - Harry Potter and the Half-Blood Prince, Chapter 6 - Draco's Detour JK Rowling also stated in 2007 that after the war, Ron joined George at the shop and the two continued the success started by Fred and George: J.K. Rowling: Ron joined George at Weasleys' Wizarding Wheezes, which became an enormous money-spinner. J.K. Rowling: Well, I don't think that George would ever get over losing Fred, which makes me feel so sad. However, he names his first child and son Fred, and he goes on to have a very successful career, helped by good old Ron. A: Fred and George get a lot of mail orders, not just in-store sales. Fred and George sell a lot by mail order, in addition to what they sell in their shop. Their business was originally run entirely by mail order, and they’d been selling mail order products before they quit Hogwarts and decided to run their business full time. They only started selling in a store after Harry gave them his Triwizard winnings and they were able to find a place. “Joke shop still on, then?’ Harry muttered, pretending to be adjusting the nozzle on his spray. ‘Well, we haven’t had a chance to get premises yet,’ said Fred, dropping his voice even lower as Mrs Weasley mopped her brow with her scarf before returning to the attack, ‘so we’re running it as a mail-order service at the moment. We put advertisements in the Daily Prophet last week.” - Harry Potter and the Order of the Phoenix, Chapter 6 (The Noble and Most Ancient House of Black) Fred and George still ran a mail order portion of Weasleys’ Wizard Wheezes even after they got their shop, and sent their products directly to Hogwarts when the students there ordered from them. “But I thought all the owls were being searched? So how come these girls are able to bring love potions into school?’ ‘Fred and George send them disguised as perfumes and cough potions,’ said Hermione. ‘It’s part of their Owl Order Service.” - Harry Potter and the Half-Blood Prince, Chapter 15 (The Unbreakable Vow) So, Hogwarts students would be able to buy from them year-round, and they did. In addition, Hogwarts students aren’t their only customers. Though Hogwarts students would be a large part of their customers, Fred and George also had others. There’s a group of ten-year-olds in their shop, who’d all be too young for Hogwarts. “A space cleared in the crowd and Harry pushed his way towards the counter, where a gaggle of delighted ten-year-olds was watching a tiny little wooden man slowly ascending the steps to a real set of gallows, both perched on a box that read: Reusable Hangman – Spell It Or He’ll Swing!” - Harry Potter and the Half-Blood Prince, Chapter 6 (Draco’s Detour) In addition, since they’ve expanded to selling things other than joke products, they’d bring in even more types of customers. Their Wonder Witch products, like Ten-Second Pimple Vanisher, could appeal to witches who’ve left Hogwarts as well. Pygmy Puffs could appeal to anyone who wants a cute pet that’s easy to take care of. Their Defense Against the Dark Arts products would appeal to anyone who wants extra protection, including the Ministry.
{ "pile_set_name": "StackExchange" }
Q: Printing prime factors of a number using a "points system" We've been given a challenge to write a program that prints prime factors of an input number. We're given an outline: the program checks for factors of the original number; each such factor gets one point. Then, if that factor is prime, it gets another point. Each factor with two points gets printed. Here's what I have so far. print('Please enter a number') x = int(input('Number:')) a = int(0) b = int(0) c = int(1) d = int(0) counter = int(0) while (a < x-1): a = a + 1 counter = 0 if (x / a % 1 == 0): b = a counter = counter + 1 while(c < b - 1): c = c + 1 if((b / c) % 1 != 0): d = b counter = counter + 1 if(counter == 2): print(d) With input of 15, I get 3 and 5, but also 15 (wrong). With 24, I get 3, 4, 6, 8, and 12; several of these are not prime. I believe the issue lies somewhere in the innermost loop, but I can't pinpoint the problem. At first the issue was I wasn't resetting the "counter", so future factors would exceed 2 "points" and nothing would print. I fixed that by resetting it before it enters the innermost loop, but sadly, that didn't fix the problem. I've also tried getting rid of 'b' and 'd' and just using two variables to see if I was somehow overcomplicating it, but that didn't help either. EDIT: Edited slightly for clarity. A: Your first sentence was enough of a clue for me to unravel the rest of your posting. Your main problems are loop handling and logic of determining a prime factor. In general, I see your program design as Input target number Find each factor of the number For each factor, determine whether the factor is prime. If so, print it. Now, let's look at the innermost loop: while(c < b - 1): c = c + 1 if((b / c) % 1 != 0): d = b counter = counter + 1 if(counter == 2): print(d) As a styling note, please explain why you are building for logic from while loops; this makes your program harder to read. Variable d does nothing for you. Also, your handling of counter is an extra complication: any time you determine that b is a prime number, then simply print it. The main problem is your logical decision point: you look for factors of b. However, rather than waiting until you know b is prime, you print it as soon as you discover any smaller number that doesn't divide b. Since b-1 is rarely a factor of b (only when b=2), then you will erroneously identify any b value as a prime number. Instead, you have to wait until you have tried all possible factors. Something like this: is_prime = True for c in range(2, b): if b % c == 0: is_prime = False break if is_prime: print(b) There are more "Pythonic" ways to do this, but I think that this is more within your current programming sophistication. If it's necessary to fulfill your assignment, you can add a point only when you've found no factors, and then check the count after you leave the for loop. Can you take it from there?
{ "pile_set_name": "StackExchange" }
Q: sql primary key and index Say I have an ID row (int) in a database set as the primary key. If I query off the ID often do I also need to index it? Or does it being a primary key mean it's already indexed? Reason I ask is because in MS SQL Server I can create an index on this ID, which as I stated is my primary key. Edit: an additional question - will it do any harm to additionally index the primary key? A: You are right, it's confusing that SQL Server allows you to create duplicate indexes on the same field(s). But the fact that you can create another doesn't indicate that the PK index doesn't also already exist. The additional index does no good, but the only harm (very small) is the additional file size and row-creation overhead. A: As everyone else have already said, primary keys are automatically indexed. Creating more indexes on the primary key column only makes sense when you need to optimize a query that uses the primary key and some other specific columns. By creating another index on the primary key column and including some other columns with it, you may reach the desired optimization for a query. For example you have a table with many columns but you are only querying ID, Name and Address columns. Taking ID as the primary key, we can create the following index that is built on ID but includes Name and Address columns. CREATE NONCLUSTERED INDEX MyIndex ON MyTable(ID) INCLUDE (Name, Address) So, when you use this query: SELECT ID, Name, Address FROM MyTable WHERE ID > 1000 SQL Server will give you the result only using the index you've created and it'll not read anything from the actual table. A: NOTE: This answer addresses enterprise-class development in-the-large. This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed. In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index. Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows. The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table. I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.
{ "pile_set_name": "StackExchange" }
Q: Jquery UI Issue with slide Here is my fiddle https://jsfiddle.net/4nnfzz5a/6/ When you click yes on 3, 4 moves down then comes back up. It looks like there is some CSS being added to #q2 A: No need to add multiple event handler you can do that with single handler. Used prev() & next() to show/hide panel. $(".panel-body input[type='radio']").change(function() { if ($(this).val() == 'yes') { $(this).parents('.panel').hide(); $(this).parents('.panel').next().show("slide", { direction: "right" }, 500); } else { $('#alert').show("slide", { direction: "up" }, 500); } }); $(".panel-heading .back").click(function() { $(this).parents('.panel').hide(); $(this).parents('.panel').prev().show("slide", { direction: "right" }, 500); }); #q1 { text-align: center; } #q2 { text-align: center; } #q3 { text-align: center; } #q4 { text-align: center; } #q5 { text-align: center; } .unsure { font-size: 20px; } .unsure a { color: #1e5973; text-decoration: underline; } #texta { margin-top: 25px; text-align: left; } #q5cdq { font-size: 18px; } .back { font-size: 13px; margin-bottom: 0px; float: left; cursor: pointer; margin-right: 15px; } .q5cdqa { text-align: left; } .center { text-align: center; } #q5faq { font-size: 18px; } #q5faq a { color: #1e5973; text-decoration: underline; } #q5n a { color: #1e5973; text-decoration: underline; } #q5wct a { color: #1e5973; text-decoration: underline; } #q5ilt a { color: #1e5973; text-decoration: underline; } div#q5wct { font-size: 18px; } div#q5ilt { font-size: 18px; } p.cdq img { width: 30px; height: 30px; } p.no img { width: 30px; height: 30px; } p.faq img { width: 30px; height: 30px; } p.wct img { width: 30px; height: 30px; } p.ilt img { width: 30px; height: 30px; } p.no { font-size: 30px; } p.faq { font-size: 30px; } p.cdq { font-size: 30px; } p.cdq:hover { color: #1e5973; cursor: pointer; } p.no:hover { color: #1e5973; cursor: pointer; } p.faq:hover { color: #1e5973; cursor: pointer; } p.wct:hover { color: #1e5973; cursor: pointer; } p.ilt:hover { color: #1e5973; cursor: pointer; } #checkbox { margin-top: 25px; } label { padding-right: 50px; padding-left: 50px; } label>input { /* HIDE RADIO */ visibility: hidden; /* Makes input not-clickable */ position: absolute; /* Remove input from document flow */ } label>input+img { /* IMAGE STYLES */ cursor: pointer; border: 2px solid transparent; } label>input:checked+img { /* (RADIO CHECKED) IMAGE STYLES */ border: 2px solid #f00; } .lightbox_title { font-family: Roboto; font-weight: 700; color: #1e5973; vertical-align: middle; padding-left: 20px; } .panel { margin-bottom: 20px; background-color: #fff; border: 1px solid transparent; border-top-color: transparent; border-right-color: transparent; border-bottom-color: transparent; border-left-color: transparent; border-radius: 4px; -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05); box-shadow: 0 1px 1px rgba(0, 0, 0, .05); } .panel-default { border-color: #ddd; } .panel-default>.panel-heading { color: #64656a; background-color: #c2cdd2; border-color: #ddd; } .panel-heading { padding: 10px 15px; border-bottom: 1px solid transparent; border-bottom-color: transparent; border-top-left-radius: 3px; border-top-right-radius: 3px; } .panel-title { margin-top: 0; margin-bottom: 0; color: inherit; font-family: Roboto; font-weight: 700; font-size: 24px; } .panel-body { background-color: #42afdf; margin: auto; margin-top: auto; } .questions { font-family: Nunito; color: #fff; font-size: 20px; padding: 15px; } .alert-danger { color: #a94442; background-color: #f2dede; border-color: #ebccd1; } .alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-top-color: transparent; border-right-color: transparent; border-bottom-color: transparent; border-left-color: transparent; border-radius: 4px; } .none { display: none; } #logo { vertical-align: middle; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script> <!-- Start Red Alert--> <div id="alert" class="alert alert-danger exit" role="alert" style="display:none;"> <span>NIH does <b>not</b> consider your study to be a clinical trial.<span><br /><br />Make sure you select a funding opportunity announcement (FOA) that is NOT specifically for clinical trials. </div> <!-- End Red Alert--> <!-- Start Question 1--> <div id="q1" class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">1</h3> </div> <div class="panel-body"> <div class="questions"> <p class="unsure">1</p> <div id="checkbox"> <label> <input type="radio" name="q1" value="yes" />YES </label> <label> <input type="radio" name="q1" value="no"/>NO </label> </div> </div> </div> </div> <!-- End Question 1--> <!--Question 2--> <div id="q2" class="panel panel-default" style="display:none;"> <div class="panel-heading"> <h3 class="panel-title"><span class="back">< Back </span> 2</h3> </div> <div class="panel-body"> <div class="questions"> <p class="unsure">2</p> <div id="checkbox"> <label> <input type="radio" name="q2" value="yes" />YES </label> <label> <input type="radio" name="q2" value="no"/>NO </label> </div> </div> </div> </div> <!--End Question 2--> <!--Question 3--> <div id="q3" class="panel panel-default" style="display:none;"> <div class="panel-heading"> <h3 class="panel-title"><span class="back">< Back </span> 3</h3> </div> <div class="panel-body"> <div class="questions"> <p class="unsure">3</p> <div id="checkbox"> <label> <input type="radio" name="q3" value="yes" />YES </label> <label> <input type="radio" name="q3" value="no"/>NO </label> </div> </div> </div> </div> <!--End Question 3--> <!--Question 4--> <div id="q4" class="panel panel-default" style="display:none;"> <div class="panel-heading"> <h3 class="panel-title"><span class="back">< Back </span> 4</h3> </div> <div class="panel-body"> <div class="questions"> <p class="unsure">4</p> <div id="checkbox"> <label> <input type="radio" name="q4" value="yes" />YES </label> <label> <input type="radio" name="q4" value="no"/>NO </label> </div> </div> </div> </div> <!--End Question 4--> <!--Question 5--> <div id="q5" class="panel panel-default" style="display:none;"> <div class="panel-heading"> <h3 class="panel-title"><span class="back">< Back </span> 5</h3> </div> <div class="panel-body"> <div class="questions"> <p class="unsure">5</p> <div id="checkbox"> DONE DONE GO BACK </div> </div> </div> </div> <!--End Question 5-->
{ "pile_set_name": "StackExchange" }
Q: Not able to see Session ID in apex debug log Salesforce Code - String sessionID = UserInfo.getSessionId(); System.debug(sessionID); Should give me Session ID, Urgent as I require it for use in SOAP UI. Is there any workaround A: Yes, it has workaround to see sessionId in Debug Logs: system.debug(UserInfo.getOrganizationId() + UserInfo.getSessionId().substring(15)); Since first 15 characters of session id is organization id, and debug logs perfectly show parts of session id string.
{ "pile_set_name": "StackExchange" }
Q: Why does my bower_install give me an error saying my package is not found? I have the following bower.json file: { "name": "user_staging", "private": true, "dependencies": { "angular": "^1.4.0", "angular-ui-router": "^0.2.0", "angular-loading-bar": "^0.6.0" }, "resolutions": { "angular": "^1.4.0" } } When I issue: bower install user_staging then it appears to install everything but finishes by telling me this: C:\G\user-staging\WebUserApp>bower install user_staging bower cached git://github.com/angular/bower-angular.git#1.3.15 bower validate 1.3.15 against git://github.com/angular/bower-angular.git#> 1.0.8 bower cached git://github.com/angular/bower-angular.git#1.4.0-rc.1 bower validate 1.4.0-rc.1 against git://github.com/angular/bower-angular.g t#^1.4.0 bower not-cached git://github.com/angular-ui/ui-router.git#^0.2.0 bower resolve git://github.com/angular-ui/ui-router.git#^0.2.0 bower download https://github.com/angular-ui/ui-router/archive/0.2.14.tar. z bower progress angular-ui-router#^0.2.0 received 0.7MB of 1.7MB downloaded 43% bower progress angular-ui-router#^0.2.0 received 0.8MB of 1.7MB downloaded 49% bower progress angular-ui-router#^0.2.0 received 0.9MB of 1.7MB downloaded 51% bower progress angular-ui-router#^0.2.0 received 0.9MB of 1.7MB downloaded 56% bower progress angular-ui-router#^0.2.0 received 1.0MB of 1.7MB downloaded 60% bower progress angular-ui-router#^0.2.0 received 1.1MB of 1.7MB downloaded 67% bower progress angular-ui-router#^0.2.0 received 1.2MB of 1.7MB downloaded 75% bower ENOTFOUND Package user_staging not found A: It's looking for the user_staging package on the internet. If user_staging is your project and you're running bower install in the same folder as the bower.json file then you can just run "bower install" without any arguments to install your project's dependencies.
{ "pile_set_name": "StackExchange" }
Q: Sensenet: Set permissions on Document Library It is possible to set permissions on document library without using the content explorer? I can set permissions for each specific file or folder, but to change the permissions of a document library I only finded a way through the content explorer... A: Ifyou want to display it on the toolbar as a 'button' add the SetPermission action as an ActionLink into the .ascx view of the document library toolbar (/Root/System/SystemPlugins/ListView/ViewFrame.ascx) Place this into the ToolbarItemGroup control in the .ascx <sn:ActionLinkButton ID="SetPermissionsActionLinkButton" runat="server" ActionName="SetPermissions" ContextInfoID="myContext" Text="<%$ Resources: Action, SetPermissions %>" /> If it's enough if the 'Set permissions' action is listed in the 'Actions' dropdown on the toolbar, add 'ListActions' to the Scenario field of the /Root/(apps)/GenericContent/SetPermissions.
{ "pile_set_name": "StackExchange" }
Q: java.sql.SQLException: Column count doesn't match value count at row 1 error I'm trying to insert data in a table, but it shows the following error: java.sql.SQLException: Column count doesn't match value count at row 1 I've searched this error and I tried all solutions but still it can't get it to work. Here's my code : class.html <html> <head> <title>Class</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form method="post" action="class.jsp"> <center> <table border="1" width="30%" cellpadding="5"> <thead> <tr> <th colspan="2">Enter Information Here</th> </tr> </thead> <tbody> <tr> <td>Class Name</td> <td><input type="text" name="name" value="" /></td> </tr> <tr> <td>Class Strength</td> <td><input type="text" name="strength" value="" /></td> </tr> <tr> <td>Room</td> <td> <input type="text" name="room" value=""> </td> </tr> <tr> <td>Section</td> <td><input type="text" name="section" value="" /></td> </tr> <tr> <td><input type="submit" value="Submit" /></td> <td><input type="reset" value="Reset" /></td> </tr> </tbody> </table> </center> </form> </body> </html> class.jsp <%@ page import ="java.sql.*" import= "java.sql.Connection" %> <% String cname = request.getParameter("name"); String cstrength = request.getParameter("strength"); String croom = request.getParameter("room"); String csection = request.getParameter("section"); //String available = request.getParameter("bavailable"); Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/web", "root", ""); Statement st = con.createStatement(); //ResultSet rs; int i = st.executeUpdate("insert into class(name, strength ,room, section) values ('" + cname + "','" + cstrength + "','" + croom + "','" + csection + "', CURDATE());"); if (i > 0) { //session.setAttribute("userid", user); response.sendRedirect("wel.jsp"); // out.print("Registration Successfull!"+"<a href='index.jsp'>Go to Login</a>"); } else { response.sendRedirect("index.jsp"); } %> A: This is the query that you're running: insert into class(name, strength ,room, section) values ('" + cname + "','" + cstrength + "','" + croom + "','" + csection + "', CURDATE());") you've mentioned 4 column values to be passed (class(name, strength ,room, section)), but then you're passing in 5 values (an extra value for CURDATE()) Either add that new column in the table and update the query to include that column as well (i.e. (class(name, strength ,room, section, curdate))) OR remove CURDATE().
{ "pile_set_name": "StackExchange" }
Q: the output of using np.empty_like in Python While studying the NumPy package of Python, I tried the following code segment import numpy as np x = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) v = np.array([1,0,1]) y = np.empty_like(x) print(y) for i in range(4): y[i,:] = x[i,:]+v print "......." print(y) However, the first print(y) gives the output such as following, instead of all zero array. On the other side, the second print(y)generates the correct result as expected. I would like to know why. [[ 72 0 0] [ 0 2676 1346720256] [1599357253 1950699087 10] [1346524499 1163154497 242503250]] ....... [[ 2 2 4] [ 5 5 7] [ 8 8 10] [11 11 13]] A: You want zeros_like. empty_like gives an array filled with who-knows-what, so it doesn't have to spend time filling it with zeros.
{ "pile_set_name": "StackExchange" }
Q: Eager Loading Deeply into a Model with a Collection Property Whose Type is Inherited Visual Studio generated this great route for me, where I can load an entity: // GET: api/Jobs/5 [ResponseType(typeof(Job))] public async Task<IHttpActionResult> GetJob(int id) { Job job = await db.Jobs.FindAsync(id); if (job == null) { return NotFound(); } return Ok(job); } Here's the Job model this is based on: public class Job { public Job() { this.Regions = new List<Region>(); this.Files = new List<JobFile>(); } public int ID { get; set; } public string Name { get; set; } public List<Region> Regions { get; set; } public JobTypes JobType { get; set; } public int UserIDCreatedBy { get; set; } public int? UserIDAssignedTo { get; set; } public List<JobFile> Files { get; set; } public bool IsLocked { get; set; } // Lock for modification access } Here's the JobFile class, which Jobs have a list of: public class JobFile { public int ID { get; set; } public string Name { get; set; } public string Url { get; set; } public int Job_ID { get; set; } } and Pdf, a subclass of JobFile: public class Pdf : JobFile { public Pdf() { this.PdfPages = new List<PdfPage>(); } public int Index { get; set; } public List<PdfPage> PdfPages { get; set; } } Now, when I hit that route, I'd like to eagerly load all the Pdfs for a Job, including their pages. I modified the route to look like this, and it works. // GET: api/Jobs/5 [ResponseType(typeof(Job))] public async Task<IHttpActionResult> GetJob(int id) { Job job = await db.Jobs.FindAsync(id); // Lookup the PDFs for this job and include their PdfPages List<JobFile> jobPdfs = db.Pdfs.Include(pdf => pdf.PdfPages).Where(pdf => pdf.Job_ID == id).ToList<JobFile>(); // Attach the job files to the job job.Files = jobPdfs; if (job == null) { return NotFound(); } return Ok(job); } Is this the best way to eagerly load all these models? Could this somehow be collapsed into one statement? It seems right now it hits the database twice. Could I build off of the original Job job = await db.Jobs.FindAsync(id); to load the Pdfs and their PdfPages all in one query? This question provided some helpful insight, but I'm not sure how I can capitalize on its conclusions. I think I need the ToList<JobFile>() (which according to the question does a trip to the database) because I actually need that data. So unless I can squash it into one more complicated Linq statement, perhaps it's unavoidable to make two trips. A: The problem here is that you'd actually want to include subtypes. If Job had a collection of Pdfs, you could have done Job job = await db.Jobs .Include(j => j.Pdfs.Select(pdf => pdf.PdfPages)) .SingleOrDefaultAsync(j => j.Id == id); But Pdf is a subtype, and EF doesn't support a syntax like Job job = await db.Jobs .Include(j => j.Files.OfType<Pdf>().Select(pdf => pdf.PdfPages)) .SingleOrDefaultAsync(j => j.Id == id); So what you do is the only way to get the Job with Pdfs and PdfPages. There are some improvements to be made though: You can just load the child objects into the context without assigning them to job.Files yourself. EF will knit the entities together by relationship fixup. You can first check if the Job is found and then load the Pdfs. Turning it into this: Job job = await db.Jobs.FindAsync(id); if (job == null) { return NotFound(); } else { // Load the PDFs for this job and include their PdfPages await db.Pdfs.Include(pdf => pdf.PdfPages).Where(pdf => pdf.Job_ID == id) .LoadAsync(); } return Ok(job);
{ "pile_set_name": "StackExchange" }
Q: Example of an iterative O(2^n) algo As the title says what is an example of an iterative O(2^n) algo? When does it normally happen? A: Tower of Hanoi can be a good example. Tower of Hanoi consists of three rods or pegs with n disks placed one over the other. The objective of the puzzle is to move the entire stack to another rod following these 3 rules. 1.Only one disk can be moved at a time. 2.Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod. 3.No larger disk may be placed on top of a smaller disk. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n − 1, where n is the number of disks. https://en.wikipedia.org/wiki/Tower_of_Hanoi#Iterative_solution
{ "pile_set_name": "StackExchange" }
Q: Unitary diagonalization of a normal matrix I will gladly appreciate explanation on how to do so on this matrix: $$ \begin{pmatrix} i & 0 \\ 0 & i \\ \end{pmatrix} $$ I got as far as calculating the eigenvalues and came up with $λ = i$. when trying to find the eigenvectors I came up with the $0$ matrix. what am I doing wrong? Much appreciation and thanks in advance. A: If $A=\begin{pmatrix}{i}&{0}\\{0}&{i}\end{pmatrix}$, then $I_2^*AI_2=A=D\text{ (diagonal)}$ and $I_2=\begin{pmatrix}{1}&{0}\\{0}&{1}\end{pmatrix}$ is an unitary matrix.
{ "pile_set_name": "StackExchange" }
Q: Useful Logon Script Commands Please post useful commands that you use in your logon script. Here are some that I use: map a network drive: net use v: \fileserver\apps map a network printer: RunDll32.EXE printui.dll,PrintUIEntry /in /n "\\printserver\Xerox DC1100 PCL" delete a network printer: RunDll32.EXE printui.dll,PrintUIEntry /dn /q /n "\\printserver\HP LaserJet 2300" disable windows firewall: netsh firewall set opmode disable install a new program: if not exist "C:\Program Files\Antivirus\" "V:\Antivirus\install.msi" create a shortcut on users Desktop: copy "V:\shortcuts\dictionary.lnk" "%USERPROFILE%\Desktop" A: I might get down voted for this, but so be it. I've always considered logon scripts to be kind of hack'ish and try to only use them as a last resort. There are so many ways to manage systems and users these days with things like Group Policy, Group Policy Preferences, and SCCM/SMS. I mean, there's always going to be cases where there just isn't a better way to do things. But many of the examples provided so far can easily be done without a login script like installing software and mapping network drives. A: Here's one of my favorites. We've got 700+ users and various divisions and subgroups that require their own drives. We're mapping based on username currently: if %username% == [username] net use /delete Z:\ if %username% == [username] net use Z: \servername\share another is the mapping of homedrives: net use H: \homeserver\%username% /persistent:yes
{ "pile_set_name": "StackExchange" }
Q: Uniqueness of automorphisms $\theta$ and $\psi$ in polar decomposition of $\alpha=\psi\theta$ Let $V$ be an inner product space finitely generated over $\mathbb{C}$ and let $\alpha\in Aut(V)$. Then there exists a unique positive-definite automorphism $\theta$ of $V$ and a unique unitary automorphism $\psi$ of $V$ satisfying $\alpha=\psi\theta$. I can show there exist $\theta$ and $\psi$ satisfying $\alpha=\psi\theta$. However, I have problem to show the uniqueness. I appreciate any help. Assume that $\psi\theta=\psi'\theta'$ where $\psi$ and $\psi'$ are unitary automorphism of $V$ and where $\theta$ and $\theta'$ are positive definite automorphism of $V$. As $\psi$ is unitary, we get $\psi^*=\psi^{-1}$. Hence, $$\theta^2=\theta\psi^*\psi\theta=(\psi\theta)^*(\psi\theta)=(\psi'\theta')^*(\psi'\theta')=\theta'(\psi')^*\psi'\theta'=(\theta')^2$$ Both $\theta$ and $\theta'$ are positive definite, but I don't know how to show they are equal. A: If you first think of $\theta$ and $\theta'$ as positive definite matrices, then $\theta^2$ (which is function composition in your setup) becomes matrix multiplication. The result I was trying to refer to is that since $\theta^2$ is positive definite, you can take a "square root" by diagonalizing it and replacing the eigenvalues with their square roots. Similarly for $(\theta')^2$. Note that this square root is unique, so they must be $\theta$ and $\theta'$ respectively. In short, $\theta^2 = (\theta')^2$ implies $\theta=\theta'$. The argument for operators is essentially the same. Here is a post that goes through the details.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap toggle menu not working I am testing a new website, and I am having a strange issue. This is the code for the index page: <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="container-fluid"> <!-- Second navbar for categories --> <nav class="navbar navbar-default"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Works</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li> <a class="btn btn-default btn-outline btn-circle" data-toggle="collapse" href="#nav-collapse1" aria-expanded="false" aria-controls="nav-collapse1">Categories</a> </li> </ul> <ul class="collapse nav navbar-nav nav-collapse" id="nav-collapse1"> <li><a href="#">Web design</a></li> <li><a href="#">Development</a></li> <li><a href="#">Graphic design</a></li> <li><a href="#">Print</a></li> <li><a href="#">Motion</a></li> <li><a href="#">Mobile apps</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav><!-- /.navbar --> <!-- Second navbar for sign in --> <nav class="navbar navbar-default"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-2"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-2"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Works</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li> <a class="btn btn-default btn-outline btn-circle" data-toggle="collapse" href="#nav-collapse2" aria-expanded="false" aria-controls="nav-collapse2">Sign in</a> </li> </ul> <div class="collapse nav navbar-nav nav-collapse" id="nav-collapse2"> <form class="navbar-form navbar-right form-inline" role="form"> <div class="form-group"> <label class="sr-only" for="Email">Email</label> <input type="email" class="form-control" id="Email" placeholder="Email" autofocus required /> </div> <div class="form-group"> <label class="sr-only" for="Password">Password</label> <input type="password" class="form-control" id="Password" placeholder="Password" required /> </div> <button type="submit" class="btn btn-success">Sign in</button> </form> </div> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav><!-- /.navbar --> <!-- Second navbar for search --> <nav class="navbar navbar-inverse"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-3"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-3"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Works</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li> <a class="btn btn-default btn-outline btn-circle" data-toggle="collapse" href="#nav-collapse3" aria-expanded="false" aria-controls="nav-collapse3">Search</a> </li> </ul> <div class="collapse nav navbar-nav nav-collapse" id="nav-collapse3"> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" /> </div> <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button> </form> </div> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav><!-- /.navbar --> <!-- Second navbar for profile settings --> <nav class="navbar navbar-inverse"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-4"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-4"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Works</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li> <a class="btn btn-default btn-outline btn-circle" data-toggle="collapse" href="#nav-collapse4" aria-expanded="false" aria-controls="nav-collapse4">Profile <i class=""></i> </a> </li> </ul> <ul class="collapse nav navbar-nav nav-collapse" role="search" id="nav-collapse4"> <li><a href="#">Support</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><img class="img-circle" src="https://pbs.twimg.com/profile_images/588909533428322304/Gxuyp46N.jpg" alt="maridlcrmn" width="20" /> Maridlcrmn <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">My profile</a></li> <li><a href="#">Favorited</a></li> <li><a href="#">Settings</a></li> <li class="divider"></li> <li><a href="#">Logout</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav><!-- /.navbar --> </div><!-- /.container-fluid --> This is the demo code that is working fine on the demo site, but on my server, the toggle menu is not working. What is wrong in the code? A: The bootstrap js you include depends on jquery. This means jquery must be included first. I swapped the order of your two includes, and you can see it now works. Always check the dependencies of code you're importing and didn't write yourself! Feel free to try the fiddle and swap the order back, you will see it breaks. :) <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="container-fluid"> <!-- Second navbar for categories --> <nav class="navbar navbar-default"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Works</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li> <a class="btn btn-default btn-outline btn-circle" data-toggle="collapse" href="#nav-collapse1" aria-expanded="false" aria-controls="nav-collapse1">Categories</a> </li> </ul> <ul class="collapse nav navbar-nav nav-collapse" id="nav-collapse1"> <li><a href="#">Web design</a></li> <li><a href="#">Development</a></li> <li><a href="#">Graphic design</a></li> <li><a href="#">Print</a></li> <li><a href="#">Motion</a></li> <li><a href="#">Mobile apps</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav><!-- /.navbar --> <!-- Second navbar for sign in --> <nav class="navbar navbar-default"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-2"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-2"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Works</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li> <a class="btn btn-default btn-outline btn-circle" data-toggle="collapse" href="#nav-collapse2" aria-expanded="false" aria-controls="nav-collapse2">Sign in</a> </li> </ul> <div class="collapse nav navbar-nav nav-collapse" id="nav-collapse2"> <form class="navbar-form navbar-right form-inline" role="form"> <div class="form-group"> <label class="sr-only" for="Email">Email</label> <input type="email" class="form-control" id="Email" placeholder="Email" autofocus required /> </div> <div class="form-group"> <label class="sr-only" for="Password">Password</label> <input type="password" class="form-control" id="Password" placeholder="Password" required /> </div> <button type="submit" class="btn btn-success">Sign in</button> </form> </div> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav><!-- /.navbar --> <!-- Second navbar for search --> <nav class="navbar navbar-inverse"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-3"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-3"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Works</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li> <a class="btn btn-default btn-outline btn-circle" data-toggle="collapse" href="#nav-collapse3" aria-expanded="false" aria-controls="nav-collapse3">Search</a> </li> </ul> <div class="collapse nav navbar-nav nav-collapse" id="nav-collapse3"> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" /> </div> <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button> </form> </div> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav><!-- /.navbar --> <!-- Second navbar for profile settings --> <nav class="navbar navbar-inverse"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-4"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-4"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Works</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li> <a class="btn btn-default btn-outline btn-circle" data-toggle="collapse" href="#nav-collapse4" aria-expanded="false" aria-controls="nav-collapse4">Profile <i class=""></i> </a> </li> </ul> <ul class="collapse nav navbar-nav nav-collapse" role="search" id="nav-collapse4"> <li><a href="#">Support</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><img class="img-circle" src="https://pbs.twimg.com/profile_images/588909533428322304/Gxuyp46N.jpg" alt="maridlcrmn" width="20" /> Maridlcrmn <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">My profile</a></li> <li><a href="#">Favorited</a></li> <li><a href="#">Settings</a></li> <li class="divider"></li> <li><a href="#">Logout</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav><!-- /.navbar --> </div><!-- /.container-fluid --> Hope this makes sense.
{ "pile_set_name": "StackExchange" }
Q: CSS issue, :checked state doesn't work I am trying to style radio buttons using this approach. Here you can find a DEMO of what I`m trying to accomplish: http://jsfiddle.net/sbef2so3/2/ CSS: /*works*/ input[type="radio"] { display:none; /*doesn`t work here*/ visibility:hidden; } /*doesn't work*/ input[type="radio"] + label span { display:inline-block; width:19px; height:19px; margin:-1px 4px 0 0; vertical-align:middle; background:url(http://csscheckbox.com/checkboxes/u/csscheckbox_ef32e9f2ed5c57aba4c2206a981ba7a4.png) 0px top no-repeat; cursor:pointer; } /*doesn't work*/ input[type="radio"]:checked { background:url(http://csscheckbox.com/checkboxes/u/csscheckbox_ef32e9f2ed5c57aba4c2206a981ba7a4.png) 0px bottom no-repeat; } The problem is, that input[type="radio"]:checked doesn't work for me. Nothing happens when I click the button. Although pseudo-classes :hover and :active work fine. I have this HTML code: <td class="AFContentCell" valign="top" nowrap=""> <div id="pt1:r1:0:sor2::content" class="af_selectOneRadio_content" name="pt1:r1:0:sor2"> <fieldset style="border:none; margin:0px; padding:0px;"> <legend class="p_OraHiddenLabel">Please choose something:</legend> <div> <span class="af_selectOneRadio_content-input"> <input id="rad1" class="af_selectOneRadio_native-input" type="radio" value="0" name="pt1:r1:0:sor2"> </span> <label class="af_selectOneRadio_item-text" for="rad1">Yes</label> </div> <div> <span class="af_selectOneRadio_content-input"> <input id="rad2" class="af_selectOneRadio_native-input" type="radio" value="1" name="pt1:r1:0:sor2"> </span> <label class="af_selectOneRadio_item-text" for="rad2">No</label> </div> </fieldset> </div> </td> This HTML is generated by ADF and I can't add or change something. As far as I understand, the problem is with that input element being in span element and label being outside of the span element. Can someone help me out with that? Important: I can't change HTML file. I need to figure out, how to get this to work using CSS. Without JavaScript or jQuery. UPDATE: Answer to Zack: I am using type="radio" and type="checkbox" together. Thank you for noticing my misprinting. Still this doesn't solve the issue for me. Answer to Diodeus: What? You can find a bunch of tutorials explaining how to do it. Here is step-by-step video tutorial: https://www.youtube.com/watch?v=FQl_bcF4jOk And this is cross-browser compatible. Answer to bigal: Thank you very much for your detailed answer. Now everything works fine for me and I understand what I was doing wrong. A: The problem first is that you have the image of the button on your span and radio button while the radio button (the thing you want the user to click on) is hidden. Remove the background image on the span tag but keep the background image on the radio button and reveal your radio button again. Then disable wekbit/moz appearance (so the default radio button goes away) and increase the width and height of the button to 21px (because 19px is too little). The final CSS I have: input[type="radio"] { display:inline-block; width:21px; height:21px; margin:-1px 4px 0 0; vertical-align:middle; background:url(http://csscheckbox.com/checkboxes/u/csscheckbox_ef32e9f2ed5c57aba4c2206a981ba7a4.png) 0px top no-repeat; cursor:pointer; appearance:none; -moz-appearance:none; /* Firefox */ -webkit-appearance:none; /* Safari and Chrome */ } input[type="radio"]:checked { background:url(http://csscheckbox.com/checkboxes/u/csscheckbox_ef32e9f2ed5c57aba4c2206a981ba7a4.png) 0px bottom no-repeat; } .af_selectOneRadio_item-text { color: Green; } Here is the link to what I've spoken about: http://jsfiddle.net/sbef2so3/16/
{ "pile_set_name": "StackExchange" }
Q: Fish RVM Use error So I installed fish and oh-my-fish, and when i want to use rvm I get this error: ➜ avalancha git:(services) ✗ rvm use 2.1.0 Using /home/matias/.rvm/gems/ruby-2.1.0 fish: The '$' character begins a variable name. The character '{', which directly followed a '$', is not allowed as a part of a variable name, and variable names may not be zero characters long. To learn more about variable expansion in fish, type 'help expand-variable'. /home/matias/.config/fish/functions/rvm.fish (line 2): begin; set -xg rvm_bin_path "/home/matias/.rvm/bin" ; set -xg GEM_HOME "/home/matias/.rvm/gems/ruby-2.1.0" ; set -xg XDG_SESSION_PATH "/org/freedesktop/DisplayManager/Session0" ; set -xg rvm_path "/home/matias/.rvm" ; set -xg XDG_SEAT_PATH "/org/freedesktop/DisplayManager/Seat0" ; set -xg DEFAULTS_PATH "/usr/share/gconf/ubuntu.default.path" ; set -xg rvm_prefix "/home/matias" ; set -xg PATH "/home/matias/.rvm/gems/ruby-2.1.0/bin" "/home/matias/.rvm/gems/ruby-2.1.0@global/bin" "/home/matias/.rvm/rubies/ruby-2.1.0/bin" "/home/matias/.rvm/bin" "/usr/local/sbin" "/usr/local/bin" "/usr/sbin" "/usr/bin" "/sbin" "/bin" "/usr/games" "/usr/local/games" ; set -xg MANDATORY_PATH "/usr/share/gconf/ubuntu.mandatory.path" ; set -xg rvm_version "1.25.29 stable" ; set -xg rvm_ruby_string "ruby-2.1.0" ; set -xg GEM_PATH "/home/matias/.rvm/gems/ruby-2.1.0" "/home/matias/.rvm/gems/ruby-2.1.0@global" ; set -xg rvm_delete_flag "0" ; set -xg rvm_debug " { (( ${rvm_debug_flag:-0} )) || return 0;" ; ;end eval2_inner <&3 3<&- ^ in . (source) call of file '-', called on line 22 of file '/home/matias/.config/fish/functions/rvm.fish', in function 'rvm', called on standard input, with parameter list 'use 2.1.0' .: Error while reading file '-' Does anyone know what could it be? A: I had the same issue. It's an incompatibility caused by the multiline value of the rvm_debug variable. I patched the function to ignore this variable completely by making a small change. Open ~/.config/fish/functions/rvm.fish and change line 7 from this: and eval (grep '^rvm\|^[^=]*PATH\|^GEM_HOME' $env_file | grep -v '_clr=' | sed '/^[^=]*PATH/s/:/" "/g; s/^/set -xg /; s/=/ "/; s/$/" ;/; s/(//; s/)//') into this: and eval (grep '^rvm\|^[^=]*PATH\|^GEM_HOME' $env_file | grep -v '_clr=' | grep -v 'rvm_debug=' | sed '/^[^=]*PATH/s/:/" "/g; s/^/set -xg /; s/=/ "/; s/$/" ;/; s/(//; s/)//') I don't know what rvm_debug is being used for, but my system seems to work without it.
{ "pile_set_name": "StackExchange" }
Q: Why is FindFit failing to find a suitable trig model? I'm trying to get FindFit (or NonlinearModelFit) to find a best fit trig function. The result I achieve is so obviously not the good fit I'd like as you can see below. I think this should be simple, but I don't seem to be able to have it work correctly. Hopefully someone will be able to put me on the right track. A: @Coolwater gave the answer: one needs good starting values. The default starting value of 1 for all parameters doesn't always work. While it would be more convenient if one wouldn't have to produce starting values, having some idea as to what the plausible values might be is usually a good idea. Fortunately the OP plotted the results and saw that there was a problem. I "digitized" the data to reproduce the results: tidedata = {{0.0322997, 2.45303}, {2.03488, 3.77871}, {3.03618, 3.98747}, {4.00517, 3.8309}, {6.04005, 2.54697}, {8.01034, 1.24217}, {8.85013, 1.09603}, {10.0452, 1.13779}, {11.9832, 2.37996}, {14.0504, 3.75783}, {15.1163, 4.07098}, {15.9884, 3.87265}, {18.0556, 2.65136}, {19.9935, 1.26305}, {21.3178, 0.782881}, {22.0284, 1.01253}, {23.9987, 2.31733}}; model = a Sin[b x + c] + d fit = FindFit[tidedata, model, {a, b, c, d}, x] (* {a -> -0.417056, b -> 0.894376, c -> 1.72554, d -> 2.48805} *) If better starting values are given, then the appropriate estimates are found. It looks like there are two full cycles over a length of 25 which means that b could be estimated by $4\pi/25$ which is close to 0.5. fit = FindFit[tidedata, model, {a, {b, 0.5}, c, {d, Mean[tidedata[[All, 2]]]}}, x] (* {a -> 1.53685, b -> 0.519602, c -> -0.0399239, d -> 2.48761} *) Show[ListPlot[tidedata], Plot[model /. fit, {x, 0, 25}]] Why the need for better starting values? In this case it's because the likelihood function is extremely "bumpy" and I'll show what is meant by that. Suppose we know a and d and have some idea of the standard error of estimate. Then we can look at the likelihood function for b and c. Below I show that likelihood function is bumpy and the result depends on the starting values used. (* Get some starting and ending values *) start1 = {1, 1}; start2 = {1, -3}; start3 = {0.8, -2}; end1 = {b, c} /. FindFit[tidedata, model, {a, {b, start1[[1]]}, {c, start1[[2]]}, d}, x]; end2 = {b, c} /. FindFit[tidedata, model, {a, {b, start2[[1]]}, {c, start2[[2]]}, d}, x]; end3 = {b, c} /. FindFit[tidedata, model, {a, {b, start3[[1]]}, {c, start3[[2]]}, d}, x]; Now show the starting and ending values on a contour plot of the likelihood function: σ = 0.1; logL = LogLikelihood[NormalDistribution[0, σ], tidedata[[All, 2]] - (model /. {x -> tidedata[[All, 1]], a -> 1.5368524967407906, d -> 2.4876143581877814})]; ContourPlot[logL, {b, 0.3, 1.1}, {c, -π, π}, PlotLegends -> Automatic, Frame -> True, FrameLabel -> (Style[#, Bold, 18] &) /@ {"b", "c"}, Contours -> -{100, 200, 300, 400, 500, 1000, 1500, 1600, 1700, 1800, 1900, 2000, 2400, 2500, 2600, 2700, 2800, 3000, 3500}, Epilog -> {PointSize[0.025], Thick, Line[{start1, end1}], Red, Point[end1], Blue, Point[start1], Line[{start2, end2}], Red, Point[end2], Blue, Point[start2], Line[{start3, end3}], Green, Point[end3], Blue, Point[start3]} ] The blue dots represent the 3 different starting values. The two red dots are the resulting wrong answers. The green dot represents the correct answer. We see that starting values for 1 end up in a trough and the starting values for 2 end up on a local peak. The global peak is found when the starting values are a bit closer to the global peak and there aren't any bumps in the way. It is simply a fact of life that sometimes really good starting values are needed. This is especially true for fitting multiple cycles of a sine wave. A: If you choose the "right" method, FindFit works without starting values: model = a Sin[b x + c] + d fit = FindFit[tidedata, model, {a, b, c, d}, x, Method -> "NMinimize"] (*{a -> -1.53685, b -> 0.519602, c -> -3.18152, d -> 2.48761}*)
{ "pile_set_name": "StackExchange" }
Q: drawRect() draw a custom shape, why can't fill color? I 'm writing a custom shaped HUD and filling it with some color, but I can't fill the right part of my HUD. #define startX 20 #define startY 20 #define circleDiameter 60 #define PI 3.14159265358979323846 Here is the code: - (void)drawRect:(CGRect)rect CGContextClearRect(UIGraphicsGetCurrentContext(), rect); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); CGContextFillRect(context,self.bounds); CGContextSetLineWidth(context, 1.0f); CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0 green:255 blue:0 alpha:0.5].CGColor); CGRect circlePoint = CGRectMake(startX, startY, circleDiameter, circleDiameter); CGContextFillEllipseInRect(context, circlePoint); CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); CGContextAddEllipseInRect(context, circlePoint); CGContextStrokePath(context); CGContextSetLineWidth(context, 1.0f); CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0 green:255 blue:0 alpha:0.5].CGColor); CGContextBeginPath(context); //line start x. CGContextMoveToPoint(context, 70, 28); CGContextAddLineToPoint(context, 170, 28); CGContextMoveToPoint(context, 70, 72); CGContextAddLineToPoint(context, 170, 72); CGContextStrokePath(context); //draw radius CGContextAddArc(context, 170, 50, 22, -PI/2, PI/2, 0); CGContextStrokePath(context); CGContextClosePath(context); CGContextFillPath(context); } I want to fill the whole path with the color green, what should I do? here is the result snapshot.: A: CGContextClearRect(UIGraphicsGetCurrentContext(), rect); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); CGContextFillRect(context,self.bounds); CGContextSetBlendMode(context, kCGBlendModeCopy); CGContextSetAllowsAntialiasing(context, YES); CGContextSetShouldAntialias(context, YES); UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(55, 28, 138, 44) cornerRadius:22]; CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0. green:0.5 blue:0. alpha:0.5].CGColor); [bezierPath fill]; [bezierPath stroke]; CGContextSetLineWidth(context, 1.0f); CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0 green:0.5 blue:0 alpha:0.5].CGColor); CGRect circlePoint = CGRectMake(startX, startY, circleDiameter, circleDiameter); CGContextFillEllipseInRect(context, circlePoint); CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); CGContextStrokeEllipseInRect(context, circlePoint); Here is the result what I expect! A: Use BezierPath to draw that rounded rectangle with fill color UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(55, 28, 140, 44) cornerRadius:22]; CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0 green:255 blue:0 alpha:0.5].CGColor); [bezierPath fill];
{ "pile_set_name": "StackExchange" }
Q: Showing an isomorphism of $R[G]$-modules using the regular representation Let $R$ be a commutative ring, and $G$ a finite group. Now suppose $M,N$ are finitely generated $R[G]$-modules such that $M\cong_R N$ (let's say they have $R$-rank$=n$). To show $M\cong_{R[G]}N$, is it sufficient to show the regular representations of $M,\,N$ are similar (as matrices)?. In other words, if I show $\rho_M(g)A=A\rho_N(g)$ for all $g\in G$, where $A\in M_n(R)$? If so, why? Intuitively, this should be clear but I am unsure (algebraically) why this should be true. Perhaps I am massively overthinking this. A: An isomorphism of $RG$-modules is an $R$-linear bijection $\phi:M\to N$ which is $G$-equivariant. That is, $$\phi(g.m)=g.\phi(m).$$ If I choose a basis $\{m_1,\ldots,m_r\}$ for $M$ and $\{n_1,\ldots,n_r\}$ for $N$, I can write $$\phi(m_j)=\sum_{i=1}^r a_{ij}n_i\;\;(1\leq j\leq n)$$ for some $a_{ij}\in R$ ($1\leq i,j\leq n$). This determines a matrix $A$. Similarly, we can obtain matrices for left multiplication by an element $g\in G$, $\rho_M(g):M\to M$ and $\rho_N(g):N\to N$. Then, $G$-equivariance is just the statement that $A\rho_M(g)=\rho_N(g)A$. EDIT Okay, let's spell out the last paragraph:For each $1\leq k\leq n$, $$g.m_k=\sum_{j=1}^nb_{jk}m_j$$ which determines a matrix $\rho_M(g)=B$, and $$g.n_k=\sum_{j=1}^nc_{jk}n_j$$ which determines a matrix $\rho_N(g)=C$. You want to know why equivariance implies $AB=CA$. Well \begin{align} \phi(g.m_k)&=\phi\left(\sum_{j=1}^kb_{jk}m_j\right)\\ &=\sum_{j=1}^nb_{jk}\phi(m_j)\\ &=\sum_{j,i=1}^nb_{jk}a_{ij}n_i\\ &=\sum_{i=1}^n\left(\sum_{j=1}^na_{ij}b_{jk}\right)n_i \end{align} and, similarly, \begin{align} g.\phi(m_k)=\sum_{i=1}^n\left(\sum_{j=1}^nc_{ij}a_{jk}\right)n_i. \end{align} The equality $\phi(g.m_k)=g.\phi(m_k)$ for all $k$ says that for all $i$ $$ \sum_{j=1}^na_{ij}b_{jk}=\sum_{j=1}^nc_{ij}a_{jk}. $$ Of course, the left hand side of the equality above is the $(i,k)$-entry in $AB$ and the right hand side is the $(i,k)$-entry of $CA$. Hence $AB=CA$ as required.
{ "pile_set_name": "StackExchange" }
Q: Difference between g++ and clang++ with enable_if I want to write a function that returns an instance of a type T but behaves differently depending on how T can be constructed. Say I have structs like these #include <type_traits> #include <iostream> struct A {}; struct B {}; struct C { C(A a) { std::cout << "C" << std::endl; } }; I want to create Cs by giving them an A. I have a struct like so that uses enable_if to choose one of two functions: struct E { template< bool condition = std::is_constructible<C, A>::value,std::enable_if_t<condition,int> = 0> C get() { return C{A{}}; } template< bool condition = std::is_constructible<C, B>::value,std::enable_if_t<condition,bool> = false> C get() { return C{B{}}; } }; This compiles fine with g++82 (and I think also g++9), but clang9 gives me the error $ clang++ --std=c++17 main.cpp main.cpp:26:12: error: no matching constructor for initialization of 'C' return C{B{}}; ^~~~~~ main.cpp:6:8: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'B' to 'const C' for 1st argument struct C { ^ main.cpp:6:8: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'B' to 'C' for 1st argument struct C { ^ main.cpp:7:3: note: candidate constructor not viable: no known conversion from 'B' to 'A' for 1st argument C(A a) { ^ 1 error generated. even though the enable_if should hide that function. (I call E e; auto c = e.get();). If I don't hardcode C but instead use a template to pass in C it works in both compilers. template<typename T> struct F { template< bool condition = std::is_constructible<T, A>::value,std::enable_if_t<condition,int> = 0> T get() { return T{A{}}; } template< bool condition = std::is_constructible<T, B>::value,std::enable_if_t<condition,bool> = false> T get() { return T{B{}}; } }; I don't understand why clang apparently typechecks the body of the function even though the function should be disabled by enable_if. A: Both compiler are right, http://eel.is/c++draft/temp.res#8.1 The validity of a template may be checked prior to any instantiation. [ Note: Knowing which names are type names allows the syntax of every template to be checked in this way. — end note ] The program is ill-formed, no diagnostic required, if: (8.1) - no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the template is not instantiated, or [..] (8.4) - a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter, or return C{B{}}; is not template dependent, and wrong. clang is fine by diagnosing the issue.
{ "pile_set_name": "StackExchange" }
Q: What is perpose of iptables NAT configuration in cell_z1? When I ssh into cell_z1. then I can see these routing tables. $ sudo iptables -t nat -L Chain PREROUTING (policy ACCEPT) target prot opt source destination w--prerouting all -- anywhere anywhere Chain INPUT (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination w--prerouting all -- anywhere anywhere Chain POSTROUTING (policy ACCEPT) target prot opt source destination w--postrouting all -- anywhere anywhere Chain w--instance-coiaggg2s3f (1 references) target prot opt source destination DNAT tcp -- anywhere cell-z1-0.node.dc1.cf.internal tcp dpt:60036 /* ac4154dd-a2bd-41d8-46bb-c5dfa3c8bfb2 */ to:10.254.0.6:8080 DNAT tcp -- anywhere cell-z1-0.node.dc1.cf.internal tcp dpt:60037 /* ac4154dd-a2bd-41d8-46bb-c5dfa3c8bfb2 */ to:10.254.0.6:2222 Chain w--instance-coiaggg2s3l (1 references) target prot opt source destination DNAT tcp -- anywhere cell-z1-0.node.dc1.cf.internal tcp dpt:60040 /* 74ab1082-7eca-4a09-7364-b266a23a7fdf */ to:10.254.0.2:8080 DNAT tcp -- anywhere cell-z1-0.node.dc1.cf.internal tcp dpt:60041 /* 74ab1082-7eca-4a09-7364-b266a23a7fdf */ to:10.254.0.2:2222 Chain w--postrouting (1 references) target prot opt source destination MASQUERADE all -- 10.254.0.0/30 !10.254.0.0/30 /* executor-healthcheck-8946f5d6-063c-4bae-474d-0032f72b8fcb */ MASQUERADE all -- 10.254.0.4/30 !10.254.0.4/30 /* ef658bba-214d-4eef-5228-410e8e8aeb69 */ MASQUERADE all -- 10.254.0.8/30 !10.254.0.8/30 /* 3cb958eb-409a-4aa9-48f1-41bb6573ebc6 */ MASQUERADE all -- 10.254.0.12/30 !10.254.0.12/30 /* 9600ee8c-9e63-4682-bed3-b14767ea46d3 */ MASQUERADE all -- 10.254.0.16/30 !10.254.0.16/30 /* executor-healthcheck-eda5cee2-81be-4890-6d67-2a9f108d6dda */ Chain w--prerouting (2 references) target prot opt source destination w--instance-coiaggg2s3f all -- anywhere anywhere /* ac4154dd-a2bd-41d8-46bb-c5dfa3c8bfb2 */ w--instance-coiaggg2s3l all -- anywhere anywhere /* 74ab1082-7eca-4a09-7364-b266a23a7fdf */ Question is: What is the perpose of these destinations? When I curl in cell_z1, it returns 301 error. So, I think it's removed. 10.254.0.6:8080 10.254.0.6:2222 10.254.0.2:8080 10.254.0.2:2222 But, it causes router returns 502 error in some pushed application when router-emitter mapped that application port to 60036, 60037, 60040, 60041 My environment: Host OS : Ubuntu Server 16.10 VirtualBox : 5.0.32 $ bosh -e bosh-lite releases Using environment '192.168.50.4' as client 'admin' Name Version Commit Hash cf 254+dev.1* 80a8305a+ cf-mysql 34.2.0+dev.1* b8dcbe32 cf-rabbitmq 222.15.0+dev.1* 377afa0a+ cf-rabbitmq-test 0.1.7 98720fb8 cflinuxfs2-rootfs 1.60.0* 0b44b228+ diego 1.11.0+dev.1* 4ee830c6 garden-runc 1.4.0* 60f9e9dd routing 0.147.0 255f268f ~ 0.136.0 d29132da+ UPDATED 4/11/2017 I have found that this information comes from the Kawasaki (Guardian's Network Library). I see route table below. But Unlike 10.254.0.6, The route table does not have virtual NIC and route for 10.254.0.2 (10.254.0.0/30) $ route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface default 10.244.16.1 0.0.0.0 UG 0 0 0 wcl8gbnff7q4-1 10.244.16.0 * 255.255.255.0 U 0 0 0 wcl8gbnff7q4-1 10.254.0.4 * 255.255.255.252 U 0 0 0 wbrdg-0afe0004 A: When you deploy an application to CF, it runs in a container on one of your Diego Cells. The container is given an internal port, at the moment this will always be 8080 with Diego, and the Cell publishes an external port (to the GoRouters). The external port is mapped to the internal port with an iptables rule on the Cell. I believe that is what you're seeing / asking about. In summary, traffic takes a path like this from your browser to the app in the container: Browser -> HTTP(S) -> Load Balancer -> HTTP(S) -> GoRouter -> (HTTP) -> External Port on Cell -> iptables -> Internal Port in Container -> Application You might also be wondering about port 2222, this is similar but the port is used for cf ssh traffic into the container. A layperson should never manually remove or adjust any of the iptables rules on a Diego Cells.
{ "pile_set_name": "StackExchange" }
Q: what idea is behind Zend Framework Frontcontroller/dispatcher Zend Framework FrontController implements Singleton and plus it has some kind a plugin "paradigm" , - what is the idea behind its architecture , maybe it implements some well known paradigm ? and if so then if u could give some links directions where I can find information about reasons that brought up that particular paradigm ? A: The basic idea of a FrontController is to provide for a single point of entry to your application. Quoting PoEAA: The Front Controller consolidates all request handling by channeling requests through a single handler object. This object can carry out common behavior, which can be modified at runtime with decorators. The handler then dispatches to command objects for behavior particular to a request. Further definitions: http://en.wikipedia.org/wiki/Front_Controller_pattern http://java.sun.com/blueprints/patterns/FrontController.html Also see the chapter in the reference guide about the Front Controller: Zend_Controller_Front implements a » Front Controller pattern used in » Model-View-Controller (MVC) applications. Its purpose is to initialize the request environment, route the incoming request, and then dispatch any discovered actions; it aggregates any responses and returns them when the process is complete. About being a Singleton Zend_Controller_Front also implements the » Singleton pattern, meaning only a single instance of it may be available at any given time. This allows it to also act as a registry on which the other objects in the dispatch process may draw. For a General Definition of the Singleton and the Registry pattern see: http://sourcemaking.com/design_patterns/singleton http://martinfowler.com/eaaCatalog/registry.html About being pluggable Zend_Controller_Front registers a plugin broker with itself, allowing various events it triggers to be observed by plugins. In most cases, this gives the developer the opportunity to tailor the dispatch process to the site without the need to extend the front controller to add functionality. A good detailed explanation how Zend Framework uses the Front Controller and what happens under the hood during an MVC rquest can be found in: Zend Framework MVC Request Lifecycle
{ "pile_set_name": "StackExchange" }
Q: What is the fastest way to check if any files in a directory tree have changed? Currently I'm checking against an XOR Checksum of the modified file time (st_mtime from fstat) for every file in the tree. I'm coupling this with the number of files found and a file size checksum (allowing overflows) to be safe but I'm quite paranoid that this can and will lead to false positives in the most extreme pathological cases. One alternative (safe) option I am considering is keeping a manifest of every file by name and a CRC32 of the file contents. This option however is pretty slow, or slower than I would like at least for many files (lets say thousands). So the question is, what are some tips or tricks you may have for determining whether any file has changed within a directory tree? I'd like to avoid a byte-by-byte comparison without trading away too much reliability. Thanks very much for your suggestions. A: You could you the "last modified on" property that files have (regardless of platform). Simply store historical values and check historical values against current values, every so often. boost::filesystem has a great cross platform API for reading this value. EDIT: Specifically look at: http://www.pdc.kth.se/training/Talks/C++/boost/libs/filesystem/doc/operations.htm#last_write_time
{ "pile_set_name": "StackExchange" }
Q: Keep element with a percentage as a position fixed I have a container of variable height, and would like to put an element at the middle of it. So I've set these styles: #parent { position: relative; } #child { position: absolute; top: 50%; transform: translateY(-50%); } Which work in most cases. However, the container's height is not only variable, but it also changes constantly. Because of this, that code won't work. An example: @keyframes changeSize { 0% { height: 100px; } 50% { height: 150px; } 100% { height: 100px; } } #parent { position: relative; width: 400px; height: 300px; background: red; animation-name: changeSize; animation-duration: 2s; animation-iteration-count: infinite; animation-timing-function: ease-in-out; } #child { position: absolute; margin-block-start: 0; margin-block-end: 0; right: 0; top: 50%; transform: translateY(-50%); } <div id="parent"> <p id="child">I should not be moving...</p> </div> As you can see, it's moving. So, my question is, is there a way to place it in the middle of the element (vertically) but without having it move if the container changes size - just with CSS? A: The issue is that percentage measure units are relative to the containing element. Since the #parent is changing in height through the animation, the value of a percentage unit changes. The unit change affects the percentage height property applied to the #child. The work-around might be some very complicated CSS (might not work in every situation) so the best solution is to use JavaScript to capture the initial 50% height in pixels so the unit no longer changes. It is important to also use a resize event listener to apply a new 50% height should the browser window be resized. window.addEventListener('load',resizeDiv()); window.addEventListener('resize',resizeDiv()); function resizeDiv(){ var initialHeight = document.getElementById('parent').offsetHeight/2; document.getElementById('child').style.top = initialHeight+'px'; } @keyframes changeSize { 0% { height: 100px; } 50% { height: 150px; } 100% { height: 100px; } } #parent { position: relative; width: 400px; height: 300px; background: red; animation-name: changeSize; animation-duration: 2s; animation-iteration-count: infinite; animation-timing-function: ease-in-out; } #child { position: absolute; margin-block-start: 0; margin-block-end: 0; right: 0; } <div id="parent"> <p id="child">Hey!! I'm not moving anymore!</p> </div>
{ "pile_set_name": "StackExchange" }
Q: How to write to Sql server from MapBasic and insert rows I have created a table in Sql server 2014 with the columns: Id (int), Geom (geometry), RouteId (int), Desc (varchar(MAX)) I have succeeded in making the table mappable through MapInfo I have checked .TAB file for the table, that it has IsReadOnly = false Stil when i try to execute an insert query on the table I get the error messsage that the table is read only. Anyone knows how to fix this? Also I cannot figure out how to write a correct insert query I have tried doing that on a copied version of the table code is as follows Dim rId As Integer Dim oPline as Object rId = 20 Dim t As String t = "test" Create pline into variable oPline 2 (1,2)(1,3) Insert into TestGeom1 (Geom, RouteId, Desc) VALUES (oPline, rId, t) Writing like above I get the error messsage field Geom does not exist in table TestGeom1 If i replace Geom with obj or just remove it completely i get the error Expression does not evaluate to a column or a table name. So please who can tell me what is the correct syntax for this? A: Make sure that you have specified a unique primary key in the table in SQL Server. Also you could take advantage of the IDENTITY type so that you don't have to manage the ID's yourself. Make sure your text columns are defined as varchar and that they aren't wider than 254. Otherwise you might have an issue editing the data Once the table is opened in MapInfo Professional your spatial column is always called OBJ. So use this insert statement: Insert into TestGeom1 (OBJ, RouteId, Desc) VALUES (oPline, rId, t) If you have a statement that works in the MapBasic window but doesn't work in the MapBasic application, you should have a look at your variable and function names. Maybe you have a variable using the same name as a table or column. Also try to create the table in the database from MapInfo Professional using File > New, when specifying the location of the table, pick an open connection to your database. In this way you can create a new table directly in your database If you use the Per Row Style option, the width of the column might prevnet you from editing the object. If the column is wider than 254, MapInfo Pro can't edit the column and so the spatial object also gets read-only
{ "pile_set_name": "StackExchange" }
Q: Basic Web Socket with ExpressJS and Jquery I'm trying to build an ExpressJS websocket backend for a jQuery-based front end using HTML5 web sockets. The ExpressJS backend code is literally copy-pasted from https://github.com/websockets/ws#expressjs-example The javascript front end code is: var socket = new WebSocket("ws://localhost:8080"); socket.onopen = function(){ console.log( "OPENED : ", socket.readyState ); } socket.onmessage = function(msg){ console.log( msg ); } socket.onclose = function(){ console.log( "CLOSED : ", socket.readyState ); } setTimeout(function(){ socket.send('test'); }, 2000); In Chrome, I'm receiving an error: "Connection closed before receiving a handshake response". I've looked online for a solution, but they are all socket.io based whereas I'm just using the NodeJS ws package. Any tips would be greatly appreciated. A: The back end code : const express = require('express') const http = require('http') const WebSocket = require('ws') var path = require('path') const app = express() app.get('/', (req, res) => { res.sendFile(path.join(__dirname + '/a.html')) }) const server = http.createServer(app) const wss = new WebSocket.Server({ server }) wss.on('connection', function connection (ws, req) { ws.on('message', function incoming (message) { console.log('received: %s', message) }) ws.send('something') }) server.listen(8080, function listening () { console.log('Listening on %d', server.address().port) }) the only change is the app.get on line 8 instead of the app.use provided in the link you gave. And the a.html file has only the front end script : <html> <head> </head> <body> <script> var socket = new WebSocket("ws://localhost:8080"); socket.onopen = function () { console.log("OPENED : ", socket.readyState); } socket.onmessage = function (msg) { console.log(msg); } socket.onclose = function () { console.log("CLOSED : ", socket.readyState); } setTimeout(function () { socket.send('test'); }, 2000); </script> </body> </html> And everything is working fine. You said you are running the server on port 3000 and yet you are trying to connect to port 8080 in the front end code. Was that a mistake ?
{ "pile_set_name": "StackExchange" }
Q: Want to hide a button by it's id/class, by clicking a checkbox input[type=checkbox]:checked ~ div#span-advanced-search { background: white; display: block; position: relative; width: 564px; padding: 10px; visibility: visible; left: -573px; top: 11px; } <label for="toggle-1" class="ds-drop-down" role="button" data-tooltip="Show search options"/> <input type="checkbox" id="toggle-1"></input> <div id="span-advanced-search"> <label>Education Level:</label> <input type="text"/><br></br> <label>Type of Learning Material:</label> <input type="text"/><br></br> <label>Difficulty Level:</label> <input type="text"/><br></br> <label>Author:</label> <input type="text"/><br></br> <input class="ds-button-field " name="submit" type="submit" i18n:attr="value" value="xmlui.general.go"> <xsl:attribute name="onclick"> <xsl:text> var radio = document.getElementById(&quot;ds-search-form-scope-container&quot;); if (radio != undefined &amp;&amp; radio.checked) { var form = document.getElementById(&quot;ds-search-form&quot;); form.action= </xsl:text> <xsl:text>&quot;</xsl:text> <xsl:value-of select="/dri:document/dri:meta/dri:pageMeta/dri:metadata[@element='contextPath']"/> <xsl:text>/handle/&quot; + radio.value + &quot;</xsl:text> <xsl:value-of select="/dri:document/dri:meta/dri:pageMeta/dri:metadata[@element='search'][@qualifier='simpleURL']"/> <xsl:text>&quot; ; </xsl:text> <xsl:text> } </xsl:text> </xsl:attribute> </input> </div> <input class="ds-button-field " name="submit" type="submit" i18n:attr="value" value="xmlui.general.go"> </input> I want to hide the button ds-button-field when I am checking the checkbox->"toggle-1".How can I do that using css and using id/class name of that button? Initially that button must be visible. A: /* initial state */ .ds-button-field { display: block; } /* button hidden if the sibling checkbox is checked */ #toggle-1:checked ~ .ds-button-field { display: none; } As a side note <input ...></input> should be <input ... />
{ "pile_set_name": "StackExchange" }
Q: How to configure a firewall on Centos using Vagrant and Chef I've created a server box using Vagrant and Chef and everything is up and running correctly. However, when the box is installed from scratch the default iptables rules are in place and so I need to disable the firewall in order to access my web server. (This is a local VM btw so I don't care about firewall security). On launching the VM I ssh to it and flush the iptables, which works fine. But what I would prefer is to run a shell script when the machine is created to do this. Even better I would like configure the iptables using a recipe but I don't see a supported cookbook. Thanks A: One way to set the firewall rules in CentOS is to replace the /etc/sysconfig/iptables entirely by using a template in the recipe. Say you want to adjust the routing because you are setting up an Apache web server ("apache2") cookbook. Create the file cookbooks/apache2/templates/default/iptables.erb with following content: # Firewall configuration created and managed by Chef # Do not edit manually *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT -A INPUT -m tcp -p tcp --dport 80 -j ACCEPT -A INPUT -m tcp -p tcp --dport 443 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWARD -j REJECT --reject-with icmp-host-prohibited COMMIT Be sure and have a line return after the COMMIT. Then call the template in your recipe, and afterward restart the iptables service. # # Load firewall rules we know works # template "/etc/sysconfig/iptables" do # path "/etc/sysconfig/iptables" source "iptables.erb" owner "root" group "root" mode 00600 # notifies :restart, resources(:service => "iptables") end execute "service iptables restart" do user "root" command "service iptables restart" end When you run vagrant up, you will see the following output (excerpt). ... INFO: Processing template[/etc/sysconfig/iptables] action create (bpif_apache2::default line 40) INFO: template[/etc/sysconfig/iptables] backed up to /var/chef/backup/etc/sysconfig/iptables.chef-20130312055953 INFO: template[/etc/sysconfig/iptables] updated content INFO: template[/etc/sysconfig/iptables] owner changed to 0 INFO: template[/etc/sysconfig/iptables] group changed to 0 INFO: template[/etc/sysconfig/iptables] mode changed to 600 INFO: Processing execute[service iptables restart] action run (bpif_apache2::default line 49) INFO: execute[service iptables restart] ran successfully ... The following links helped me grok and finally solve this problem. https://github.com/pdaether/LAMP-CentOS-with-Vagrant/blob/master/files/iptables.txt http://infrastructure.fedoraproject.org/csi/security-policy/en-US/html/HostIptables-Standard-Introduction-Prerequisites.html FWIW, Opscode seems to be to find the firewalls in CentOS a bit of a challenge, too, as per their apache2 cookbook README (Feb 23, 2013): The easiest but certainly not ideal way to deal with IPtables is to flush all rules. Opscode does provide an iptables cookbook but is migrating from the approach used there to a more robust solution utilizing a general "firewall" LWRP that would have an "iptables" provider. Alternately, you can use ufw, with Opscode's ufw and firewall cookbooks to set up rules. See those cookbooks' READMEs for documentation.
{ "pile_set_name": "StackExchange" }
Q: How i can add phing task for automated parsing my project and cresting a PO for translation? How i can add phing task for automated parsing my project and creating a PO for translation? A: You can use xgettext to collect all gettext-translatable strings: http://sourceforge.net/p/semanticscuttle/code/ci/cb4b0469ca48d9865c8b162c1446d9011adf249b/tree/scripts/update-translation-base.php#l11 $ xgettext -kT_ngettext:1,2 -kT_ -L PHP -o data/locales/messages.po src/ Execute that from your phing task.
{ "pile_set_name": "StackExchange" }
Q: command to retrieve the parent directory name if file doesn'texists in child directory in linux Get the directory name as output(19.08) when final.txt doesn't appears in trans sub folder. Main parent directory names( 19.02,19.04,19.06) keeps changing. But the subfolder names(base and trans) are always same and final.txt always will be available only under trans folder. When the final.txt is not available under the trans folder it should return the 19.08 as output in linux/shell? Please suggest on this |--Project |-- 19.02 | |-- base | |-- trans -- final.txt |-- 19.04 | |-- base | |-- trans -- final.txt |-- 19.06 | |-- base | |-- trans -- final.txt |-- 19.08 |-- base |-- trans Thanks in advance!! A: The pure find solution, based on this thread: find . -mindepth 2 -maxdepth 2 -type d '!' -exec sh -c 'test -e "$1"/trans/final.txt' -- {} ';' -print | # remove the leading Project from path xargs -n1 basename Find directories that are exactly two level down For each entry execute test -e <entry>/trans/final.txt - ie. check if final.txt exists If it does not '!' exist, then -print the path. The | xargs -n1 basename is used to transform ./Project/19.08 into just 19.08. My first solution using comm and creating lists, with comments in code: # Create an MCVE mkdir -p Project/19.0{2,4,6,8}/{base,trans} touch Project/19.0{2,4,6}/trans/final.txt # Extract only unique lines from the first list # So the folders which do not have final.txt in them comm -23 <( # Create a list of all Project/*/ folders find . -mindepth 2 -maxdepth 2 | sort ) <( # Create a list of all Project/*/*/final.txt files find . -mindepth 4 -maxdepth 4 -name final.txt -type f | # Extract only Project/*/ part, so twice dirname xargs -n1 dirname | xargs -n1 dirname | sort ) | # Remove the leading 'Project' name xargs -n1 basename
{ "pile_set_name": "StackExchange" }
Q: How to require other CoffeeScripts files in main CoffeeScript with Laravel? I have one CoffeeScript project with "Ruby on Rails" framework. Now I want to use "Laravel" framework instead of "Ruby on Rails". In "Ruby on Rails", there is "Sprocket" asset pipeline management library. With "Sprocket", I can import other coffeescript files in main coffeescript file with #= require or #= require_tree statement e.g. #= require views/view #= require_tree ./views #= require_tree ./templates init = -> document.removeEventListener 'DOMContentLoaded', init, false if document.body app.init() else setTimeout(init, 42) What are the counterparts on Laravel for these #= require and #= require_tree statements? Is there any other ways to solve this problem with Elixir? A: As there is no answer, I have to explore the solution by myself and here is the one. In Laravel-elixir version (2.3.6), there is a concatenation feature for coffeescript. You have to store coffeescript files in resources/assets/coffee directory. Then, the following script in gulpfile.js will generate a single app.js that compile and concatenate all coffeescripts in the provided array parameter. elixir(function(mix) { mix.coffee(['app.coffee', 'collection.coffee']); }); So, you don't need to include other coffeescript files in main coffeescript file like in Sprocket of Ruby on Rails. But there is still one issue that how to require all coffeescript files in more than one directory. These coffeescript files should also be in order so that their dependencies don't broken. It is cumbersome to write each coffeescript file name in order to be required. The following script can perfectly solve this issue. mix.coffee([ 'lib/license.coffee', 'lib/*.coffee', 'app/app.coffee', 'app/config.coffee', 'app/*.coffee', 'collections/collection.coffee', 'collections/*.coffee', 'models/model.coffee', 'models/*.coffee', 'views/view.coffee', 'views/*.coffee', 'templates/*.coffee', 'application.coffee' ]); mix.scripts(null, 'public/js/vendor.js', 'resources/assets/coffee/vendor'); You can require all coffeescript files in directory with *(asterisk) sign like that 'models/*.coffee'. You can also specify the file that should be required at first before requiring all the files in directory, by their filename like that 'models/model.coffee'. Laravel-elixir is intelligent enough to not compile and concatenate that file again. That's the way how I solved the problem in my question.
{ "pile_set_name": "StackExchange" }
Q: Acts_as_commentable not getting commentable_id So I've been stuck at this for an hour or so now. The problem I am having is not getting the "Tour.id". However if I do: commentable = Tour.find(1) comment = commentable.comments.create it saves with the right commentable_id and commentable_type. Here's how things are looking: show.html.erb <%= form_for [@tour, @comment] do |f| %> <%= f.text_area :comment %> <% end %> tours_controller.rb @tour = Tour.find(params[:id]) @comment = @tour.comments.new comments_controller.rb @commentable = @tour @comment = @commentable.comments.create routes.rb resources :tours do resources :comments member do put :submitreview end end results in: NoMethodError in CommentsController#create undefined method `comments' for nil:NilClass Request Parameters: {"utf8"=>"✓", "authenticity_token"=>"mxHD+yj6PKG4gCrYuGrwKEKWHOofCaoE4G7bAoEs6J4=", "comment"=>{"comment"=>"okokok"}, "commit"=>"Create Comment", "tour_id"=>"1"} What am I doing wrong here?! A: In the action in your comments controller, you aren't assigning @tour any value thus it's nil. And then your calling comments on it in the next line. Which is why you're getting that error.
{ "pile_set_name": "StackExchange" }
Q: iOS UIScrollview Auto Layout - UILayoutFittingCompressedSize I'm following Apple's guidelines on implementing Auto Layout with UIScrollView at the link below. http://developer.apple.com/library/ios/#releasenotes/General/RN-iOSSDK-6_0/index.html It says, "Alternatively, you can create a view subtree to go in the scroll view, set up your constraints, and call the systemLayoutSizeFittingSize: method (with the UILayoutFittingCompressedSize option) to find the size you want to use for your content view and the contentSize property of the scroll view." My problem is, when I call CGSize newSize = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; newSize has widths that are greater than 320. How can I constrain it so that the newSize has a width of 320, and so the function systemLayoutSizeFittingSize returns a large height to fit all the views? Is there a different argument I could use instead of UILayoutFittingCompressedSize? Thanks! EDIT: I have a UILabel subview of contentView, and it's numberOfLines is set to 0. However, I see that when I call sizeThatFits on this UILabel, it returns widths greater than 320. As a result, the self.contentView method call returns a newSize that is big enough to support the UILabel. Therefore, I think the problem originates with my UILabel. How do I make sure that the UILabel, when sizeToFit is called, returns a width that is less than 320, so only the height is scaled to fit the body of the text? A: Found a solution. The property called preferredMaxLayoutWidth for UILabel worked for me. I applied it to the UILabel with a value of 320, and now the self.contentView method does not return a width greater than 320. It is interesting to note that the UILabel sizeThatFits method DOES NOT take into consideration the preferredMaxLayoutWidth, as the CGSize it returned still had widths greater than the prefferedMaxLayoutWidth.
{ "pile_set_name": "StackExchange" }
Q: date of birth - day filter depending on month I am currently working on a day dropdown list for date of birth, the values in this field will depend on what month is selected. I currently have this working as shown below but I want to move the logic into the controller or a filter and not leave it in the html file. <select name="personal_dob_day" ng-model="dob_day"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> <option>10</option> <option>11</option> <option>12</option> <option>13</option> <option>14</option> <option>15</option> <option>16</option> <option>17</option> <option>18</option> <option>19</option> <option>20</option> <option>21</option> <option>22</option> <option>23</option> <option>24</option> <option>25</option> <option>26</option> <option>27</option> <option>28</option> <option ng-if=" dob_month != 'February' || !( dob_year % 4)")> 29 </option> <option ng-if=" dob_month != 'February'"> 30 </option> <option ng-if=" dob_month == 'January' || dob_month == 'March' || dob_month == 'May' || dob_month == 'July' || dob_month == 'August' || dob_month == 'October' || dob_month == 'December'"> 31 </option> </select> What I want to do is in the controller create an array as such: var dayRange = []; for(var i=1;i<=31;i++) { dayRange.push(i); } $scope.days = dayRange; and use ng-options to loop through like this: <select ng-options="day for day in days track by day" name="personal_dob_day" ng-model="dob_day" > I am thinking if I do it this way is it possible to implement a filter of some sort which would check the values of the month model and only display the appropriate days in the dropdown for days? If so how would I go about creating such a filter as my experience with them is limited. Or perhaps there is a better way all together to go about this? Any help on this matter would be greatly appreciated. Thanks. A: You should consider using the ng-options directive passing in an expression that pulls the labels from an array in the model of the controller. First construct the controller that will hold the arrays for the Years, Months and Days. Create properties on the $scope object so you can access those arrays through the ng-options directive on the view. If you include JQuery as a dependency you can construct your arrays the following way: var years = $.map($(Array(numberOfYears)), function (val, i) { return i + 1900; }); var months = $.map($(Array(12)), function (val, i) { return i + 1; }); var days = $.map($(Array(31)), function (val, i) { return i + 1; }); If you prefer not to have a JQuery dependency just use a good old for loop for all three arrays. The following code will give you accessors on the $scope for the arrays: $scope.Years = years; $scope.Months = months; $scope.Days = days; Back in your HTML view add a select element with the ng-options and ng-model ng-options directives for example: <div class="ng-scope" ng-controller="BirthdayController"> <select ng-model="SelectedYear" ng-options="label for label in Years"></select> <select ng-model="SelectedMonth" ng-options="label for label in Months"></select> <select ng-model="SelectedDays" ng-options="label for label in Days"></select> </div> I am assuming you are familiar with creating AngularJS modules and adding controllers to it as well as adding the necessary ng-app directive, ng-scope class and ng-controller directives to the containers. Up to this point you will have three drop down lists containing a list of years, a list of 12 months and a list of 31 days respectively. If you want to have a dependent day list keep reading! :) Refer to this plnkr for the basic version: http://plnkr.co/edit/VfEpwPv084H7XiifEsnm?p=preview Bonus round: You can take this one step further and make the days list show correct number of days since days really has a dependency on the month and year selected. February has 28 days on non leap years and 29 days on leap years. Other months have 30 or 31 days depending on the month. If you want to go all fancy you need a function in the controller to determine leap years and to determine how many days to return to calculate whether a year is a leap year in javascript the following function is quite useful: var isLeapYear = function (selectedYear) { var year = SelectedYear || 0; return ((year % 400 == 0 || year % 100 != 0) && (year % 4 == 0)) ? 1 : 0;} Although it will look slightly different using Angular since the $scope will already contain the selectedYear and won't have to be passed in. The isLeapYear helper function is accessed by another function which determines how many days to display for the given month and year combination as follows: var getNumberOfDaysInMonth = function (selectedMonth) { var selectedMonth = selectedMonth || 0; return 31 - ((selectedMonth === 2) ? (3 - isLeapYear()) : ((selectedMonth - 1) % 7 % 2));} Now all that needs to be done on the original select element for days would be to add a limitTo filter on the ng-options directive to change how many elements are actually rendered. The Select element for Months and Years require a ng-Change directive so we can update the field on the $scope which will hold the number to limit the days by. <select ng-model="SelectedYear" ng-options="label for label in Years" ng-change="UpdateNumberOfDays()"></select> <select ng-model="SelectedMonth" ng-options="label for label in Months" ng-change="UpdateNumberOfDays()"></select> <select ng-model="SelectedDays" ng-options="label for label in Days | limitTo:NumberOfDays"></select> Where NumberOfDays is populated in the function on the controller $scope.UpdateNumberOfDays() which of course will utilize the helper function GetNumberOfDaysInMonth described above. And as an extra bonus here is a plnkr for the smart version: http://plnkr.co/edit/AENh6Ynj4kNKZfLsXx4N?p=preview Enjoy!
{ "pile_set_name": "StackExchange" }
Q: When is a metric space Euclidean, without referring to $\mathbb R^n$? Normally, the Euclidean space is introduced as $\mathbb R^n$. However, I've now been thinking about how one might define the $n$-dimensional Euclidean space only from the properties of the metric. I've come up with the following conjecture: A metric space $(M,d)$ is an $n$-dimensional Euclidean space iff it has the following properties: Line segment (L): For any two points $A,B\in M$ and any number $\lambda\in [0,1]$, there exists exactly one point $C\in M$ so that $d(A,C)=\lambda\,d(A,B)$ and $d(C,B)=(1-\lambda)\,d(A,B)$. Uniqueness of extension (U): If for any points $A,B,C,D\in M$ with $A\ne B$ we have $d(A,C)=d(A,B)+d(B,C)=d(A,D)=d(A,B)+d(B,D)$ then $C=D$. Homogeneity (H): For any four points $A,B,C,D\in M$ with $d(A,B)=d(C,D)$ there exists an isometry $\phi$ of $M$ so that $\phi(A)=C$ and $\phi(B)=D$. Scale invariance (S): For any $\lambda>0$ there exists a function $s\colon M\to M$ so that for any two points $A,B\in M$ we have $d(s(A),s(B)) = \lambda\,d(A,B)$. Dimension (D): The maximal number of different points $P_1,\ldots,P_k$ so that each pair of them has the same distance is $n+1$. Now my question: Is this correct? That is, do those conditions already guarantee that the metric space is an $n$-dimensional Euclidean space? If not, what would be an example of a metric space which is not Euclidean, but fulfils all the conditions above? What I already found (unless I've done an error, in that case, please correct): It is easy to see that it contains a full line for each pair of points: Given the points $A$ and $B$, the condition (L) already gives the points in between $A$ and $B$. Now for any $r>0$, (S) tells us that there exist two points $C,D$ so that $d(C,D) = (r+1)\,d(A,B)$. Then (L) guarantees the existence of a point $E$ with $d(C,E)=1$ and $d(E,D)=r$. And (H) guarantees us an isometry $\phi(C)=A$ and $\phi(E)=B$. Then the line segment from $A$ to $\phi(D)$ extends the line segment in the direction of $B$. (U) guarantees us that this extension is unique. If we define a straight line $l$ as a set of points so that for any three points $A, B, C\in l$ the largest of their distances is the sum of the other two distances, then from we also get immediately that two lines can intersect at most in one point (because if they have two points in common, then (L) guarantees that all points in between are also common, and I just showed that the extension is also unique). I can also use the law of cosines to define the angle $\phi = \angle ABC$ as $\cos\phi = \frac{d(A,C)^2-d(A,B)^2-d(B,C)^2}{2\,d(A,B)\,d(B,C)}$ (of course the law of the cosine assumes Euclidean geometry, but since I'm defining the angle, this just means that if the space is not Euclidean, the angle I just defined is not the usual angle). It is obvious that this angle is independent of scaling (because a common factor just cancels out). I also think that with the definition of the angle above, I should get that the sum of angles in the triangle is always $\pi$ (because I can just map the three points individually on three points with the same distance onto a known Euclidean plane, and there I know that the angles add up to $\pi$). However is that already sufficient to show that it is an Euclidean space? Or could there be some strange metric space where all this is true without it being an Euclidean space? A: Maybe this has some relevance: Cayley–Menger determinants. (Most of this Wikipdia article was destroyed on November 11th by a user called "Toninowiki". I've restored much of what was destroyed. The original poster in this present thread has commented below that the article does not deal with higher dimensions. That is wrong. If you look at it and don't see anything on higher dimensions, then look at the version of the article that was there before November 11th. Or at the one I left there a few minutes ago.) A: I think the issue here is that there is some confusion between your use of the terms metric space, Euclidean and $\mathbb{R}^{n}$. The most general object in the list above is that of a metric space. The axioms given in the question are satisfied by any complete homogenous metric space -- for example the hyperbolic metric on the unit $n$-ball. So if you start with the underlying space $\mathbb{R}^n$, and give $\mathbb{R}^n$ the standard metric, then the axioms are satisfied. If you take a different underlying set, say the unit ball, and put a hyperbolic metric on it, again the axioms are satisfied! So your axioms do not really distinguish between different metrics. They just give properties satisfied by many metrics on different spaces. If you are asking if $\mathbb{R}^n$ can be given a metric that satisfies the axioms but where the cosine law say is different, then the answer is no. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: self.connect() vs QMainWindow.connect() playing as a newbie with pyQT4 SIGNAL and SLOT, I realized that in all my simple cases there is actually no difference between <class>.connect(...) and self.connect(...) , meaning that both do what I want. Most simple case would be connecting a Button of a QWindow like in the title of the question. Is there a difference and can someone explain it to me? A: The connect method you're refering to is acutally QObject.connect, which is a static method. So it doesn't really matter if you call it on an instance or a subclass of QObject or on QObject directly. That said, don't use it. It's better to use the connect method of the signal instead: qobject_instance.signal_name.connect(slot_or_callable) This is referred to as "new style signals", and it's the preferred way of connecting signals in PyQt4. In PyQt5 the old style signals are even gone completely, that means QObject.connect doesn't exist anymore and you must use new style signals.
{ "pile_set_name": "StackExchange" }
Q: Combine CSS background-image and gradient on third h3 using nth-child I'm having a heck of a time trying to combine a diagonal linear gradient and regular background-image together plus apply it only to the second h3 element; here is what I've got: HTML <div id="something"> <div><h3>...</h3></div> <div><h3>...</h3></div> <div><h3>...</h3></div> <div><h3>...</h3></div> </div> CSS #something h3:nth-child(2) { background: linear-gradient(135deg, rgba(221,221,221,1) 0%, rgba(221,221,221,1) 95%, rgba(0,0,0,1) 95%, rgba(0,0,0,1) 100%), #ddd url(/assets/img/bullet.png) left 12px no-repeat; } I've had the nth-child selector working on other stuff previously before and this gradient is from an online generator, what am I missing here? A: Looks like the selector should be: #something > div:nth-child(3) > h3 https://jsfiddle.net/db2n5r63/1/
{ "pile_set_name": "StackExchange" }
Q: Access playbook variables from custom module in Ansible I'm writing a custom module in Ansible, specific to a Playbook. Is it possible to directly access a playbook variable, without needing to pass it to the task as a parameter? A: It is not possible, because the module is executed remotely and all the variables are not available unless explicitly passed. I had the same question a while ago and Pruce P offered an interesting workaround in his answer. Though I had another idea in the meantime, but this is only theoretical and never tested: Beside normal modules, Ansible has a special kind of module: action plugins. (...not documented) They are used exactly like modules but are executed locally. Since they run locally they do have access to Ansibles runner object which holds all the group/host vars etc. The cool thing is, you can call a module programmatically from the action plugin. So you could have a small wrapper action plugin which then calls the actual module and passes all (required) vars to it. Since it is undocumented you need to look at the available plugins. For instance here is one which calls a module: assemble. I have written something here which interacts with vars from the runner object.
{ "pile_set_name": "StackExchange" }
Q: Is there a way I can take a macro picture without a macro lens? I have a Nikon d3300 camera, but the only two lenses I have for it are a 18-52mm and a 70-300mm. I would like to take macro pictures, but can't really afford a specialized lens yet. When I try to take a picture close up, the lenses I have can't focus close enough to anything for it to work properly. There's only so far I can crop and zoom before the picture quality gets so bad. Is there a way I can take a macro picture without actually having a macro lens? A: You can actually flip the lens around and use it as a macro lens that way. Since it's not going to be connected to the camera body, you're obviously going to lose the ability to zoom, and you'll have to focus by moving the camera to and from the object, but it actually works quite well once you get the hang of it. The only thing I've found that's a pain is keeping the aperture open. source The aperture is closed by default, and opened using a little switch in the part of the lens that connect to the camera body. You can kind of see it in the picture above, it's on the right next to the screw. You'll have to hold that switch open in order to let enough light in through the lense to take any pictures. Just be warned, there's a big downside to using this method, because you're holding the lense out in the open like that you're allowing dust and dirt to get into it. You can get lens reversal kits, which are cheaper than getting an actual macro lens. All they'll do is allow you to connect the lens on backwards, and protect the backside of your lense from dust.
{ "pile_set_name": "StackExchange" }
Q: What are the naming guidelines for ASP.NET controls? We are in the process of nutting out the design guidelines we would like to use in our development team and got into a discussion today around how ASP.NET controls should be named. I am talking about our good friends Label, TextBox, Button etc. We came up with the following three possibilities that we voted on: (Example is a TextBox to enter/display a FirstName) Add the control type as a postfix to your controls ID: [FirstName_TextBox] or [FirstName_tbx] Add the control type as a prefix to your controls ID [tbxFirstName] Set the ID of the control to FirstName and name related fields (like a label for the textbox or a validator) as in option 2 [lblTextBox]. We ended up deciding to use option 2. It's not as verbose as option 1 and I like that it specifies what control it is before the name of the control. My question is whether Microsoft has released any guidelines for these prefixes and or if you have any comments about our decision. A: The reason Visual Studio adds "TextBox1" when you add it to the page is because Microsoft has no way of knowing how you intend to use it. Naming it "Control1" would be too confusing because it could be any number of controls. Microsoft provides guidance in general for OO naming conventions, but not specifically for naming UI controls. Since UI controls are ultimately variables used in code, they should follow the same convention as any other variable - no hungarian notation prefix. msdn.microsoft.com/en-us/library/xzf533w0(vs.71) msdn.microsoft.com/en-us/library/ms229002(VS.80) The main reasons are... Type of control may change from textbox to listbox, then all associated code will have to be fixed (noted earlier) Your code should be more concerned with the content of the control and less with what type of control it is. When you are concerned with the type of the control, you start to depend on certain functionalities and you break encapsulation - you should be able to easily swap controls without changing much or any code. (Basic OOP principle) It is fairly easy to come up with prefixes for the standard controls, but new controls are being developed every day. You may make your own WebUserControl, or you may purchase a set of third party controls. How will you decide which prefix to use for the custom controls? Instead of focusing on the type of control, your code should be concerned with what information is contained in it. Examples txtFirstName => firstName or FirstName txtState => state or State cboState => state or State (prime example of changing control types what about lstState or rdoState - they should all have the same name because your code is not concerned about the type of control,rather the state the user selected) ctlBilling => billingAddress or BillingAddress (custom control - with hungarian notation it is not very evident what the control even is, but with a meaningful name I begin to understand the information contained in it. i.e. billingAddress.Street, billingAddress.FullAddress etc.) A: Not sure about Microsoft official standards, but this is what i've done through out my development career. I generally abbreviate the control type in front of the the name of what the control does. I keep the abbreviation lower case and the control's name CamelCase. E.g. A texbox for username becomes tbUserName Here is a list of standard abbreviations I use: Abbr - Control btn - Button cb - CheckBox cbl - CheckBoxList dd - DropDownList gv - GridView hl - Hyperlink img - Image ib - ImageButton lbl - Label lbtn - LinkButton lb - ListBox lit - Literal pnl - Panel ph - PlaceHolder rb - RadioButton rbl - RadioButtonList txt - Textbox A: I find that most of the time I care about what kind of information the control is for rather than what control type is currently being used to capture that data, so I prefer the type of information before the control type, so I can find it in a sorted list in the IDE: AgeRangeDropDownList AgreedToTermsCheckBox FirstNameTextBox LastNameTextBox VS: chkAgreedToTerms ddlAgeRange txtFirstName txtLastName
{ "pile_set_name": "StackExchange" }
Q: bash - make command not found I have created make file named Makefile in my linux ec2 server. all: a b a: daemon.cpp dictionary_exclude.cpp g++ -o a daemon.cpp dictionary_exclude.cpp -lpthread -std=c++0x -L. b: user_main.cpp client.cpp g++ -o b user_main.cpp client.cpp I could run each of this independently successfull. But when I execute make make -f Makefile It says make : -bash: make: command not found Any idea? I can see manually for make is available through man make A: Please execute following command to install make in your system sudo yum install build-essential A: In CentOS or Red Hat, try this: yum groupinstall "Development Tools"
{ "pile_set_name": "StackExchange" }
Q: How do I revert an SVN commit? I have found various examples of how to revert an SVN commit like svn merge -r [current_version]:[previous_version] [repository_url] or svn merge -c -[R] . But neither of them seems to work. I tried those commands and checked the files that were changed by hand. How do I revert a commit with revision number 1944? How do I check that the revert has been done (without looking in the actual file to the changes have been reverted)? A: Both examples must work, but svn merge -r UPREV:LOWREV . undo range svn merge -c -REV . undo single revision in this syntax - if current dir is WC and (as in must done after every merge) you'll commit results Do you want to see logs? A: If you're using the TortoiseSVN client, it's easily done via the Show Log dialog. A: svn merge -r 1944:1943 . should revert the changes of r1944 in your working copy. You can then review the changes in your working copy (with diff), but you'd need to commit in order to apply the revert into the repository.
{ "pile_set_name": "StackExchange" }
Q: How can I setup a Calendar that has a form field to submit appointments? I'm trying to implement the planningCalendar to have a form that allows a user to enter an appointment time. Once the appointment has been submitted, it should automatically be displayed on the Calendar. Not sure how to implement this. Here's a link to the Calendar I have already constructed. A: You just have to update the model bound to the PlanningCalendar. The changes will automatically be reflected in the PlanningCalendar. You have to use the JSONModel.setProperty() to apply the changes to the model so that the model gets aware that there are changes. It will then update the bindings and with that the PlanningCalendar. The following code should work with the SAP example code you have linked. var model = this.getView().getModel(); //You will have to find the index of the person first. in this example: 0 var appointments = model.getProperty("/people/0/appointments"); appointments.push({ start: myFormularsStartDate, end: myFormularsEndDate, title: myFormularsTitle, ... }); model.setProperty("/peaople/0/appointments",appointments); For more information on databinding in sapui5 i would recommend you take the walkthrough. Example Plunker here.
{ "pile_set_name": "StackExchange" }
Q: Facebook OG Image suddenly misbehaving We've had news articles sharing to facebook correctly for a long time but as of last weekend we are starting to see the wrong og:image when shared to facebook. Using the debugger tool, the first time it is fetched I get a warning "image too small" which is probably why it defaults to another image. But the image in question is not too small. Could this be some issue with headers of my images in Amazon Bucket maybe? Cannot pin point the problem yet. Pressing scrape again 2 times then I get the correct og:image As an attempt to fix this I have added og:image:width and og:image:height but so far to no avail. Debugger url: https://developers.facebook.com/tools/debug/sharing/?q=http%3A%2F%2Fwww.maltatoday.com.mt%2Fnews%2Fworld%2F79568%2Fsicily_firefighters_caused_fires_for_cash A: Adding og:image:width and og:image:height as additional meta tags solved the issue for me. User nunsy_grey mentioned that this doesn't solve it for some user so worth looking at this alternative solution
{ "pile_set_name": "StackExchange" }
Q: Python: for multiple properties use one getter and setter method I have created a class that has multiple properties. I want to use one function for the getter method and the second one for the setter method. class person: def __init__(self, fname, lname, city, state): # make all attributes as private self._fname = fname self._lname = lname self._city = city self._state = state @property # get method def fname(self): return self._fname @fname.setter # set method def fname(self,fname): self._fname = fname @property def lname(self): return self._lname @lname.setter def lname(self,lname): self._lname = lname @property def city(self): return self._city @city.setter def city(self, city): self._city = city @property def state(self): return self._state @state.setter def state(self, state): self._state = state How to use all properties for one get methods and one set method? e.g.: def get(self): return self._attr def set(self,value): self._attr = value A: class person: def __set_name__(self, name): self.name = name def __get__(self, obj, type=None) -> object: return obj.__dict__.get(self.name) def __set__(self, obj, value) -> None: obj.__dict__[self.name] = value my_value = person my_values.fname = 'Shivam' my_values.lname = 'Gupta' print(my_values.fname) #--> Shivam print(my_values.lname) #--> Gupta
{ "pile_set_name": "StackExchange" }