qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
11,459
What is the difference between *Ereignis* and *Vorkommen*. I keep on needing explanation in this question even so some can think it's nonsense. If someone, in Hedegger's understanding, could explain me, it would be even more thankful.
2014/04/14
[ "https://german.stackexchange.com/questions/11459", "https://german.stackexchange.com", "https://german.stackexchange.com/users/5209/" ]
Because it's explicitely asked for, I give some definitions for `Ereignis` and `Vorkommen` in some scientific fields. Feel free to add others. Ereignis ======== Probability theory ------------------ `Ereignis` is a subset of a sample space. Physics ------- `Ereignis` is a single element of the spacetime. Astronomy --------- `Ereignis` is any observable phenomenon in the sky. Vorkommen ========= Geology ------- `Vorkommen` is any local amount of ore, minerals or rock. Geography without Geology ------------------------- `Vorkommen` is any local, regional or national amount of any economic ressource. Biology ------- `Vorkommen` is the set of individuals of a given species living in a specific area.
28,698,441
Sorry if the title isn't descriptive, but I'm working on a web-based application in javascript using the HTML5 canvas. I want the page to adjust to the window size, but I also want the columns to be resizable - that is, you can drag the vertical lines to change their width. The thing is, the canvas width and height attributes must be in pixels (setting the CSS properties stretches the image instead of widening the drawing surface). I need to change the canvas attributes through javascript. I have trouble working with all of these constraints together. ![Disposition example](https://i.stack.imgur.com/BowtE.png) I tried Making the templates-panel float left and the properties-panel float right, but it ends up below the canvas and above the status-bar everytime. I've also got the status bar set to `position:fixed` but it tends to go above the canvas a bit. How would you do it? Keep in mind I have to be able to resize the window or the panels individually (except the menubar and status bar which never change size). EDIT: quick edit to add that I can't use JQuery / JQuery-UI. The application is quite computer-intensive, so I had to get rid of it. My compatibility target is IE9 anyway.
2015/02/24
[ "https://Stackoverflow.com/questions/28698441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813263/" ]
I did a quick google search on how to do this and found a stack overflow post with a similar answer, here is the fiddle that was provided, here is the javascript portion: ``` var i = 0; $('#dragbar').mousedown(function(e){ e.preventDefault(); $('#mousestatus').html("mousedown" + i++); $(document).mousemove(function(e){ $('#position').html(e.pageX +', '+ e.pageY); $('#sidebar').css("width",e.pageX+2); $('#main').css("left",e.pageX+2); }) console.log("leaving mouseDown"); }); $(document).mouseup(function(e){ $('#clickevent').html('in another mouseUp event' + i++); $(document).unbind('mousemove'); }); ``` <http://jsfiddle.net/gaby/Bek9L/> And here is the post: [Emulating frame-resize behavior with divs using jQuery without using jQuery UI?](https://stackoverflow.com/questions/4673348/emulating-frame-resize-behavior-with-divs-using-jquery-without-using-jquery-ui) The fiddle uses jQuery but not jQuery UI, You will need to use percentages for width, look into responsive design. <http://learn.shayhowe.com/advanced-html-css/responsive-web-design/> I hope this helps
71,036,090
Not able to click on the button inside iframe using cypress **HTML** ``` <button class="MuiButtonBase-root MuiCardActionArea-root jss9" tabindex="0" type="button"> <div class="MuiPaper-root MuiCard-root jss11 MuiPaper-elevation1 MuiPaper-rounded"> <div class="MuiBox-root jss25 jss12"> <div class="MuiCardContent-root"> <div class="MuiBox-root jss26 jss13"><i class="icon-ehr"></i></div> <div class="MuiBox-root jss27"> <h5 class="MuiTypography-root jss14 MuiTypography-h5">SOME HEADER</h5> </div> <p class="MuiTypography-root MuiTypography-body2">SOME TEXT</p> </div> </div> </div> <span class="MuiCardActionArea-focusHighlight jss10"></span><span class="MuiTouchRipple-root"></span> </button> ``` **code:** ``` it('Open Product Dashboard and EHR App ', function () { cy.get('#dashboardMfcApp').then(($iframe) => { const $doc = $iframe.contents() cy.wrap($doc.find('button')) .get('.MuiButtonBase-root') .children() .within(() => { cy.find('.MuiButtonBase-root') .get('.MuiTypography-root') .contains('SOME HEADER') .click() }) }) }) ``` **Error:** > > Timed out retrying after 4000ms: Expected to find element: > MuiTypography-root, but never found it. > > >
2022/02/08
[ "https://Stackoverflow.com/questions/71036090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2384416/" ]
Try using xpath for the button. I had the same issue and it worked when I used the xpath in cypress.
32,653,448
We are using Angular UI Grid in out project. I need to put current date in file name with exported CSV data. What I'm doing now on "export" button click: ``` $scope.exportCSV = function () { $scope.gridOptions.exporterCsvFilename = getDate() + ".csv"; $scope.gridApi.exporter.csvExport("all", "visible"); }; ``` The problem is that filename is configured only once and doesn't change in next clicks. How can I set file name again?
2015/09/18
[ "https://Stackoverflow.com/questions/32653448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226395/" ]
For dynamically changing the file name you need to inject **uiGridExporterService** service, then you can call the **downloadFile** function that accepts file name as a first argument. Example: ``` var app = angular.module('app', ['ngAnimate', 'ui.grid', 'ui.grid.selection', 'ui.grid.exporter']); app.controller('MainCtrl', ['$scope','uiGridExporterConstants','uiGridExporterService', function ($scope,uiGridExporterConstants,uiGridExporterService) { $scope.exportCSV = function(){ var exportService=uiGridExporterService; var grid=$scope.gridApi.grid; var fileName=getDate() + ".csv"; exportService.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function() { var exportColumnHeaders = exportService.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE); var exportData = exportService.getData(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE); var csvContent = exportService.formatAsCsv(exportColumnHeaders, exportData, grid.options.exporterCsvColumnSeparator); exportService.downloadFile(fileName, csvContent, grid.options.exporterOlderExcelCompatibility); }); } }]); ``` Live example: <http://plnkr.co/edit/O44fbDiCe6Pb5vNYRVSU?p=preview>
65,552,256
I've been working on a simple horizontal navigation bar using html, css and javascript. The navigation bar contains a dropdown menu (named More). Clicking on the More menu causes hidden links to be shown (vertically) beneath the More heading, and clicking again causes the links to be hidden again. I tried setting the positions of the navigation bar element and More menu element to be "relative" in the css code, and set the position of the hidden links element to be "absolute", also in the css code. However, when I then clicked on the More menu, it didn't show the hidden links. Nothing happened. But if I comment out the "relative" positioning of both the navigation bar and More menu, clicking on the More menu works (the hidden links are shown). I've included the buggy code (html, css and javascript). Why doesn't the buggy code display the hidden links when clicking on More? Thanks, Mfl. ```js function clickMoreMenu() { var x = document.getElementById("hiddenlinks"); if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } } ``` ```css #navbar { margin : 0; padding : 0; background : Pink; overflow : hidden; position : relative; } .navoption { float : left; } #moremenu { position: relative; display : inline-block; background : Pink; } #hiddenlinks { display: none; position : absolute; z-index : 1; background : Pink; } div a { display : block; text-align : center; text-decoration : none; color : Black; padding : 10px; } div a.current {background : HotPink; } div a:hover { background : DeepPink; color : White; } ``` ```html <html lang = "en"> <head> <meta charset = "utf-8"> <title>Test Navigation Bar Page</title> <link href="testnav.css" type="text/css" rel="stylesheet" /> </head> <body> <div id = "navbar"> <div class="navoption"> <a href="option1.html">Option 1</a> </div> <div class="navoption"> <a href="option2.html">Option 2</a> </div> <div class="navoption"> <a href="option3.html">Option 3</a> </div> <div class="navoption" id = "moremenu"> <div> <a href="javascript:void(0);" onclick="clickMoreMenu()">More</a> </div> <div id = "hiddenlinks"> <a href="option4.html">Option 4</a> <a href="option5.html">Option 5</a> <a href="option6.html">Option 6</a> </div> </div> </div> <h1>Test Navigation Bar Page</h1> <script src="moremenu.js"></script> </body> </html> ```
2021/01/03
[ "https://Stackoverflow.com/questions/65552256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14928239/" ]
You set overflow of #navbar, which makes your hiddenlinks invisible simply because they are not fitting in. A possible solution is not using overflow hidden: ```js function clickMoreMenu() { var x = document.getElementById("hiddenlinks"); if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } } ``` ```css #navbar { margin : 0; padding : 0; background : Pink; position : relative; display: flex; } .navoption { float : left; } #moremenu { position: relative; display : inline-block; background : Pink; } #hiddenlinks { display: none; position : absolute; z-index : 1; background : Pink; } div a { display : block; text-align : center; text-decoration : none; color : Black; padding : 10px; } div a.current {background : HotPink; } div a:hover { background : DeepPink; color : White; } ``` ```html <html lang = "en"> <head> <meta charset = "utf-8"> <title>Test Navigation Bar Page</title> <link href="testnav.css" type="text/css" rel="stylesheet" /> </head> <body> <div id = "navbar"> <div class="navoption"> <a href="option1.html">Option 1</a> </div> <div class="navoption"> <a href="option2.html">Option 2</a> </div> <div class="navoption"> <a href="option3.html">Option 3</a> </div> <div class="navoption" id = "moremenu"> <div> <a href="javascript:void(0);" onclick="clickMoreMenu()">More</a> </div> <div id = "hiddenlinks"> <a href="option4.html">Option 4</a> <a href="option5.html">Option 5</a> <a href="option6.html">Option 6</a> </div> </div> </div> <h1>Test Navigation Bar Page</h1> <script src="moremenu.js"></script> </body> </html> ```
35,921,024
What's the most elegant solution in Django to take data from database and pass it into Highcharts? I stumbled across [this question](https://stackoverflow.com/questions/27810087/passing-django-database-queryset-to-highcharts-via-json), but I keep on getting the following error: JSerror: Invalid property id at `var chart_id = {{ chartID|safe }}`, if I try to use it in my example. template looks like this: ``` <html> <div id={{ chartID|safe }} class="chart" style="height: 100px; width: 500px"></div> <script> var chart_id = {{ chartID|safe }} var series = {{ series|safe }} var title = {{ title|safe }} var xAxis = {{ xAxis|safe }} var yAxis = {{ yAxis|safe }} var chart = {{ chart|safe }} </script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> ``` In case there are better ways to pass data to highcharts please let me know.
2016/03/10
[ "https://Stackoverflow.com/questions/35921024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5757338/" ]
Maybe you are missing the quotes in your javascript: ``` var chart_id = "{{ chartID|safe }}"; ```
12,806,023
I found an example ``` try { String data = "YOUR REQUEST BODY HERE"; // CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials("YOUR USER NAME HERE", "YOUR PASSWORD HERE")); // DefaultHttpClient http = new DefaultHttpClient(); http.setCredentialsProvider(credProvider); // HttpPut put = new HttpPut("YOUR HTTPS URL HERE"); try { put.setEntity(new StringEntity(data, "UTF8")); } catch (UnsupportedEncodingException e) { Log.e(TAG, "UnsupportedEncoding: ", e); } put.addHeader("Content-type","SET CONTENT TYPE HERE IF YOU NEED TO"); HttpResponse response = http.execute(put); Log.d(TAG, "This is what we get back:"+response.getStatusLine().toString()+", "+response.getEntity().toString()); } catch (ClientProtocolException e) { // Log.d(TAG, "Client protocol exception", e); } catch (IOException e) { // Log.d(TAG, "IOException", e); } ``` but I have to send a string in the format of the authorization: `<Login>@<ID>:<Passsword>` how to do this?
2012/10/09
[ "https://Stackoverflow.com/questions/12806023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1568164/" ]
It will be quite difficult (I am not even sure if it's possible) to implement the .NET interface directly in Delphi. There are, however, a few options available to you depending on how dirty you would like to get your hands. 1) You could create a ActiveX DLL in Delphi and then import this library into .NET. You could then create a proxy class in C# that implements the interface and just route the calls onto the Delphi ActiveX DLL. 2) You could create a native windows DLL in Delphi and then code the interface in .NET. You could then create a proxy class in C# that implements the interface and just route the calls onto the Delphi DLL. 3) You could use a plugin framework like Hydra (http://www.remobjects.com/hydra/) that supports both .NET and Delphi. In all of these cases you should be careful to handle the 32/64 bit situations as .NET code is capable of running in both but the Delphi code would need to be compiled for each environment independently. Another option depending on your situation might be to write the Delphi code in a form of object pascal that will produce .NET byte code called Oxygene (http://www.remobjects.com/oxygene/). **Edit:** If you are trying to create Delphi plug-ins for use in your .NET plugin framework it would be best to do something like this: Create a new interfaces in Delphi that match your IPlugIn and IPlugInHost interfaces. You could then build a .NET Delphi plugin wrapper that will have some configuration information to specify which Delphi plugin to load. This .NET wrapper would then load the Delphi DLL and call the DLL methods as required. Visual stuff would need some sort of ActiveX wrapper but you should be able to use the non visual stuff fine.
102,293
First, I am not a native English-speaking student so I am not good at physics definitions in English. I participated in the MIT e-learning course on classical physics. The 1st lesson is about 3 fundamental physical quantities (time, length and mass). > > It mentions dimensional units/quantity and dimensional state. I couldn't find the meaning of those in a dictionary. Can someone give me an specific explanation? > > > Also, in the lesson, why are the quantities always associated with some power of unknown value like $\alpha,\beta$, etc when we predict the equation? And how do we know what quantities should be added into the equation of a model? > > >
2014/03/06
[ "https://physics.stackexchange.com/questions/102293", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/41974/" ]
$x=x(y,z)$, $y=y(x,z)$, $z=(x,y)$ $$dx= (\frac{\partial x}{\partial y})\_z dy + (\frac{\partial x}{\partial z})\_y dz$$ $$dy= (\frac{\partial y}{\partial x})\_z dx + (\frac{\partial y}{\partial z})\_x dz$$ $$\therefore dx= (\frac{\partial x}{\partial y})\_z [(\frac{\partial y}{\partial x})\_z dx + (\frac{\partial y}{\partial z})\_x dz] + (\frac{\partial x}{\partial z})\_y dz$$ $$dx= (\frac{\partial x}{\partial y})\_z (\frac{\partial y}{\partial x})\_z dx + [(\frac{\partial x}{\partial y})\_z(\frac{\partial y}{\partial z})\_x + (\frac{\partial x}{\partial z})\_y] dz$$ $$(\frac{\partial x}{\partial y})\_z (\frac{\partial y}{\partial x})\_z dx + [(\frac{\partial x}{\partial y})\_z(\frac{\partial y}{\partial z})\_x + (\frac{\partial x}{\partial z})\_y] dz=1dx+0dz$$ $$ (\frac{\partial x}{\partial y})\_z(\frac{\partial y}{\partial z})\_x + (\frac{\partial x}{\partial z})\_y=0 $$ Using reciprocal relation: $$ (\frac{\partial x}{\partial y})\_z = \frac{1}{(\frac{\partial y}{\partial x})\_z} $$ $$\left( \frac{\partial x}{\partial y} \right)\_{z}\left( \frac{\partial y}{\partial z} \right)\_{x}\left( \frac{\partial z}{\partial x} \right)\_{y}=-1$$
60,358,675
I have a variable `x` that is between 0 and 1, or (0,1]. I want to generate 10 dummy variables for 10 deciles of variable `x`. For example `x_0_10` takes value 1 if x is between 0 and 0.1, `x_10_20` takes value 1 if x is between 0.1 and 0.2, ... The Stata code to do above is something like this: ``` forval p=0(10)90 { local Next=`p'+10 gen x_`p'_`Next'=0 replace x_`p'_`Next'=1 if x<=`Next'/100 & x>`p'/100 } ``` Now, I am new at R and I wonder how I can do above in R?
2020/02/23
[ "https://Stackoverflow.com/questions/60358675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9919210/" ]
`cut` is your friend here; its output is a `factor`, which, when used in models, R will auto-expand into the 10 dummy variables. ``` set.seed(2932) x = runif(1e4) y = 3 + 4 * x + rnorm(1e4) x_cut = cut(x, 0:10/10, include.lowest = TRUE) summary(lm(y ~ x_cut)) # Call: # lm(formula = y ~ x_cut) # # Residuals: # Min 1Q Median 3Q Max # -3.7394 -0.6888 0.0028 0.6864 3.6742 # # Coefficients: # Estimate Std. Error t value Pr(>|t|) # (Intercept) 3.16385 0.03243 97.564 <2e-16 *** # x_cut(0.1,0.2] 0.43932 0.04551 9.654 <2e-16 *** # x_cut(0.2,0.3] 0.85555 0.04519 18.933 <2e-16 *** # x_cut(0.3,0.4] 1.26441 0.04588 27.556 <2e-16 *** # x_cut(0.4,0.5] 1.66181 0.04495 36.970 <2e-16 *** # x_cut(0.5,0.6] 2.04538 0.04574 44.714 <2e-16 *** # x_cut(0.6,0.7] 2.44771 0.04533 53.999 <2e-16 *** # x_cut(0.7,0.8] 2.80875 0.04591 61.182 <2e-16 *** # x_cut(0.8,0.9] 3.22323 0.04545 70.919 <2e-16 *** # x_cut(0.9,1] 3.60092 0.04564 78.897 <2e-16 *** # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # Residual standard error: 1.011 on 9990 degrees of freedom # Multiple R-squared: 0.5589, Adjusted R-squared: 0.5585 # F-statistic: 1407 on 9 and 9990 DF, p-value: < 2.2e-16 ``` See `?cut` for more customizations You can also pass `cut` directly in the RHS of the formula, which would make using `predict` a bit easier: ``` reg = lm(y ~ cut(x, 0:10/10, include.lowest = TRUE)) idx = sample(length(x), 500) plot(x[idx], y[idx]) x_grid = seq(0, 1, length.out = 500L) lines(x_grid, predict(reg, data.frame(x = x_grid)), col = 'red', lwd = 3L, type = 's') ``` [![plot with fit](https://i.stack.imgur.com/Yetn8.png)](https://i.stack.imgur.com/Yetn8.png)
6,754,021
I'm trying to use my 'context' object in a using statement. It works on one project, but on another, I'm getting the following error. > > '...': type used in a using statement must be implicitly convertible > to 'System.IDisposable' > > > When I'm referring to the 'context' object, I'm referring to the object automatically created when you're working with LINQ to SQL. The class I'm working within, implements another interface, could that be screwing up this context object? ``` using (TGDC context = new TGDC()) { } ``` the word > > using > > > has the red squigly line under it (error).
2011/07/19
[ "https://Stackoverflow.com/questions/6754021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/164882/" ]
You should add a reference to `System.Data.Linq`. I suspect that's the issue.
48,917,591
I'm always connecting to the "admin" DB, which is a [fixed bug](https://jira.mongodb.org/browse/NODE-1286). Using Mongoose 5.0.6 MongoDb 3.6 and trying to connect to Atlas. 1. My question, what driver Mongoose 5.0.6 depend on? 2. How can I find out when Mongoose will have that fix? 3. On a different direction, is there a way to connect with MongoDB then use this connection with Mongoose? Cheers
2018/02/22
[ "https://Stackoverflow.com/questions/48917591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5664546/" ]
Basically you should try connecting with your url link, and specify the DB name on the mongoose connect method so if your cluster link is: ``` mongodb+srv://userName:Passwrod@clustor.mongodb.net/ ``` and your DB name is: ``` testDB ``` then you should call the mongoose.connect method as follows: ``` mongoose.connect('mongodb+srv://userName:Passwrod@cluster.mongodb.net/', {dbName: 'testDB'}); ```
55,708,571
I've noticed that I can cast a closure that has regular arguments to a closure that has its arguments wrapped in a tuple. But only if I use a particular method of casting! ``` let myClosure = { (a: Int, b: Float) -> Void in print(a, b) } // I want to convert the closure to be of this type. var myClosureWithTupleArgVar: (((Int, Float)) -> Void)? = nil // Cast A is possible. myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure) myClosureWithTupleArgVar?((1, 2)) // Cast B will always fail and return nil (as warned by the compiler). myClosureWithTupleArgVar = myClosure as? (((Int, Float)) -> Void) myClosureWithTupleArgVar?((3, 4)) ``` Outputs: ``` 1 2.0 ``` Why is it possible to cast using cast A but not cast B? What is the difference between using an `as` Swift-style cast and the C-style function call cast? (I am not interested in the difference between as, as?, and as!)
2019/04/16
[ "https://Stackoverflow.com/questions/55708571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407757/" ]
The extra parenthesis is reason why facing this warning (despite this, it shows the result of " 1 2.0 3 4.0" on playground). First, let me confirm that: it should be `myClosureWithTupleArgVar?((1, 2))` instead of `myClosureWithTupleArgVar?(1, 2)` as well as `myClosureWithTupleArgVar?((3, 4))` instead of `myClosureWithTupleArgVar?(3, 4)` That's because `myClosureWithTupleArgVar` type is `(((Int, Float)) -> Void)?`. For a reason, the compiler recognizes that `(Int, Float) -> Void` (the type of `myClosure`) is *not* the same as `((Int, Float)) -> Void` (the type of `myClosureWithTupleArgVar`). At this point, if you tried to edit your code as: ``` let myClosure = { (a: Int, b: Float) -> Void in print(a, b) } var myClosureWithTupleArgVar: ((Int, Float) -> Void)? = nil // This cast is possible. myClosureWithTupleArgVar = ((Int, Float) -> Void)?(myClosure) myClosureWithTupleArgVar?(1, 2) myClosureWithTupleArgVar = myClosure as? ((Int, Float) -> Void) myClosureWithTupleArgVar?(3, 4) ``` by removing the extra parenthesis (`((Int, Float) -> Void)?` instead of `(((Int, Float)) -> Void)`) you should see the opposite warning! Which is: > > Conditional cast from '(Int, Float) -> Void' to '(Int, Float) -> Void' > always succeeds > > > which means that you don't even have to mention the `as` casting anymore (they are having the exact same type for now): ``` myClosureWithTupleArgVar = myClosure ``` instead of ``` myClosureWithTupleArgVar = myClosure as? ((Int, Float) -> Void) ``` Also: ``` myClosureWithTupleArgVar = myClosure ``` instead of: ``` myClosureWithTupleArgVar = ((Int, Float) -> Void)?(myClosure) ``` --- Keep in mind that this case is not only for casting closures. Example: ``` let int1 = 100 var int2: Int? = nil // unnecessary castings: int2 = Int(int1) // nothing shown here, because of Int init: init(_ value: Int) int2 = int1 as? Int // Conditional cast from 'Int' to 'Int' always succeeds ```
8,514,298
I want to normalize weights in a list of particles. These weights belong to particle-objects. I try to normalize them by dividing them with the sum of the weights. All the weights are declared in doubles. When the program starts dividing at the start of the list, the value is correct, but soon after second or third division, I get wrong results.. which has the consequence that the sum of the weights after the operation is not 1, which it should be. Can anyone help me with this problem ? Maybe something to do with threading ? Thx in advance.. ``` // normalizing weights double weightsum = 0; double check = 0; List<ParticleRobot> temporalparticleSet = new List<ParticleRobot>(); for (int i = 0; i < particleSet.Count; i++) { weightsum = weightsum + this.particleSet[i].Weight; } Program.Weightsum = weightsum; Console.WriteLine("Sum of unnormalized particleweights is " + weightsum); foreach (ParticleRobot p in this.particleSet) { Program.Weight = p.Weight; p.Weight = Program.Weight / Program.Weightsum; Console.WriteLine("Updated Particleweight is now : " + p.Weight); } // checking that they sum up to 1 for (int i = 0; i < particleSet.Count; i++) { check = check + this.particleSet[i].Weight; } Console.WriteLine("Check: Sum of particles-weights is = " + check); ```
2011/12/15
[ "https://Stackoverflow.com/questions/8514298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1099004/" ]
I'm not sure whether a usual interpolation is right here. It seems that your image was created from separate column-measurements. If you look at your data it seems that neighboring columns are almost copies of each other. They seem just a bit translated. If you take the brightness of two neighboring columns and plot it, you see ![enter image description here](https://i.stack.imgur.com/LcHgl.png) that for the two peaks, which are vessel-like structures in your image, this seems really the case. So what about calculating the correlation of two neighboring columns to get the offset ![enter image description here](https://i.stack.imgur.com/b6UIP.png) You see that the two columns correlate the most if they are shifted by a few pixel. So here is what I would try first. Calculate the offset of each neighboring column. You get a list of offsets which tells you how much you have to translate a line to make it the best match with its neighbor. Then you smooth this list and use the smoothed version to translate every column. This should repair columns like the one at x=7 in your raw image. Furthermore, you could of course stretch your image in x-direction by interpolating this list of offsets. Say you have 10 neighboring columns and their offsets, where they match the most. ![enter image description here](https://i.stack.imgur.com/C7ky1.png) Then you could use the intermediate steps by using the same line with different translations. In this way you would get a smooth transition from column to column and you would resize the x-direction. ![enter image description here](https://i.stack.imgur.com/J7lO8.png) Edit ---- This > > Then you smooth this list and use the smoothed version to translate every column. This should repair columns like the one at x=7 in your raw image. > > > needs clarification. When you have the list of offsets, what you want to use for the translation of each column is the difference between this list and its smoothed version. I hope I'm right here, because I didn't try it.
3,279,475
Im using [DatePicker](http://www.frequency-decoder.com/2009/09/09/unobtrusive-date-picker-widget-v5) plugin for a project. But I want to Disable dates older than today .(User couldnt select the old dates) My js is: ``` datePickerController.createDatePicker({ formElements:{"inp1":"d-ds-m-ds-Y"} }); ``` In manual :`Both methods accept an Object that represents the dates or date ranges to disable.` I couldnt disable the old days yet with many trial and error. Can you please show me any way to do this? Thanks in advance Edit: ``` datePickerController.setRangeLow("myElementID",$today); datePickerController.setRangeHigh("myElementID",$old_dayes); ``` I want to set dynamic date in `("myElementID","20081201")` . Date ranges : `$today` and `$old_days = 'dates older than $today'`
2010/07/19
[ "https://Stackoverflow.com/questions/3279475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361635/" ]
from the [docu](http://www.frequency-decoder.com/2009/09/09/unobtrusive-date-picker-widget-v5) (note: this is exactly the link you've posted!) > > Limiting date selection i.e. setting > date ranges > > > The datePicker enables you to define > both a lower and upper limit for date > selection. > > > To add a lower or upper limit, just > add the parameters “rangeHigh” and/or > “rangeLow” to the initialisation > object and set their values to be a > YYYYMMDD date format String; for > example, the following code will limit > date selection outside of the range > 13/03/1970 to 20/12/1999: > > > ``` var opts = { formElements:{"inp1":"d-sl-m-sl-Y"}, // Set a range low of 13/03/1970 rangeLow:"19700313", // Set a range high of 20/12/2009 rangeHigh:"20091220" }; datePickerController.createDatePicker(opts); ``` for those, who are not willing to scroll (just one line down in the docu)... > > Setting the date range dynamically > > > The upper and lower date ranges can > also be set programmatically by > calling the following two methods: > > > ``` // Set the lower limit to be 01/12/2008 datePickerController.setRangeLow("myElementID","20081201"); // Set the upper limit to be 01/12/2009 datePickerController.setRangeHigh("myElementID","20091201"); ``` **edit:** html: ``` <input type="text" id="datepicker"/> ``` javascript: ``` var today = new Date(); var options = { formElements: { "datepicker": "d-sl-m-sl-Y" }, rangeLow: today.getFullYear() + today.getMonth() + today.getDay(), }; datePickerController.createDatePicker(options); ```
27,930,041
I have a multi-project build with several sub projects and I want to use the gradle wrapper. What's the idiomatic way to do this? Should I configure the wrapper in every subproject by adding the following code to `build.gradle` in the root? ``` allprojects { task wrapper(type: Wrapper) { gradleVersion = '2.2' } } ``` But then, do I check all the `gradlew.bat`, `gradlew.sh`, `gradle/wrapper/gradle-wrapper.jar`, etc. files from *all* the subproject directories into version control?? That seems inefficient, but if I don't then how can I execute `./gradlew.sh` in a sub project directory? What is the preferred way to use gradle wrapper in a subproject? Do developers just use the gradle installed on the filesystem for this case? The most important question is the first: what's the idiomatic way to do this?
2015/01/13
[ "https://Stackoverflow.com/questions/27930041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361855/" ]
You should just have the wrapper task outside of the allprojects block so you only have one `gradlew.bat`, `gradlew.sh`, and `gradle/wrapper/gradle-wrapper.jar` at the top level of your project structure. You can run the `./gradlew tasks --all` to verify the wrapper can see the subproject tasks Or you can run the `./gradlew <subproject_name>:tasks` command to view just one subproject's tasks.
69,367
### 1 Context Near pg. 184 of *Lambda Calculus and Combinators*, the author is discussing the theory of dependent types. In particular, we are extending the lambda calculus to look at terms of form $$ \Pi x : \sigma . \tau (x) $$ Now terms of this form denote type functions with **degree** and **ranks**, unless I am mistaken. ### 2 Textbook Passage on Degrees vs. Ranks Here is what the textbook states: > > The definition assumes that we are given a set (possibly infinite) of > *atomic type constants*, $\theta^n\_i$, each with a *degree $n$*. Each atomic type constant with degree $n$ will represent a type function > intended to take $n$ arguments, the value of which is a type. > > > and then later: > > **Definition 13.7 (Type functions and types)** *Type functions* of given degrees and ranks are defined in terms of *proper* type > functions, which are defined as follows. > > > 1. An atomic type constant of degree $n$ is an atomic proper type > function of degree $n$ and rank $0$. > 2. If $\sigma$ is a proper type function of degree $m > 0$ and rank > $k$ and $M$ is any term, then $\sigma M$ is a proper type function of > degree $m - 1$ and rank $k$. > 3. If $\sigma$ is a proper type function of degree $m$ and rank $k$, > then $\lambda x . \sigma$ is a proper type function of degree $m+1$ > and rank $k$. > 4. If $\sigma$ and $\tau$ are proper type functions of degree $0$ and > ranks $k$ and $l$ respectively, and if $x \notin FV(\sigma)$, then > $(\Pi x : \sigma . \tau)$ is a proper type function of degree $0$ and > rank $1 + k + l$. > > > A type function of degree $m$ represents a function of $m$ arguments > which accepts types as inputs and produces types as outputs. THe rank > of a type function measures the number of occurrences of $\Pi$ in the > normal form of the term representing it. > > > ### 3 Question **Question:** I am totally confused between the notion of a type function's **degree** versus its **rank**. The book states that the rank of a term is the number of $\Pi$'s in its (normal) form. But doesn't the number of such $\Pi$'s correspond exactly to the number of arguments it takes? That is, if a type function takes $n$ arguments, then doesn't that just mean there must be $n$ $\Pi$ symbols to capture those $n$ arguments?
2017/01/26
[ "https://cs.stackexchange.com/questions/69367", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/49236/" ]
> > The book states that the rank of a term is the number of $\Pi$'s in its (normal) form. But doesn't the number of such $\Pi$'s correspond exactly to the number of arguments it takes? That is, if a type function takes $n$ arguments, then doesn't that just mean there must be $n$ $\Pi$ symbols to capture those $n$ arguments? > > > Nope. Let $\sigma, \tau$ be types (i.e., type functions with degree=rank=$0$). The type $$ \prod\_{x:\sigma} \tau $$ is the type of functions $\sigma \to \tau$, which do not take *type* arguments -- they take *value* arguments (of type $\sigma$). So, the degree is $0$ (not $1$), while the rank is $1$.
35,667,013
This link leads to where my code is ran. <http://erobi022.pairserver.com/phpvalidate1.php> ``` <!DOC TYPE html> <html> <body> This is a simple form <form method="post" action="send_phpvalidate1.php"> Please enter your first name: <input type="text" name="First"></p> Please enter your last name: <input type="text" name="Last"></p> <button type="submit">Submit</button> </form> </body> </html> ``` Once the submit button is hit, all data is sent and posted here. I can get first and last name to output fine, but if i leave them blank it will only say that i left my first name field blank. <http://erobi022.pairserver.com/send_phpvalidate1.php> ``` <!DOCTYPE html> <html> <body> Welcome, </P> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name1 = $_POST["First"]; if (empty($name1)) { echo "You've entered nothing for first name"; echo "<br>"; echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>"; die; //if you mess up, youll have to fix it } else { echo " Your first name is $name1 "; } } echo "<br>"; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name2 = $_POST["Last"]; if (empty($name2)) { echo "You've entered nothing for last name"; echo "<br>"; echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>"; die; //if you mess up, youll have to fix it } else { echo " Your last name is $name2 "; } } ?> <?php // can have multiple php sections echo "<a href='phpvalidate1.php'>Return to form</a></p>"; //have to use a simple qoute within html to make it work ?> </p> <a href=".">Return to home page</a> </body> </html> ```
2016/02/27
[ "https://Stackoverflow.com/questions/35667013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5989394/" ]
Type this in your console: `chooseCRANmirror()` And choose your CRAN Mirror. I like Spain :). Then try re-installing your package.
26,491
I'm traveling from Europe (Belgium) to USA soon. While on a road trip from New Orleans to Miami, I'd like to access the internet without paying exorbitant amounts of money on roaming fees. I was thinking about getting a pre-paid SIM card from an American provider to lower the costs. It seems hard to order a pre-paid SIM from an American provider without an address in the USA. What are my options?
2014/04/27
[ "https://travel.stackexchange.com/questions/26491", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/13257/" ]
I traveled all the way through the USA from the east coast to the west coast, by car and RV. I thought about getting a UMTS / LTE stick for my Notebook, too. But there really wasn't any need for this. You can get **FREE WIFI** almost everywhere: * Coffee Shops (Starbucks, etc.) * Fast food Restaurants (Pizza Hut, McDonalds, KFC, etc.) * Camp grounds * Hotels * Shops / Malls * Libraries In rare cases you get WIFI access even here: * Cinemas * Grocery Stores * Gas Stations I can also tell you, that the UMTS internet coverage isn't that good when you plan to visit national parks or other nature reserves. Whilst driving through the less populated middle of the USA there are times when you even don't get your cell phone working --> NO Service! So if you really feel the need for uninterupted internet access, you should **carefully check the coverage** of your Mobile-ISP
20,251
My Laney Lv300 Tube Fusion Combo amp, doesn't have a Line-In, as such. It merely has one "Input" on the front, for the guitar and a pair of FX sockets, as an FX Loop (FX Send and FX Return). It also has one "Speaker Out" socket, for connection to an 8ohm-plus extension speaker. What I need to know is this, is there any way for me to connect an MP3 player for example, to this amp?? I know that it is a Valve Driven Pre-amp Combo and that the two inbuilt 12" Celestions may not be the correct ones to give me an excellent audio out for general music, but my requirement is just to be able to generate an acceptable audio outside, for a forthcoming Open Day. I do also understand that the potential Stereo output from the MP3 player will have to be resolved to mono. I do have a pair of 8ohm PA speakers that I can use as well. I plan to plug one extension speaker, into the single provided extension socket and I also plan to install a separate second output socket, into the rear of the amp cabinet, using a switched 1/4" Phone socket, that should then isolate the inbuilt speakers, when the extension is plugged into it. That will allow me to run at the minimum 4ohms that the amp requires. Any thoughts, comments or suggestions on the best way to do all of this, would REALLY be appreciated. The speaker mod, I am sure that I can resolve, but the method of connecting an MP3 type player into the amp, to play music for the masses on that day, is something that I am desperate to sort out. Thanking you in advance for ANY help with this....John. I have managed to partially answer my own question. I dug out an old Vestax PCV-150 that I have and ran a 3.5 stereo jack from the player, which terminates in 2 phono jacks that I plugged into one of the Line input banks on the Vestax. The output from the Vestax, has been taken from one of the two "Sub-Master" 1/4" sockets, connected through a standard guitar lead, into the Laney amp Input. I plan to try using a "split lead "Y" connector", which will allow me to use both of the Sub-Master Outputs from the Vestax, as soon as I have one available, whilst still using the guitar lead into the amp. Latest update.... I purchased a 1/4" "Y" split lead recently and connected the joined "Y" end, into both of the Sub-master output connectors on the Vestax. As previously, I then connected the remaining portion of the "Y" lead, into the Laney Input. This appears to now work exactly as I need it to. Thank you to everyone that has posted comments here, to help me with this. I hope that this post ends up being of help to others, in a similar predicament to myself.
2014/06/13
[ "https://music.stackexchange.com/questions/20251", "https://music.stackexchange.com", "https://music.stackexchange.com/users/12125/" ]
If you have access to a looper pedal, such as the Boss RC series, they have a line in. Connect the pedal to the looper, and then your MP3 player to the line in of the loop pedal.
102,831
I'm a Canadian citizen born in Iraq. I came to Canada at a young age. Could I be denied a tourist visa to China? The visa agency said I might be. What's the likelihood of this happening?
2017/09/26
[ "https://travel.stackexchange.com/questions/102831", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/68516/" ]
Any citizen of any country could be denied a visa by any other country, there are no guarantees. A Visa Service will inform you of this upfront to avoid any legal issues later, if by chance you are one of the unlucky few. In your particular situation, the chances of a denied visa are likely low. But we don't know your situation (work, background, income, etc) to be certain.
5,289
I'm waiting for my Pi. From reading the tutorials and books on doing i/o on the Pi I'm getting the impression that linux makes entries in /dev on the fly, which is nice, but they're owned by someone other than the pi user. Is there a way to have Linux make the /dev entries world writable or owned by pi?
2013/03/05
[ "https://raspberrypi.stackexchange.com/questions/5289", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/6292/" ]
You can change the permissions on a device node using `chmod`, eg: ``` chmod g+rw /dev/whatever ``` This adds read/write permissions for the group owning 'whatever'. A lot of stuff in /dev is uid and gid 0 (owner root, group root) but some things have a separate group such as 'video' or 'disk', and when this is the case, the group will already have read write permissions on the node. So, first check if the node you are interested in is like that: ``` stat -c "%A %G" /dev/whatever ``` If so, just add the pi user to that group. If the group is called "mydevice": ``` usermod -a -G mydevice pi ``` Done. If the node does not belong to a special group, you can create one: ``` addgroup mydevice ``` Note on some distros this command is `groupadd`. Now chown the device to that group and tweak the permissions: ``` chown root.mydevice /dev/whatever chmod g+rw /dev/whatever ``` Then add the pi user to the group. The new group, and the pi user's membership in it, are permanent (until you change them again). However, the dev nodes are actually created at boot, so any changes you make to them will not persist. You can make that permanent by adding a *udev rule*. Create a text file in `/etc/udev/rules.d` called mydevice.rules (or anything with the suffix `.rules`) and add a rule: ``` KERNEL=="whatever", NAME="%k", GROUP="mydevice", MODE="0660" ``` Beware the difference between == and = there. Here's a (slightly aged) [guide to udev rules](http://www.reactivated.net/writing_udev_rules.html), most of which still seems to be valid.
17,150,999
I am trying to integrate an application with a third party webservice. The signature of the method I have to call is something like this (generated by VS proxy generator): ``` string MyFoo(string param1, string param2, string param3, string someXml) ``` Now for the first 3 parameters there's no problem. The fourth parameter, as per vendor specifications, should contain "unescaped xml wrapped in a CDATA block", like this: ``` <![CDATA[<?xml version="1.0" encoding="utf-8"?><rootNode></rootNode>]]> ``` Now, c# escapes (as I would expect it to do) all the characters that must be escaped, mainly the "<" and ">" characters, even in the CDATA statement, resulting in something like this: ``` &lt;![CDATA[&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;rootNode&gt;&lt;/rootNode&gt;]]&gt; ``` As far as I know this is a correct behaviour, and there's no way to override it, as it could potentially generate a bad request (invalid soap message) and even a security issue. Does anyone know if I'm missing out on something, not knowing something, or this is correct and the expectation of the third party webservice cannot be complied? Thanks.
2013/06/17
[ "https://Stackoverflow.com/questions/17150999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232940/" ]
Your code look fine.......you are saying that you have assigned permission too. The only problem is that you may be passing a wrong "Source"which is causing problem..Check your source string it may have an error...... path should be like ``` WebRequest request = WebRequest.Create("ftp://host.com/directory123"); ``` it mean directory will be created with name "directory12" if your are specifying path like this ``` WebRequest request = WebRequest.Create("ftp://host.com/directory123/directory1234"); ``` this mean "<ftp://host.com/directory123/>" should already exist and new directory will be created with name "directory1234" hope it will help
461,490
If I have a list $L$ in GAP, and a certain list of properties $a,b,c$, how can I count the the number of elements in my list that have all three properties? I've searched the manual (chapter on Lists), but haven't found the function I'm looking for. Specifically, if $G$ is a finite group, the list I am working with is: ``` L:=List(ConjugacyClassesSubgroups(G),c->Representative(c)); ``` I'd like to count the elements in this list that would return true for all three of the following queries: ``` IsAbelian(c) Exponent(c)=n Order(c)=m ``` for specified values of $m$ and $n$. I'd like to avoid going through a list and counting 'trues,' so it would be great if GAP could just give me a number.
2013/08/07
[ "https://math.stackexchange.com/questions/461490", "https://math.stackexchange.com", "https://math.stackexchange.com/users/65034/" ]
More succinct is: ``` Number(L,c->IsAbelian(c) and Exponent(c)=n and Order(c)=m); ```
13,223,035
The following code list all the invoices, and I just want the oldest invoice from a vendor: ``` SELECT DISTINCT vendor_name, i.invoice_number AS OLDEST_INVOICE, MIN(i.invoice_date), i.invoice_total FROM vendors v JOIN invoices i ON i.vendor_id = v.vendor_id GROUP BY vendor_name, invoice_number, invoice_total ORDER BY MIN(i.invoice_date); ```
2012/11/04
[ "https://Stackoverflow.com/questions/13223035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1798706/" ]
We'll use `ROW_NUMBER()` to "rank" the invoices by date per vendor, and then select only the oldest per vendor: ``` SELECT vendor_name, invoice_number AS oldest_invoice, invoice_date, invoice_total FROM vendors v INNER JOIN (SELECT invoices.*, ROW_NUMBER() OVER (PARTITION BY vendor_id ORDER BY invoice_date ASC) AS rn FROM invoices) i ON i.vendor_id = v.vendor_id AND i.rn = 1; ```
41,635
### Introduction In the [**last challenge**](https://puzzling.stackexchange.com/questions/33597/who-stole-the-bitcoins), you found out who stole the bitcoins. Now is the task to steal the bitcoins back. I didn't manage to steal them back so I'm going to give you the hints that I found. **Let's get started**. --- ### Story First of all, I hacked into Bee Holzman's laptop and found the following files: > > **Zinc.txt** > > > Which contained the following text: > > [**recursion**](https://puzzling.stackexchange.com/questions/41635/stealing-the-bitcoins-back) > > > The second file is: > > [**Molybdenum.txt**](http://pastebin.com/3nZ6gM6Z) (pastebin link) (text also found below) > > > It contains 150 private keys for bitcoin addresses, but I checked all of them and they we're all empty. I didn't understand why though. The last thing I found was a script. A *very weird script* that can be found [here](http://05ab1e.tryitonline.net/#code=MTY3NjQzMTI3ODU2NDRJMjE0w7Y3ODk1JTQrRkQqwqcxMDDCo33CrCJISktISktISktISktIInPDqDVzwqs_NjJCNDnCoyJJMGxPIiJKMUxQIuKAoSw&input=VGVzdA). It seems to decrypt a password filled in in **input** and converts it to a private key. --- **Do you know what the private key is?** --- To prevent link rot, the external data linked to above can also be found below. Pastebin Contents: ``` Molybdenum.txt 5HEUvjdY7r76UXrS19gBL8eJU2mKWn1UndF6p4RB8gYRubyFERB 5JJURS6ggDeQEVnorCWrswvJEw26DSaominKLzdeksWqQJkDymH 5JURoSTwtRUwTMFVtZZZyEY7XQeNgh49RDaxFDAFbMaNYngtmu3 5JfJYawNAncbi9UbscyzktURZhxWz1Q9ygZWkfG7yZLuXgLJpJ8 5KeNNexg5yq8NVFo6MZTwm3jmB9PVBU2zANy98KitxNPLH4fX95 5HhzHWxugpCM2VzxH6Bq9Yz6gRNMo5Z16Um8xmX8N4t7ryjS3wH 5K9LGhWxpD8fsegiYNQqFvRiEPcGgogvGPiggTCDVZuSUH6THuP 5KxFppuVkFYoVzcRBJCW6ihbRT52T9Ahtc4YCPyLSZvp714hnVa 5JL7vEwo6fNZzfPYxKYn2uuJSM5ttvvwBxYmQ4zFWiBMHUFGvCw 5JRHrAoB8xwW2UTsV3d38c9ngNZvZPJCeMKJMgRSRX6XVwk982m 5JRHTVibNdMMh9a9yyDqkJU1jmTehvj6mv7WuwYrsFeQ7dVpQCf 5HP2nRxugCKRv72vCSRhviuCPeHk1GkD58HpxwYWV7WnaenWG7h 5HqphpUVWyYF7Svq85hhThjDyxEPN92toUgb7UmFV6n9peQcw3Q 5JdFd1DD8FYCK7gq2xCSr7YNB9wYDwnCwyk8xZFGTeVGqndQFnx 5J1UfcKm4dBteSVAL8vdBaqi8pfrzGf8pzvZcFDxjwuNkkPjtPi 5JfKe1LBS8kjdm7kTwLsWgGb3Ur464ibkb9NLAzxP8qXuHJHZ14 5JkEr1Yx9BEVFF5zodAKyMuxBcWBAyCxehonjt1nUXu3hsGjwFp 5K9DjZn4zamtKyhYC4WYbpbwbf2kAJ4KVd3t5FtMXrTUHRBUFfN 5J2mxu56V6yYsj5Mbe6A5DeCaNHgp4bdc75pLPPRamQCDgo3256 5KY6DE5SKjGtQTbjz4nTDV19F6NPG7aP3pbaCbVnRmhrUiMeg9Z 5HC53xdgB8S6WeiHWuAegfyGwG6Y78fWgUjx64fUJ1abQuXxWD9 5K8cEnjQPy8io5BywYQo1FRCX77YTF3EFa4Uuj6JrXvnTjUzoCn 5JrQ73Rd4QD9fwgWsJWxsQdks8qApGqSQNu6mn1zHdYQ5UxqeoK 5JLFxTozpQCgvT6a6dAYYfHXdgi4azskHfUf7nWF6qX7P31Qm7d 5KALHRBdqq8KfboyNVeYRGKx7brekJBvpAMouKaTzoPJ1RnPUFK 5H2njzQ8vA4bKZx8QcA9KVceBBh7XAZyXkpzs5ca4QVmKyp5RFi 5JbybCuV1GxvoaFZJ1tcGx4boruguaoFNrS2TcZEnNaZ7Xa66yK 5KGYSW683q5RomaXRZUbuiXG8oe6auqKxbhQHffqV2DYWfUZdTd 5K7FkeHrZ89ojsg8YA9Q1DSSQrLcPn3pLdkkCLuA2WdzEpgD4ro 5JAVrEjmw7vXqEJxWz1HUeZpo3zRgsA3UjmxP3tJihh8uuTZZxq 5HMMR4hEGAZKGaseoyyxrKkrUKQZx5ktj3LRYYnx7B8q6F3tmyw 5H3Z5r4vT8kMsMv9xYQWRDxSLppEtBkx9iy3udMnoBZ1kTpKZAz 5Jmcbqz6UuezsmgZiTQjvZNpTkX4UaKn97tCVXU1Xy1rRYbr2q4 5K1YdcbVYFcf3wbzHMWRipcia87iSEDQ2PGTDXGSGMPipUybCuf 5HpALTeFFwAHSFRhxJUwU8z72FBCgJStPVx8C6rWKRVp5Qn3Mrw 5HfYr9sFmiTyy8bAkTQBAMtGfNhsXvcGnUfKwb1UHAXK8zXZPds 5KcnUxgjGrZrbdFdSZcnzXMYH9oLg6qzREKZt99DX3MbLH6pXjh 5H7Ubn1LG6oUfDGs6obDnRTsXzB7gJPh5iaKnx1dYgfxBwtE8Bq 5KUCFXxqJv5bHfyogPkDyKBebzZAKqxomb9fmwDuCPhBoAzf8Xa 5HFwcyxLQcTvBfusdALvzYseQv9Gr5fzuMiHgid8K73gKQijJyA 5JEUGk5nDUKALJAVTwhRHXo5JqAgJbgCzDcGqH6At9ssXP3TDqr 5Kcdmh7f9j49v3PHizmoZeMb4c4WyE5o1deS8J9RkZsYDG3kEYd 5JYYimawEAej1qQ1MKr85gmiHguMKR4ah4A7Tiz2YT6YVTFFZ4f 5Jq9rGnEqHGr5RskpewgSZxxJ9sZD5Fz78bV3NmKBJuRKQzihqb 5JFwNeYJTJvfJkEYPmD3Yzvbq5hjhpx7EA8YtSTDhYoWJxvmH1j 5Jmv9yNGj6FN5FpepoNeXDbpV4JkufqiMR7B5XfYXpzPGFrHLSV 5JNdF76BhxKx3Tn9EfuQZGjbSVUxSNowkX4BF1zpU5wZD1X8Jas 5JHZskzhP6pYtghkqsn9e1qkKpvMDjDpyxkZpcHAfbJrnUQLMmN 5KNaeNJTaiku2GAJBiyGY4w64XKXdpAQF5qWktfwoV5fjX24EVU 5KD91ejf73tezuDeBzE1PgvP2t6CCe8u7FFa6tVhEh1P8ntVARe 5HVjK2H2VeTyYmtgdibhMrUJT77yx7Z1euC9KYEjXBGkdjekMsN 5H3k9faP1uFkbMPK3ajNHKHEgtgtvS74fVhB6FTu1sfcBLdtcnw 5JdyzfU9nrHzUwf7bHAodvf3dtft1f8c8bMJpztRPpJHhKWzXKd 5HCXWpDgUSGFA5NkC923sYGtAHb1hth2baZACgsyzMA4qHsBfQD 5KYwKJ81j3jSGHGKUvsHqCi2Zy6tyhwXj7ZUnt81dG76m4XWH2H 5JaMrBXBDtEjvxEDdTNCfWiy1Wgcc84qwLE6V2yM6TSMTZrzoCb 5H3JruoQhA1MLr61SbTRHodZnjHvY6gbVZJZbcVShifnsENFw57 5JM7qDFnQC5hKMpkXahixn5F5fFrS7LQVREDBVXHkz5C6kw5CSQ 5JXV2XF7KYK6TeJaDuej72t4hwUxMVaeM6m3QqrCABWJ6eQ7RMX 5JqnTZMUgVHgDm2YruPHcjUPA8uZnJ5ocaZF4AVcKqHVz8CjBRw 5KhrsoRpsHhcBcfJRGiDsdHz18rQ1M3xCx6nhFUmXakMNiR3fQR 5JFsqmJKbwG8GsVEgRdmmURKnDQ7Kuws18odGoEqDvbFQzV9Ew6 5KowouSwRL1g1wf9tpSMbMzyFEeaFu5CzNNvKjtDAixAnQ9GRPP 5Hih6H9hyWXYn1EnA1TQwJ1nKbBn2wwsHtCRzc6yjSECCLAQPRr 5KK679qdt9cDwUmP4gsYXS1K56Hi6RpHJmom2ra2pWhkgfZnPtF 5Kt5QQmZhx8Cbcv1HseLmiqShnXny2JGdfAqwcNV4ihVKAkyEyC 5KCD2qXzbhvTmsWVUvd47DrTsG19oU3oK8wvkmUWZZvmSR97ea3 5HRK5gviPMuxYpWog6hbi3Y25pYjKj4gMPJPaFNk8EzLn9iz4YX 5KqYayGRhBQZAagEmAvEiYYWggHfmJY9FtCPcVNFoF5ZmmH6MhA 5KD2H9mbQk9gUBKTroCe5tCt4YCHDFNRpZsQaLdAxgrXnr7AZBg 5KW9ECSfzuV3TC3wFwKdrHwiBALufmFyLLtyj4JacRkDf9Rw8ok 5KRafZKMn7jfU6UoYumNtx5HQNpGcgsgXKLSYJAd9444Ro8ZJkd 5KR1zjayL5c2PYhf3w8nEEFCf1cV1kRW3D4PnKNhab3MDMzCww6 5JTZuR4icDfDspAeKp762jTE3CwryxS6XJtrFohm2QZMHsWvsdJ 5HPWBNCixBAoeLbKyEpnHp7dSCrvWrnKBLBij24pSHJ8yVgcvSU 5KFbCmJgtpQ9nyjEFiaeT9cKJCSTYD6FftbQ93ngchNfmCo4Bc8 5HKQSGkfK2kAHTLor1JoRJtPypJjHK49VxGcxEuCLyvwaeHmbQt 5HfXpzbCDvaPdsHUgRXwCrjcNbg5EQSupR4o6fvxWFu8REwyBNQ 5HLok7BsWWtMShaJmBctapFrKP8jX5XCcVsX4zdrX857aaKb9dc 5JaZjxT2AhBc7bG9bYc7pGFxDbXF2BpjEGRa62veuojELhKBnP3 5KBFFyWpw3BiHMXDFZxdPtjCxsWcPH3WN5nNArb2K6FauRvqveb 5Kn74kmtbvBcHLzCjFMkF93c7WTyKeS6XuhiDpLzRgupRHTPxtF 5J67Jm7ygwJ5Q5kKNdgoHQC25oLKStY6Fp6uqtkjhu4XW2sriJy 5JmLb9jj2W6wsuh5kvsUinHDdeTrkA39K2cfs5iC5ysenv5c72x 5Hev855ZJetRKmD4XPtSNFLFs8aEHR1kyTzQyLjdafWozrcTo3S 5HYNVj8iWWER7gTjmteebCzH6QDAnvna6Xf3txF5qg9JjhJvWMD 5KvTKeiGWkhuaaGtVCrsKWMh6R8Hs9dmjCL8NG5Ax52DLWuE9mM 5JK7yJu9fgB5adxmwBGZLgXWfZx9GgmwnW3ihdXn7mkyiFLqNsj 5HATEiHBPSeQv5j2EkHRqaws27gy28dX8KVDuyRzgJztXjKfggU 5KDQKMjE1PZYWuJTuMWQFzzw83H5qYaJeqUtLfBaG7dXPZrLxMG 5KgUMo84LxWs6v3sf7CvtF6fkvJT6shmjtjQv8Jui2z4Tvakb6F 5K87MyBncH1RMYBxiiM5w3uy9h4hvKXmwYLpWcjthYyFqiotNBo 5JpzUtfCprEXz5NrpuCydgPRi8UT8sf2QDpPb75cDaLwXuui2J7 5JAAQmVapXvMY4Nrea78nxYHNMqhgA2NFMjKVn39nWDr77jCKiE 5JvxkU4KaaTeNLjBMKUnEUrzs9348zxbpY54Yk7QgpQ6vKh5WVM 5KGPyRmYz8JkDXTMp9t1cZiUVg4bmB5z9KKqJYEcwmHMArneCYP 5HBQmTdLVmiCmvhziqZhQURbRVQZ8NiEFfzaQ42r3oU7zBFBVpe 5JFLCY66gMMMod7ANcsX8SdxDxcgQMKg5XKfACxsHETCo1Vu7Yt 5H6EhWTyEqt22zok1PCDR6nqhduQahzZKxkZ1pQthuAXmHBgPJT 5HMFEkQW9MEaFJuDxDYB3A8MGVRsSiRzXsD7RAEywxrycBj6M4E 5Jak3359oLAG2us7ytWBHLeFDknz3qGLnaxoaWqPkYxj3wSW9KZ 5HQonFUhwByxwEHqzgwSqPaEvtHAEM8yspeC5r4xzK7kzsgVtNi 5JqKyTKoi6FsGprjpWgTntVimCP53JDYrUfJZv59NHUUvbhZAR1 5HGfRebSpfFwadmwR1hD9ZVw8P13nLzRqAUsoU6MSw5Jkp7tyVE 5HdNMVFYJHsBGUn2m5SqXVeHK4vzMujNW153XimkY394q7GPBJH 5HnxCfZg1F99ztjZbfgoAd3cuXbQBdSXdCdvc7eUpMy7H5tHdZh 5H1uFriM3dwo4XewZs9nAx5g59YDvBQeK8cbrPtCy7DRG8982Be 5JNRpEyzmCDo52pgMzQPnG2pkiC5AB8gSxVwQg3WZDrpFN51ik4 5JVn4HSu3dbrhWHmKba1Y6v7KQPw8ApbNmc77FYgBxG9k5xvogJ 5KPdQMCwnntekmXGJGymeUF9EUoCrbsSC93vMgR3Z4YLoQwaxts 5K6paJ5hdmF26Z6CRJorUFdcMsPjSYsqpxxW56pPGboPtV3xqcS 5HdndYJQZ4Ah9hQFuqZL9PzrHuoUknk1rniQNywewkNnuRny8Ew 5Jcm6BTjEjfsyNhBaUAYku477jnzWEtSDUDp4jbGxB43VDBBY7h 5HCtWa495XdQUvWuqjRswX4ggt4RCZpbdjhrmGLFGsq9SfvaTz8 5Kugaji6xHEpb5VwU5GLKBat9JNBthTJ8AJ9ygPDYU8LpXwmjKR 5JJu2PMBhNAKGWeXG8AG3wDwKW1Ngs1qAEUEp9BdMgjZh1a6y3q 5HvtTpAS4k3VkPhCp2mULxEGENmAwTysP8D6BS6ppbTaJkK4oL2 5KsJ2TKJggzavq9ErLzoidQo1YgLQkXmSQfvv3eLWw8zfUHVvbx 5HEqqinkUGerCLKxKEM2ytxy7YfPxECtEFhD1Pr7x6ppsCxxeC3 5KkaE9yeNWE9vohFQ6i5strwj4nmmM7UEsLMnsDkXSSrstR3FWs 5K7F9YgcupdNKvSyeikLfMQxMAJaBQWtX7ri7Pjdop1gqgdKS8U 5HUrTvpsKeXna2YYxHpSCVJ7SucJXXdrDjydvFHDZtvVXkFX7Sk 5HWak6CYgyNuuxxwi2EAoP7VRww5Ki99rMyYwbsypC3R5ZAqvTj 5KhUrHgocJFpXfpTuNhvEvZvBkGDaqx66ApmHZzbzNBTpFfZmWP 5H2D2JXoiX4jUJreVMTv2dSeTvKW5ntjFNtAo5ufEvafNwYe67y 5H2uBm2ijzTYawA8up9bUwVvrvhLnHTeyLazF5THQ8P2EcQtMd7 5KB4Hx1r1nZAh3CGP5MoYP79MiefyKfQCpdKboTPnqYvBaedRM3 5JMWwsLZnVZWCEYbsftjuC7PU6KjP7csVACNwYWLrM2nrUQxs7J 5JaVUvCwsHNXcwYG7UEHkdJhZdh2jzAaXSNgQa1UKBGU4BXsysw 5HCWsT6dVE6MuGimYgqggrqyyEo3jpCPtQy6dwQtaGDMGiwGZmJ 5K5hWUM8sfV2hW3zoXXSt8raCHRPHgLiSiqQJQJPgqHjVjvAf8D 5HkVXzf1gcH6k4CYtf6NVxxxnvpbXx1T1GQCNjV8QZxDQXfcbQY 5KxLVvpyEttmd2K5QnecgNAsJyFGqnBdGCBuocmusJjfQCYeJUB 5H5FKC1rB57hZv7SJ6jrjEfFQ7GfTtMCgmmH1F4RckJLzWMAyDv 5JLKpfBHo2BmnhLB2C2zDyhuXt8kBgFkqRtSYPGjthG26eGbdaj 5HyGkjgBxRTGVCXmJNrVviPrzJagodM1tHpKQEmf1n5JwkGRkW8 5KAAit5qHczzaqKVo88KvppumQHnFt9fXfm3usouCFFEqtnLZ9W 5JLA3xkNioSFyFhWhWq6kJKznc5SiL7GDRDanNsriwNM6HboGqz 5KZA9fJPrL9WGx7sCcq41mNvSZBpS6zPV3mzWnnRbyBXHtLFb6p 5JGewR3idBbBKijdXN4KrBKhcuVEyDahvodcJNVDFLi1sycnM86 5KWSb7ui3k5fKJnET2pdrYXAWHckYiH9r4GRVZ8a7HYkM8EXm11 5KQwcuTWmzJBmZscrsQxWQ6UZ5RNZ35hNGmaNfviVVEsZFtpHCF 5KeATp4pJz1u89z2Xn5naCDwHUXGsi3CL5qZqjFbaD3NEjMCnVL 5JMKPZedfmVZtBDMfQxdtzqkrm8wvrCnteELouoPsSMgUgHqB3u 5JXTWQMNHxYxpyLeXwLqHjNVg85nDrREq6FvVDyrUCud5zATKYS 5HDpr2SsUNURoXutbYCHG71YkCsoyJu7spRigSYb7fj692JDBem 5HDuZmTobPaVjuZRH58fDBGJwYHwmAasxR7qa3at9YvsJzBWdQ8 5HJwQkBCxqn2TyWeC6L7H6quk4Pztez9Fjk4ZD7ypK8JhNSeQaa 5JUkZ8hJux2f7PqtNZj5kPhoYQQxULctrXnDcYYjb5BRpF4jhg1 5HenY8dwYAJYjVJCEofjrpX4R4FAMDKcKT31S91f3GtCq5MGdqZ ``` Very Weird Script: ``` 16764312785644I214ö7895%4+FD*§100£}¬"HJKHJKHJKHJKH"sè5s«?62B49£"I0lO""J1LP"‡, ``` ... written in [05AB1E](https://github.com/Adriandmen/05AB1E), a golfing language that is, as of the time of this writing, the first language listed at <http://tryitonline.net/> due to alphabetic sorting on that site --- ### Hints > > **Hint 1:** the SHA256 hash of the key is `d60f9c637d9d5a067fdb33751ce56a97760b5bef208b3688f2a663b7903675f1`. > > > > > **Hint 2:** the keys in the file **Molybdenum.txt** have no bitcoins in it, and have therefore no meaning (*do they?*). > > >
2016/08/29
[ "https://puzzling.stackexchange.com/questions/41635", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/23266/" ]
### Step 1: Figuring out the password I have used 4 potential passwords: > > Zinc, recursion, Molybdenum and Test (Unlikely) > > > These give respectfully: > > 5HNivwnPCJ4bmwJ2RfPfdZQdMsqLsLxsvF7xj1HWAgsP9SPEsJk, 5J2sEtNF8ePJLvLgHPMUKuAR32PJRsAf2EB7d5MjNnkvV7eB14V, 5J4PBeAoDt679T2PJD1Ys1gyi2C1N65tFL71coYPUttPL9dpdt3, 5J3TbqXNZkzi2chux679A3KLLyZmWEmFUJmvR54FaL25qWJnM41, > > > ### Step 2: Figuring out the Private key I'm a bit stumped here. The possible private keys don't match any of the addresses listed.
39,289,048
I have 2 radio buttons which when I click on one of them I get dropdown menu where must choose amount. So far I was able to make it check/unchek them but the problem is that when I uncheck the radio button dropdown doesn't hide again. I'm not very good in javascript so please help on this one. Here is the part of code ``` <div class="radio"> <label><input type="radio" autocomplete="off" id="paypal" name="paypal"></label> PayPal </div> <div class="radio"> <label><input type="radio" autocomplete="off" name="bank" id="bank"></label> Bank </div> <div class="form-group"> <span id="paypalamount" style="display:none"> <label class="col-sm-3 control-label" for="price"></label> <div class="col-sm-9"> <div class="input-group"> <span class="input-group-addon">$</span> <select id="paypalamount" required="required" class="form-control"> <option selected value="50">50</option> </select> </div> </div> </span> <span id="bankamount" style="display:none"> <label class="col-sm-3 control-label" for="price">Please Choose Amount to Deposit</label> <div class="col-sm-9"> <div class="input-group"> <span class="input-group-addon">$</span> <select id="bankamount" required="required" class="form-control"> <option selected value="50">50</option> <option value="100">100</option> </select> </div> </div> </div> </span> ``` Here is JS ``` $(document).ready(function(){ $("#paypal").change(function(){ var showOrHide =$(this).is(':checked'); $("#paypalamount").toggle(showOrHide); $('[name="description"]').toggleClass('#paypalamount',showOrHide ) }); $("#bank").change(function(){ var showOrHide =$(this).is(':checked'); $("#bankamount").toggle(showOrHide); $('[name="description"]').toggleClass('#bankamount',showOrHide ) }); $("input[type='radio']").click(function() { var previousValue = $(this).attr('previousValue'); var name = $(this).attr('name'); if (previousValue == 'checked') { $(this).removeAttr('checked'); $(this).attr('previousValue', false); } else { $("input[name="+name+"]:radio").attr('previousValue', false); $(this).attr('previousValue', 'checked'); } }); }); ``` And this is working demo of the code above [JSFIDDLE](https://jsfiddle.net/2xemy1dp/1/)
2016/09/02
[ "https://Stackoverflow.com/questions/39289048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1158599/" ]
```js $(document).ready(function() { $(":radio[name=bankpaypal]").change(function() { if ($(this).is(':checked')) { var name = $(this).attr('id') $('span').hide() $('span#' + name + 'amount').show() } }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="radio"> <label> <input type="radio" autocomplete="off" id="paypal" name="bankpaypal"> </label>PayPal </div> <div class="radio"> <label> <input type="radio" autocomplete="off" name="bankpaypal" id="bank"> </label>Bank </div> <div class="form-group"> <span id="paypalamount" style="display:none"> <label class="col-sm-3 control-label" for="price"></label> <div class="col-sm-9"> <div class="input-group"> <span class="input-group-addon">$</span> <select id="paypalamount1" required="required" class="form-control"> <option selected value="50">50</option> </select> </div> </div> </span> <span id="bankamount" style="display:none"> <label class="col-sm-3 control-label" for="price">Please Choose Amount to Deposit</label> <div class="col-sm-9"> <div class="input-group"> <span class="input-group-addon">$</span> <select id="bankamount1" required="required" class="form-control"> <option selected value="50">50</option> <option value="100">100</option> </select> </div> </div> ``` 1. Name of radio button should be same to select only 1 2. ID should be unique 3. Get the selected radio button and show its counter select using its ID since they are similar
28,375,573
I have my structure set up like this ``` struct judges { char surname[20]; int id; struct judges *wsk; } ``` How can I get random number from given IDs? Like for example, I add 3 judges with IDs 3, 7, and 253, is there a way to get random number only from these ones?
2015/02/06
[ "https://Stackoverflow.com/questions/28375573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539058/" ]
Pick a random item from an array of these structures and read its ID.
6,673,022
I have a GUI application, which I am developing cross-platform for Linux and Windows. On Linux, everything works smoothly. However, I've run into a hitch on Windows. I would like to be able to log certain messages to the console with a GUI app on Windows, Linux-style. What I mean by Linux-style is, if the program is opened from a console, the output will go to the console, but if the program is opened, for example, through the start menu, the user will never see console output. Apparently, this is harder than it sounds on Windows. Currently, I use the following trickery in main(): ``` #if _WINDOWS /* Fix console output on Windows */ if (AttachConsole(ATTACH_PARENT_PROCESS)) { freopen("CONOUT$","wb",stdout); freopen("CONOUT$","wb",stderr); } #endif ``` This allows me to create output before a window is actually opened by the program, such as responding to "--help" from the command line. However, once a window is actually initialized and opened by my program, the console is returned. I need a solution that will allow me continued access to the console throughout the life of my program, without opening a new console if none was originally used.
2011/07/13
[ "https://Stackoverflow.com/questions/6673022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/213445/" ]
We use ::AllocConsole() instead of ::AttachConsole and it remains open throughout the app. Try that?
23,491,948
I have two div align in two side of my page and I want now that the div between them align in the center. here's a [FIDDLE](http://jsfiddle.net/nxHet/) I want center the Blue Div. HTML : ``` <div class="lateral_div" style="float: left"></div> <div class="center_div" ></div> <div class="lateral_div" style="float: right"></div> ``` CSS : ``` .lateral_div { width: 80px; height: 100px; background-color: red; margin: 0 10px; } .center_div { width: 200px; height: 160px; background-color: blue; float: left; } ```
2014/05/06
[ "https://Stackoverflow.com/questions/23491948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1383538/" ]
You need to add `text-align:center` to your `body` (or other parent element) to center inline elements, then unfloat the centered `div` and give it `display:inline-block` [Demo Fiddle](http://jsfiddle.net/swfour/nxHet/1/) -------------------------------------------------- Revised CSS ``` body { text-align:center; } .lateral_div { width: 80px; height: 100px; background-color: red; margin: 0 10px; } .center_div { width: 200px; height: 160px; background-color: blue; display:inline-block; } ```
41,207,336
I need to create array of numbers between a and b for later use in ArrayFormula. For example: hardcoded for a=2, b=5 it would be {2,3,4,5} This seems very basic, but i failed to find the answer.
2016/12/18
[ "https://Stackoverflow.com/questions/41207336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3538145/" ]
You can do it using INDIRECT to define a range (like A2:A5) and then ROW to get the rows as numbers ``` =SUMPRODUCT(ROW(INDIRECT("A"&a&":A"&b))) ``` I'm testing it by using SUMPRODUCT to total up the numbers {2,3,4,5} = 14 but you should be able to use it in a different formula. The values a and b are defined using named ranges.
10,170,964
I wonder if there is any posibility to sort a text file by columns. For example I have `aux1.txt` with rows like this ``` Name SecondName Grade ``` In shell i can do this ``` sort -r -k 3 aux1 ``` It sorts the file by the 3rd column(grade). In batch ``` sort /+3 < aux1.txt ``` sorts the file after the 3rd letter. I read the sort manual for batch but no results.
2012/04/16
[ "https://Stackoverflow.com/questions/10170964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1331244/" ]
You could write your own *sort-wrapper* with a batch file. You only need to reorder the columns into a temporary file, sort it and order it back. (nearly obvious) ``` REM *** Get the desired colum and place it as first column in the temporary file setlocal DisableDelayedExpansion ( for /F "tokens=1-3 delims= " %%A in (aux1.txt) DO ( set "par1=%%A" set "par2=%%B" set "par3=%%C" setlocal EnableDelayedExpansion echo(!par2! !par1! !par2! !par3! endlocal ) ) > aux1.txt.tmp REM ** Now sort the first colum, but echo only the rest of the line for /F "usebackq tokens=1,* delims= " %%A in (`sort /r aux1.txt.tmp`) DO ( echo(%%B ) ```
1,086,956
I was working through my Precalculus 12 book, when I came across these questions: *Is each point on the unit circle? Give evidence to support your answer* a) $(0.65, -0.76)$ b) $\left(-\frac{\sqrt{2}}{2}, -\frac{\sqrt{2}}{2}\right)$ My book says that both of these points lie on the unit circle, but I can't understand how.
2014/12/31
[ "https://math.stackexchange.com/questions/1086956", "https://math.stackexchange.com", "https://math.stackexchange.com/users/204152/" ]
**Hint:** A point with coordinates $(a,b)$ is in the unit circle if and only if $$ a^2+b^2=1. $$ Explanation: The unit circle is by definition a circle with radius equal to $1$ and center $(0,0)$, so the distance of the points $(x,y)$ in that circle to the center is equal to $1$, hence by the distance formula : $$ \sqrt{a^2+b^2}=1\iff a^2+b^2=1. $$
58,613,108
I'm trying to learn how to implement MICE in imputing missing values for my datasets. I've heard about fancyimpute's MICE, but I also read that sklearn's IterativeImputer class can accomplish similar results. From sklearn's docs: > > Our implementation of IterativeImputer was inspired by the R MICE > package (Multivariate Imputation by Chained Equations) [1], but > differs from it by returning a single imputation instead of multiple > imputations. However, IterativeImputer can also be used for multiple > imputations by applying it repeatedly to the same dataset with > different random seeds when sample\_posterior=True > > > I've seen "seeds" being used in different pipelines, but I never understood them well enough to implement them in my own code. **I was wondering if anyone could explain and provide an example on how to implement seeds for a MICE imputation using sklearn's IterativeImputer?** Thanks!
2019/10/29
[ "https://Stackoverflow.com/questions/58613108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7488114/" ]
`IterativeImputer` behavior can change depending on a random state. The random state which can be set is also called a "seed". As stated by the documentation, we can get multiple imputations when setting `sample_posterior` to `True` and changing the random seeds, i.e. the parameter `random_state`. Here is an example of how to use it: ``` import numpy as np from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer X_train = [[1, 2], [3, 6], [4, 8], [np.nan, 3], [7, np.nan]] X_test = [[np.nan, 2], [np.nan, np.nan], [np.nan, 6]] for i in range(3): imp = IterativeImputer(max_iter=10, random_state=i, sample_posterior=True) imp.fit(X_train) print(f"imputation {i}:") print(np.round(imp.transform(X_test))) ``` It outputs: ``` imputation 0: [[ 1. 2.] [ 5. 10.] [ 3. 6.]] imputation 1: [[1. 2.] [0. 1.] [3. 6.]] imputation 2: [[1. 2.] [1. 2.] [3. 6.]] ``` We can observe the three different imputations.
42,711,574
I try to save and read multiple objects in one XML-File. The function Serialize is not working with my existing List, but i dont know why. I already tried to compile it but i get an error wich says, that the methode needs an object refference. Program.cs: ``` class Program { static void Main(string[] args) { List<Cocktail> lstCocktails = new List<Cocktail>(); listCocktails.AddRange(new Cocktail[] { new Cocktail(1,"Test",true,true, new Cocktail(1, "Test4", true, true, 0) }); Serialize(lstCocktails); } public void Serialize(List<Cocktail> list) { XmlSerializer serializer = new XmlSerializer(typeof(List<Cocktail>)); using (TextWriter writer = new StreamWriter(@"C:\Users\user\Desktop\MapSample\bin\Debug\ListCocktail.xml")) { serializer.Serialize(writer, list); } } private void DiserializeFunc() { var myDeserializer = new XmlSerializer(typeof(List<Cocktail>)); using (var myFileStream = new FileStream(@"C:\Users\user\Desktop\MapSample\bin\Debug\ListCocktail.xml", FileMode.Open)) { ListCocktails = (List<Cocktail>)myDeserializer.Deserialize(myFileStream); } } ``` Cocktail.cs: ``` [Serializable()] [XmlRoot("locations")] public class Cocktail { [XmlElement("id")] public int CocktailID { get; set; } [XmlElement("name")] public string CocktailName { get; set; } [XmlElement("alc")] public bool alcohol { get; set; } [XmlElement("visible")] public bool is_visible { get; set; } [XmlElement("counter")] public int counter { get; set; } private XmlSerializer ser; public Cocktail() { ser = new XmlSerializer(this.GetType()); } public Cocktail(int id, string name, bool alc,bool vis,int count) { this.CocktailID = id; this.CocktailName = name; this.alcohol = alc; this.is_visible = vis; this.counter = count; } } } ``` Ii also think I messed something up with the DiserializeFunc().
2017/03/10
[ "https://Stackoverflow.com/questions/42711574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7685488/" ]
``` passenger = Passenger.where("DATE(created_at) = ?", Date.yesterday) ```
55,435
I'm trying to plot a violin plot with a split based on Sex ( like in the fourth example in the [doccumentation](https://seaborn.pydata.org/generated/seaborn.violinplot.html) but with Sex) [![Example plot from the doccumentation](https://i.stack.imgur.com/46Jgl.png)](https://i.stack.imgur.com/46Jgl.png) I can produce a categorical scatter plot and split it by Sex. However, when i attempt the same but as a violin plot; it throws an error. ``` Traceback (most recent call last): File "<ipython-input-868-0599b976fd6c>", line 1, in <module> sns.catplot(x="Batch", y="Age", hue = 'Sex', data = ages, kind='violin') File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 3755, in catplot g.map_dataframe(plot_func, x, y, hue, **plot_kws) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py", line 820, in map_dataframe self._facet_plot(func, ax, args, kwargs) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py", line 838, in _facet_plot func(*plot_args, **plot_kwargs) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 2387, in violinplot color, palette, saturation) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 564, in __init__ self.estimate_densities(bw, cut, scale, scale_hue, gridsize) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 679, in estimate_densities kde, bw_used = self.fit_kde(kde_data, bw) File "/home/tasty/anaconda3/lib/python3.7/site-packages/seaborn/categorical.py", line 719, in fit_kde kde = stats.gaussian_kde(x) File "/home/tasty/anaconda3/lib/python3.7/site-packages/scipy/stats/kde.py", line 208, in __init__ self.set_bandwidth(bw_method=bw_method) File "/home/tasty/anaconda3/lib/python3.7/site-packages/scipy/stats/kde.py", line 540, in set_bandwidth self._compute_covariance() File "/home/tasty/anaconda3/lib/python3.7/site-packages/scipy/stats/kde.py", line 551, in _compute_covariance aweights=self.weights)) File "/home/tasty/anaconda3/lib/python3.7/site-packages/numpy/lib/function_base.py", line 2427, in cov avg, w_sum = average(X, axis=1, weights=w, returned=True) File "/home/tasty/anaconda3/lib/python3.7/site-packages/numpy/lib/function_base.py", line 419, in average scl = wgt.sum(axis=axis, dtype=result_dtype) File "/home/tasty/anaconda3/lib/python3.7/site-packages/numpy/core/_methods.py", line 36, in _sum return umr_sum(a, axis, dtype, out, keepdims, initial) TypeError: No loop matching the specified signature and casting was found for ufunc add ``` My code is: ``` >>> print(ages.head()) Age Sex Batch PassengerId 852 74 male Train 86 33 female Train 161 44 male Train 812 39 male Train 837 21 male Train >>> sns.catplot(x="Batch", y="Age", hue = 'Sex', data = ages, kind='violin') ``` Removing the kind argument produces the following scatterplot: [![Scatter plot that i can correctly produce](https://i.stack.imgur.com/F1z17.png)](https://i.stack.imgur.com/F1z17.png) How do I get rid of the error to display the data as a violin plot? Thanks in advance edit: Seaborn version: 0.9.0 Numpy version: 1.16.2 Python version: 3.7.3
2019/07/10
[ "https://datascience.stackexchange.com/questions/55435", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/77162/" ]
I had tried the suggestion from @foxthatruns's answer to no avail. I found that changing my numeric column to `float64` solved the problem ([reference](https://www.reddit.com/r/learnpython/comments/7ivopz/numpy_getting_error_on_matrix_inverse/dr1w9pm/)). `df['my_column']=df['my_column'].astype('float64')` This was done with Python 3.7, seaborn 0.9.0, numpy 1.16.4.
67,678,503
I am using jinja template to print the key of a dictionary. here is the code: ``` from jinja2 import Template import json data = ''' hello {{Names}} Heading is {{ Names.keys() }} ''' schema = ''' { "Names" : [ "Name1", "Name2", "Name3" ] } ''' k = json.loads(schema) tm = Template(data) jdata = tm.render(Names=k) print(jdata) ``` with this it is printing template as `dict_keys`, see output below: ``` hello {'Names': ['Name1', 'Name2', 'Name3']} Heading is dict_keys(['Names']) ``` so, I think `dict_keys` is of type `set` which doesn't support indexing and also i am not able to use `list` method (as normally used in python) to convert it to list and then use indexing. I want to print it as a string, expected output: ``` hello {'Names': ['Name1', 'Name2', 'Name3']} Heading is Names # see the Names, it is string ```
2021/05/24
[ "https://Stackoverflow.com/questions/67678503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7400128/" ]
how about : ``` select * from ( select * , row_number() over (partition by month_id order by rand()) rn from my_table ) t where rn <= 1000000 order by month_id ```
61,638,447
I have got a situation where the `$user_id` parameter is optional and I used to do this in codeigniter in the way written below. But I am not able to figure it out, How can I write this query in laravel's eloquent and query builder as well. Any help is much appreciated. ``` function get_user($user_id) { $this->db->select('u.id as user_id, u.name, u.email, u.mobile'); if($user_id != '') { $this->db->where('user_id', $user_id); } return $this->db->get('users as u')->result(); } ``` Thanks
2020/05/06
[ "https://Stackoverflow.com/questions/61638447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6551438/" ]
This is because `points.append(point)` is a method and doesn't return a value, hence when you do `points = points.append(point)`, `points` takes the (lack of a) return value and becomes `None` (you overwrote the `list` type with `None` type). However, when you do `point.append(point)`, you are correctly adding elements to the list by calling its built-in method, and not overwriting anything, which is why the second code works but not the first.
284,680
The following sum $$\sqrt{8+\frac2n}\cdot\left(\frac2n\right) + \sqrt{8+\frac4n}\cdot\left(\frac2n\right) + \ldots+ \sqrt{8+\frac{2n}n}\cdot\left(\frac2n\right)$$ is a right Riemann sum for the definite integral. (1) $\displaystyle\int\_6^b f(x)dx$; $f(x)=~$? It is also a Riemann sum for the definite integral. (2) $\displaystyle\int\_8^b g(x)dx$; $g(x)=~$?
2013/01/23
[ "https://math.stackexchange.com/questions/284680", "https://math.stackexchange.com", "https://math.stackexchange.com/users/59255/" ]
Instead of just giving you the answer, for the second one, you are wanting to compare $$ \sum\_{i=1}^{n} f(8 + i\Delta x)\Delta x $$ with $$ \sum\_{i=1}^{n} \sqrt{8 + i\frac{2}{n}}\frac{2}{n}. $$ (Noting that this sum is the sum that you have in your question). * First: Can you see what $\Delta x$ should be? * Second: Can you then guess what $f$ could be? * Third: If $\Delta x = \frac{b - a}{2}$ where here $a=8$, what would $b$ be? Now try to do similarly for the first one. Hint: Here you might note that $8 = 2 + 6$.
47,492,685
I have a dataframe with two columns as below: ``` Var1Var2 a 28 b 28 d 28 f 29 f 29 e 30 b 30 m 30 l 30 u 31 t 31 t 31 ``` I'd like to create a third column with values which increases by one for every change in value of another column. ``` Var1Var2Var3 a 28 1 b 28 1 d 28 1 f 29 2 f 29 2 e 30 3 b 30 3 m 30 3 l 30 3 u 31 4 t 31 4 t 31 4 ``` How would I go about doing this?
2017/11/26
[ "https://Stackoverflow.com/questions/47492685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4389921/" ]
Using `category` ``` df.Var2.astype('category').cat.codes.add(1) Out[525]: 0 1 1 1 2 1 3 2 4 2 5 3 6 3 7 3 8 3 9 4 10 4 11 4 dtype: int8 ``` Updated ``` from itertools import groupby grouped = [list(g) for k, g in groupby(df.Var2.tolist())] np.repeat(range(len(grouped)),[len(x) for x in grouped])+1 ```
2,560,688
I am on the edge of submitting my first iPhone Application. So, now I have little confusion in the submitting process.. My application is only for iPhone and ipod touch users only, not for the ipad (yet). So, i don't know where I need to specify this option while submitting app to the apple. If anybody can help me then it would be greatly appreciated. Thanks in advance... **EDIT:** While submitting app to the app store I got one radio button option which is asking like **" Do you want to limit your app to only run on devices with specific capabilities?" Yes | No.** (this question can be found just below the description field) I don't know what to select and why..
2010/04/01
[ "https://Stackoverflow.com/questions/2560688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87942/" ]
It doesn't matter if your app isn't an "iPad app". If you submit it, it'll be submitted as an iPhone/iPod Touch app. The iPad will be able to run it using it's scaling mode, and there's no way you can prevent this. Unless you create your app to be universal for iPhone and iPad, this is how it will work.
45,931,335
I'm getting an error while pushing one object into another object. But the 2nd object is an array and inside an array there is an object. How can I fix this cause I want to add that into my object My object just like this I want to add the the **Object2** into **Object1** **Objet1** ``` stdClass Object ( [id_laporan_pemeriksa] => 5 [no_pkpt] => SNE [tgl_pkpt] => 2010 [no_penugasan] => ST-4000/PW25/2/2017 [tgl_penugasan] => 2017-08-09 [judul_laporan] => Masukkan Kode disini [no_laporan] => LBINA-9000/PW25/2/2017 [tgl_laporan] => 2017-08-01 [tahun_anggaran_penugasan] => 2009 [nilai_anggaran_penugasan] => 10000000 [realisasi_anggaran_penugasan] => 100000000 [jenis_anggaran_penugasan] => Utang [sumber_laporan] => Inspektorat Maluku [nama_sumber_penugasan] => PKPT [nama_ketua_tim] => Abdul Rofiek, Ak. [nama_pengendali_teknis] => Alfian Massagony, S.E. [nama_unit_penugasan] => Irban Wil. I [nama_penugasan] => Penjaminan [nama_sub_penugasan] => Audit [id_s_sub_penugasan] => 010105 [nama_s_sub_penugasan] => Audit atas hal-hal lain di bidang kepegawaian. ) ``` **Object2** ``` stdClass Object ( [id] => 3 [data_sebab] => Array ( [0] => stdClass Object ( [id] => 4 [data_rekomendasi] => Array ( [0] => stdClass Object ( [id] => 4 [data_tindak_lanjut] => Array ( [0] => stdClass Object ( [id] => 9 [tgl_tindak_lanjut] => 0000-00-00 ) ) ) [1] => stdClass Object ( [id] => 5 [id_rekomendasi] => [data_tindak_lanjut] => Array ( [0] => stdClass Object ( [id] => 10 [id_tindak_lanjut] => [tgl_tindak_lanjut] => 0000-00-00 ) [1] => stdClass Object ( [id] => 11 [id_tindak_lanjut] => [tgl_tindak_lanjut] => 0000-00-00 ) ) ) ) ) ) ) ``` I have tried ``` $Object1['data']->$Object2; ``` But i got an error > > **Cannot use object of type stdClass as array** > > >
2017/08/29
[ "https://Stackoverflow.com/questions/45931335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7840345/" ]
The syntax of adding `$Object2` as a property of `$Object1` is: ``` $Object1->Object2 = $Object2; ``` Or: ``` $Object1->{'Object2'} = $Object2; ```
28,612,173
I have a text file that was created when someone pasted from Excel into a text-only email message. There were originally five columns. ``` Column header 1 Column header 2 ... Column header 5 Row 1, column 1 Row 1, column 2 etc ``` Some of the data is single-word, some has spaces. What's the best way to get this data into column-formatted text with unix utils? Edit: I'm looking for the following output: ``` Column header 1 Column header 2 ... Column header 5 Row 1 column 1 Row 1 column 2 ... ... ``` I was able to achieve this output by manually converting the data to CSV in vim by adding a comma to the end of each line, then manually joining each set of 5 lines with J. Then I ran the csv through `column -ts,` to get the desired output. But there's got to be a better way next time this comes up.
2015/02/19
[ "https://Stackoverflow.com/questions/28612173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440257/" ]
Perhaps a perl-one-liner ain't "the best" way, but it should work: ``` perl -ne 'BEGIN{$fields_per_line=5; $field_seperator="\t"; \ $line_break="\n"} \ chomp; \ print $_, \ $. % $fields_per_row ? $field_seperator : $line_break; \ END{print $line_break}' INFILE > OUTFILE.CSV ``` Just substitute the "5", "\t" (tabspace), "\n" (newline) as needed.
238,192
Someone asked about this question on the main StackOverflow. The full question is: > > Given a value N, find `p` such that all of `[p, p + 4, p + 6, p + 10, p + 12, p + 16]` are prime. > > > * The sum of `[p, p + 4, p + 6, p + 10, p + 12, p + 16]` should be at least N. > > > My thinking is: * Sieve all primes under N * Ignore primes below `(N-48)/6` * Create consecutive slices of length 6 for the remaining primes. * Check if the slice matches the pattern. Here's my solution. I'd appreciate some feedback. ``` from itertools import dropwhile, islice def get_solutions(n): grid = [None for _ in range(n+1)] i = 2 while i < n+1: if grid[i] is None: grid[i] = True for p in range(2*i, n+1, i): grid[p] = False else: i += 1 sieve = (index for index, b in enumerate(grid) if b) min_value = (n - 48) / 6 reduced_sieve = dropwhile(lambda v: v < min_value, sieve) reference_slice = list(islice(reduced_sieve, 6)) while True: try: ref = reference_slice[0] differences = [v - ref for v in reference_slice[1:]] if differences == [4, 6, 10, 12, 16]: yield reference_slice reference_slice = reference_slice[1:] + [next(reduced_sieve)] except StopIteration: break n = 2000000 print(next(get_solutions(n))) # or for all solutions for solution in get_solutions(n): print(solution) ```
2020/03/01
[ "https://codereview.stackexchange.com/questions/238192", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/217493/" ]
Overall, good first question! The first obvious improvement is to factor out the code that generates the primes ``` def prime_sieve(n): grid = [None for _ in range(n+1)] i = 2 while i < n+1: if grid[i] is None: grid[i] = True for p in range(i*i, n+1, i): grid[p] = False else: i += 1 return (index for index, b in enumerate(grid) if b) ``` Note that `for p in range(i*i, n+1, i):` starts later than the `for p in range(2*i, n+1, i):` which you used. This is safe because anything less than the current prime squared will have already been crossed out. This difference alone makes the code about 2x faster for `n = 4000000`. By separating the sieve, it makes things like profiling much easier, and you can see that most of the time this method takes is still in the sieve. Using some tricks from [Find primes using Sieve of Eratosthenes with Python](https://codereview.stackexchange.com/questions/194756/find-primes-using-sieve-of-eratosthenes-with-python), we can focus our efforts on speeding this part up. ``` def prime_sieve(n): is_prime = [False] * 2 + [True] * (n - 1) for i in range(int(n**0.5 + 1.5)): # stop at ``sqrt(limit)`` if is_prime[i]: is_prime[i*i::i] = [False] * ((n - i*i)//i + 1) return (i for i, prime in enumerate(is_prime) if prime) ``` This prime sieve works pretty similarly, but is shorter, and about 4x faster. If that isn't enough, numpy and <https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188> can come to the rescue with this beauty which is another 12x faster. ``` import numpy def prime_sieve(n): """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool) for i in range(1,int(n**0.5)//3+1): if sieve[i]: k=3*i+1|1 sieve[ k*k//3 ::2*k] = False sieve[k*(k-2*(i&1)+4)//3::2*k] = False return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)] ``` At this point, further speedup would need to come from fancy number theory, but I'll leave that for someone else.
48,547
I've been told that there's a design rule of thumb that whenever you have a "bus" providing power and ground (for example, in an array of PWM outputs) that the ground connection is placed nearest the edge. What is the reasoning behind this? ![enter image description here](https://i.stack.imgur.com/FkxpF.png)
2012/11/09
[ "https://electronics.stackexchange.com/questions/48547", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/17697/" ]
Ground ring around the periphery as a sort of EMI shield is what I was taught, but I understand that in a quarter century, the validity of that purpose may have worn off. Pure speculation alert: One possible benefit of keeping the neutral rail consistently at the outer periphery of a board is that accidental contact between two boards near the edges would not cause catastrophic short circuits. There is no reference I can quote to validate this speculation, though.
54,015,119
I’m writing a cache handler that needs a unique ID number for every instance of the application, so that when someone has two projects open in two instances, the caches don’t get confused. According to [this thread](http://forums.codeguru.com/showthread.php?452992-What-exactly-is-hInstance), it appears the `HINSTANCE` passed to `WinMain` is a handle to the module, which could simply be the exe, not necessarily a unique process ID. The thread seems to say that information about the module/process to be run is brought into memory only once, and the `HINSTANCE` is a handle to that. Does that mean the `HINSTANCE` can’t be used as a unique identifier for the process because they all point to the same module? Or am I mistaken?
2019/01/03
[ "https://Stackoverflow.com/questions/54015119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5456130/" ]
`HINSTANCE` is mostly obsolete, a holdover from 16-bit days. It'll have the same value for all instances of your application. For a unique process ID, use [`GetCurrentProcessId`](https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessid)
73,275,340
I'm trying to install NET. 6.3 on my chromebook with Linux but when I try to execute ```bash ./dotnet-install.sh -c Current ``` in the Linux Terminal it always gives me this error: ```bash -bash: ./dotnet-install.sh: No such file or directory ``` Any way around it/any fix for it? I have done sudo -i so I got full permission and I have put the file I'm trying to execute in a lot of folders including my Linux folder. Any help is appreciated!
2022/08/08
[ "https://Stackoverflow.com/questions/73275340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19716022/" ]
I suppose you should: ```bash chmod +x ./dotnet-install.sh ./dotnet-install.sh -c Current ``` or ```bash /bin/bash dotnet-install.sh -c Current ```
63,135,921
Working on a project, new to c# here, and I'm trying to take care of unhanded exceptions. What I'm trying to do is give the user a helpful error message whenever they type something that isn't one of the choices and keep prompting them until they enter a valid response. ``` string input = Console.ReadLine(); // bool userBool = false; // while( userBool){ // } switch (Int32.Parse(input)) { case 1: farm.AddGrazingField(new GrazingField()); Console.WriteLine("Your Facility has been added"); break; case 2: farm.AddPlowedField(new PlowedField()); Console.WriteLine("Your Facility has been added"); break; case 3: farm.AddNaturalField(new NaturalField()); Console.WriteLine("Your Facility has been added"); break; case 4: farm.AddChickenHouse(new ChickenHouse()); Console.WriteLine("Your Facility has been added"); break; case 5: farm.AddDuckHouse(new DuckHouse()); Console.WriteLine("Your Facility has been added"); break; default: break; } ``` I know I could do this with a while loop and conditionals but havent been successful doing that with switch case.
2020/07/28
[ "https://Stackoverflow.com/questions/63135921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14009868/" ]
You can use function to both read and also validate the input of the user: ``` int GetUserInput() { while (true) { Console.Write("Please enter a number: "); var input = Console.ReadLine(); if (int.TryParse(input, out var value)) return value; } } ``` This function will not throw an exception if the user enters an invalid value. Instead it will prompt the user again. You can expand this to limit the range of the input that you allow and write descriptive error messages.
3,179,439
Is it possible to detect a programming language source code (primarily Java and C# ) in a text? For example I want to know whether there is any source code part in this text. ``` .. text text text text text text text text text text text text text text text text text text text text text text text text text text text public static Person createInstance() { return new Person();} text text text text text text text text text text text text text text text text text text text text text text text text text text text .. ``` I have been searching this for a while and I couldn't find anything. A solution with Python would be wonderful. Regards.
2010/07/05
[ "https://Stackoverflow.com/questions/3179439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336583/" ]
There are some syntax highlighters around ([pygments](http://pygments.org), [google-code-prettify](http://code.google.com/p/google-code-prettify/)) and they've solved code detection and classification. Studying their sources could give an impression how it is done. (now that I looked at pygments again - I don't know if they can autodetect the programming language. But google-code-prettify definitly can do it)
103,998
The Torah says if a man seduces a woman he must pay her 50 silver shekel and should marry her ([Shemot 22,16](https://www.sefaria.org.il/Exodus.22.15?lang=bi&aliyot=0)): > > וְכִי־יְפַתֶּה אִישׁ בְּתוּלָה אֲשֶׁר לֹא־אֹרָשָׂה וְשָׁכַב עִמָּהּ מָהֹר יִמְהָרֶנָּה לּוֹ לְאִשָּׁה׃ > > > If a man seduces a virgin for whom the bride-price has not been paid, and lies with her, he must make her his wife by payment of a bride-price. > > > What if the woman seduces the man, must he pay the penalty?
2019/05/24
[ "https://judaism.stackexchange.com/questions/103998", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/17060/" ]
If the *Naara* seduces the man and her father is not alive he does not pay the penalty as she wanted it and she has forgiven the money (but if she was raped he would have to pay her) Mishne Lemelech Naaro Besula 2,14: > > ואם אין לה אב הרי הן של עצמה. פי' דוקא באונס אבל מפותה אין לה כלום שכבר מחלה > > > However when the father is alive she is in his jurisdiction so the man should have realised when she was trying to seduce him that the rights for consummation belong to her father. So regardless whether she seduced him or not, she is not in charge of her body and he has to pay for "seducing" her away from her father and **he is benefiting from the cohabitation at the expense of her father's monetary loss** as she is no longer virgin. However it is the father's right be *Mochel* forgive the monetary damages (just like all monetary obligations) as he has the potential to make her get married against her will to a person who is repulsive or with leprosy so Kesubos 40b: > > **ונתן האיש השוכב עמה לאבי הנערה חמשים כסף הנאת שכיבה חמשים** מכלל דאיכא בושת ופגם ואימא לדידה ...מסתברא דאביה הוי דאי בעי מסר לה למנוול ומוכה שחין: > > >
834,479
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
2009/05/07
[ "https://Stackoverflow.com/questions/834479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57698/" ]
Return the StringBuilder if you're going to further modify the string, otherwise return the string. This is an API question. Regarding efficiency. Since this is a vague/general question without any specifics then I think mutable vs. immutable is more important than performance. Mutability is an API issue of letting your API return modifiable objects. String length is irrelevant to this. That said. If you look at StringBuilder.ToString with Reflector: ``` public override string ToString() { string stringValue = this.m_StringValue; if (this.m_currentThread != Thread.InternalGetCurrentThread()) { return string.InternalCopy(stringValue); } if ((2 * stringValue.Length) < stringValue.ArrayLength) { return string.InternalCopy(stringValue); } stringValue.ClearPostNullChar(); this.m_currentThread = IntPtr.Zero; return stringValue; } ``` You can see it may make a copy but if you modify it with the StringBuilder then it will make a copy then (this is what I can tell the point of m\_currentThread is because Append checks this and will copy it if it mismatches the current thread). I guess the end of this is that if you do not modify the StringBuilder then you do not copy the string and length is irrelevant to efficiency (unless you hit that 2nd if). **UPDATE** System.String is a class which means it is a reference type (as opposed to value type) so "string foo;" is essentially a pointer. (When you pass a string into a method it passes the pointer, not a copy.) System.String is mutable inside mscorlib but immutable outside of it which is how StringBuilder can manipulate a string. So when ToString() is called it returns its internal string object by reference. At this point you cannot modify it because your code is not in mscorlib. By setting the m\_currentThread field to zero then any further operations on the StringBuilder will cause it to copy the string object so it can be modified **and** not modify the string object it returned in ToString(). Consider this: ``` StringBuilder sb = new StringBuilder(); sb.Append("Hello "); string foo = sb.ToString(); sb.Append("World"); string bar = sb.ToString(); ``` If StringBuilder did not make a copy then at the end foo would be "Hello World" because the StringBuilder modified it. But since it did make a copy then foo is still just "Hello " and bar is "Hello World". Does that clarify the whole return/reference thing?
31,117,435
I have two models: an `owner` and a `pet`. An owner `has_many :pets` and a pet `belongs_to :owner`. What I want to do is grab *only those owners* that have *pets which ALL weigh over 30lbs*. ```rb #app/models/owner.rb class Owner < ActiveRecord::Base has_many :pets #return only those owners that have heavy pets end #app/models/pet.rb class Pet < ActiveRecord::Base belongs_to :owner scope :heavy, ->{ where(["weight > ?", 30])} end ``` Here is what is in my database. I have three owners: 1. *Neil*, and *ALL of which ARE heavy*; 2. *John*, and *ALL of which ARE NOT heavy*; 3. *Bob*, and *SOME of his pets ARE heavy* and *SOME that ARE NOT heavy*. The query should return only *Neil*. Right now my attempts return *Neil* and *Bob*.
2015/06/29
[ "https://Stackoverflow.com/questions/31117435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044009/" ]
What if you do it in two steps, first you get all `owner_ids` that have at least 1 heavy pet, then get all `owner_ids` that have at least 1 not-heavy pet and then grab the owners where id exists in the first array but not in the second? Something like: ``` scope :not_heavy, -> { where('weight <= ?', 30) } ``` ... ``` owner_ids = Pet.heavy.pluck(:owner_id) - Pet.not_heavy.pluck(:owner_id) owners_with_all_pets_heavy = Owner.where(id: owner_ids) ```
223,651
In the book that I am currently writing, all vampires have this kind of "control" over their own blood using magic. Only vampires who are extremely experienced in magic can interact with the blood of other creatures, but if the creature itself is another vampire, the task is way more difficult.
2022/02/04
[ "https://worldbuilding.stackexchange.com/questions/223651", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/91672/" ]
Instinctual familiarity ----------------------- The hemomancers have instinctual familiarity with their own blood. They know the properties of it so well that they can easily control it. Other blood can *also* be manipulated but there are so many small things that are *different* that it is difficult to generalise the experience with your own blood to others. On purely biochemical level, the blood of others could have different viscosity, different percentage of different types of cells, different amounts of other trace materials, etc. On metaphysical level, the blood is going to have intrinsically different links. Learning the more general way of manipulating any blood is very hard. Harder still when trying to apply it for other *vampires*. Knowing how to manipulate the blood of the mortal needs you to *understand* the blood and apply the correct magic force to correctly affect it. However, a *vampire* has stolen the blood of many mortals. It is a big mix. That changes after every feeding. It is much harder to properly understand that blood enough to manipulate it with magic. Vampires know how to manipulate their own blood but not in a way that they can express to others. The same way you can know how to juggle. Sure, you can do it. You can also *show* somebody how to juggle. However, but you cannot explain to them how to do it. They need to learn themselves. Only with blood manipulation, there is no easy visual shortcut that they can mimic until they actually get the tiny but important details of.
2,898,059
There are 10 points in a plane and 4 of them are collinear. Find the number of triangles formed by producing the lines resulting from joining the points infinitely in both directions (assuming no two lines are parallel). I can see that there are 10C2-4C2=40 straight lines. If no two pairs of lines were concurrent we would have 40C3=9880 triangles. However, I do not know how to adjust for the concurrent lines. Any help/suggestions much appreciated.
2018/08/29
[ "https://math.stackexchange.com/questions/2898059", "https://math.stackexchange.com", "https://math.stackexchange.com/users/49971/" ]
In the statement, "assuming no two lines are parallel" probably means that the $$\binom{10}{2}-\binom{4}{2}+1=40$$ lines are distinct and pairwise concurrent. Then the number of triangles is $\binom{40}{3}=9880$.
69,625,065
I have found this code online but not sure what does "any" do there!? ``` def fibonacci(count): fib_list = [0, 1] any(map(lambda _: fib_list.append(sum(fib_list[-2:])), range(2, count))) return fib_list[:count] print(fibonacci(20)) ```
2021/10/19
[ "https://Stackoverflow.com/questions/69625065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17188165/" ]
`Element '<shortcut>' is missing a required attribute, 'android:shortcutId'.` is showing because the minSdkVersion must be 25. That being said, if you still want your app to support OS below SDK 25, you can create a xml folder for SDK 25: `xml-v25` put your shortcuts file in it. `xml-v25/shortcuts.xml` Edit the `xml/shortcuts.xml` and remove any `<shortcut>` tag. Shortcuts will be available for SDK 25 and above, and your app can be installed for anything that match your minSDKVersion
72,416,734
I want to increase the value of i every time the button is clicked I've tried this code but it's not working. ``` val textview = findViewById<TextView>(R.id.texttest) var i = 10 bookbutton.setOnClickListener { i++ } textview.text = "$i" ```
2022/05/28
[ "https://Stackoverflow.com/questions/72416734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17438980/" ]
You have to set the text inside the listener: ``` bookbutton.setOnClickListener { i++ textview.text = "$i" } ```
57,147,178
It's easy to produces multi-level groupby result like this ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 Parrot Captive 30.0 Wild 20.0 ``` The code would look like `df.groupby(['animal', 'type'])['speed'].max()` However, if I want to add a total row to each subgroup, to produce something like this ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 overall 390.0 Parrot Captive 30.0 Wild 20.0 overall 30.0 ``` How can I do it? The reason for adding the sub-level-row, is that it enables choosing category when I put it into BI tools for other colleagues. UPDATE: in the example above I show using `max()`, I also want to know how to do it with `user_id.nunique()`. --- Right now I produce the result by 2 groupby and then concat them. something like ``` df1 = df.groupby(['animal', 'type'])['speed'].max() df2 = df.groupby(['animal'])['speed'].max() ##### ... manually add `overall` index to df_2 df_total = pd.concat([df1, df2]).sort_index() ``` but it seems bit too manual, is there better approach?
2019/07/22
[ "https://Stackoverflow.com/questions/57147178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1794744/" ]
You can do this with 2 `concat`'s, starting from your `groupby` result. --- ``` g = df.groupby(level=0).max() m = pd.concat([g], keys=['overall'], names=['Type']).swaplevel(0, 1) pd.concat([df, m], axis=0).sort_index(level=0) ``` ``` Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 overall 390.0 Parrot Captive 30.0 Wild 20.0 overall 30.0 ```
23,855,399
do you know how can I add a Respring button in Setting>My tweak? I know the code must added in the PreferenceBundle folder, but I don't know the code :D Example: <http://i.imgur.com/aAOiAiyl.png> Thanks in advance! P.S: I know how to use Theos (if this can be useful)
2014/05/25
[ "https://Stackoverflow.com/questions/23855399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3515609/" ]
For theos just do this: 1. In the settings bundle open "resources" and then the .plist file of your tweak (maybe it will be "my tweak settings.plist" and add a button with this value: `cell: PSButtonCell label: Respring action: respring` 2. Now go back in your settings bundle and open the file called "my tweak settings.mm" and, in the @implementation part, add the method for the respiring action: ```cpp -(void)respring { [(SpringBoard *)[UIApplication sharedApplication] _relaunchSpringBoardNow]; } ``` Non you will have a PSButtonCell that will respiring your device.
16,724,395
I created a `UIView` which I want to display over my `UITableView`. I add it by adding to the current view: `[self.view addSubview:self.adBanner];` When I `scroll` the `section headers` will hover over top of this `view`. Am I adding the `view` over table correctly or should I be adding it to a different `view`?
2013/05/23
[ "https://Stackoverflow.com/questions/16724395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362413/" ]
Have you trie the following? ``` [self.view insertSubview:self.adBanner aboveSubview:yourTableview]; ```
41,221,474
Hi I'm trying to play a sound on tapping of an image but it is not playing. Actually here i'm also using one media element to play a sound on this page continuously. It is playing but other which should be played on tapping of image is not playing.Any idea would be appreciated. Xaml code ``` <MediaElement x:Name="mycontrol" Source="/Audio/bg_sound.mp3" AutoPlay="True"/> <MediaElement x:Name="mediaElement1" /> ``` C# Code ``` public sealed partial class Home : Page { public Home() { this.InitializeComponent(); } private void L_color_tap(object sender, TappedRoutedEventArgs e) { mediaElement1.Source = new Uri("ms-appx:///Assets/LearnColor/Objectnamesmp3/colors.mp3"); mediaElement1.AutoPlay = true; this.Frame.Navigate(typeof(L_Col_Act)); } } ```
2016/12/19
[ "https://Stackoverflow.com/questions/41221474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7268189/" ]
First of all as you are using color list for radio buttons , its the way for Checkbox list . But if you wanna use it like this only , you can do it by adding a `ng-change` in it like - View Code- ``` <div class="form-group" > <label class="control-label">Select Colors : </label> <div ng-repeat = "color in colorlist"> <input type="radio" name="color" ng-change="changed(color)" ng- value="true" ng-model="color.idDefault"/> {{color.colorName}} </div> Colors : {{colorlist}} ``` and in controller add a method - ``` $scope.changed=function(color){ for(var i=0;i<$scope.colorlist.length;i++) if($scope.colorlist[i].colorName!==color.colorName){ $scope.colorlist[i].idDefault=false; } } ``` Check the [fiddle](https://jsfiddle.net/z7k9okvw/) hope it will work for you.
51,613,428
I have file with following lines: **lines.txt** ``` 1. robert smith 2. harry 3. john ``` I want to get array as follows: ``` ["robert\nsmith","harry","john"] ``` I tried something like this: ``` with open('lines.txt') as fh: m = [re.match(r"^\d+\.(.*)",line) for line in fh.readlines()] print(m) for i in m: print(i.groups()) ``` It outputs following: ``` [<_sre.SRE_Match object; span=(0, 9), match='1. robert'>, None, <_sre.SRE_Match object; span=(0, 8), match='2. harry'>, <_sre.SRE_Match object; span=(0, 7), match='3. john'>] (' robert',) Traceback (most recent call last): File "D:\workspaces\workspace6\PdfGenerator\PdfGenerator.py", line 5, in <module> print(i.groups()) AttributeError: 'NoneType' object has no attribute 'groups' ``` It seems that I am approaching this problem in very wrong way. How you will solve this?
2018/07/31
[ "https://Stackoverflow.com/questions/51613428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6357916/" ]
You may read in the file into memory and use ``` r'(?ms)^\d+\.\s*(.*?)(?=^\d+\.|\Z)' ``` See the [regex demo](https://regex101.com/r/humIzT/1) **Details** * `(?ms)` - enable `re.MULTILINE` and `re.DOTALL` modes * `^` - start of a line * `\d+` - 1+ digits * `\.` - a dot * `\s*` - 0+ whitespaces * `(.*?)` - Group 1 (this is what `re.findall` returns here): any 0+ chars, as few as possible * `(?=^\d+\.|\Z)` - up to (but not inlcuding) the first occurrence of + `^\d+\.` - start of a line, 1+ digits and `.` + `|` - or + `\Z` - end of string. Python: ``` with open('lines.txt') as fh: print(re.findall(r'(?ms)^\d+\.\s*(.*?)(?=^\d+\.|\Z)', fh.read())) ```
47,031,464
I'm using Firebase for iOS on my app the user has to associate a photo with his profile on MySQL there is BLOB type to save images inside the database but on Firebase I don't find such a thing
2017/10/31
[ "https://Stackoverflow.com/questions/47031464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1763004/" ]
You have to use `Firebase Storage` to upload the image, and then get the URL and save the URL somewhere in your database. Here's the documentation on how to upload files: <https://firebase.google.com/docs/storage/ios/upload-files> Here's an example from one of my projects ``` FIRStorageReference *ref = [[[FIRStorage storage] reference] child:[NSString stringWithFormat:@"images/users/profilesPictures/pp%@.jpg", [UsersDatabase currentUserID]]]; [ref putData:imageData metadata:nil completion:^(FIRStorageMetadata * _Nullable metadata, NSError * _Nullable error) { if (error) { [[self viewController] hideFullscreenLoading]; [[self viewController] showError:error]; } else { [ref downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) { if (error) { [[self viewController] hideFullscreenLoading]; [[self viewController] showError:error]; } else { [[self viewController] hideFullscreenLoading]; [self.profilePictureButton setImage:nil forState:UIControlStateNormal]; [[UsersDatabase sharedInstance].currentUser setProfilePictureURL:[URL absoluteString]]; [UsersDatabase saveCurrentUser]; // This also updates the user's data in the realtime database. } }]; } }]; ```
14,078,677
here is my code ``` $id = $this->user->id; $data['last_cust_code'] = $a_Search['custcode']; $data['last_paid_filter'] = $a_Search['paid']; $data['last_unpd_filter'] = $a_Search['unpaid']; $data['last_group_field'] = $a_Search['grouping']; $data['last_session_code'] = $a_Search['session']; $out = $objDb->update('tblusrusers', $data,array("id = ?"=>$id)); ``` profiler output ``` UPDATE `tblusrusers` SET `last_cust_code` = ?, `last_paid_filter` = ?, `last_unpd_filter` = ?, `last_group_field` = ?, `last_session_code` = ? WHERE (id = '70') Array ( [1] => TESTAAA [2] => N [3] => N [4] => 1 [5] => 19993E ) ``` when i update directly through mysql client its updating properly. IMPORTANT:When i select the output through a query i am able to see the update ,but not in through phpmyadmin.does it has something to do with commit statements ,i mean is my autocommit is false?for some other queries am using transactions will it effect my above update query?please help
2012/12/29
[ "https://Stackoverflow.com/questions/14078677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1300034/" ]
Actually the problem is someone in my production team just put an `$objDb->beginTransaction()` but did not commit using `$objDb->commit()` which resulted in mysql database auto commit to false(bcoz the began transaction statement set autocommit to false) therefore all the other queries where not working since commit was not happening .
12,815,269
The image filenames are stored by unique by add `vendorID` before with it like "200018hari". The below picture show the Table where the `filename` is stored in the column `Cmp_DocPath`. ![The Table where the filename is stored in the column Cmp_DocPath](https://i.stack.imgur.com/SNfMH.png) I want to display the particular `VendorID` image from the Server folder "D:\Upload\Commerical Certificates" when the user select the `vendorID` from the dropdownlist.(The picture will not show the full form design with the dropdownlist.) ![Form design](https://i.stack.imgur.com/odxmM.png) I try this in Inline code but image not display. But I know this will not help me if the user select other `VendorID` from the dropdown. How I will do by the code-behind in C# ? ``` <asp:Image ID="Image1" runat="server" Height="400px" Width="400px" ImageUrl ="AdminCompanyInfo.aspx?FileName=~/Upload/Commerical Certificates/200027mcp.png"/> ```
2012/10/10
[ "https://Stackoverflow.com/questions/12815269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206192/" ]
``` #pragma push_macro("new") #undef new new(pointer) my_class_t(arg1, arg2); #pragma pop_macro("new") ``` or ``` #pragma push_macro("new") #undef new #include <...> #include <...> #include <...> #pragma pop_macro("new") ```
61,241
There is a rule that if you are eating multiple items that are in the same blessing category (e.g. shehakol) then you only say one blessing and have in mind the other items. Does this inclusion have an expiration? For example you are having ice cream and have in mind to have tea right after when you recite the shehakol blessing how much time after the ice cream can you have the tea without an additional blessing? On a relates note, does the tea need to be already prepared (i.e. not in front of you) at the time of the blessing or can you make it after finishing the ice cream?
2015/07/15
[ "https://judaism.stackexchange.com/questions/61241", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/3006/" ]
This is one of the many self-flagellative practices of the [Hassidei Ashkenaz](https://en.wikipedia.org/wiki/Ashkenazi_Hasidim). The [Rokeah](https://en.wikipedia.org/wiki/Eleazar_of_Worms), for example, writes (Hilkhot Teshuva: 11) that sitting in ice or snow is an appropriate form of penance for sexual relations with a married woman: > > הבא על אשת איש שהוא במיתה יסבול צער קשה כמיתה ישב בקרח או בשלג בכל יום שעה אחת בכל יום פעם אחת או פעמיים > > > It doesnt seem that one needs to do that act of self-affliction in particular; it is just a way of causing great suffering to oneself, "similar to death". Accordingly, in the summer, he suggests (there) other forms of self-flagellation, such as sitting among bees or other insects. He further generally recommends all types of self-flagellation and suffering. This is similar to the writings of his mentor [R. Yehuda HaHassid](https://en.wikipedia.org/wiki/Judah_ben_Samuel_of_Regensburg) who in Sefer Hassidim (ed. Margolis: 176) suggests torturing oneself by sitting in ice. (Although perhaps this refers to sitting in a frozen river (cf. 177) in which the pain comes from the cold water, rather than the ice.) He similarly approvingly cites a story (528) about a pious person sitting with his feet in freezing water until his feet became frozen together. Here too it doesn't sound like there is significance to torturing yourself with ice in particular; winter just affords someone with great snow and ice torture opportunities. During the summer other forms of self-affliction are possible (cf. 167). Importantly, however, the Sefer Hassidim adds (there; in parenthesis in ed. Margolis) that water is particularly appropriate for use in afflicting oneself, as there is a Midrash that Adam afflicted himself for 130 years with water as a form of penance for eating from the *ets hadaat*. (Perhaps this would apply to snow or ice as well): > > ולמה במים אמרו במדרש ק"ל שנים היה אדם הראשון יושב במים עד חוטמו להתכפר על שחטא בעץ הדעת שנגזר גזירה על כל הדורות > > >
189,153
I have a program which generates some html documentation. At the end of the script, I use the `open` command to automatically view the page in the browser. ``` generate-document > index.html open index.html ``` However, after iterating on the code, I end up with numerous obsolete copies of `index.html` open in my browser. Is there a way (either from the command line, or within the browser) to say something like "if index.html is already being viewed refresh it, otherwise load it."? ``` generate-document > index.html open-or-reload index.html ``` Safari or Chrome specific methods are fine.
2015/05/28
[ "https://apple.stackexchange.com/questions/189153", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/25478/" ]
The following command line can be added to your script and it will refresh the Tab that has focus in the frontmost Safari window, (even if the frontmost window only has a single page loaded): ``` osascript -e \ 'tell application "Safari" to set URL of current tab of front window to "file:///foo.html"' ```
29,483,616
This was working, but right now when I got back to this, it stopped working. I can't seem to figure out what the problem is. Please help. ``` <?php if(isset($_POST['submit'])) { require("dbconn.php"); $filename = $_POST['filename']; $name = $filename . pathinfo($_FILES['ufile']['name'],PATHINFO_EXTENSION); //$name = $_FILES['ufile']['name']; echo $name; //$size = $_FILES['file']['size'] //$type = $_FILES['file']['type'] $tmp_name = $_FILES['ufile']['tmp_name']; $error = $_FILES['ufile']['error']; if (isset ($name)) { if (!empty($name)) { $location = 'uploads/'; if (move_uploaded_file($tmp_name, $location.$name)) { $filename = $_POST['filename']; $filepath = $location.$name; $advname = $_POST['advname']; $year = $_POST['year']; $cname = $_POST['cname']; $ctype = $_POST['ctype']; $sqlq = "INSERT INTO file (filename, filepath, advname, year, cname, ctype) VALUES ('".$filename."','".$filepath."','".$advname."','".$year."','".$cname."','".$ctype."');"; $result = mysql_query($sqlq); if(!$result) { die("Error in connecting to database!"); } } } } } ?> <form id="form1" method="POST" action="" enctype="multipart/form-data"> <label>File Name</label> <input id="filename" name="filename" type="text" value=""/><br> <label>Advocate Name</label> <select name = "advname"> <option value=""></option> <option value="Adv 1">Adv 1</option> <option value="Adv 2">Adv 2</option> <option value="Adv 3">Adv 3</option> </select><br> <label>Year<label> <input id="year" name="year" type="date"><br> <label>Company Name</label> <input id="cname" name = "cname" type="text"><br> <label>Court Type</label> <input id="ctype" type="text" name = "ctype"><br> <label>Scan</label> <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button> <button type="button" class="btn btn-info" onclick="scan();">Scan</button><br> <label>Upload</label> <input type="file" name="ufile" id="ufile"><br> <input type="submit" name="submit" value="Submit" onclick="submitForm1();"> </form> ``` Both these code are a part of the same file. Please let me know of where I could be going wrong, because I can't seem to find any mistake. I've tried echoing inside the if statement and it doesn't display anything.
2015/04/07
[ "https://Stackoverflow.com/questions/29483616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373769/" ]
You can try this! ``` getResources().getStringArray(R.id.dog_breeds)[selectedIndex]; ``` -and you can get your desired solution -Please let me know if it was helpful or not or you can also correct me if i am wrong.!
42,748,745
I'm actually trying to understand PHPUNIT and unit testing with PHP. I have a classic divide methode. ``` public function divide($firstNumber, $secondNumber){ if( !is_numeric($firstNumber) || !is_numeric($secondNumber) ){ throw new Exception("Not a number") ; } if( $secondNumber == 0 ) throw new Exception("Can't divide by zero") ; return $firstNumber/$secondNumber ; } ``` As you can see It can return a Number or Exception. Here is the testDivide code that I used. ``` /** * @dataProvider diviserDateProvider * @covers MyTools::diviser */ public function testDivide($firstNumber, $secondNumber, $expected) { $myToolsClasse = new MyTools(); $this->assertEquals($expected, $myToolsClasse->diviser($firstNumber, $secondNumber)); } public function diviserDateProvider() { return array( array(1, 0, new Exception("Can't divide by zero")), array(1, 2, 0.5), array("", "", 0.5) ); } ``` As you can see there is a DataProvider with multiple testing values. The problem is I have to Except/Assert an Exception which is the best way to do it ? Should I use @exceptException and use try catch in my testDivide code ? Thanks for your help have a nice day!
2017/03/12
[ "https://Stackoverflow.com/questions/42748745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4651657/" ]
The [best practice](https://thephp.cc/news/2016/02/questioning-phpunit-best-practices) for testing exceptions with PHPUnit is to use `expectException()` in your test method's code.
18,848,090
I have a text file from where i read values ``` FileInputStream file = new FileInputStream("C:/workspace/table_export.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(file)); String line = null; while( (line = br.readLine())!= null ) { String [] tokens = line.split("\\s+"); String var_1 = tokens[0]; System.out.println(var_1); getstaffinfo(var_1,connection); } ``` The values read from text file is passed to getstaffinfo method to query the db ``` public static String getstaffinfo(String var_1, Connection connection) throws SQLException, Exception // Create a statement { StringBuffer query = new StringBuffer(); ResultSet rs = null; String record = null; Statement stmt = connection.createStatement(); query.delete(0, query.length()); query.append("select firstname, middlename, lastname from users where employeeid = '"+var_1+"'"); rs = stmt.executeQuery(query.toString()); while(rs.next()) { record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3); System.out.println(record); } return record; } ``` I get almost 14000 values read from text file which is passed to getstaffinfo method, all database activities such has loading driver, establishing connectivity all works fine. But while printing it throws error ``` java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-01000: maximum open cursors exceeded ORA-01000: maximum open cursors exceeded ``` Although i understand that this error is to do with database configuration, Is there an efficent way of making one db call and exceute the query for multiple values read from text file. Any inputs would be of great use. Many Thanks in advance!!
2013/09/17
[ "https://Stackoverflow.com/questions/18848090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1744539/" ]
Close ResultSet `rs.close();` and Statement `stmt.close();` after your while loop in `getstaffinfo()`, preferably inside a `finally{}`
7,582,218
Is it possible to compile a 64-bit binary on a 32-bit Linux platform using gcc?
2011/09/28
[ "https://Stackoverflow.com/questions/7582218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362738/" ]
If you have a multilib GCC installed, it's as simple as adding `-m64` to the commandline. The compiler should complain if it is not built with multilib support. In order to link, you'll need all the 64-bit counterparts of the standard libraries. If your distro has a multilib GCC, these should also be in the repositories.
22,204
I've had these pepper plants for a year and a half now. They weren't 100% healthy when I bought them. The actual plan was to pick the fruits and then bin the plants, but I felt bad doing that! They had gotten lots of bugs on my balcony, so I applied soapy water and alcohol and rinsed and replanted them. They have been doing great, giving me good fruits, but I could never get rid of the curly leaves. (Here is my [previous question](https://gardening.stackexchange.com/questions/14623/home-made-solution-for-white-spotted-curley-leaves-on-pepper-leaves) regarding this.) A while back I went away for a month, (I attempted to give them a self-watering system), and came back to see lots of leaves that looked burnt/dried. I trimmed them, and they had started doing okay again, but now there are loads and loads of annoying brown bugs. I've applied an alcohol/soapy water spray over and over, but it hasn't helped. The last time was around 10 days ago when I was going to leave for a week, and I decided that I'd bin them forever if the bugs weren't gone when I got back. Not only are they still there, but there are many more of them, and they're killing all the blooms and baby fruits. Is it worth attempting to fix them or should I just bin the whole thing? [![enter image description here](https://i.stack.imgur.com/eqrGJ.jpg)](https://i.stack.imgur.com/eqrGJ.jpg) [![enter image description here](https://i.stack.imgur.com/a5UKa.jpg)](https://i.stack.imgur.com/a5UKa.jpg) [![enter image description here](https://i.stack.imgur.com/IcYMI.jpg)](https://i.stack.imgur.com/IcYMI.jpg) P.S. They're next to my tomato boxes, all sitting inside a south-facing window shelf. I confess that some of the tomatoes are also mildly infected, but since the tomatoes won't last long, I'm not too worried. I have a bonsai ficus, and some African violets, on the other end of the house, at the north-facing windows, and I'm paranoid that they've got the curly leaves from these peppers as well. (It's not just paranoia, as I think I can see that the leaves are curled!) I've also gotten a cactus recently, and I hope that one survives!
2015/10/23
[ "https://gardening.stackexchange.com/questions/22204", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/6990/" ]
To be frank, I'd bin them without a second's hesitation, and would have done so a while back, and that's what I recommend to you. They're serving no useful purpose other than as a source of infection to your other plants, but it may be too late, the aphid infestation may already have spread to those too - use neem spray to treat them with. Curled leaves on African violets often indicates cyclamen mite, but I'm not at all sure that's a problem where you live. Inspect the backs of the leaves and every part of the plant to see what you can find.
60,899,557
My situation is following. I have a sting "list" like this ``` Text1 Text2: value1 Text3: Text4: Text5: value2 ... ``` Now I want to split the text into a dictionary with Key-Value Pair. I tryed it with this 1liner ``` sp = dict(s.split(':') for s in list.split('\n') if len(s) > 1 and s.count(':') > 0) ``` This works great until there is no value like in Text3 and Text4. My final dictionary should look like this ``` { Text2:value1,Text3:'',Text4:'',Text5:value2 } ``` Text1 should be skipped - but Text3 & Text4 I need in the dictionary, also if the value is empty.
2020/03/28
[ "https://Stackoverflow.com/questions/60899557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3352603/" ]
You can verify how it works with this simple example : ``` num <- 2 x <- 0 y<- 0 while (TRUE){ if (num %% 10 == 0){ cat('\nprinting from 1: ', num) x <- x + 1 break } if (num %% 2 == 0){ cat('\nprinting from 2: ', num) y <- y+ 1 } num <- num + 1 } #printing from 2: 2 #printing from 2: 4 #printing from 2: 6 #printing from 2: 8 #printing from 1: 10 x #[1] 1 y #[1] 4 ``` `while(TRUE)` makes it run for an infinite time. Every time `num` is divisible by 2 `y` is incremented and when `num` is divisible by 10 it increments `y` and the `while` loop breaks.
27,968,162
I'm trying to add all the elements of an array in which are embedded 3 other arrays of differing lengths. At the third level are two 1-element arrays whose values I cannot figure out how to access. What am I doing wrong? Please advise (no lamp-throwing, please). ``` function addArrayElems(arr) { var sum = 0; for (var i = 0; i < arr.length; i++) { if (typeof arr[i] === "number") sum += arr[i]; for (var j = 0; j < arr.length; j++) { if (typeof arr[i][j] === "number") sum += arr[i][j]; } //arr[i][j][k] doesn't work for (var k = 0; k < arr.length; k++) { if (typeof arr[i][j][k] === "number") sum += arr[i][j][k]; } for (var l = 0; l < arr.length; l++) { if (typeof arr[i][j] === "number") sum += arr[i][j]; } } return sum; } var arr = [1, 2, 3, 4, 5, [6, 7, 8, [9], [10]]]; console.log(addArrayElems(arr)); ```
2015/01/15
[ "https://Stackoverflow.com/questions/27968162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3743226/" ]
You get `null` because your `Test` calls `DbConnection.connectDB();` before making a call to `loadProp()`. You can fix this problem if you copy the first two lines from the `main` into your code. However, this would not be a good fix, because you have a non-static method `loadProp()` that modifies `static String properties[]` array. You would be better off making `loadProp()` static. In order to do that you would have to replace `this.getClass()` with a static way of obtaining the class - for example, by using `DbConnection.class`. Moreover, you could convert the method to a static initializer, and avoid calling it explicitly altogether: ``` static { Properties prop = new Properties(); InputStream input = DbConnection.class.getResourceAsStream("connection.properties"); try { prop.load(input); } catch (IOException ex) { Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex); System.out.println("exception " + ex); } String username = prop.getProperty("username"); String password = prop.getProperty("password"); properties[0] = username; properties[1] = password; System.out.println(properties[0]); System.out.println(properties[1]); } ``` Now your new `main` would work properly.
33,870,029
I am storing `TIMESTAMP` in database and when i fetch it back from database i want to convert it into AM and PM date format. ``` var dbDate = moment(milliseconds); // **i am getting an error over here** var data = dbDate.format("hh:mm:A").split(":"); ``` but i am getting following error `moment(milliseconds);` > > "Deprecation warning: moment construction falls back to js Date. This > is discouraged and will be removed in upcoming major release. Please > refer to <https://github.com/moment/moment/issues/1407> for more info. > > >
2015/11/23
[ "https://Stackoverflow.com/questions/33870029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/405383/" ]
The moment library, by default, only supports a limited number of formats within the constructor. If you don't use one of those formats, it defaults back to using `new Date`, where [browsers are free to interpret the given date how they choose](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2) unless it fits certain criteria. The deprecation warning is there to warn you of this behaviour - it's not necessarily an error. In your case, you have milliseconds, so you can use the [moment constructor that has a format parameter](http://momentjs.com/docs/#/parsing/string-format/), telling it you're specifically passing in milliseconds: ``` var dbDate = moment(milliseconds, 'x'); ``` All this assumes that you currently have `milliseconds` being returned to your JavaScript layer as a String. If you return it and treat it as a Number, you shouldn't be seeing that warning, as moment also has a [specific constructor that takes a single Number](http://momentjs.com/docs/#/parsing/unix-offset/), which if your `milliseconds` parameter is a Number should be being used already.
69,612,135
The code below is part of my repository. The static function cannot be used as follows, but I want to receive a different query depending on the parameter value taken over by the service. Can you give me a hand? Thank you in advance. ``` @Query(value = " select * " + "from t_user usr " + "left outer join t_sale_order ord on usr.id = ord.user_idx " + "LEFT OUTER JOIN ( " + "SELECT " + "sale_order_idx, sum(taxable_amount) + sum(non_taxable_amount) as amount " + "FROM t_sale_receipt " + "GROUP BY sale_order_idx " + ") receipt " + "ON receipt.sale_order_idx = ord.id " + "where NOT exists ( " + "select 1 from t_encourage_sent_list sl " + "where sl.user_idx = usr.id and sl.push_idx = ?1 " + ") " + "AND NOT EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id ) " + // readBookCondition(readBook) + "AND usr.active = 1", nativeQuery = true) List<User> findEncouragePushMsgTarget(Integer pushIdx, Integer readBook); static String readBookCondition(Integer readBook) { String readBookCondition = "AND NOT EXISTS ( SELECT 1 FROM t_user_study us WHERE us.user_idx = usr.id ) "; if ( readBook != null ) return ""; if ( readBook != 0 ) readBookCondition.replace("NOT", ""); return readBookCondition; } ```
2021/10/18
[ "https://Stackoverflow.com/questions/69612135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12192313/" ]
At the moment, this cannot be done. AFAIU, Google needs to update its tools to use the customer's domain in the return path of emails to solve this issue.
68,124,627
I have written this program, it passes all manual test conditions but says "wrong answer" when I submit online on an IDE. Constraints 0≤a,b,c≤180 ``` #include <iostream> using namespace std; int main() { // your code goes here double a,b,c; cin>>a>>b>>c; if(a+b+c==180) cout<<"YES"; else cout<<"NO"; return 0; } ```
2021/06/25
[ "https://Stackoverflow.com/questions/68124627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10238277/" ]
Pull the `Diet`s out of the EF query using `ToListAsync`. Then grab the `Recipes` off them. ``` var diets = await _context.Diets .Include(d => d.Recipes) .Where(d => d.DietId == DietId) .ToListAsync(); return diets.Select(x => x.Recipes).ToList(); ```
28,567,868
I'm trying to put datepicker on input inside bootstrap modal.The datepicker it works well inside template except for modals (using JQuery 2+) However, if I'm using JQuery 1.9 for example, the datepicker works well everywhere. I tried [this example](http://jsfiddle.net/sudiptabanerjee/93eTU/) ```js $('#idTourDateDetails').datepicker({ dateFormat: 'dd-mm-yy', minDate: '+5d', changeMonth: true, changeYear: true, altField: "#idTourDateDetailsHidden", altFormat: "yy-mm-dd" }); ``` ```css .clsDatePicker { z-index: 100000; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <!-- Button trigger modal --> <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> <div class="col-md-12"> <div class="row"> <label for="idTourDateDetails">Tour Start Date:</label> <div class="form-group"> <div class="input-group"> <input type="text" name="idTourDateDetails" id="idTourDateDetails" readonly="readonly" class="form-control clsDatePicker"> <span class="input-group-addon"><i id="calIconTourDateDetails" class="glyphicon glyphicon-th"></i></span> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> ``` Here,also when you switch to jQuery 2.0.2 ,that one not works anymore. I need some help in this way, and I don't want to use previous versions of JQuery. Thanks,
2015/02/17
[ "https://Stackoverflow.com/questions/28567868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1856538/" ]
I wouldn't use the `[NotMapped]` attribute as that makes more work for you to insert that data. I know this technique works to make a property read-only, so I'd imagine it could be used to make it write-only. However, since you don't want to load it, you'll have to add `.Select` statements to your queries, otherwise it will pull that data in. Not necessarily the cleanest solution, but it will give you what you want without having to bend over backwards to insert and update that column. What you'll want to do is make the `get;` on the property `protected internal` instead of the default of `public`. That way, EF will not freak out over not having access to the property, and you'll never have read access to the property outside of the data access layer of your project. ``` class Foo { public int Id { get; set; } public string Name { get; set; } public string BigTextColumn { protected internal get; set; } } ``` Then in your queries do something like the following: ``` context.Foos.FirstOrDefault().Select(f => new Foo { Id = f.Id, Name = f.Name }); ```
4,748,669
If I have a class with an array of pointers to another class *Vehicle* : ``` class List { public: //stuff goes here private: Vehicle ** vehicles; } ``` If I now write the destructor of the class `List`, do I manually iterate over the array (I know how many items are in the array) and `delete` every pointer to a vehicle, or will C++ automatically call the destructors of all the Vehicles in the array? (Like it does if there's a private string/... in the class or if it would be a STL container of Vehicle pointers) EDIT: I forgot about `delete [] vehicles`, but if I would do that, would it also delete the memory used by all the vehicles in the array, or would it just delete the memory used by the pointers?
2011/01/20
[ "https://Stackoverflow.com/questions/4748669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538047/" ]
You have to delete all the entries in the array AND delete the array. There are methods in C++ (STL) to avoid this: use a vector, so you don't have to delete the array. Use scoped\_ptr/shared\_ptr per Vehicle, so you don't have to delete the vehicles.
770,306
How do I solve for $x$ from this equation? $$2\cos\frac {x^2+x}{6}=2^x+2^{-x}$$
2014/04/26
[ "https://math.stackexchange.com/questions/770306", "https://math.stackexchange.com", "https://math.stackexchange.com/users/47820/" ]
$-2\le2\cos(\frac{x^2 + x}{6})\le 2$ and $2\le2^x + 2^{-x}$. Therefore the only possible solution is when both equal $2$.
25,211,679
I have a iron route that searches for a collection item based on the url param. If it finds it, it returns the item as a data context, otherwise it renders a `notFound` template. The code looks like this: ``` this.route('profileView', { path: list_path + '/profiles/:_id', fastRender: true, waitOn: function() { if (Meteor.user()) { return [Meteor.subscribe('singleProfile', this.params._id, Session.get("currentListId"))]; } }, data: function() { var profile = Profiles.findOne({ _id: this.params._id }); if (!profile) { this.render("notFound"); } else return profile; } }); ``` The problem is the `notFound` template gets loaded briefly prior to profile getting returned, although I thought the `waitOn` function would have handled that. What's the correct pattern to have the desired result using iron router? Thanks.
2014/08/08
[ "https://Stackoverflow.com/questions/25211679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1691147/" ]
When you do `line1=file.readlines()[2:]`, the "cursor" moves to the end of the file. Then you ask to write the line with the replaced value, so isn't it copied at the end of the file instead of being just modified in place? Maybe you miss a `file.seek(...)` call before writing.
27,777,205
Suppose I have a matrix ``` A=[1 2 3] ``` which is row matrix. Not I want to do it "page" matrix, i.e. align elements along 3rd dimension. I noticed, that the following ``` A=permute(A,[3 1 2]) ``` works, while the following ``` A=permute(A,[3 2 1]) ``` does not. Why?
2015/01/05
[ "https://Stackoverflow.com/questions/27777205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1171620/" ]
If `Vector extends Matrix`, you can: ``` public class Matrix { public Matrix scale(int scaleFactor) { ... return Matrix ... } } public class Vector extends Matrix { ... @Override public Vector scale(int scaleFactor) { // <-- return sub type here! ... return Vector ... } } ``` The rule that overridden methods must have the same type has been weakened in Java 5: You can now use subtypes as well to make overridden methods "more specific." The advantage of this approach over generics is that it's clean, no (implicit) casting is required and it exactly limits the types without any generics magic. **[EDIT]** Now `Vector` is just a special kind of `Matrix` (the 1-column/row type) which means that the code in `scale()` is the same. Unfortunately, this doesn't work: ``` public class Vector extends Matrix { ... @Override public Vector scale(int scaleFactor) { // <-- return sub type here! return (Vector) super.scale(scaleFactor); } } ``` since you can't cast `Matrix` instances into a `Vector`. The solution is to move the scale code into a helper method: ``` public class Matrix { protected void doScale(int scaleFactor) { ... original scale() code here... } public Matrix scale(int scaleFactor) { doScale(scaleFactor); return this; } } public class Vector extends Matrix { ... @Override public Vector scale(int scaleFactor) { doScale(scaleFactor); return this; } } ``` If the class is immutable (and it probably should be), then you need to use the copy constructor, of course: ``` public Matrix scale(int scaleFactor) { Matrix result = new Matrix(this); result.doScale(scaleFactor); return result; } ```
70,817
I am new to the finance world, and I keep hearing *fund* and *portfolio*. What is the meaning of these words and how are they related? Can someone please explain with examples? Is there any difference between them?
2016/09/16
[ "https://money.stackexchange.com/questions/70817", "https://money.stackexchange.com", "https://money.stackexchange.com/users/48601/" ]
**A "Fund" is generally speaking a collection of similar financial products, which are bundled into a single investment**, so that you as an individual can buy a portion of the Fund rather than buying 50 portions of various products. e.g. a "Bond Fund" may be a collection of various corporate bonds that are bundled together. The performance of the Fund would be the aggregate of each individual item. Generally speaking Funds are like pre-packaged "diversification". Rather than take time (and fees) to buy 50 different stocks on the same stock index, you could buy an "Index Fund" which represents the values of all of those stocks. **A "Portfolio" is your individual package of investments**. ie: the 20k you have in bonds + the 5k you have in shares, + the 50k you have in "Funds" + the 100k rental property you own. You might split the definition further buy saying "My 401(k) portfolio & my taxable portfolio & my real estate portfolio"(etc.), to denote how those items are invested. The implication of "Portfolio" is that you have considered how all of your investments work together; ie: your 5k in stocks is not so risky, because it is only 5k out of your entire 185k portfolio, which includes some low risk bonds and funds. **Another way of looking at it, is that a Fund is a special type of Portfolio.** That is, a Fund is a portfolio, that someone will sell to someone else (see Daniel's answer below). **For example**: Imagine you had $5,000 invested in IBM shares, and also had $5,000 invested in Apple shares. Call this your portfolio. But you also want to sell your portfolio, so let's also call it a 'fund'. Then you sell half of your 'fund' to a friend. So your friend (let's call him Maurice) pays you $4,000, to invest in your 'Fund'. Maurice gives you $4k, and in return, you given him a note that says "Maurice owns 40% of atp9's Fund". The following month, IBM pays you $100 in dividends. But, Maurice owns 40% of those dividends. So you give him a cheque for $40 (some funds automatically reinvest dividends for their clients instead of paying them out immediately). Then you sell your Apple shares for $6,000 (a gain of $1,000 since you bought them). But Maurice owns 40% of that 6k, so you give him $2,400 (or perhaps, instead of giving him the money immediately, you reinvest it within the fund, and buy $6k of Microsoft shares). Why would you set up this Fund? Because Maurice will pay you a fee equal to, let's say, 1% of his total investment. Your job is now to invest the money in the Fund, in a way that aligns with what you told Maurice when he signed the contract. ie: maybe it's a tech fund, and you can only invest in big Tech companies. Maybe it's an Index fund, and your investment needs to exactly match a specific portion of the New York Stock Exchange. Maybe it's a bond fund, and you can only invest in corporate bonds. **So to reiterate**, a *portfolio* is a collection of investments (think of an artist's portfolio, being a collection of their work). Usually, people refer to their own 'portfolio', of personal investments. A *fund* is someone's portfolio, that other people can invest in. This allows an individual investor to give some of their decision making over to a Fund manager. In addition to relying on expertise of others, this allows the investor to save on transaction costs, because they can have a well-diversified portfolio (see what I did there?) while only buying into one or a few funds.
21,900,159
I've been doing some research about draggable & resizable plugins from jQuery but encountered an issue recently. I've tried to replicate this situation on the following fiddle: ``` $('.event').draggable({ grid: [120, 12], cursor: 'move', containment: '#container', start: function (event, ui) { console.log("event dragging started"); } }).resizable({ containment: 'parent', grid: 12, handles: { 'n': '#ngrip', 's': '#egrip' }, start: function (e, ui) { console.log('resizing started'); }, ``` }); Here's [a fiddle](http://jsfiddle.net/flaszer/M2umR/2/). The resizable south handle doesn't work at all, also the strange thing happens to the north handle -> it decreases size of my div an pushes it rapidly to the right. What am I doing wrong?
2014/02/20
[ "https://Stackoverflow.com/questions/21900159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2305130/" ]
**Your code:** ``` $('.event').draggable({ grid: [120, 12], cursor: 'move', containment: '#container', start: function (event, ui) { console.log("event dragging started"); } }).resizable({ containment: 'parent', grid: 12, handles: { 'n': '#ngrip', 's': '#egrip' }, start: function (e, ui) { console.log('resizing started'); }, }); ``` **Code Needed** ``` $('.event').draggable({ grid: [120, 12], cursor: 'move', containment: '#container' }).resizable({ containment: 'parent', grid: [ 120, 12 ], handles: "n, e, s, w" }); ``` 1) remove trailing comma in the end 2) make handles as `handles: "n, e, s, w"` but there is still some bug after this you can only resize after you have dragged from once and resizing work precisely from a pixel maybe because you are using custom resize handlers, I am not sure. Read the [documentation](http://api.jqueryui.com/resizable/) for more help. **New Code** ``` $('.event').draggable({ cursor: 'move', containment: '#container' }).resizable({ containment: '#container', handles:"n, e, s, w", start: function (e, ui) { console.log('resizing started'); } }); ```
10,584,861
I am searching for a library function to normalize a URL in Python, that is to remove "./" or "../" parts in the path, or add a default port or escape special characters and so on. The result should be a string that is unique for two URLs pointing to the same web page. For example `http://google.com` and `http://google.com:80/a/../` shall return the same result. I would prefer Python 3 and already looked through the `urllib` module. It offers functions to split URLs but nothing to canonicalize them. Java has the `URI.normalize()` function that does a similar thing (though it does not consider the default port 80 equal to no given port), but is there something like this is python?
2012/05/14
[ "https://Stackoverflow.com/questions/10584861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1018226/" ]
How about this: ``` In [1]: from urllib.parse import urljoin In [2]: urljoin('http://example.com/a/b/c/../', '.') Out[2]: 'http://example.com/a/b/' ``` Inspired by answers to [this question](https://stackoverflow.com/questions/2131290/how-can-i-normalize-collapse-paths-or-urls-in-python-in-os-independent-way). It doesn't normalize ports, but it should be simple to whip up a function that does.
15,177,105
I have a simple node.js server testing the connect-redis module as a session store. It all works but I've noticed that I get a new sess: key in redis on every single request. I expected only one key since there is only one session. ![redis-cli showing multiple sess: keys](https://i.stack.imgur.com/40ZZ2.png) Here's my code : ``` var connect = require('connect'); var util = require("util"); var RedisStore = require("connect-redis")(connect); var http = require('http'); var app = connect() .use(connect.cookieParser('keyboard cat')) .use(connect.query()) .use(connect.session( { secret:"elms", store:new RedisStore({prefix:'sid_'}), cookie:{maxAge:60000, secure:false} })) .use(function(req, res, next) { var sess = req.session; if (sess.views) { res.setHeader('Content-Type', 'text/html'); res.write("<p>" + util.inspect(req.cookies) + "</p>"); sess.basket = sess.basket || {book1:0, book2:0, book3:0}; if(req.query.buyBook1) {sess.basket.book1 ++;} if(req.query.buyBook2) {sess.basket.book2 ++;} if(req.query.buyBook3) {sess.basket.book3 ++;} if(req.query.expiresession) { sess.cookie.maxAge = 0; } res.write('<p>views: ' + sess.views + '</p>'); res.write('<ul>\ <li>book1 ' + sess.basket.book1 + ' - <a href="/?buyBook1=true">Add</a></li>\ <li>book2 ' + sess.basket.book2 + ' - <a href="/?buyBook2=true">Add</a></li>\ <li>book3 ' + sess.basket.book3 + ' - <a href="/?buyBook3=true">Add</a></li>\ </ul>\ <a href="/?expiresession=true">Expire session</a>'); res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>'); res.write('<p>httpOnly: ' + sess.cookie.httpOnly + '</p>'); res.write('<p>path: ' + sess.cookie.path + '</p>'); res.write('<p>domain: ' + sess.cookie.domain + '</p>'); res.write('<p>secure: ' + sess.cookie.secure + '</p>'); sess.views ++; } else { sess.views = 1; } res.write("<p>" + util.inspect(req.cookies) + "</p>"); res.end('welcome to the session demo. refresh!'); }); http.createServer(app).listen(3000); ``` I've noticed that the req.session.cookie.domain is always null. I'm on windows 8 and using the hosts file to map 127.0.0.1 to www.gaz-node.com, which is what I exepected the cookie domain to be at the server. Could be related. Any ideas? Thanks
2013/03/02
[ "https://Stackoverflow.com/questions/15177105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241587/" ]
The answer was very simple. I got up especially early on this sunday morning in order to debug it and the answer became suddenly clear midway through my first mug of coffee, which subsequently tasted better than the first half. **The Revenge of the /favicon.ico Request** I wasn't handling the request from the browser for /favicon.ico which is bit of a gotcha for node newbies like me. Every request is followed by a /favicon.ico request (by Chrome at least) so the browser can display the site's icon. It never gives up until it gets a favicon.ico. The actual session was working perfectly well, there was only one session id for that but the request for /favicon.ico doesn't send any cookies over and it was this that was triggering a new zombie session every request. To fix this I added a module to handle the /favicon.ico request and serve a 404 response. I could just as easily have given the relentless browser a favicon and sent that instead using the "fs" module. It's important that you handle the /favicon.ico and end the response, without calling next(), before you use the session module! Here's the fixed code : ``` var connect = require('connect'); var util = require("util"); var RedisStore = require("connect-redis")(connect); var http = require('http'); var app = connect() .use(function(req, res, next) { if(req.url == '/favicon.ico') { serve404(res); } else { next(); } }) .use(connect.cookieParser())//"elms123")) .use(connect.query()) .use(connect.session( { secret:"elms123", store:new RedisStore({prefix:'sid_'}), cookie:{maxAge:60000, secure:false, domain:"gaz-node.com"} })) .use(function(req, res, next) { var sess = req.session; res.setHeader('Content-Type', 'text/html'); res.write('welcome to the session demo. refresh!'); if (sess.views) { res.write("<p>" + util.inspect(req.cookies) + "</p>"); sess.basket = sess.basket || {book1:0, book2:0, book3:0}; if(req.query.buyBook1) {sess.basket.book1 ++;} if(req.query.buyBook2) {sess.basket.book2 ++;} if(req.query.buyBook3) {sess.basket.book3 ++;} if(req.query.expiresession) {sess.cookie.maxAge=0;} if(req.query.forceerror) {/*idontexist()*/throw new Error('ahhhh!');} res.write('<p>views: ' + sess.views + '</p>'); res.write('<ul>\ <li>book1 ' + sess.basket.book1 + ' - <a href="/?buyBook1=true">Add</a></li>\ <li>book2 ' + sess.basket.book2 + ' - <a href="/?buyBook2=true">Add</a></li>\ <li>book3 ' + sess.basket.book3 + ' - <a href="/?buyBook3=true">Add</a></li>\ </ul>\ <a href="/?expiresession=true">Expire session</a>\ <a href="/?forceerror=true">Force error</a>'); res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>'); res.write('<p>httpOnly: ' + sess.cookie.httpOnly + '</p>'); res.write('<p>path: ' + sess.cookie.path + '</p>'); res.write('<p>domain: ' + sess.cookie.domain + '</p>'); res.write('<p>secure: ' + sess.cookie.secure + '</p>'); sess.views ++; } else { sess.views = 1; } res.end("<p>" + util.inspect(req.cookies) + "</p>"); }) .use(connect.errorHandler()); http.createServer(app).listen(3000); function serve404(res) { res.writeHead(404, {"content-type": "text/plain"}); res.end("Error : Resource not found"); } ```
17,938,248
html ``` <ul id="tabs"> <li><a href="#tab-1" class="active">Tab-1</a></li> <li><a href="#tab-2">Tab-2</a></li> <li><a href="#tab-3">Tab-3</a></li> </ul> <div class="tab-contents" id="tab-1" style="display: block;"> some text </div> ``` css ```css .tab-contents{ background: #2b2a26; padding: 0px 8px; clear: both; } #tabs { border-collapse: separate; border-spacing: 4px 0; float: right; list-style: none outside none; margin: 0 -4px 0 0; padding: 0; } #tabs li { background: none repeat scroll 0 0 #000000; border-radius: 19px 19px 0 0; display: table-cell; height: 47px; margin: 0 4px; text-align: center; vertical-align: middle; width: 145px; } #tab-1:before{ content: ""; display: block; width: 200px; height: 200px; background: #f00; padding-top: 10px; /* not working as expected but giving padding to bottom */ } ``` [demo](http://jsfiddle.net/SmN28/1/) Within gray box the red box should behave the padding top. How can I do that?
2013/07/30
[ "https://Stackoverflow.com/questions/17938248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313718/" ]
You could use padding-top to `.tab-contents` instead. ``` .tab-contents{ background: #2b2a26; padding: 0px 8px; clear: both; padding-top: 10px; } ``` [Demo](http://jsfiddle.net/SmN28/2/) Alternatively, You could use `position: relative; top: 10px;` to your `#tab-1:before` instead of padding-top. [demo](http://jsfiddle.net/SmN28/6/)
9,411,011
in post: [Copy sublist from list](https://stackoverflow.com/questions/9337775/copy-sublist-from-list#comment11791540_9337775) was stayed explained me that for copy a sublist in a list need copy single elements doing so: ``` for iIndex2 := 0 to MyList.Last.Count-1 do MySubList.Add(MyList.Last[iIndex2]); ``` I have verified that this method of copy for elements much much highest in list take much time, in order too of some minetes. Trying to simulate with static array in same condition i take few miliseconds, copying all sublist in an array in one time and not for single element. Just for explain better, i have: ``` program Test_with_array_static; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, System.Generics.Collections; type TMyArray = array [1..10] of Integer; TMyList = TList<TMyArray>; var MyArray: TMyArray; MyList: TMyList; iIndex1, iIndex2: Integer; begin try { TODO -oUser -cConsole Main : Insert code here } MyList := TList<TMyArray>.Create; try for iIndex1 := 1 to 10 do begin if MyList.Count <> 0 then MyArray := MyList.Last; MyArray[iIndex1] := iIndex1; MyList.Add(MyArray); end; for iIndex1 := 0 to Pred(MyList.Count) do begin for iIndex2 := 1 to 10 do Write(MyList[iIndex1][iIndex2]:3); Writeln; end; finally MyList.Free; end; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; Readln; end. ``` So i have thinked to use not list as sublist but array and so work, but in my case i don't know in general how much are element in array and need dynamic array for it. I have changed code in: ``` program Test_with_array_dynamic; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, System.Generics.Collections; type TMyArray = array of Integer; TMyList = TList<TMyArray>; var MyArray: TMyArray; MyList: TMyList; iIndex1, iIndex2: Integer; begin try { TODO -oUser -cConsole Main : Insert code here } MyList := TList<TMyArray>.Create; try SetLength(MyArray, 10); for iIndex1 := 1 to 10 do begin if MyList.Count <> 0 then MyArray := MyList.Last; MyArray[iIndex1] := iIndex1; MyList.Add(MyArray); end; for iIndex1 := 0 to Pred(MyList.Count) do begin for iIndex2 := 1 to 10 do Write(MyList[iIndex1][iIndex2]:3); Writeln; end; finally MyList.Free; end; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; Readln; end. ``` and so, i have again the problem of before; of course, changing this line: ``` if MyList.Count <> 0 then MyArray := MyList.Last; ``` in mode of copy single element, all work. Now i ask, if really not is possible copy an array in a time, without do a copy for single elements, i need it for question of speed only. And time is very much important. Thanks again very much to all that can solve me this problem. Thanks again.
2012/02/23
[ "https://Stackoverflow.com/questions/9411011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1940338/" ]
You need to add a *copy* of the array. Otherwise, since you keep setting the array variable's length to the same value, you end up working on the same single dynamic array. To make a copy of an array, simply call [`Copy`](http://docwiki.embarcadero.com/Libraries/en/System.Copy) prior to adding it to your list: ``` MyList.Add(Copy(MyArray)); ```
244,748
I have a script which runs several commands remotely through ssh. I'm running each command separately because I want to do other things in between executions. However, I don't want to recreate an ssh session every time I issue a new command. I've read about `-oControlMaster` but I can't seem to get it to work. When I run: ``` ssh -oControlMaster=yes -oControlPath=/tmp/test.sock root@host ``` after I enter my password, I just get an ssh session. If I exit out, the `/tmp/test.sock` file is no where to be found. What am I missing?
2015/11/22
[ "https://unix.stackexchange.com/questions/244748", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/6266/" ]
You can use the `ControlPersist` option to leave the socket after you disconnect from the server. e.g in my ssh config file i have this snippet, which leave the connection open 3 sec. ``` Host * ControlMaster auto ControlPath ~/.ssh/master-socket/%r@%h:%p #ControlPath ~/.ssh/%r@%h:%p ControlPersist 3s ```
20,098,052
the problem is that i don't receive any $\_POST['registerationID'] from android webview i have this code in android java :: ``` @Override protected void onRegistered(Context context, String registrationId) { String URL_STRING = "http://mysite.org/mysite/index.php/user/notification/"; Log.i(MyTAG, "onRegistered: registrationId=" + registrationId); // notification ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("registrationId",registrationId)); try{ HttpPost httppost = new HttpPost(URL_STRING); httppost.setHeader("Content-Type","text/plain"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false); HttpResponse response = httpclient.execute(httppost); Log.i("LinkPOST:", httppost.toString()); Log.i("postData", response.getStatusLine().toString()); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null){ //System.out.println("Not Empty"); String responseBody = EntityUtils.toString(httpEntity); System.out.println(responseBody); } else { System.out.println("Empty"); } } catch(Exception e) { Log.e("log_tag", "Error in http connection "+e.toString()); } } ``` and i handle the httprequest post in php (using codeigniter) as the following : ``` function notification() { $registrationId = $_POST['registrationId']; if($this->session->userdata('emailid')) { //echo 'working from inside the if statement'.$this->session->userdata('emailid'); //$query = $this->db->query('INSERT INTO user (`deviceid`) VALUES ('.$_GET['registerationID'].') where `emailid`='.$this->session->userdata('emailid').';'); $data = array( 'deviceid' => $registrationId, ); $this->db->where('emailid', $this->session->userdata('emailid')); $this->db->update('user', $data); if($this->db->affected_rows() == 1) { // some code } else { // some code } } ```
2013/11/20
[ "https://Stackoverflow.com/questions/20098052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892114/" ]
`gets` (which shall not be used and has actually been removed from the most recent C standards) does not save the `\n` in its buffer (while `fgets` does). And `fputs`, unlike `puts`, does not automatically insert one at the end of the string it writes. So by adding a `fputs("\n", fp);` (or `fputc('\n', fp)`) after outputting each typed line, you insert the missing newline in the file.
38,980,044
I've written a Python Flask app, and initially used MySQLdb to access MySQL. Later I've switched to flaskext.mysql for the same purposes, but now when I use this module I cannot see how to get a dictionary structured cursor. When I using the MySQLdb module I was using the following line to open a dictionary based cursor - ``` import MySQLdb as mdb con = mdb.connect('localhost','root','root','transport') with con: cur = con.cursor(mdb.cursors.DictCursor) ``` Now I'm trying to do the same with flaskext.mysql, my currect code looks like this - ``` from flaskext.mysql import MySQL cur = mysql.get_db().cursor() ``` What should I feed the cursor object in order to get the same type of cursor?
2016/08/16
[ "https://Stackoverflow.com/questions/38980044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3833773/" ]
[`mysql.get_db()`](https://github.com/cyberdelia/flask-mysql/blob/master/flaskext/mysql.py#L58) would result into your "connection" object, you can do: ``` import MySQLdb as mdb cur = mysql.get_db().cursor(mdb.cursors.DictCursor) ``` Or, you can also set the default `cursorclass` when initializing the extension: ``` mysql = MySQL(cursorclass=mdb.cursors.DictCursor) ```
46,469,258
I am new to React-native and enzyme, I am trying to create a custom component here. I will be displaying an Image based on `this.props.hasIcon`. I set default props value for `hasIcon` as `true`. When I check `Image` exists in enzyme ShallowWrapper. I am getting `false`. `tlProgress.js` ``` class TLProgress extends Component { render() { return ( <View style={styles.container}> {this.renderImage} {this.renderProgress} </View> ); } } TLProgress.defaultProps = { icon: require("./../../img/logo.png"), indeterminate: true, progressColor: Colors.TLColorAccent, hasIcon: true, progressType: "bar" }; ``` and `renderImage()` has the `Image` ``` renderImage() { if (this.props.hasIcon) { return <Image style={styles.logoStyle} source={this.props.icon} />; } } ``` Now, If I check `Image` exists in enzyme am getting false. `tlProgress.test.js` ``` describe("tlProgress rendering ", () => { let wrapper; beforeAll(() => { props = { indeterminate: false }; wrapper = shallow(<TLProgress {...props} />); }); it("check progress has app icon", () => { expect(wrapper.find("Image").exists()).toBe(true); // fails here.. }); }); ```
2017/09/28
[ "https://Stackoverflow.com/questions/46469258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2906641/" ]
You are not calling the renderImage function in your render() -- you forgot the brackets, thus it is being interpreted as an undefined variable. It should be: (I am assuming you want to call renderProgress() and not renderProgress as well) ``` class TLProgress extends Component { render() { return ( <View style={styles.container}> {this.renderImage()} {this.renderProgress()} </View> ); } ```
72,227,653
I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this: ``` $datauser = DB::table('users') ->join('activitates','users.id','=','activitates.user_id') ->join('taga_cars','taga_cars.id','=','activitates.tagacar_id') ->join('clients','users.id','=','clients.user_id') ->where('users.id','=','1') ->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name') ->get(); return response()->json($datauser); ``` But I would want something like this(which I just can't seem to figure out) ``` public function showuser($id) { $userid = User::findOrFail($id); $datauser = DB::table('users') ->join('activitates','users.id','=','activitates.user_id') ->join('taga_cars','taga_cars.id','=','activitates.tagacar_id') ->join('clients','users.id','=','clients.user_id') ->where('users.id','=',$userid) ->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name') ->get(); return response()->json($datauser); } ``` Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data
2022/05/13
[ "https://Stackoverflow.com/questions/72227653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18367436/" ]
I don't know if I understood correctly, but you want this ? ``` void mymethod(String? s) { print(s ?? "Empty"); } int? a; // this could be null already mymethod(a?.toString()); // "a" could be null, so if it is null it will be set, otherwise it will be set to String ``` [![enter image description here](https://i.stack.imgur.com/JDXJe.png)](https://i.stack.imgur.com/JDXJe.png)
49,558,818
I want to change the ordering of this numpy images array to channel\_last training\_data : (2387, 1, 350, 350) to (2387,350,350,1) validation\_data : (298, 1, 350, 350) to (298, 350, 350, 1) testing\_data : (301, 1, 350, 350) to (301, 350, 350, 1) I tried this but it is not working ``` np.rollaxis(training_data,0,3).shape np.rollaxis(validation_data,0,3).shape np.rollaxis(testing_data,0,3).shape ```
2018/03/29
[ "https://Stackoverflow.com/questions/49558818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3257991/" ]
You need the `np.transpose` method like this: ``` training_data = np.transpose(training_data, (0, 2,3,1) ``` The same for the other ones
6,920,238
I have a List of vectors and a PlayerVector I just want to know how I can find the nearest Vector to my PlayerVector in my List. Here are my variables: ``` List<Vector2> Positions; Vector2 Player; ``` The variables are already declared and all, I just need a simple code that will search for the nearest position to my player. Isn't there a simple way?
2011/08/03
[ "https://Stackoverflow.com/questions/6920238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/858329/" ]
Since you don't need the exact distance (just a relative comparison), you can skip the square-root step in the Pythagorean distance formula: ``` Vector2? closest = null; var closestDistance = float.MaxValue; foreach (var position in Positions) { var distance = Vector2.DistanceSquared(position, Player); if (!closest.HasValue || distance < closestDistance) { closest = position; closestDistance = distance; } } // closest.Value now contains the closest vector to the player ```
62,548
I've been trying to figure out for days how <http://quotelicious.com> was able to place thumbnails and category links in a separate box alongside the actual post. Any ideas?
2012/08/21
[ "https://wordpress.stackexchange.com/questions/62548", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19519/" ]
They are actually doing this is one loop, here's an example to show similar structure. ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="article"> <div class="left"> <?php the_post_thumbnail( $size, $attr ); ?> <?php get_the_category(); ?> </div><!-- end left side --> <div class="right"> <?php the_excerpt(); ?> </div> <!-- end right side--> </div> <?php endwhile; else: endif; ?> ```
53,335,006
Being new to VBA I would love some inputs to this code, to improve the speed of it... It doesn't feel so "VBA"-ish currently; however the "result" of the code correct... ``` Sub Rigtig() Set Marketshare = Sheets("Output").Range("p40:p50") 'Select. Sheets("Output").Select Cells(38, 17).Copy Sheets("Input").Select Cells(33, 28).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Marketshare.Cells(1, 1).Copy Sheets("Input").Select Cells(23, 28).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Cells(40, 17).Copy Cells(40, 17).Select Selection.PasteSpecial Paste:=xlPasteValues Marketshare.Cells(2, 1).Copy Sheets("Input").Select Cells(23, 28).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Cells(41, 17).Copy Cells(41, 17).Select Selection.PasteSpecial Paste:=xlPasteValues Marketshare.Cells(3, 1).Copy Sheets("Input").Select Cells(23, 28).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Cells(38, 18).Copy Sheets("Input").Select Cells(33, 28).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Marketshare.Cells(1, 1).Copy Sheets("Input").Select Cells(23, 28).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Cells(40, 18).Copy Cells(40, 18).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Cells(38, 19).Copy Sheets("Input").Select Cells(33, 28).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Marketshare.Cells(1, 1).Copy Sheets("Input").Select Cells(23, 28).Select Selection.PasteSpecial Paste:=xlPasteValues Sheets("Output").Select Cells(40, 19).Copy Cells(40, 19).Select Selection.PasteSpecial Paste:=xlPasteValues Marketshare.Cells(2, 1).Copy Sheets("Input").Select Cells(23, 28).Select Selection.PasteSpecial Paste:=xlPasteValues ``` I would like to do the same "copy paste" approx 10 times in rows, and then change the column. Thanks in advance Best Valdemar
2018/11/16
[ "https://Stackoverflow.com/questions/53335006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10662016/" ]
As @Glitch\_Doctor said - if it's just the values you're after you can do this "this cell = that cell" rather than copy/paste. To shorten your code and make it a bit more "VBA"-ish you could put your cell reference pairs into an array and step through the array: ``` Sub Test() Dim vAddresses As Variant Dim vRef As Variant vAddresses = Array( _ Array("Q38", "AB33"), _ Array("A1", "AB23")) For Each vRef In vAddresses Worksheets("Input").Range(vRef(1)) = Worksheets("Output").Range(vRef(0)) Next vRef End Sub ``` You could also use a [With...End With](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/with-end-with-statement) block so you don't have to use the sheet name each time: ``` Sub Test1() With Worksheets("Output") Worksheets("Input").Cells(33, 28) = .Cells(38, 17) End With End Sub ``` If you want to copy everything (formula, formatting) then use Copy & paste in a single line: ``` Sub Test2() With Worksheets("Output") Worksheets("Input").Cells(33, 28).Copy Destination:=.Cells(38, 17) End With End Sub ```
32,195
I have a fifteen-months-old nephew who reacts strongly when people around him cough or make unwanted loud noises (i.e. sneeze). His reaction is often staring at the whoever made the noise, screaming protesting and crying, even if his mother does that. Should we be worried about his mental health? or is there anything special we should do to prevent future problems?
2017/10/25
[ "https://parenting.stackexchange.com/questions/32195", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/23858/" ]
If you just startle him when someone sneezes loudly then looking at them, or even crying, seems like a reasonable response. Hey you just scared the kid. If there are any other reasons to doubt his mental health you should see a professional. Are there any of the expected milestones he is missing (like first steps and/or first words). Those are certainly signs to see a professional. If it's just oversensitive to sound for example. Then still see a professional but personally i wouldn't be worried if my kid looked at me every time i sneezed (the screaming and crying really depends on how inconsolable they are. and what other reasons you have to suspect anything)
66,772,227
i cant' switch router ### index.js In this project used `ConnectedRouter` ``` ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </Provider>, document.getElementById('root') ); ``` ### App.js ``` <nav className="flexVCent row gutterH"> <Link to="/" className="App-logo-wrap"> <img src={logo} className="App-logo" alt="logo" /> </Link> <div className="flexHRight"> <div className="flexExpand"> </div> </div> </nav> ``` How correctly wrap Link ? package.json ``` "dependencies": { ... "connected-react-router": "^6.2.2", "history": "^4.7.2", ... }, ```
2021/03/23
[ "https://Stackoverflow.com/questions/66772227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8865030/" ]
You can't use `indexOf()` for this purpose, unless you abuse the purpose of the `equals()` method. Use a `for` loop over an `int` variable that iterates from `0` to the length of the List. Inside the loop, compare the name if the ith element, and if it's equal to you search term, you've found it. Something like this: ``` int index = -1; for (int i = 0; i < pets.length; i++) { if (pets.get(i).getName().equals(searchName)) { index = i; break; } } // index now holds the found index, or -1 if not found ``` If you just want to find the object, you don't need the index: ``` pet found = null; for (pet p : pets) { if (p.getName().equals(searchName)) { found = p; break; } } // found is now something or null if not found ```
9,643,859
I am trying to use this query in Postgres 9.1.3: ``` WITH stops AS ( SELECT citation_id, rank() OVER (ORDER BY offense_timestamp, defendant_dl, offense_street_number, offense_street_name) AS stop FROM consistent.master WHERE citing_jurisdiction=1 ) UPDATE consistent.master SET arrest_id = stops.stop WHERE citing_jurisdiction=1 AND stops.citation_id = consistent.master.citation_id; ``` I get this error: ``` ERROR: missing FROM-clause entry for table "stops" LINE 12: SET arrest_id = stops.stop ^ ********** Error ********** ERROR: missing FROM-clause entry for table "stops" SQL state: 42P01 Character: 280 ``` I'm really confused. The WITH clause appears correct per Postgres documentation. If I separately run the query in the WITH clause, I get correct results.
2012/03/10
[ "https://Stackoverflow.com/questions/9643859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425477/" ]
From the [fine manual](http://www.postgresql.org/docs/current/static/sql-update.html): > > There are two ways to modify a table using information contained in other tables in the database: using sub-selects, or specifying additional tables in the `FROM` clause. > > > So you just need a FROM clause: ``` WITH stops AS ( -- ... ) UPDATE consistent.master SET arrest_id = stops.stop FROM stops -- <----------------------------- You missed this WHERE citing_jurisdiction=1 AND stops.citation_id = consistent.master.citation_id; ``` The error message even says as much: > > ERROR: missing FROM-clause entry for table "stops" > > >
47,157,155
Can anyone please help me how to save multiple selection in the `DB`? ``` <div class="col-sm-10"> <select id="tag_list" name="tag_list[]" class="form-control" multiple></select> </div> ``` Controller function is like this: ``` public function store(Request $request) { $comics = new Comic(); $tags = $request->input('tag_list'); $comics->appreance = implode(',', $tags); $comics->save(); return redirect('/comic'); } ``` Please help, thanks.
2017/11/07
[ "https://Stackoverflow.com/questions/47157155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3119809/" ]
Although it's not clear enough how you save your `tags or appearance`, i `assume` it save one tag in a `single` row. If that's the case then you can do something like ``` public function store(Request $request) { $tags = $request->input('tag_list'); foreach($tags as $tag){ $comics = new Comic(); $comics->appreance = tag; $comics->save(); } return redirect('/comic'); } ``` Hope this helps :)
16,223,759
I have this page: ``` <?php for($i=1; $i<=3; $i++){ $until_he.$i = htmlentities($_POST['until'.$i]) } ?> <form action="" method...> <?php for($i=1; $i<=3; $i++){ ... print '<input name="until'.$i.'" id="until'.$i.'" class="textinput" value="'.$until_he.$i.'" type="date" min="'.date("Y-m-d").'"/>'; ... } ?> ... ``` Now: ``` $until_he ``` has content only once the form is posted, otherwise it's empty. On the other hand ``` $i ``` is already defined. So as I load the page I get values 1, 2, 3 on the fields. I'd like to get values on the files only once the user post the forum. As I load the page the fields should be empty. Thank you
2013/04/25
[ "https://Stackoverflow.com/questions/16223759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2120569/" ]
Try this: ``` <?php for($i=1; $i<=3; $i++){ $until_he.$i = htmlentities($_POST['until'.$i]); $fieldValue = (trim($until_he.$i)==$i)?"":$until_he; ... print '<input name="until'.$i.'" id="until'.$i.'" class="textinput" value="'.$fieldValue.'" type="date" min="'.date("Y-m-d").'"/>'; ... } ?> ```