source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0057891494.txt" ]
Q: How to calculate intersection point of a line on a circle using p5.js I have a line (se) that I know starts inside a circle, and I know ends outside of a circle. I'm trying to find a point l where the line crosses the circle. I'm using the p5.js library and have access to all of its Vector functions. My thoughts were, that if I can make a right angle on the line, to the radius, I can start solving some things. // Get the vector between s and c let scVector = p5.Vector.sub(start, circleCenter); // Get the angle between se and sc let escAngle = this.v.angleBetween(scVector); // Get the distance between t (where the right angle hits the center of the circle) and c let tcDistance = Math.sin(escAngle) * scVector.mag(); // Get the distance between t and where the line intersects the circle let tlDistance = Math.sqrt(Math.pow(hole.r, 2) - Math.pow(tcDistance, 2)); // Get the distance between the start point and t let stDistance = Math.sqrt(Math.pow(scVector.mag(), 2) - Math.pow(tcDistance, 2)); // Add the two distances together, giving me the distance between s and l let totalDistance = tcDistance + stDistance; // Create a new Vector at this angle, at the totalDistance Magnitude, then add it to the current position let point = p5.Vector.fromAngle(this.v.heading(), totalDistance).add(start); // Mark a point (hopefully l) on the edge of the circle. points.push({ x: point.x, y: point.y, fill: '#ffffff' }) Unfortunately, as my objects pass through the circle, they aren't leaving dots on the edge, but further away from the circle's edge. The tiny dots are the marked positions, the coloured dots are the objects (which have a start and end point) I have a demo here, the questionable bit is line 42 onwards: https://codepen.io/EightArmsHQ/pen/be0461014f9868e3462868776d9c8f1a Any help would be much appreciated. A: To find the intersection of a point and a line, I recommend to use an existing algorithm, like that one of WolframMathWorld - Circle-Line Intersection. The algorithm is short, well explained an can be expressed in an short function. The input parameters p1, p2, and cpt are of type p5.Vector, r is a scalar. This parameters define an endless line form p1 to p2 and a circle with the center point cpt and the radius r. The function returns a list of inter section points, with may be empty: intersectLineCircle = function(p1, p2, cpt, r) { let sign = function(x) { return x < 0.0 ? -1 : 1; }; let x1 = p1.copy().sub(cpt); let x2 = p2.copy().sub(cpt); let dv = x2.copy().sub(x1) let dr = dv.mag(); let D = x1.x*x2.y - x2.x*x1.y; // evaluate if there is an intersection let di = r*r*dr*dr - D*D; if (di < 0.0) return []; let t = sqrt(di); ip = []; ip.push( new p5.Vector(D*dv.y + sign(dv.y)*dv.x * t, -D*dv.x + p.abs(dv.y) * t).div(dr*dr).add(cpt) ); if (di > 0.0) { ip.push( new p5.Vector(D*dv.y - sign(dv.y)*dv.x * t, -D*dv.x - p.abs(dv.y) * t).div(dr*dr).add(cpt) ); } return ip; } If you want to verify, if a point is "in between" to other points, you can use the Dot product. If you know that 3 points on a line, then it is sufficient to calculate the distances between the points, to determine, if 1 point is in between the 2 other points. p1, p2, and px are of type p5.Vector. The points are on the same line. The function returns true, if px is between p1 and p2 and false else: inBetween = function(p1, p2, px) { let v = p2.copy().sub(p1); let d = v.mag(); v = v.normalize(); let vx = px.copy().sub(p1); let dx = v.dot(vx); return dx >= 0 && dx <= d; } See the example, which I've implemented to test the function. The circle is tracked by the mouse and is intersected by an randomly moving line: var sketch = function( p ) { p.setup = function() { let sketchCanvas = p.createCanvas(p.windowWidth, p.windowHeight); sketchCanvas.parent('p5js_canvas') } let points = []; let move = [] // Circle-Line Intersection // http://mathworld.wolfram.com/Circle-LineIntersection.html p.intersectLineCircle = function(p1, p2, cpt, r) { let sign = function(x) { return x < 0.0 ? -1 : 1; }; let x1 = p1.copy().sub(cpt); let x2 = p2.copy().sub(cpt); let dv = x2.copy().sub(x1) let dr = dv.mag(); let D = x1.x*x2.y - x2.x*x1.y; // evaluate if there is an intersection let di = r*r*dr*dr - D*D; if (di < 0.0) return []; let t = p.sqrt(di); ip = []; ip.push( new p5.Vector(D*dv.y + sign(dv.y)*dv.x * t, -D*dv.x + p.abs(dv.y) * t).div(dr*dr).add(cpt) ); if (di > 0.0) { ip.push( new p5.Vector(D*dv.y - sign(dv.y)*dv.x * t, -D*dv.x - p.abs(dv.y) * t).div(dr*dr).add(cpt) ); } return ip; } p.inBetween = function(p1, p2, px) { let v = p2.copy().sub(p1); let d = v.mag(); v = v.normalize(); let vx = px.copy().sub(p1); let dx = v.dot(vx); return dx >= 0 && dx <= d; } p.endlessLine = function(x1, y1, x2, y2) { p1 = new p5.Vector(x1, y1); p2 = new p5.Vector(x2, y2); let dia_len = new p5.Vector(p.windowWidth, p.windowHeight).mag(); let dir_v = p5.Vector.sub(p2, p1).setMag(dia_len); let lp1 = p5.Vector.add(p1, dir_v); let lp2 = p5.Vector.sub(p1, dir_v); p.line(lp1.x, lp1.y, lp2.x, lp2.y); } p.draw = function() { if (points.length == 0) { points = []; move = []; for (let i=0; i < 2; ++i ) { points.push( new p5.Vector(p.random(p.windowWidth-20)+10, p.random(p.windowHeight-20)+10)); move.push( new p5.Vector(p.random(2)-1, p.random(2)-1) ); } points.push( new p5.Vector(p.mouseX, p.mouseY)); } else { for (let i=0; i < 2; ++i ) { points[i] = points[i].add(move[i]); if (points[i].x < 10 || points[i].x > p.windowWidth-10) move[i].x *= -1; if (points[i].y < 10 || points[i].y > p.windowHeight-10) move[i].y *= -1; move[i].x = Math.max(-1, Math.min(1, move[i].x+p.random(0.2)-0.1)) move[i].y = Math.max(-1, Math.min(1, move[i].y+p.random(0.2)-0.1)) } points[2].x = p.mouseX; points[2].y = p.mouseY; } let circle_diameter = p.min(p.windowWidth, p.windowHeight) / 2.0; let isectP = p.intersectLineCircle(...points, circle_diameter/2.0); // draw the scene p.background(192); p.stroke(0, 0, 255); p.fill(128, 128, 255); for (let i=0; i < points.length; ++i ) { p.ellipse(points[i].x, points[i].y, 10, 10); } for (let i=0; i < isectP.length; ++i ) { if (p.inBetween(points[0], points[1], isectP[i])) { p.stroke(255, 0, 0); p.fill(255, 128, 0); } else { p.stroke(255, 128, 0); p.fill(255, 255, 0); } p.ellipse(isectP[i].x, isectP[i].y, 10, 10); } p.stroke(0, 255, 0); p.noFill(); p.endlessLine(points[0].x, points[0].y, points[1].x, points[1].y) p.ellipse(points[2].x, points[2].y, circle_diameter, circle_diameter); } p.windowResized = function() { p.resizeCanvas(p.windowWidth, p.windowHeight); points = []; } p.mouseClicked = function() { points = []; } p.keyPressed = function() { points = [] } }; var circle_line = new p5(sketch); <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script> <div id="p5js_canvas"></div>
[ "drupal.stackexchange", "0000049656.txt" ]
Q: How to make a reservation and a booking of seminars during the Commerce checkout process? I have set up my first Drupal Commerce shop that works as it should with fixed booking ("selling") of seminars. Now these seminars (realized as line items) must not only be booked ("sold") but must also be available for reservation. It is needed that booking and reservation has to be done during the checkout process, where only booked items must be paid. My problem is now, that I do not know how to combine booking and reservation in one line item and also how to separate it during checkout process, as both need different information and also a variable amount of input fields, depending on number of participants. Maybe someone can give me some hints how to do it - I am stuck at the moment ... A: Your usage of the terms "booking" and "reservation" seems a bit strange to me. In the context of Drupal they are often used as synonyms of each other. I am not sure if I correctly interpret the difference you make, but I think this is crucial for you to differentiate (define?) them: Booking = item that must be payed at checkout time. Reservation = item that you must also be able to checkout, but you don't have to pay for it (or at least not yet). So I think your question actually consists of 2 questions: How to integrate this in Drupal Commerce? How to ensure availability? Below is what I think might help you find a possible solution. Drupal Commerce integration You should look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site, or just use that distribution (attention: it only has a beta release so far). Here are some more details about this distribution (quotes from its project page): ... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online. It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts. Easy booking profile is powered by Drupal Rooms and Drupal Commerce - widely used and popular contributed decisions, which means active maintaining and timely technical support. Check availability Take a look at these modules, which all have a stable (not alfa or beta only) release: Availability Calendars (Reported installs: 2.061 sites). MERCI (Reported installs: 441 sites). Resource Conflict (Reported installs: 329 sites). Simple Reservation (Reported installs: 202 sites). Room Reservations (Reported installs: 156 sites). I've ordered the list above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module. So do your homework to pick the right one for you.
[ "stackoverflow", "0017289313.txt" ]
Q: Jqgrid popup positioning trouble I am facing the problem of positioning of the update confirmation box/ delete confirmation box/ No row selected error box/ edit modal popup/ add modal popup etc to the center of the screen ….. I have looked a lot but could not find any helpful answers ….. can you please suggest that what can be done to achieve this result. I have two grids and the default positioning is not going well with it as for the second grid the popup's appear underneath and I have scroll down to get to the edit/add modal popup. A: I think that the most effective way to change position of all message boxes and dialogs displayed by jqGrid would be subclassing of $.jgrid.showModal method internally used in jqGrid. I hope that you'll can create the corresponding solution based on idea from the answer. Instead of animation effects you can change position of the dialog/message box before is will be shown.
[ "stackoverflow", "0001510252.txt" ]
Q: Is there a way for find how many keys are currently in a NSMutableDictionary? Just curious if there is a way to find the number of keys in a NSMutableDictionary? Also is there a way to access each key in turn and find its value, or do I need to access the data manually via the predefined keys? (i.e.) myTown = [cryo objectForKey: @"town"]; myZip = [cryo objectForKey: @"HT6 4HT"]; myEmail = [cryo objectForKey: @"pink@grapefruit.xxx"]; I guess I am thinking using a wildcard or something for the key? gary A: -[NSMutableDictionary count]
[ "stackoverflow", "0060241804.txt" ]
Q: laravel route::resource can't find edit function in my controller When I call my edit function I get a 404|not found page. this is the code in my View <a href="{{ route('admin.edit', $user->id) }}"> <button type="button" class="btn btn-primary btn-sm crudbtn">Edit</button> </a> This is the code in my web.php route::namespace('Admin')->prefix('admin')->middleware(['auth', 'auth.admin'])->name('admin.')->group(function(){ route::resource('/', 'AdminController'); }); This is my edit function in my AdminController public function edit($id) { if(Auth::user()->id == $id){ return redirect()->route('admin.index'); } return view('admin.edit')->with(['user' => user::find($id), 'roles' => Role::all()]); } And this is the output of my php artisan route:list +--------+-----------+------------------------+------------------+------------------------------------------------------------------------+---------------------+ | Domain | Method | URI | Name | Action | Middleware | +--------+-----------+------------------------+------------------+------------------------------------------------------------------------+---------------------+ | | GET|HEAD | / | | Closure | web | | | POST | admin | admin.store | App\Http\Controllers\Admin\AdminController@store | web,auth,auth.admin | | | GET|HEAD | admin | admin.index | App\Http\Controllers\Admin\AdminController@index | web,auth,auth.admin | | | GET|HEAD | admin/create | admin.create | App\Http\Controllers\Admin\AdminController@create | web,auth,auth.admin | | | DELETE | admin/{} | admin.destroy | App\Http\Controllers\Admin\AdminController@destroy | web,auth,auth.admin | | | PUT|PATCH | admin/{} | admin.update | App\Http\Controllers\Admin\AdminController@update | web,auth,auth.admin | | | GET|HEAD | admin/{} | admin.show | App\Http\Controllers\Admin\AdminController@show | web,auth,auth.admin | | | GET|HEAD | admin/{}/edit | admin.edit | App\Http\Controllers\Admin\AdminController@edit | web,auth,auth.admin | When i call my index function the proper page is loaded, but I can't figure out why my edit function cant' be found. What am I missing or doing wrong? A: Try route::namespace('Admin')->middleware(['auth', 'auth.admin'])->group(function(){ route::resource('admin', 'AdminController'); });
[ "english.stackexchange", "0000102852.txt" ]
Q: A word or phrase describing "cheap talk" or "cheap issues" Cheap talk like a kind of talking back of actors'/actresses' lives or an interview about their secret lives in some popular magazines or cheesy show off like reality shows you can find in TV channels. Making a drama or love story of any simple or ordinary happening in its fake version only to take attention or advertise for someone or something. We have an interesting equal in Persian/Farsi language which is "Yellow Matters". Do you have something like this for it? A: "Sensationalism" for starters and "tabloid reporting" for another - both of which are extremely popular in our society at this time. Definition of "sensational" from M-W.com: 2 : arousing or tending to arouse (as by lurid details) a quick, intense, and usually superficial interest, curiosity, or emotional reaction ex.: sensational tabloid news
[ "stackoverflow", "0006616214.txt" ]
Q: how to rebind click event to anchor after unbind? I want to unbind the anchor after the first click, but when user click a specific button, I want to rebind the click event to this anchor I wrote this code $(document).ready(function(){ $("a.package").click(function(){ //alert('click'); $(this).unbind('click'); // the rest of the code }); $('#activate').click(function(){ $('a.package').bind('click'); // the rest of the code }); }); the unbind function works well, but the bind function does not work, why? and how to make it work? A: Store your click function in a variable so that it can easily be re-assigned... $(document).ready(function() { var onclick = function(e) { //alert('click'); $(this).unbind('click'); // the rest of the code } $("a.package").click(onclick); $('#activate').click(function() { $('a.package').click(onclick); // the rest of the code }); });
[ "stackoverflow", "0002965251.txt" ]
Q: JavaMail with Gmail: 535-5.7.1 Username and Password not accepted I get this error when I try to send a mail using JavaMail API. I am sure that the username and password are 100% correct. The Gmail account which I'm connecting is an older account, because they say it takes time for it to work with new accounts. DEBUG SMTP RCVD: 535-5.7.1 Username and Password not accepted. Learn more at 535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 x35sm3011668 wfh.6 javax.mail.SendFailedException: Sending failed; nested exception is: javax.mail.AuthenticationFailedException at javax.mail.Transport.send0(Transport.java:218) at javax.mail.Transport.send(Transport.java:80) at Main.(Main.java:41) at Main.main(Main.java:51) and this is my code: import javax.mail.*; import javax.mail.internet.*; import java.util.*; public class Main { String d_email = "abc@gmail.com", d_password = "pass", d_host = "smtp.gmail.com", d_port = "465", m_to = "abc@gmail.com", m_subject = "Testing", m_text = "testing email."; public Main() { Properties props = new Properties(); props.put("mail.smtp.user", d_email); props.put("mail.smtp.host", d_host); props.put("mail.smtp.port", d_port); props.put("mail.smtp.starttls.enable","true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.debug", "true"); props.put("mail.smtp.socketFactory.port", d_port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); SecurityManager security = System.getSecurityManager(); try { Authenticator auth = new SMTPAuthenticator(); Session session = Session.getInstance(props, auth); session.setDebug(true); MimeMessage msg = new MimeMessage(session); msg.setText(m_text); msg.setSubject(m_subject); msg.setFrom(new InternetAddress(d_email)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to)); Transport.send(msg); } catch (Exception mex) { mex.printStackTrace(); } } public static void main(String[] args) { Main blah = new Main(); } private class SMTPAuthenticator extends javax.mail.Authenticator { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(d_email, d_password); } } } A: I had same issue : I refer this link, I have followed below steps it worked for me. By default Gmail account is highly secured. When we use gmail smtp from non gmail tool, email is blocked. To test in our local environment, make your gmail account less secure as Login to Gmail. Access the URL as https://www.google.com/settings/security/lesssecureapps Select "Turn on" A: The given code snippet works fine on my Gmail account, so this problem lies somewhere else. Did you follow the link given in the error message? It contains the following hints: Make sure that you've entered your full email address (e.g. username@gmail.com) Re-enter your password to ensure that it's correct. Keep in mind that passwords are case-sensitive. Make sure your mail client isn't set to check for new mail too often. If your mail client checks for new messages more than once every 10 minutes, your client might repeatedly request your username and password. Especially the last point is important. Google is very strict in this. If you're trying to connect Gmail for example more than 10 times in a minute programmatically, then you may already get blocked. Have a bit of patience, after some time it will get unblocked. If you'd like more freedom in sending mails, I recommend to look for a dedicated mail host or to setup your own mail server, such as Apache James or Microsoft Exchange. I've already answered this in detail in one of your previous questions. A: I encountered the exact same problem, for me the reason is I have turned on 2-step verification on my gmail account. After generating a new application-specific password and use that in my java application, this "535 5.7.1" issue is gone. You can generate a new application-specific password following this official google guide.
[ "stackoverflow", "0027025486.txt" ]
Q: Express.js multiple methods So in Express you can do: app.get('/logo/:version/:name', function (req, res, next) { // Do something } and app.all('/logo/:version/:name', function (req, res) { // Do something } Is there a way to just have two methods (ie. GET and HEAD)? Such as: app.get.head('/logo/:version/:name', function (req, res, next) { // Do something } A: You can use .route() method. function logo(req, res, next) { // Do something } app.route('/logo/:version/:name').get(logo).head(logo); A: Just pull out the anonymous function and give it a name: function myRouteHandler(req, res, next) { // Do something } app.get('/logo/:version/:name', myRouteHandler); app.head('/logo/:version/:name', myRouteHandler); Or use a general middleware function and check the req.method: app.use('/logo/:version/:name', function(req, res, next) { if (req.method === 'GET' || req.method === 'HEAD') { // Do something } else next(); });
[ "electronics.stackexchange", "0000380218.txt" ]
Q: gain of inverting op amp with resistor on input I´m trying to figure out the transfer function of the attached op amp circuit. I came to the conclusion that v_out = - v_in as as the two resistors in the upper path are equally sized, and the non inverting input is on ground potential. However this is a task from one of our exams which I try to solve and it seems that my solution isn`t right according to the following tasks, however I got no solutions to this exam. Do I miss something? Kind Regards Marc A: Your conclusion that Vout = - Vin is correct. Capacitor C and resistor R2 are just there to confuse you. As there is no current flowing into (or out of) the + input of the opamp, Vin+ = 0 The opamp will try to make Vin- = 0 as well if possible. Let's assume the opamp can manage that so we assume Vin- = 0 That means the current Iin = Vin / Rin with In flowing in the direction as shown. This Iin cannot flow into the opamp's - input, all of it has to go through the other resistor R1. The left side of R1 will be at 0 V, the current will flow from left to right and that means that Vout has to be negative with a value of Vout = Iin * R1. So Vout = - Vin.
[ "stackoverflow", "0000614754.txt" ]
Q: Flash Movie Not Loaded in IE6 I have a .swf file that I try to browse to and it loads fine in Firefox, but in IE6 it doesn't load. When right-clicking it says "movie not loaded". Any suggestions? A: Make sure the OBJECT element has a child PARAMETER elememt named movie and an attribute called data that both point to your SWF file. A: The actual problem was the application uses SSL with client authentication and there is a strange issue where when loading the application in IE it wasn't filling out a certain header in the HTTP request, so I had to use a custom servlet filter which inserted the header.
[ "graphicdesign.stackexchange", "0000106003.txt" ]
Q: Enlarging a path like a stroke New person here! I am messing around with logos at the moment, and I want to make the text's path bigger like making it bold. I know you can do this by duplicating an object and adding a stroke to one of them and then unite them, but the process becomes tedious especially while working with large amounts of text. Is there any way to automate this? Or is there an alternative solution? Thank you! A: You can use bold fonts in Inkscape, if you have a bold version of the font installed on your system. I wouldn't recommend adding a stroke to a font to make it look bold, mainly because it usually doesn't look that good. It's no substitute for a real bold font. By the way, you don't have to duplicate/unite anything. If you want to add a stroke to make a font look bold, you can apply it to editable text. If you want to mess with the font outlines, or turn it to outlines for SVG output then yes, but for general use there's no need. For other paths/shapes, there's also a possibility that you are looking for the Path > Outset / Dynamic Offset functions. But these don't work so well with text outlines because it will distort shapes/round the corners. However these can work well for other paths/shapes.
[ "stackoverflow", "0033086212.txt" ]
Q: Center 3 floating divs inside a wrapper div I have 3 divs inline a wrapper div. i want all three divs to be in the center of the 100% width wrapper div. i tried margin: 0 auto but it didn't work because of the 100% width. here is the code: #first, #next, #last { float: left; width: 300px; height: 320px; border: 1px solid black; } #content #kompetenzen { text-align: center; } and the html <div id="kompetenzen"> <div id="first"> <img src="images/kompetenzen/graphic.png" alt="Werbegrafik" /> <ul> <h3>HEADER</h3> <br> <li>LEISTUNG1</li> <li>LEISTUNG2</li> </ul> </div> <div id="next"> <img src="images/kompetenzen/design.png" alt="Werbegrafik" /> <ul> <h3>HEADER</h3> <br> <li>LEISTUNG1</li> <li>LEISTUNG2</li> <li>LEISTUNG3</li> <li>LEISTUNG4</li> </ul> </div> <div id="last"> <img src="images/kompetenzen/dev.png" alt="Werbegrafik" /> <ul> <h3>HEADER</h3> <br> <li>LEISTUNG1</li> <li>LEISTUNG2</li> </ul> </div> <div style="clear:both"></div> </div> A: Remove the float:left from the #first etc., and replace it with a display:inline-block; #first, #next, #last { width: 300px; display:inline-block; height: 320px; border: 1px solid black; } #kompetenzen { text-align: center; } http://jsfiddle.net/70e2uqc1/1/
[ "stackoverflow", "0010421775.txt" ]
Q: Trying to use regular expressions in ruby to find specific characters I am trying to use regular expressions in a ruby on rails app to search through a given string and find any instances of opening and closing square brackets, (ie [ and ]) and select the contents between the two. For example: Lorem ipsum [dolor sit] amet... In this string the result would be: [dolor sit] I played around with rubular a bit and found that this more or less does what I want /\[.*?\]/ So my question is, how do i match everything within the two square brackets without selecting the brackets themselves? And also how do I actually integrate them into a ruby script? Regular expressions are totally new ground for me so any help you guys can offer would be much appreciated :) A: Collecting multiple captures of a regexp is a job for String#scan >> s="Lorem ipsum [dolor sit] [amet] ..." => "Lorem ipsum [dolor sit] [amet] ..." >> s.scan(/\[([^\]]*)\]/).flatten => ["dolor sit", "amet"]
[ "stackoverflow", "0033219978.txt" ]
Q: node.js fs.writeFile issue So this question extends this one here after figuring out what was happening i need to know if it's a bug I'm using node.js v4.1.0 on Debian and to solve my issue i was having with fs.writeFile i had to put the full path e.i /apps/json.json for it to actually save it where i wanted it to be but using ./json.json would save it to the /root instead of where my server.js file resided but how come when using require("./json.json") it works correctly and grabs the file relative to where the server.js is e.i /apps/server.js. Is this a know issue? A: You're confusing the current directory with the directory containing your script. All fs APIs resolve paths relative to the current directory, which may be anything. require(), by contrast, ignores the current directory entirely and resolves paths based on the directory containing the JS file.
[ "stackoverflow", "0003950992.txt" ]
Q: C# Return Value, But keep getting error. Why? Hello fellow stackoverflow members! I'm very new to the C# language transfer from Java, Obj-C. It looks pretty same as Java, but I have trouble issue in very simple thing. I have created two individual class files, Class-A and Class-Human. Specification for Class-A it contains the static main method declared.And I've tried to create the new instance of Class-Human. public static void main(String args[]) { Human human = new Human("Yoon Lee", 99); int expected = human.getNetID; //<-gets the error at this moment. } Specification for Class-Human namespace Class-A { public class Human { public String name; public int netId; public Human(String name, int netId) { this.name = name; this.netId = netId; } public int getNetID() { return netId; } } Why can't copy over into local variable? The compiler prompts me the error of 'Cannot convert method group of 'getNetID' delegate blah blah' Thank you. A: Change the method-call to: int expected = human.getNetID(); In C#, method-calls require parantheses () containing a comma-separated list of arguments. In this case, the getNetID method is parameterless; but the empty parantheses are still required to indicate that your intention is to invoke the method (as opposed to, for example, converting the method-group to a delegate-type). Additionally, as others have pointed out, there is a mismatch betweem the return-type of the method and the variable you're assigning its value to, which you're going to have to resolve somehow (change both the field-type and method return-type to int / parse the string as an integer, etc.). On another note, C# natively supports properties for getter-setter semantics, so the idiomatic way of writing this would be something like: //hyphens are not valid in identifiers namespace ClassA { public class Human { // these properties are publicly gettable but can only be set privately public string Name { get; private set; } public int NetId { get; private set; } public Human(string name, int netId) { this.Name = name; this.NetId = netId; } // unlike Java, the entry-point Main method begins with a capital 'M' public static void Main(string[] args) { Human human = new Human("Yoon Lee", 99); int expected = human.NetId; // parantheses not required for property-getter } } }
[ "stackoverflow", "0016197749.txt" ]
Q: Vim highlight regex I have a syntax highlight for cpp to highlight STL algorithms, one line is syn keywork cppSTL find My problem is that on a project that I am working, there are a number of classes with a method named find which are getting highlighted, and I want it only highlighted for STL calls. So I decided to change the previous line to: syn match cppSTL /[^.>:]\<find\>/ms=s+1 syn match cppSTL /\<std::find\>/ contains=cppScope syn match cppScope /::/ hi clear cppScope And it works most of the time. However if fails in this line: vector<string>::iterator i = find(find(x.begin(), x.end(), val), x.end(), term); ^^^^ The first find is highlighted correctly, but the second fails. My limited knowledge of vim regex says it should match, but I can't figure out why it doesn't. A: I got it! The problem is that my regex required a char behind find, and inside the parenthesis, the open parenthesis had already been matched, invalidating my regex. It works if I replace the first line with: syn match cppSTL "[^.>:]\@<=\<find\>"
[ "stackoverflow", "0014809683.txt" ]
Q: Float Value Is Lost in Int Trying to cast float to int but there's something missing float submittedAmount = 0.51f; int amount = (int)(submittedAmount * 100); Why is the answer 50? A: Because of floating point aritmethics, the multiplied value isn't exactly 51. When I tried now, *0.51f * 100* gave the result 50.9999990463257. And when you parse 50.9999990463257 to and int, you surely get 50. If you want calculations like this to be exact, you will have to use a type like decimal instead of float. If you want to understand why, read the article I have linked below. What Every Computer Scientist Should Know About Floating-Point Arithmetic
[ "stackoverflow", "0005720232.txt" ]
Q: In what circumstances would a GetMsgProc functions would receive a code of less than 0? As the question asks, in what circumstances would the procedure supplied to SetWindowsHookEx with WH_GETMESSAGE as hook ID would receive a "code" parameter less than zero? The help for the function states : If code is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx. For some reasons, I believe I'm receiving a message with a Code parameter of less than 0 when I would need to actually process the message. Any insight? A: Those < 0 codes are used internally to manage the list of hooks (Meaning you should always pass them along without looking at the data!) See this blog post for details about how people abused the old version and why we now have the Ex versions...
[ "stackoverflow", "0050908833.txt" ]
Q: how to add a character variable to character array in c++ I want to write the C++ code that can help me to give the drive letter which contains the given folder. I am writing the given code and getting the error while adding the character variable to a string variable at line 11. Can anyone help me out in rectifying the below code. #include "stdafx.h" #include <string> #include <windows.h> #include <iostream> #include "Shlwapi.h" int main() { char var; for (var = 'A'; var <= 'Z'; ++var) { char buffer_1[] = var +":\\PerfLogs"; ------->>>> line where i am getting the error char *lpStr1; lpStr1 = buffer_1; int retval; retval = PathFileExists(lpStr1); if (retval == 1) { std :: cout << "Search for the file path of : " << lpStr1; system("PAUSE"); } } } A: You should use the string library: std::string str1="Str 1"; std::string str2=" Str 2"; str1.append(str2); //str1 = "Str 1 Str 2"
[ "stackoverflow", "0036268843.txt" ]
Q: Python - only allow specific words (variables) and mathematical operators as input What is the best way in python to validate a string so that it only contains specific (pre-defined) words or some other characters [e.g. +, -, /, *, (, ) ]? My end goal is to validate input (string which will be used as a mathematical formula), for example: foo = Valid fooo = Invalid bar = Valid foo/(bar+foo) = Valid foo*bar - foo = Valid foo + tree = Invalid + = Invalid I have been searching for and found similar questions but none that seem to fit exactly my needs. I have kind of managed to create a flawed workaround where I do the following: allowed_words = ('foo', 'bar', ' + ') # and so on... which is tedious input_str = raw_input("foo + bar") split_string = re.split('(\W+)', input_str) for word in split_string: match = False for allowed_word in allowed_words: if word == allowed_word: match = True else: pass if match == True: print "%s is valid" % word else: print "%s is NOT valid" % word I also attempted to use if not re.match = ("(\b(?=foo\b|bar\b|\d+\b)\w+\b)|\s|[*/+()-]", input_str) which seemed to work here: http://regexr.com (but I suspect re.match is not the right way to go..) Could someone please inform me of the best way to achieve my goal? Thanks. A: This is the canonical lexing and parsing problem: how do you identify a string of characters as valid tokens and interpret whether they are valid? Regular expressions are involved, but not in the way you think: regular expressions are usually insufficient by themselves when you have a formal grammar to match against (which you do, otherwise simply having a + with no operands would be considered valid). PLY is a parser-lexer written in Python that is essentially a port of Lex and Yacc. It will take out much of the burden in solving this problem and requires fairly little code to get this done. Your grammar is pretty much the calculator grammar with a simple modification (the following is in Brackus-Naur format): expression : expression + term | expression - term | term term : term * factor | term / factor | factor factor : IDENTIFIER | ( expression ) where IDENTIFIER here can represent any of the valid words you want. You can even go one step further and replace IDENTIFIER with the specific words you want it to parse. The PLY page I linked to gives a full tutorial on how to implement this, complete with code. For the lexer, you need only specify the the individual regexes that match a token. In other words, you only need to tell the lexer to tag all strings that look like a + as a PLUS, rather than every possible combination of these characters. This saves a lot of trouble: you no longer have just one regular expression matching the whole string, only a regular expression to identify each part of a string. Again, the PLY documentation covers this exhaustively.
[ "ru.stackoverflow", "0000769431.txt" ]
Q: Как закрыть приложение в Android У меня приложение выполняется в главном активити MainActivity а мне нужно, чтобы приложение закрывалось через пункт меню настроек. Я пробовал вот так вызывать в классе settings extends PreferenceActivity но ничего не происходит: Preference pfinish = (Preference)findPreference(getString(R.string.settings_finish)); pfinish.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener(){ @Override public boolean onPreferenceClick(Preference preference) { MainActivity mp = new MainActivity(); mp.finish(); return true; } }); Вообще, во многих пограммах есть пункт Exit как это сделать? A: Если это единственное открытое activity в приложении, то можно использовать просто: finish(); без обращения к какому-либо экземляру. Чтобы закрыть приложение с любым количеством activity есть: android.os.Process.killProcess(android.os.Process.myPid()); Но вам скорее всего подойдет и finish()
[ "unix.stackexchange", "0000358545.txt" ]
Q: Why total installed size of packages are often multiple size of the downloaded binaries? I decided it is about time to move into the XXI century and replace my netctl network solution with network manager; resolving dependencies... looking for conflicting packages... Packages (10) {bluez-libs-5.44-1 (...) networkmanager-1.6.2-3} Total Download Size: 4.59 MiB Total Installed Size: 29.84 MiB Installed size is about 6X the downloaded size, where does this extra 'weight' come from? I mean in general, not this example-specific? Can this even be explained in 'general' terms? A: The basic reason is compression: packages are compressed, so the download size is reduced compared to the installation size. In some cases the compression can be very effective. Other factors come into play with many packaging tools: when upgrading packages, some distributions support downloading binary delta packages, which reduces the download size even further; when re-installing packages, some tools take your local cache into account — so if you’ve already downloaded a package which needs to be installed (but it’s not installed yet), that download size isn’t taken into account.
[ "stackoverflow", "0017541570.txt" ]
Q: jQuery - Populate closest hidden input with radio's value I have the following HTML and jQuery to populate hidden fields within each <td> element: <td> <div id="sex_div" style="text-align: left; width:120;"> <input type="hidden" id="sex" value=""/> <input type="radio" id="sex_male" name="sex_div" value="M"/><label for="sex_male">Male</label> <input type="radio" id="sex_female" name="sex_div" value="F"/><label for="sex_female">Female</label> </div> </td> The jQuery I have is as follows: $("input :radio").click(function() { $(this).siblings("input [type='hidden']").val($(this).val()); }); and obviously the buttonset, $("#sex_div").buttonset(); This is just a small part of the whole form. The rest all looks similar. Now the issue is that the hidden field is not being set when clicking/selecting a radio button. I have been struggling with this seemingly easy problem for two days now! Thanks for any help! A: $(this).siblings("input[type='hidden']").val($(this).val()); There should be no space between input and [type='hidden']. Spaces in selectors mean to search for descendant elements that match the next token.
[ "stackoverflow", "0035297562.txt" ]
Q: when should callback be executed I'm trying to log my colors variable after the forEach block completes execution. As the code stands now it simply returns an empty array. I guess I'm not console.logging at the right moment, but I'm confused about when that should happen. Basically, what I need is to be able to use my colors array to execute other functions on it. But before I do that I have to make sure that the createParentComponent function finished executing. Thanks in advance! var colors = []; function createParentComponent(array){ var count = 0; array.forEach(function(image){ var parent = document.createElement('div'); parent.style.height = '50px'; parent.style.width = '50px'; parent.className = 'parent'; var imgData = createImgandColorDiv(image); var img = imgData[0]; var cdiv = imgData[1]; parent.appendChild(img); parent.appendChild(cdiv); document.getElementById('container').appendChild(parent); count ++; console.log(count); }); if(count === array.length){console.log(colors);} } function createImgandColorDiv(url){ var img = document.createElement('img'); img.style.height = '50px'; img.style.width = '50px'; var cdiv=document.createElement('div'); cdiv.style.height = '50px'; cdiv.style.width = '50px'; cdiv.className = 'cdiv'; img.onload = function(){ var hsl = getDominantHSLColor(img); colors.push(hsl); cdiv.style.backgroundColor = 'hsl('+hsl[0]+','+hsl[1]+'%,'+hsl[2]+'%)'; }; img.src = url; return [img, cdiv]; } I was trying to inspire myself from this. A: You are declaring a count variable both in createParentComponent and the anonymous inner function that you use in forEach (var count = imgData[2];). As you can't increment (++) whatever ends up being count there, you'll get NaN. I'd suggest renaming the inner count variable getting rid of the inner count variable altogether, since createImgandColorDiv only returns two values anyway. :)
[ "mathematica.stackexchange", "0000002116.txt" ]
Q: Why round to even integers? According to the Mathematica help: Round rounds numbers of the form x.5 toward the nearest even integer. For example: Round[{0.5, 1.5, 2.5, 3.5, 4.5}] gives {0, 2, 2, 4, 4} What's the rationale behind this? Why not the usual x.5 always rounds up? A: I think the reason is to prevent biasing numbers on average upward or downward. For example if you have a list of numbers that include a lot of x.5 and you were to round all these upward, the average magnitude of the list would also shift upward. Likewise if you round downward, downward. By rounding to the nearest even number these would balance out, given enough samples. SetAttributes[RoundUp, Listable] RoundUp[a_] := If[FractionalPart[a] >= 1/2, Ceiling[a], Floor[a]] d = Table[i, {i, 0, 100, 1/10}]; Mean[Round[d]] // N 50. Mean[RoundUp[d]] // N 50.05 Mean[d] 50 Additional references According to Wikipedia this is also known as: unbiased rounding, convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, odd-even rounding3 or bankers' rounding, and is widely used in bookkeeping. Searching for some of those terms returns many good results including: stackoverflow.com It does not suffer from negative or positive bias as much as the round half away from zero method over most reasonable distributions. ... But the question was why [] use Banker's actual rounding as default - and the answer is that Microsoft has followed the IEEE 754 standard. mathforum.org Where statistics matter, and where numbers that END with the 5 are common, the method you referred to is preferred, because it avoids a bias toward rounding up. On the other hand, there may be some situations where a bias toward numbers that end in an even digit might be bad. Each method has its place. blogs.msdn.com Ideally when you are taking an average you want to take an average of the raw data with as much precision as you can get. But in the real world we often have to take averages of data which has lost some precision. In such a situation the Banker's Rounding algorithm produces better results because it does not bias half-quantities consistently down or consistently up. It assumes that on average, an equal number of half-quantities will be rounded up as down, and the errors will cancel out. cplusplus.com Given a number exactly halfway between two values, round to the even value (zero is considered even here). ... For random data this is very convenient. Bankers like it because money deposited and withdrawn is random. (There are trends, mind you, but you cannot predict exactly how much will be deposited and withdrawn.) The important point is that the bankers rounding is still biased if the data is biased. It is only unbiased with random data. www.russinoff.com One consequence of this result is that a midpoint is sometimes rounded up and sometimes down, and therefore, over the course of a long series of computations and approximations, rounding error is less likely to accumulate to a significant degree in one particular direction than it would be if the the choice were made more consistently. The cost of this feature is a more complicated definition, requiring a more expensive implementation. A: It is called bankers' rounding. The rationale is that the rounding behaves "nicely" even if you have negative numbers, i.e. rounding commutes with negation, which is nice. A: The answer is very nicely illustrated in following link at the topics "Round-Half-Even (Banker's Rounding)" and "Round-Half-Odd": Clive (Max) Maxfield and Alvin Brown, Rounding Algorithms 101 http://www.clivemaxfield.com/diycalculator/popup-m-round.shtml#A5
[ "stackoverflow", "0009089124.txt" ]
Q: var = [[0]*5]*5 Help understanding python lists? I came across a piece of python list decclaration. I am bit confused about the behavior of it. Can somone please explain this. Appreciate your help. >>> v = [[0]*2]*2 >>> v [[0, 0], [0, 0]] >>> v[1][1] = 23 >>> v [[0, 23], [0, 23]] >>> v[1][1] = 44 >>> v [[0, 44], [0, 44]] >>> A: The * operator for lists repeats their contents, as you can clearly see in the output. However, it does not copy elements, it just copies object references. So in this case, both [0,0 ]s have the same underlying list object, which should explain the phenomenon. To verify this, try v[0] = [0,44] to assign a new (and thus independent!) list object to the first element of the master list; then re-try changing v[1][1]. This time only one entry will change in the output.
[ "stackoverflow", "0022810710.txt" ]
Q: Backbone model, add global attribute which will be there on every instance of the model How do I set a property to my backbone model and keep it "globally" in every instance of the model. var myModel = new MyModel(); myModel.set('test', 1234); And now, in another view, I instantiate the model again: var myModel = new MyModel(); myModel.get('test') Should return 1234, not null. Any ideas on how to do it? I need this because I fetch a token from my rest api and I want to pass it to every request. So, after I do myModel.fetch(), I would like to add the value of the token, bind it to the model, so I'll have it in all my future requests. Edit, here is the actual code: var proxy = new Proxy(), target = '?csurl=http://laravelws.dev/account/token'; proxy.urlRoot = proxy.urlRoot + target; proxy.fetch( { dataType: 'json', success : function (resp) { that.token = resp.get('_token'); proxy.set('_token', that.token); }, error : function (model, xhr, options) { console.log('router.js - could not fetch the CSRF token'); } } ); I want to atach the token to the proxy model, and make the token available for all the future instances of the model. This code goes into the router's initialize function - so this get request will be made every time someone lands on my app, or refreshes the page. A: Use defaults: var MyModel = Backbone.Model.extend({ defaults: { test: 1234 } }); Edit: To achieve what you're looking for, you could set the value on the prototype: Proxy.prototype.token = "XXX"; var proxy = new Proxy(); console.log(proxy.token); Just be aware that the token value will be shared (if you change the value, it changes for all proxy instances).
[ "stackoverflow", "0057078640.txt" ]
Q: Ansible error - implementation error: unknown type string requested for name I am getting the unknown type string error when I execute the ansible playbook implementation error: unknown type string requested for name I am trying to display my name using a ansible playbook. The bg code is python. --- - name: Test hello module hosts: localhost tasks: - name: run the hello module hello: name: 'Test' register: helloout - name: dump test output debug: msg: '{{ helloout }}' #!/usr/bin/python def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True, type='string') ), supports_check_mode=False ) name = module.params['name'] module.exit.json(changed=False, meta=name) from ansible.module_utils.basic import * if __name__ == '__main__': main() [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [Test hello module] **************************************************************************************************************************** TASK [Gathering Facts] ****************************************************************************************************************************** ok: [localhost] TASK [run the hello module] ************************************************************************************************************************* fatal: [localhost]: FAILED! => {"changed": false, "msg": "implementation error: unknown type string requested for name"} PLAY RECAP ****************************************************************************************************************************************** localhost : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0 A: In the AnsibleModule() method argument argument_spec, the type you are looking for is actually str and not string: module = AnsibleModule( argument_spec=dict( name=dict(required=True, type='str') ), supports_check_mode=False ) You can see the list of accepted type specifications for the argument in the documentation.
[ "biology.stackexchange", "0000061214.txt" ]
Q: Is there any species that cannot reproduce without its symbiont? I was thinking about humans and machines being symbiotic "species". So I wonder if there exists in biology a species that could not reproduce without its symbiont. A: To the exception of many Monocercomonoides (thanks @canadianer for pointing the exception), all eukaryote (incl. animals, plants, fungi and others but excl. bacteria) all have one or more types of endosymbionte (e.g. mitochondria) and cannot function without it. So yes, any eukaryote is an example.
[ "stackoverflow", "0030523927.txt" ]
Q: Confusion regarding blocks in ios I have a bit of confusion regarding blocks. Say for example I have a block with completion BOOL: -(void) addNewSubGoalToLocalDatabaseAndParse:(CompletionBlock )cb { SubGoal* subGoalToAdd = [SubGoal new]; subGoalToAdd.name = subGoalName; subGoalToAdd.parentGoal = goal; Score* scoreToAdd = [Score new]; scoreToAdd.score = 0; scoreToAdd.subgoal = subGoalToAdd; [subGoalToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { if (succeeded) { [scoreToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error){ if (succeeded) { NSLog(@"NEW SUBGOALS AND SCORES ADDED"); [subGoalToAdd saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { if (succeeded) { [scoreToAdd saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { if (succeeded) { NSLog(@"NEW SUBGOALS AND SCORES ADDED"); cb(true); } }]; } }]; } }]; } }]; } Now here i am sending true to the block when all the operations are completed.Say if i send true to the block after the first succeeded will it exit the whole block or continue to run the code asynchronously? A: In your function,that is callBack,not return.You method will return first.Because there is a lot async code in your code So,if -(void) addNewSubGoalToLocalDatabaseAndParse:(CompletionBlock )cb { SubGoal* subGoalToAdd = [SubGoal new]; subGoalToAdd.name = subGoalName; subGoalToAdd.parentGoal = goal; Score* scoreToAdd = [Score new]; scoreToAdd.score = 0; scoreToAdd.subgoal = subGoalToAdd; [subGoalToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { if (succeeded) { cb(true); [scoreToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error){ if (succeeded) { NSLog(@"NEW SUBGOALS AND SCORES ADDED"); [subGoalToAdd saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { if (succeeded) { [scoreToAdd saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { if (succeeded) { NSLog(@"NEW SUBGOALS AND SCORES ADDED"); cb(true); } }]; } }]; } }]; } }]; } You will have two callBack. I test with those code -(void)testFunction:(CALLBACK)callback{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ sleep(2); callback(@"1"); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ sleep(2); callback(@"2"); }); }); } Then call [self testFunction:^(NSString *str) { NSLog(@"%@",str); }]; This will output 2015-05-29 15:57:24.945 OCTest[5009:261291] 1 2015-05-29 15:57:26.950 OCTest[5009:261291] 2
[ "math.stackexchange", "0002403077.txt" ]
Q: Problem in a GCD proof On the second page, $c$ is considered an arbitrary positive constant, also $c$ divides $ax+by$ - which means $ax+by=kc$. If by chance $x/k$ and $y/k$ belong to integers, $c$ will belong to set $S$ and $c$ will be smaller than the least element $d$. Isn't that a contradiction? Where am i wrong? A: Suppose that $c$ is an arbitrary positive common divisor of the non-zero integers $a$ and $b$ (trivial if either integer equals $0$) and $\gcd(a,b) = d$. Then $\exists$ $p,q \in \mathbb{Z}$ such that $$a = pc \qquad b = qc$$ Consequently, we can substitute into $ax+by$ to get $$(pc)x+(qc)y = d \implies c(px + qy) = d$$ So $px + qy$ is what $k$ is explicitly equal to. Now, if we attempt to do what you propose, we find that $$a \Big(\frac{x}{px+qy} \Big) + b \Big(\frac{y}{px+qy} \Big) = c$$ If $px + qy = 1$, then there is no issue as it is clear that, in fact, $c = d$ and we do not contradict the minimality of $d$. If, on the other hand, we suppose that $px + qy > 1$ (which would make $c < d$), then the expressions $$\frac{x}{px+qy} \quad \text{and} \quad \frac{y}{px+qy}$$ are not in the form $X$, $Y$ as mentioned in the comments. In fact, Question: Is either expression an integer? To investigate this, let us first note that at least one of $x$ or $y$ must be non-zero, or else $d = 0$. Without loss of generality, let $x \neq 0$ and $x/(px+qy) \in \mathbb{Z}$. Then $\exists \ m \in \mathbb{Z}$ such that $$x = m(px+qy) \implies x(1-mp) = mqy$$ Rewriting the second expression in the following manner: $$\frac{y}{px+qy} = \Big(\frac{mq}{mq} \Big) \frac{y}{px+qy}$$ (This is legal since $b \neq 0 \implies q \neq 0$ and $x \neq 0 \implies m \neq 0$). Substituting for $mqy$ gives us $$\frac{x(1-mp)}{mq(px+qy)} = \frac{x(1-mp)}{xq} = \frac{1-mp}{q} \quad \Big( = \frac{y}{px+qy} \Big)$$ if $y = 0$, then we force $mp = 1 \implies m = p = \pm 1$. Then $a = \pm c \implies b = \pm qa$, contradicting the generality of our choice of the integers $a, b$. Otherwise, if $y \neq 0$ and $y/(px+qy) \in \mathbb{Z}$, then $\exists k \in \mathbb{Z}$ such that $$1 - mp = kq \implies 1 = p\cdot(m) + q\cdot(k)$$ The equality implies that $p, q$ are relatively prime, for $\gcd(p,q) = 1 \iff$ we can write a $\mathbb{Z}$-linear combination of $p,q$ equal to 1. But then this implies that $c = d$, contradicting both the hypotheses that $c < d$ and $px + qy > 1$. Note that this is true by referring to this question and observing that $a/c = p, b/c = q,$ and \begin{align}\frac{a}{c} (m) + \frac{b}{c} (k) = 1 &\iff \gcd \Big(\frac{a}{c},\frac{b}{c} \Big) = 1 \\ & \iff c = \gcd(a,b) = d \end{align} Thus it follows that $c \notin S$.
[ "stackoverflow", "0047825953.txt" ]
Q: Vue.js same form for add and edit I'm a rookie on vue.js and I'm trying to extend some tutorials a completed. Been fighting with this three hours now and I'm frustrated. FYI, I'm using firebase but I'm not sure it really matters here. So, I have a CRUD app for listing movies (I told you it was basic!). There is a form at the top of the page where you can add movies, and a table below it, where the new registries are listed. This works well. I added Edit and Delete buttons to each row on the table. The delete function works. But the Edit function is the problem. I'd like to use v-if on the initial form, to trigger different methods (save, edit) and show different buttons (Add, Save, Cancel). I'm not sure how to access the objects to do this, I tried a couple of things and the v-if says the object is not defined. thank you for reading, please ask anything you need. import './firebase' // this has my credententials and initializeApp import Vue from 'vue' import App from './App' import VueFire from 'vuefire' Vue.use(VueFire) Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', components: { App } }) <template> <div id="app" class="container"> <div class="page-header"> <h1>Vue Movies</h1> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3>Add Movie</h3> </div> <div class="panel-body"> <div v-if="!isEditing"> <form id="form" class="form-inline" v-on:submit.prevent="addMovie"> <div class="form-group"> <label for="movieTitle">Title:</label> <input type="text" id="movieTitle" class="form-control" v-model="newMovie.title"> </div> <div class="form-group"> <label for="movieDirector">Director:</label> <input type="text" id="movieDirector" class="form-control" v-model="newMovie.director"> </div> <div class="form-group"> <label for="movieUrl">URL:</label> <input type="text" id="movieUrl" class="form-control" v-model="newMovie.url"> </div> <input type="submit" class="btn btn-primary" value="Add Movie"> </form> </div> <div v-else> <form id="form" class="form-inline" v-on:submit.prevent="saveEdit(movie)"> <div class="form-group"> <label for="movieTitle">Title:</label> <input type="text" id="movieTitle" class="form-control" v-model="movie.title"> </div> <div class="form-group"> <label for="movieDirector">Director:</label> <input type="text" id="movieDirector" class="form-control" v-model="movie.director"> </div> <div class="form-group"> <label for="movieUrl">URL:</label> <input type="text" id="movieUrl" class="form-control" v-model="movie.url"> </div> <input type="submit" class="btn btn-primary" value="Save"> <button v-on:click="cancelEdit(movie['.key'])">Cancel</button> </form> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3>Movies List</h3> </div> <div class="panel-body"> <table class="table table-stripped"> <thead> <tr> <th>Title</th> <th>director</th> </tr> </thead> <tbody> <tr v-for="movie in movies"> <td> <a v-bind:href="movie.url" v-bind:key="movie['.key']" target="_blank">{{movie.title}}</a> </td> <td> {{movie.director}} </td> <td> <button v-on:click="editMovie(movie)">Edit</button> </td> <td> <button v-on:click="removeMovie(movie)">Remove</button> </td> </tr> </tbody> </table> </div> </div> </div> </template> <script> import { moviesRef } from './firebase' export default { name: 'app', firebase: { movies: moviesRef }, data () { return { isEditing: false, // maybe this helps? newMovie: { title: '', director: '', url: 'http://', edit: false // or maybe this?? } } }, methods: { addMovie: function() { moviesRef.push( this.newMovie ) this.newMovie.title = '', this.newMovie.director = '', this.newMovie.url = 'http://' this.newMovie.edit = false }, editMovie: function (movie){ moviesRef.child(movie['.key']).update({ edit:true }); // can't access this one with v-if, not sure why //this.newMovie = movie; }, removeMovie: function (movie) { moviesRef.child(movie['.key']).remove() }, cancelEdit(key){ moviesRef.child(key).update({ edit:false }) }, saveEdit(movie){ const key = movie['key']; moviesRef.child(key).set({ title : movie.title, director : movie.director, url : movie.url, edit : movie.edit }) } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style> A: You should change the isEditing to true when the Edit button clicked, and you should define the data movie. editMovie: function (movie){ ... this.movie = Vue.util.extend({}, movie); // deep clone to prevent modify the original object this.isEditing = true; },
[ "stackoverflow", "0058018659.txt" ]
Q: Split Access database in separate files I want to export each table of one database in separate accdb files and I don't get it. With the following code -> https://www.devhut.net/2012/09/27/ms-access-vba-export-database-objects-to-another-database/ the destination database must already exist. How can I create e.g. for table1 the file table1.accdb and export only one table into this database? If the main database has 10 tables 10 files should be created and the belonging table should export as well. A: Here is how: Public Function ExportTables() Const Path As String = "C:\Test\" Dim Workspace As DAO.Workspace Dim Database As DAO.Database Dim Table As DAO.TableDef Dim Tablename As String Set Workspace = DBEngine(0) For Each Table In CurrentDb.TableDefs If Table.Attributes = 0 Then ' This is a local table and not a system table. Tablename = Table.Name Set Database = Workspace.CreateDatabase(Path & Tablename, dbLangGeneral) DoCmd.TransferDatabase acExport, "Microsoft Access", Database.Name, acTable, Tablename, Tablename Debug.Print "Exported " & Tablename End If Next End Function
[ "stackoverflow", "0042417997.txt" ]
Q: Display local html file content in UWP WebView I believe this is pretty straightforward task and I've seen a lot of examples in the web but still none of them is working for me since I experience different exceptions. html: <html lang="en"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <p> Help html content. </p> </body> </html> xaml: <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="30"/> </Grid.RowDefinitions> <WebView x:Name="webView" /> <Button x:Name="buttonRefresh" Grid.Row="1" HorizontalAlignment="Center" Click="buttonRefresh_Click"> Refresh </Button> </Grid> To display static html saved in help.html file in my UWP application LocalFolder I've already tried the following: - Use Navigate method: private void buttonRefresh_Click(object sender, RoutedEventArgs e) { var uri = new Uri("ms-appdata:///local/help.html"); webView.Navigate(uri); } and the result is the following exception: System.ArgumentException: Value does not fall within the expected range. at Windows.UI.Xaml.Controls.WebView.Navigate(Uri source) at SimpleUwpApp.Proxy.SimplerPage.buttonRefresh_Click(Object sender, RoutedEventArgs e) - Try to set Source property of webView explicitly in code behind: private void buttonRefresh_Click(object sender, RoutedEventArgs e) { var uri = new Uri("ms-appdata:///local/help.html"); webView.Source = uri; } result: System.ArgumentException: Value does not fall within the expected range. at Windows.UI.Xaml.Controls.WebView.put_Source(Uri value) at SimpleUwpApp.Proxy.SimplerPage.buttonRefresh_Click(Object sender, RoutedEventArgs e) - Set Source property of webView explicitly in xaml: This is the exact example from microsoft documentation. <WebView x:Name="webView" Source="ms-appdata:///local/help.html" /> As a result exception on startup: Windows.UI.Xaml.Markup.XamlParseException: The text associated with this error code could not be found. Failed to assign to property 'Windows.UI.Xaml.Controls.WebView.Source' because the type 'Windows.Foundation.String' cannot be assigned to the type 'Windows.Foundation.Uri'. [Line: 16 Position: 54] at Windows.UI.Xaml.Application.LoadComponent(Object component, Uri resourceLocator, ComponentResourceLocation componentResourceLocation) at SimpleUwpApp.Proxy.SimplerPage.InitializeComponent() - Tried using url string directly in Navigate() arguments as in this microsoft examples but Navigate() accepts only Uri as an aargument so the documentation is either invalid, either for older version of xaml toolkit. webView.Navigate("ms-appx-web:///help.html"); result: Syntax error. The only solution I've temporary came up with is reading the content of html file with some kind of file manager and using NavigateToString() method: var content = fileManager.Read("help.html"); // Manually read the content of html file webView.NavigateToString(content); So the question is why described examples don't work? How to avoid using NavigateToString? A: So i got two different things, which worked for me: The XAML-version: <WebView x:Name="webView" Source="ms-appx-web:///help.html"/> Here you need to use the ms-appx-web prefix. The code-behind version: webView.Navigate(new Uri("ms-appx-web:///help.html")); The difference to your version is, that you are not allowed to enter the string only. You need to create a new Object of the Uri-Class. In both versions, the html-file is a direct child of the project and the project is a Windows-10-UWP Application [You didnt say, if you use Windows 8 or Windows 10] A: The solution provided by TheTanic will work for files that are delivered with your package. For files stored in your LocalFolder or TemporaryFolder you must follow special URI scheme: The WebView support for this scheme requires you to place your content in a subfolder under the local or temporary folder. This enables navigation to Uniform Resource Identifier (URI) such as ms-appdata:///local/folder/file.html and ms-appdata:///temp/folder/file.html This means that if you use LocalFolder then URI will start like this: ms-appdata:///local/ after this must be a folder and inside your file. Here is a working sample: StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///help.html")); StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("anyFolder", CreationCollisionOption.OpenIfExists); await file.CopyAsync(folder, "help.html", NameCollisionOption.ReplaceExisting); webView.Navigate(new Uri("ms-appdata:///local/anyFolder/help.html")); Note also that all the content used must be also in that folder as: Each of these first-level subfolders is isolated from the content in other first-level subfolders.
[ "stackoverflow", "0005196047.txt" ]
Q: indent grouped cells like iphone contacts I'd like to have a gruped table where the first section has 2 row and 1 imageview like contacts app. something like this: screeshot How can I do that? Thanks, Max A: The other solutions require you to create your own background images and use two tableviews which is not convenient. What I did was subclass UITableViewCell and indented the background views as such: #define INDENT_WIDTH 84 ... - (void)layoutSubviews { [super layoutSubviews]; //Indent the background views. CGRect frame = self.backgroundView.frame; frame.origin.x = frame.origin.x + INDENT_WIDTH; frame.size.width = frame.size.width - INDENT_WIDTH; self.backgroundView.frame = frame; self.selectedBackgroundView.frame = frame; //Also indent the UIImageview that contains like a shadow image over the backgroundviews (in grouped tableview style only). for (UIView *subview in self.subviews) { if ([subview isKindOfClass:[UIImageView class]]) { CGRect frame = subview.frame; frame.origin.x = frame.origin.x + INDENT_WIDTH; frame.size.width = frame.size.width - INDENT_WIDTH; subview.frame = frame; } } } Since the content view has a transparent background color you can place a UIImageView (e.g on your storyboard cell prototype) on the left side and you should get the same effect as the "Add Contact" view in the Contacts App.
[ "sharepoint.stackexchange", "0000273051.txt" ]
Q: Create headers from csv file I want to use a csv file to create headers in a document library or some other file type if that works better. A: Per my knowledge, you will always need to create the columns manually and specify the column type or use some third party tools. You can do it in PowerShell, however still you need to specify each column settings.
[ "stackoverflow", "0051902044.txt" ]
Q: How can I use Regex to remove the newline between these tags? I did see another solution on SO but it made the entire file with no new lines. I only need a particular section with no new lines. I am attempting to remove the spacing between these tags so that they are right right next to one another such as this: <a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""><img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"></a><a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""><img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"></a><a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""><img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"></a><a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""><img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"></a> They currently looks like this: <a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""> <img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"> </a> <a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""> <img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"> </a> <a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""> <img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"> </a> <a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""> <img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"> </a> A: Here is an example of the suggested regex I put in the comments, I added \t & \s{2,} to pull out tab characters and 2 or more white space characters. let temp = `<a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""> <img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"> </a> <a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""> <img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"> </a> <a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""> <img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"> </a> <a rel="nofollow noopener" style="display:inline; text-decoration: none;" href=""> <img border="0" class="full" height="auto" width="300" alt="" src="http://via.placeholder.com/600x338"> </a>`; console.log(temp.replace(/[\r\n|\r|\n|\t]/g, '').replace(/\s{2,}/g, ' '))
[ "stackoverflow", "0059928427.txt" ]
Q: Writing letter directly behind a value I need to assign a time to a profile value from our database, but I don't know how to seperate the values. It is the following code: var pauze_datum = new Date("2020-01-27T10:33:00"); The time should be assigned to var Temporary_Date which is a filled in date in a form. How do you seperate the letter e and T? var pauze_datum = new Date("Temporary_Date T10:33:00"); A: You can use either regular concatenation: var value = "2020-01-27"; var pauze_datum = new Date(value + "T10:33:00"); or template literals: var value = "2020-01-27"; var pauze_datum = `${value}T10:33:00`;
[ "stackoverflow", "0014674469.txt" ]
Q: Abort SQL Query with process time limit Can I write SQL queries using DELPHI, dbgo DB components and a SQL Server database server which are limited in respect to the process time ? Like select * from table where ...... and process_time_limit = 5 sec ? Better you give me 10% of the rows within a time limit instead of waiting hours for the complete query dataset A: ADO components: I would give a try to the asynchronous data fetch. When you'd execute the query, you'll remember when you've started and every time the OnFetchProgress event fires, you'll check if the EventStatus is still in esOK state and check the time elapsed from the query execution. If it elapsed, you might cancel data fetch by using the Cancel method on your dataset. I meant to use something like the following (untested) pseudocode: var FQueryStart: DWORD; procedure TForm1.FormCreate(Sender: TObject); begin // configure the asynchronous data fetch for dataset ADOQuery1.ExecuteOptions := [eoAsyncExecute, eoAsyncFetchNonBlocking]; end; procedure TForm1.Button1Click(Sender: TObject); begin // store the query execution starting time and execute a query FQueryStart := GetTickCount; ADOQuery1.SQL.Text := 'SELECT * FROM Table'; ADOQuery1.Open; end; procedure TForm1.ADOQuery1FetchProgress(DataSet: TCustomADODataSet; Progress, MaxProgress: Integer; var EventStatus: TEventStatus); begin // if the fetch progress is in esOK (adStatusOK) status and the time since // the query has been executed (5000 ms) elapsed, cancel the query if (EventStatus = esOK) and (GetTickCount - FQueryStart >= 5000) then DataSet.Cancel; end;
[ "math.stackexchange", "0000462901.txt" ]
Q: How are $C^0,C^1$ norms defined How are $C^0,C^1$ norms defined? I know $L_p,L_\infty$ norms but are the former defined. A: On $\mathcal{C}^{0}([a,b])$, the usual norm is $$ \Vert f \Vert = \sup \limits_{x \in [a,b]} \vert f(x) \vert $$ (the interesting point is that $\left( \mathcal{C}^{0}([a,b]), \Vert \cdot \Vert \right)$ is a Banach space. On $\mathcal{C}^{1}([a,b])$, you can define the norm $$ \Vert f \Vert_{\mathcal{C}^{1}} = \sup_{x \in [a,b]} \vert f(x) \vert + \sup_{x \in [a,b]} \vert f'(x) \vert $$ (and $\left( \mathcal{C}^{1}([a,b]),\Vert \cdot \Vert_{\mathcal{C}^{1}} \right)$ is also a Banach space.)
[ "stackoverflow", "0063653416.txt" ]
Q: Highlight the active collection button in shopify I have a list of a collection I am calling in Shopify. I tried to use the link active tag but its not working. Here is my snippet {% for collection in collections %} {% unless collection.handle == 'frontpage' %} <button type="button" class="btn btn-outline-info {% if link.active %}class='active'{% endif %}">{{ collection.title | escape | link_to: collection.url }}</button> {% endunless %} {% endfor %} I am trying to add active class to the active collection, or the collection URL I am on presently. I don't know what I am missing here. A: Based on your comments, your code will function erratically. collection is a reserved variable in Shopify and by using the same variable in the loop, you might be changing the actual collection altogether. And secondly, link.active will only work inside a linklists loop. Here's what you can do: change the assigning variable for the unit in your loop and validate if the handles are the same. {% for thisCollection in collections %} {% unless thisCollection.handle == 'frontpage' %} <button type="button" class="btn btn-outline-info {% if thisCollection.handle == collection.handle %}class='active'{% endif %}">{{ thisCollection.title | escape | link_to: thisCollection.url }}</button> {% endunless %} {% endfor %}
[ "stackoverflow", "0011389714.txt" ]
Q: How to write this IF condition correctly, inside WHERE clause codeigniter I am using codeigniter, I want to use an IF condition in WHERE clause. But it is not executing properly. $where_string="( a.FirstName LIKE '".$search_phrase."%' OR ( IF(c.PrivacySettingElephantiUser=1,'a.LastName LIKE \'".$search_phrase."%\' OR CONCAT(a.FirstName, \' \', a.LastName) LIKE \'".$search_phrase."%\' ','')))"; $this->db->where($where_string); i am doing a search here . by first name , last name and first name concat last name . i check the value c.PrivacySettingsElephantiUser . if only it is true , i am cheking for last name and first name last name concat value , the thing is if the c.PrivacySettingsElephantiUser=1 ANDc.PrivacySettingsElephantiUser=0, this part is not executing . OR ( IF(c.PrivacySettingElephantiUser=1,'a.LastName LIKE \'".$search_phrase."%\' OR CONCAT(a.FirstName, \' \', a.LastName) LIKE \'".$search_phrase."%\' ','') it is only searching by the first name always , ignoring the if condition , How to write this correctly? Is there an easy way to do this using AND ,OR logic? UPDATE this my full query public function search_people($profile_id,$search_phrase=NULL,$country=NULL,$state=NULL,$city=NULL,$neighborhood=NULL,$type=NULL,$limit=NULL,$offset=NULL) { $this->db->select('SQL_CALC_FOUND_ROWS a.ProfileID,a.FirstName,a.LastName,a.StateName,a.CityName,a.ShowLastName,a.UserType,a.ProfileImg,b.FriendStatus,b.RequesterID,b.AccepterID',FALSE); $this->db->from($this->mastables['xxxxxxxx'].' as a'); $this->db->join($this->mastables['yyyyyyyyyyy'].' as b'," b.RequesterID=a.ProfileID AND b.AccepterID=".$profile_id." OR b.AccepterID=a.ProfileID AND b.RequesterID=".$profile_id,'left'); $this->db->where('a.ProfileID !=',$profile_id); $this->db->where('a.UserType',2); if($type=="friend") { $this->db->join($this->mastables['profile_privacy_settings'].' as c'," c.EntityID=a.ProfileID AND c.UserType=2 AND c.ProfilePrivacySettingDefaultID=1 ",'inner'); $where_string="( a.FirstName LIKE '".$search_phrase."%' OR ( IF(c.PrivacySettingFriend=1,'a.LastName LIKE \'".$search_phrase."%\' OR CONCAT(a.FirstName, \' \', a.LastName) LIKE \'".$search_phrase."%\' ','')))"; $this->db->where($where_string); $this->db->where('b.FriendStatus',1); } else if($type=="other") { $this->db->join($this->mastables['profile_privacy_settings'].' as c'," c.EntityID=a.ProfileID AND c.UserType=2 AND c.ProfilePrivacySettingDefaultID=1 ",'inner'); $where_string="( a.FirstName LIKE '".$search_phrase."%' OR ( IF(c.PrivacySettingElephantiUser=1,'a.LastName LIKE \'".$search_phrase."%\' OR CONCAT(a.FirstName, \' \', a.LastName) LIKE \'".$search_phrase."%\' ','')))"; $this->db->where($where_string); $this->db->where ('(b.FriendStatus IS NULL OR b.FriendStatus=0)'); } else { $this->db->join($this->mastables['profile_privacy_settings'].' as c'," c.EntityID=a.ProfileID AND c.UserType=2 AND c.ProfilePrivacySettingDefaultID=1 ",'inner'); $where_string="( a.FirstName LIKE '".$search_phrase."%' OR ( IF(c.PrivacySettingElephantiUser=1 OR c.PrivacySettingFriend=1,'a.LastName LIKE \'".$search_phrase."%\' OR CONCAT(a.FirstName, \' \', a.LastName) LIKE \'".$search_phrase."%\'','')))"; //$where_string="( a.FirstName LIKE '".$search_phrase."%' OR ( IF(c.PrivacySettingElephantiUser=1 OR c.PrivacySettingFriend=1,'a.LastName LIKE b%','')))"; $this->db->where($where_string); } if($country) { $this->db->where('a.CountryID',$country); } if($state) { $this->db->where('a.StateID',$state); } if($city) { $this->db->where('a.CityID',$city); } if($neighborhood) { //$this->db->where('',$neighborhood); } if($limit) { $this->db->limit($limit,$offset); } $query = $this->db->get(); //echo $this->db->last_query();die; $result['result'] = $query->result_array(); $query = $this->db->query('SELECT FOUND_ROWS() AS `Count`'); $result["totalrows"] = $query->row()->Count; if(!empty($result)) { return $result; } } A: not getting PHP operations just writing sql code.. Use Case statement in your where query case when (c.PrivacySettingElephantiUser=1 AND (a.LastName LIKE '%something%' OR CONCAT(a.FirstName, \' \', a.LastName) like '%something%') then 1 else 0 end;
[ "stackoverflow", "0001203027.txt" ]
Q: How can I easily mock out a static method in Java (jUnit4) How do I easily mock out a static method in Java? I'm using Spring 2.5 and JUnit 4.4 @Service public class SomeServiceImpl implements SomeService { public Object doSomething() { Logger.getLogger(this.class); //a static method invoked. // ... } } I don't control the static method that my service needs to invoke so I cannot refactor it to be more unit-testable. I've used the Log4J Logger as an example, but the real static method is similar. It is not an option to change the static method. Doing Grails work, I'm used to using something like: def mockedControl = mockFor(Logger) mockControl.demand.static.getLogger{Class clazz-> … } … mockControl.verify() How do I do something similar in Java? A: Do you mean you can't control the calling code? Because if you control the calls to the static method but not the implementation itself, you can easily make that testable. Create a dependency interface with a single method with the same signature as the static method. Your production implementation will just call through to the static method, but anything which currently calls the static method will call via the interface instead. You can then mock out that interface in the normal way. A: The JMockit framework promises to allow mocking of static methods. https://jmockit.dev.java.net/ In fact, it makes some fairly bold claims, including that static methods are a perfectly valid design choice and their use should not be restricted because of the inadequacy of testing frameworks. Regardless of whether or not such claims are justifiable, the JMockit framework itself is pretty interesting, although I've yet to try it myself. A: PowerMock has this ability. It can also mock instantiations of objects inside the class under test. If your tested method calls new Foo(), you can create a mock object for that Foo and replace it in the method you are testing. Things like suppressing constructors and static initializers are also possible. All of these things are considered untestable code and thus not recommended to do but if you have legacy code, changing it is not always an option. If you are in that position, PowerMock can help you.
[ "stackoverflow", "0032574621.txt" ]
Q: How to render json without having .json at the end of the url I want to implement ODATA formatting to my CakePHP REST API. My problem is CakePhp expects .json at the end of the resource to understand the response format. How can I render json and remove ".json" part from my request url? I.e. Current GET: api.local/api/v2_agent_properties/83.json Target GET: api.local/api/v2_agent_properties(83) A: you could set this in the beforeRender of the appController: $this->RequestHandler->renderAs($this, 'json');
[ "astronomy.stackexchange", "0000018794.txt" ]
Q: Will the Earth ever be tidally locked to the Moon? From my basic understating, Momentum is being transfered from the Earth's rotation to the Moon's orbit by tidal friction. The Earth's rotation slows down and the Moon receedes from the Earth as it moves into a higher orbit. This will continue until the Earth's rotational period is equal to the orbital period of the Moon, i.e the Earth is tidally locked to the Moon. Assuming I have the above correct - and please correct me if I don't - will there, realistically, be enough time for tidal locking to occur before the sun expands and engulfs the Earth? Or is there another reason the Earth will never be locked towards the Moon? A: As the moon orbits Earth, tidal forces slow down the Earth's rotation by 2 milliseconds per century. Eventually, in tens of billions of years, the Earth and Moon would achieve a double tidal lock, where both are stuck with one side facing the other as they orbit the Earth-Moon barycenter. In 7.5 billion years, the Sun will expand past the Earth's current orbit, but the Earth may drift out further, preventing it from being vaporized. However, this is beside the point, because in about one billion years, all of Earth's water will have boiled away, meaning that there would be no more ocean tides, and thus the Earth-Moon system will likely never achieve a double tidal lock. References: Will the Moon ever leave Earth’s orbit? - Giles Sparrow, Space Answers Harvesting Lunar Eccentricity? - Terry R. McConnell, Syracuse University When Will Earth Lock to the Moon? - Fraser Cain, Universe Today The Sun Will Eventually Engulf Earth--Maybe - David Appell, Scientific American Distant future of the Sun and Earth revisited - K.-P. Schröder and Robert Connon Smith, MNRAS When will Earth lose its oceans? - CNRS, Science Daily
[ "stackoverflow", "0020455789.txt" ]
Q: Excel VBA - when looping through files in a directory, how to skip to next file onError I'm looping through the files in a directory, where I need to open each file, do some manipulations and then close it. From time to time the Workbooks.Open fails with an error, and I simply want to display a MsgBox and then continue to the next file in the directory loop. But since the Error block is outside the loop, I can't just call 'Loop'... so how do I do this ? The test below immediately triggers an error that I can't call "Loop" without a "For"... Sub test() Dim folderPath As String Dim filename As String folderPath = 'C:\myDirectory' filename = Dir(folderPath & "*.xlsx") Do While filename <> "" On Error GoTo OpenFailedError Set wb = Workbooks.Open(folderPath & filename) On Error GoTo 0 filename = Dir Loop Exit Sub OpenFailedError: MsgBox ("Unable to open file " & filenameString) Loop End Sub A: This is untested, but better, I'm sure. Note that you have a couple of undeclared variables: wb and filenameString. I strongly recommend using Option Explicit at the top of each module to avoid undeclared or misnamed variables. In this case, it looks like filenameString was supposed to be FileName. Note also that I put some capitals in the variable names. This helps you notice when you mistype a name (using lower-case letters) as it will fail to resolve to upper-case. At any rate, I'd move the error-check inside the main loop: Sub test() Dim FolderPath As String Dim FileName As String Dim wb As Excel.Workbook FolderPath = "C:\myDirectory\" FileName = Dir(FolderPath & "*.xlsx") Do While FileName <> "" On Error Resume Next Set wb = Workbooks.Open(FolderPath & FileName) If Err.Number <> 0 Then MsgBox ("Unable to open file " & FileName) End If On Error GoTo 0 FileName = Dir Loop End Sub EDIT: Per Sid's suggestion, added a "\" to the end of FolderPath.
[ "stackoverflow", "0044459083.txt" ]
Q: Size of ram used increase abnormally after serialization/deserialization I using following methods to save application data into a file after serialization and load data from this file after deserialization (en/decrypted). private void SaveClassToFile(string fileAddress, string password, object classToSave) { const int ivSaltLength = 16; byte[] salt = new byte[ivSaltLength]; byte[] iv = new byte[ivSaltLength]; byte[] codedClass = new byte[0]; iv = CreateIV(); salt = CreateSalt(); using (var memoryStream = new MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, classToSave); codedClass = new byte[Convert.ToInt32(memoryStream.Length)]; memoryStream.Seek(0, SeekOrigin.Begin); if (memoryStream.Read(codedClass, 0, Convert.ToInt32(memoryStream.Length)) != memoryStream.Length) {throw new Exception("failed to read from memory stream"); } } using (SpecialCoderDecoder specialCoder = new SpecialCoderDecoder(SpecialCoderDecoder.Type.Coder, password, salt, iv)) { specialCoder.Code(codedClass); } using (FileStream streamWriter = new FileStream(fileAddress, FileMode.CreateNew)) using (BinaryWriter binaryWriter = new BinaryWriter(streamWriter)) { binaryWriter.Write(salt); binaryWriter.Write(iv); binaryWriter.Write(codedClass); } } private object LoadClassFromFile(string fileAddress, string password) { const int ivSaltLength = 16; byte[] salt = new byte[ivSaltLength]; byte[] iv = new byte[ivSaltLength]; byte[] codedClass = new byte[0]; int codedClassLengthToRaed = 0; FileInfo fileInfo; object result = null; fileInfo = new FileInfo(fileAddress); using (FileStream streamWriter = new FileStream(fileAddress, FileMode.Open)) using (BinaryReader binaryreader = new BinaryReader(streamWriter)) { salt = binaryreader.ReadBytes(ivSaltLength); iv = binaryreader.ReadBytes(ivSaltLength); codedClassLengthToRaed = Convert.ToInt32(fileInfo.Length) - (2 * ivSaltLength); codedClass = binaryreader.ReadBytes(codedClassLengthToRaed); } using (SpecialCoderDecoder specialDecoder = new SpecialCoderDecoder(SpecialCoderDecoder.Type.Decoder, password, salt, iv)) { specialDecoder.Decode(codedClass); } using (MemoryStream memoryStream = new MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(); memoryStream.Write(codedClass, 0, codedClass.Length); memoryStream.Seek(0, SeekOrigin.Begin); result = (object)binaryFormatter.Deserialize(memoryStream); } return result; } If there be no data in application and I add about 100MB data to it (base on task manager) and save it. After loading data, task manager shows that application data is about 200-400 MB! For encapsulating application class to one class for use this methods I use a class like: public class BigClass { public ClassA classA; public ClassB classB; public BigClass(ClassA a, ClassB b) { classA = a; classB = b; } } That each one of ClassA and ClassB (classes that should saves/loads) are like: public class ClassA { List<ClassASub> list = new List<ClassASub>(); //some variables... //some methodes private class ClassASub { int intValue; long longValue; string stringValue; Image image; //some simple methodes.... } } I do not talk about size of used RAM in serialization/deserialization progress. I speak about used RAM after that, when only application data should exists. A: You're loading the data into memory as an array (codedClass). This array, by your indication, is presumably around 100MB, which is more than enough to ensure that it gets allocated on the Large Object Heap. Now: GC is designed to optimize your overall system performance; it is not designed to aggressively reclaim memory constantly, for multiple reasons: it is unnecessary overhead if you have lots of memory free in your system (you're not under memory pressure) and there's no specific need to collect some data is more expensive to collect than others; the most expensive of these is the Large Object Heap, so it goes to the back of the queue; other memory is released first even if data was free, it isn't necessarily advantageous to release those pages back to the OS; the process could validly decide to hold onto them to avoid constantly asking the OS for memory and handing it back In your case, you could try using the methods on System.GC to forcibly run a collection, but I think the real goal would be to not allocate those big arrays. If you can do anything to move to a Stream-based model rather than an array-based model, that would be good. This would presumably mean changing SpecialCoderDecoder significantly. Key point: the upper size of an array hard a hard cap; you cannot scale your current implementation beyond 2GB (even if <gcAllowVeryLargeObjects> is enabled). Additionally, I suspect that BinaryFormatter is exacerbating things - it almost always does. Alternative more efficient well-worn serializers exist. Reducing the serialized size would be an alternative option to consider, either instead of - or in combination with - moving to a Stream-based model. Additionally additionally: you could try using compression techniques (GZipStream, DeflateStream, etc) inside the encrypted payload. You shouldn't attempt to compress encrypted data - you need to ensure that the order is: Serialize -> Compress -> Encrypt -> (storage) -> Decrypt -> Decompress -> Deserialize The serialization and compression stages are already fully Stream-compatible. If you can make the encryption layer Stream-compatible, you're onto a winner.
[ "tex.stackexchange", "0000269489.txt" ]
Q: Little diagram in LaTeX I would like to draw the following diagram in my text: How could I proceed? A: It's not a nice code but it may work \documentclass{article} \usepackage{mathtools} \begin{document} \[ \overset{\underbrace{p \to F}}{\quad\left.\begin{matrix}F'\\ \uparrow\\ p'\end{matrix}\right\}} \underbrace{F''\leftarrow p''}_{\quad\left.\begin{matrix}F'''\\ \uparrow\\ p'''\end{matrix}\right\}\displaystyle\mathrlap{\dots}} \] \end{document} Basically I split the formula in two pieces: the left part is a vertical matrix on whose top the term with the underbrace is placed with \overset. The right part just uses \underbrace and puts the verical matrix under it. (One may have used \underset here.) A: With tikz (decorations.pathreplacing library) \documentclass[border=5mm]{standalone} \usepackage{tikz} \usetikzlibrary{decorations.pathreplacing} % define horizontal and vertical braces \newcommand{\horbrace}[4][->]{ \node (#2)[right of=#3]{$#2$}; \draw[#1](#2)--(#3); \draw [decorate,decoration={brace,amplitude=5pt},thick] (#2.south east) -- (#3.south west) node(#4) [black,midway,below=5pt] {$#4$};} \newcommand{\vertbrace}[3]{ \node (#2)[below of=#1]{$#2$}; \draw[->](#2)--(#1); \draw [decorate,decoration={brace,amplitude=5pt},thick] (#1.north east) -- (#2.south east) node(#3) [black,midway,right=5pt] {$#3$};} \begin{document} \begin{tikzpicture}[>=stealth,node distance=1.5cm] \node (P){$P$}; \horbrace[<-]{F}{P}{F'} \vertbrace{F'}{P'}{F''} \horbrace{P''}{F''}{F'''} \vertbrace{F'''}{P'''}{...} \end{tikzpicture} \end{document} Output
[ "stackoverflow", "0055774105.txt" ]
Q: Can't get any packages to work with Laravel Mix I can't figure out how to include JavaScript packages in my Laravel project. I've been trying to install packages, and I can't figure out how it works. For example: Let's say I want to install Bootstrap Confirmation (http://bootstrap-confirmation.js.org/). I install it from my project root folder. $ npm install bootstrap-confirmation2 After that, the package.json file looks like the following. { "private": true, "scripts": { "dev": "npm run development", "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch": "npm run development -- --watch", "watch-poll": "npm run watch -- --watch-poll", "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", "prod": "npm run production", "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" }, "devDependencies": { "axios": "^0.18", "bootstrap": "^4.0.0", "cross-env": "^5.2.0", "jquery": "^3.2", "laravel-mix": "^4.0.7", "lodash": "^4.17.5", "popper.js": "^1.15.0", "resolve-url-loader": "^2.3.1", "sass": "^1.15.2", "sass-loader": "^7.1.0", "vue": "^2.5.17", "vue-template-compiler": "^2.6.10" }, "dependencies": { "@types/bootbox": "^4.4.36", "bootbox": "^5.1.2", "bootstrap-confirmation2": "^4.1.0" } } I then add the package to app.js. require('bootstrap-confirmation2'); And my webpack.mix.js looks like this: const mix = require('laravel-mix'); mix.js('resources/js/app.js', 'public/js') .sass('resources/sass/app.scss', 'public/css'); After that, I run this from my console: npm run dev If I try to use my Bootstrap confirmation package it doesn't work, no errors, nothing. <button class="btn btn-default" data-toggle="confirmation">Confirmation</button> I know the problem is not in the package but in the way I try to install packages and including them in my app.js file that is loaded once I open the app. I checked the 'Network' tab in Chrome dev tools, checked that 'app.js' is loaded, searched the file and the package I installed and included is INSIDE the JS file and it still doesn't work. Any help is appreciated. A: In the terminal run the install: npm install bootstrap-confirmation2 package.json Should now look something like the following. Dependencies are, jQuery, Popper.js (for Bootstrap 4) and of course, Bootstrap 4. "dependencies": { "bootstrap": "^4.3.1", "bootstrap-confirmation2": "^4.1.0", "jquery": "^3.4.0", "laravel-mix": "^4.0.15", "popper.js": "^1.15.0" webpack.mix.js mix.js('resources/js/app.js', 'public/js') .sass('resources/sass/app.scss', 'public/css'); app.css // Variables @import 'variables'; // Bootstrap @import '~bootstrap/scss/bootstrap'; app.js try { window.Popper = require('popper.js').default; window.$ = window.jQuery = require('jquery'); require('bootstrap'); require('bootstrap-confirmation2'); } catch (e) {} In your Blade template/layout: <a class="btn btn-large btn-primary" data-toggle="confirmation" data-title="Open Google?" href="https://google.com" target="_blank">Confirmation</a> At the end of the file, after the closing body tag: </body> <script src="{{ mix('js/app.js') }}"></script> In app.js... $('[data-toggle=confirmation]').confirmation({ rootSelector: '[data-toggle=confirmation]', // other options }); At the terminal: npm run prod Hope that helped.
[ "codereview.stackexchange", "0000114661.txt" ]
Q: Execute every Monday that is not the Monday following last Saturday in month I think the following is good but wondering if it can be simplified or improved. My condition for code execution is the following: It is a Monday AND It is not the Monday following the last Saturday in the month. This is the current sql: DECLARE @now DATETIME = DATEADD(dd,DATEDIFF(dd,'19000101',SYSDATETIME()),'19000101'); IF ( (--is it a monday? SELECT DATEPART(dw,@now) ) = 2 AND (--is it not the monday following the last Saturday of the month? ( SELECT DATEDIFF( DAY, @now-2, DATEADD(MONTH,DATEDIFF(MONTH,0,@now-2)+1,0)-1 ) ) > 6 ) ) BEGIN; ... ... END; A: Sometimes, comments aren't the clearest way to make a script readable: IF ( (--is it a monday? SELECT DATEPART(dw,@now) ) = 2 Consider: declare @MONDAY int; set @MONDAY = 2; if (datepart(weekday,@now) = @MONDAY) Does one need a comment to figure out what's going on? I hope not! This part however: DECLARE @now DATETIME = DATEADD(dd,DATEDIFF(dd,'19000101',SYSDATETIME()),'19000101'); If it wasn't of the @now identifier, I'd wonder what this convoluted assignment intends to do. Why not just do this instead? declare @now date = cast(getdate() as date); I mean, why work with a datetime when clearly you're only interested in the date part from that point on? I find there's way too much whitespace in your code, you need to strike a balance between wall-of-code and air code. Now, changing @now from a datetime to a date will break your code. The @now-2 here: DATEDIFF(DAY, @now-2, DATEADD(MONTH,DATEDIFF(MONTH,0,@now-2)+1,0)-1 ...is illegal because... I would extract that bit of logic into its own variable, for readability's sake, and using a dateadd function there would be no issue with subtracting 2 days from that date.
[ "stackoverflow", "0036683317.txt" ]
Q: Custom list adapter onClick method returning a null view id In creating a custom list adapter to be able to click different elements in a single row entry and start different activities, I ran across a problem where my findViewById() method was returning null. Additionally, only the first item in my ListView calls the onClick method; the other rows don't register clicks. public class CustomListAdapter extends SimpleAdapter implements View.OnClickListener { Context context; TextView habitId; Intent intent; public CustomListAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.habit_entry, null); } TextView tv = (TextView) v.findViewById(R.id.habitTitle); tv.setOnClickListener(this); ImageView iv = (ImageView) v.findViewById(R.id.plus); iv.setOnClickListener(this); return super.getView(position, convertView, parent); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.habitTitle: Log.d("Test", "habitid = " + v.findViewById(R.id.habitId)); break; case R.id.plus: Log.d("Test", "plus clicked"); default: break; } } When the code is run, the habitTitle case of onClick prints D/NULL: habitid = null habit_entry <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:src="@drawable/ic_plus" android:id="@+id/plus" android:scaleType="centerCrop" android:paddingRight="20dp" android:paddingLeft="20dp" android:background="#9bfcff" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/habitId" android:visibility="gone" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="difficulty" android:id="@+id/habitDifficulty" android:gravity="right" android:paddingLeft="15dp" android:layout_alignParentBottom="true" android:layout_alignRight="@+id/habitTitle" android:layout_alignEnd="@+id/habitTitle" android:layout_marginRight="30dp" android:layout_marginEnd="30dp" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@id/plus" android:layout_above="@id/habitDifficulty" android:layout_alignWithParentIfMissing="true" android:text="Your new habits go here!" android:id="@+id/habitTitle" android:padding="5dp" android:textColor="#444444" android:textSize="20sp" android:textStyle="bold" android:layout_alignParentStart="false" android:gravity="right" android:allowUndo="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="frequency" android:id="@+id/habitFrequency" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> </RelativeLayout> call in MainActivity if(habitList.size() != 0) { ListView listView = (ListView) findViewById(android.R.id.list); ListAdapter adapter = new CustomListAdapter( this, habitList, R.layout.habit_entry, new String[]{"habitId", "title", "difficulty", "frequency"}, new int[]{ R.id.habitId, R.id.habitTitle, R.id.habitDifficulty, R.id.habitFrequency}); listView.setAdapter(adapter); } The list populates perfectly, so I'm not sure why I'm having so much trouble with my adapter. A: I see a couple problems here. You are inflating the View yourself and then returning the View returned by calling super.getView(position, convertView, parent);. You should instead rely on super.getView(position, convertView, parent); to create the View for you since you are using the default implementation like this: @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); v.findViewById(R.id.habitTitle) .setOnClickListener(this); v.findViewById(R.id.plus) .setOnClickListener(this); return v; } Also v.findViewById(R.id.habitId)); is returning null inside onClick() because the variable v itself is the TextView with id = R.id.habitId.
[ "stackoverflow", "0061021398.txt" ]
Q: How do I use createProxyMiddleware with the nested logic /node_modules/http-proxy/lib/http-proxy/index.js:120; Error: socket hang up Previous Post: /node_modules/http-proxy/lib/http-proxy/index.js:120; Error: socket hang up I'm trying to use createProxyMiddleware({ target: serviceProvider}) instead of apiProxy.web(req, res, {target: serviceProvider});. The browser hangs and doesn't show anything (I see the spin in the tab though) How do I properly use createProxyMiddleware with the nested codebase like below? Here is the source code. app.get('/source*', function(req, res, next) { req.query.RelayState = req.url; if(req.user) { // if user is authenticated, if(req.originalUrl) { resource_path = req.originalUrl.split('/source')[1]; console.log(req.user['email'] + ' is viewing ' + req.originalUrl); } createProxyMiddleware({ target: serviceProvider}) // apiProxy.web(req, res, {target: serviceProvider}); } else { if(process.env.MODE=='HACK') { createProxyMiddleware({ target: serviceProvider}) // apiProxy.web(req, res, {target: serviceProvider}); } else { passport.authenticate('samlStrategy')(req, res, next); } } }, ); Between, this works: app.get('/source*', createProxyMiddleware({ target: serviceProvider})) A: The problem is that the proxy middleware is created but not actually called and as a result the request hangs. One way to solve this is to create the middleware as you did (but preferably outside the route handler, as it would get created on each request), and then call it with the current express middleware's arguments: const serviceProviderProxy = createProxyMiddleware({target: serviceProvider }); app.get('/source*', (req, res, next) => { req.query.RelayState = req.url; if (req.user) { // if user is authenticated, if (req.originalUrl) { resource_path = req.originalUrl.split('/source')[1]; console.log(req.user['email'] + ' is viewing ' + req.originalUrl); } return serviceProviderProxy.call(serviceProviderProxy, req, res, next); // you need to return here if there's more code below the else block, otherwise return is not needed } else { if(process.env.MODE=='HACK') { return serviceProviderProxy.call(serviceProviderProxy, req, res, next); } else { passport.authenticate('samlStrategy')(req, res, next); } } // potential more code ... });
[ "stackoverflow", "0010514709.txt" ]
Q: finding matching rows in matrix Suppose I have an (m x n) matrix Q, and a row vector r, e.g. Q = [ 1 2 3 ; 4 2 3 ; 5 6 7 ; 1 2 3 ; 1 2 3 ; 1 2 5 ]; r = [ 1 2 3 ]; What is the easiest way to obtain a logical vector (of length m) that indicates which of the rows in Q are identical (for all elements) to the specified row r? In the sample case above, that should be [ 1 0 0 1 1 0 ]; A: You can use ismember and do it in a single line: >> ismember(Q,r,'rows')' ans = 1 0 0 1 1 0 A: all(bsxfun(@eq, r, Q),2)' bsxfun(@eq, r, Q) compares each row and returns a matrix with same size as Q: >> bsxfun(@eq, r, Q) ans = 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 1 0 the all function computes if the result of bsxfun is all true along each row separately. Thus it returns: >> all(ans,2)' ans = 1 0 0 1 1 0 and yeah, there is also a transpose operator ' to match your desired row output
[ "stackoverflow", "0046807403.txt" ]
Q: Minimal Example for dlib SVM using Python/Numpy I need to deploy an SVM in a C++ build target system. Therefore I want to train an SVM using dlib with python/numpy, serialize it and evaluate in the target system. The python documentation for dlib is rather obscure to me, so can anyone help me with this minimal example? import dlib # My data in numpy feature_column_1 = np.array([-1, -2, -3, 1, 2, 3]) feature_column_2 = np.array([1, 2, 3, -1, -2, -3]) labels = np.array([True, True, True, False, False, False]) # Features feature_vectors = dlib.vectors() for feature_column in [feature_column_1, feature_column_2]: feature_vectors.append(dlib.vector(feature_column.tolist())) # Labels labels_array = dlib.array(labels.tolist()) # Train svm = dlib.svm_c_trainer_linear() svm.train(feature_vectors, labels_array) # Test y_probibilities = svm.predict(labels_array_new) I get following error for the training: ---> 18 svm.train(vectors, array) ValueError: Invalid inputs A: I just added an official example for this to dlib. I was surprised to find it wasn't included when I looked. It's available here: https://github.com/davisking/dlib/blob/master/python_examples/svm_binary_classifier.py. Here are the relevant details: import dlib import pickle x = dlib.vectors() y = dlib.array() # Make a training dataset. Here we have just two training examples. Normally # you would use a much larger training dataset, but for the purpose of example # this is plenty. For binary classification, the y labels should all be either +1 or -1. x.append(dlib.vector([1, 2, 3, -1, -2, -3])) y.append(+1) x.append(dlib.vector([-1, -2, -3, 1, 2, 3])) y.append(-1) # Now make a training object. This object is responsible for turning a # training dataset into a prediction model. This one here is a SVM trainer # that uses a linear kernel. If you wanted to use a RBF kernel or histogram # intersection kernel you could change it to one of these lines: # svm = dlib.svm_c_trainer_histogram_intersection() # svm = dlib.svm_c_trainer_radial_basis() svm = dlib.svm_c_trainer_linear() svm.be_verbose() svm.set_c(10) # Now train the model. The return value is the trained model capable of making predictions. classifier = svm.train(x, y) # Now run the model on our data and look at the results. print("prediction for first sample: {}".format(classifier(x[0]))) print("prediction for second sample: {}".format(classifier(x[1]))) # classifier models can also be pickled in the same was as any other python object. with open('saved_model.pickle', 'wb') as handle: pickle.dump(classifier, handle) However, if you want to use C++ you should just use C++. Dlib is primarily a C++ library rather than a python library. The whole point of dlib is to provide a nice C++ API for people who want to do machine learning. So you would be much better off just using C++ for training. There are 99 full C++ examples that come with dlib and complete C++ API documentation. For example, here is a relevant example http://dlib.net/svm_c_ex.cpp.html. I really should emphasise that dlib's C++ API is much more flexible than the python API. Really, the point of dlib is to make machine learning easy in C++, the python API for dlib is an afterthought. In fact, there are a lot of features of dlib that are expressed using things like C++ templates which have no possible correlate in Python (e.g. since python has nothing like C++ templates) and so these features are not exposed to python. So really, if you want to use C++ then use C++. There is no reason to use the Python API if you know how to write C++.
[ "stackoverflow", "0039494345.txt" ]
Q: Retrieving received SMS with iOS 10 Messages API Is there a way I can retrieve received messages and save them in a host app using an iMessage extension ? A: Absolutely no way. This is a question of privacy, Apple will never let any extension read/save messages from users. https://developer.apple.com/videos/play/wwdc2016/224/ : Apple is very, very concerned about user privacy and we really very highly value the privacy of our customers, so we don't expose contact information at all to iMessage apps. The only thing you can do, is retrieving messages sent via your iMessage extension, within certain conditions (if the user has selected the message for instance)
[ "stackoverflow", "0043860603.txt" ]
Q: Create multiple background using SASS mixin I'm trying to create a mixin in Sass to generate multiple background, problem is the number of background is unknow, it's can be 3, 4 or even 5. Here what I try and fail. @mixin multiBg($page: index, $sec: sec01,$from: 1, $to: 3, $type: jpg){ $url: (); // i'm try to create a empty array first $newUrl: null; // and an empty variable @for $i from $from through $to { $newUrl: append($url, url(../img/#{$page}/#{$sec}_bg0#{$i}.#{$type})); // then append value to variable; } background: $newUrl; } #sec05 { @include multiBg(index,sec05); } current output: background: url(../img/index/sec05_bg03.jpg); expected output: background: url(../img/sec05_bg01.jpg),url(../img/sec05_bg02.jpg), url(../img/sec05_bg03.jpg); I don't know how to fix this problem since i'm still learing SASS. Can someone enlighten me please. A: You're on the right track! But your syntax and logic are slightly off. Here's what I came up with: @mixin multiBg($page: index, $sec: sec01, $from: 1, $to: 5, $type: jpg) { $url_list: (); @for $i from $from through $to { // I broke constructing the url and adding it to the set into two steps here. // We could do this all at once, but separating it can make it easier to read. // First, generate the url. $url_string: url(../img/#{$page}/#{$sec}_bg0#{$i}.#{$type}); // Then add it to the list (the 'comma' part is important) $url_list: append($url_list, $url_string, comma); } // Done looping? Output the final list! background-image: $url_list; } That seems to return what you're looking for. Here are the official docs on list functions - I always forget one or two, may be useful for you too. Also, since you mentioned you're new to sass - check out Sassmeister if you haven't already. It's a handy little sandbox for quickly prototyping and trying things out in sass; similar to Codepen but a bit more specialized. It's what I used to experiment with this question.
[ "meta.stackoverflow", "0000385708.txt" ]
Q: Rename [free] to [free-memory] Somewhat related to this question, but that one was asking for a disambiguation. free is still being misused on the edges. The core concept is on-topic, but the tag name itself is too vague. People use it for anything free, including software shipping booking dates heap space (not memory related) free-memory makes more sense. The vast majority are talking about this programming concept and it goes beyond malloc. This way it can stop being misused. A: On the tag name: as you know, the primary, C meaning concerns an ubiquitous function called free. As far as that is concerned, free is a crystalline tag name. From that point of view, free-memory is a substantially worse alternative: it looks awkward (like a Wikipedia disambiguation title -- "Free (memory)" -- but without the parentheses) and reads ambiguously (is "free" a verb or an adjective?). On misuse: from a quick look at the question feed, I count six (1, 2, 3, 4, 5, 6) blatantly mistagged questions among the last hundred free questions, spanning a period of six months -- and at least half of those should have been closed. Is that significant misuse? Maybe. Is it significant enough to justify changing the tag to a substantially worse name? Probably not. All in all, I tend to agree with Hans on this change not being worth the trouble -- with the caveat that a strong consensus in the other direction among C and C++ contributors (who presumably do the brunt of the curation in this tag) should suffice to override my concerns.
[ "math.stackexchange", "0000960311.txt" ]
Q: Trying to understand negation of quantifiers Trying to understand the negation of the following: For this: ∀x~P(x) I have this as negation: ~∃xP(x) For this: ~∃x(∀yP(y) Λ Q(x)) I have this: ∀x(~∃yP(y) V ~Q(x)) Are these correct? If not please provide the right negation Moving the negation signs: ∃x~P(x) ☰ ~∃xP(x)? ∀x(~∃yP(y) V ~Q(x)) ☰ ∀x~(∀yP(y) Λ Q(x)) ☰ ~∃x(∀yP(y) Λ Q(x))?? Are the above still equivalent? A: $\forall x.\neg P(x)$ and $\neg \exists x.P(x)$ are not each other's negations -- on the contrary they are equivalent. If you negate $\forall x.\neg P(x)$ you get either $\neg\forall x.\neg P(x)$ which is equivalent to $\exists x.P(x)$. $\exists x.\neg P(x)$ is not equivalent to $\neg\exists x.P(x)$. $\exists x.\neg P(x)$ is equivalent to $\neg\forall x.P(x)$. When you move a negation through a quantifier, the quantifier changes from $\exists$ to $\forall$ or vice versa.
[ "stackoverflow", "0017405012.txt" ]
Q: Reference for iOS app design I want to learn objective C and adapt to xcode. I also want a reference with tutorials and examples to help me improve and become faster at ios app development. I am wasting too much time even for simple syntax errors. As there are several sources, I am quiet confused. I have good C/C++ and C# background. I have significant UI design experience. I can also adapt well to open source libraries as I worked with opencv, opencvsharp, gtkmm, and qt for a long time. However, couldn't adapt to obj. C easily. Where to start? A: Best way to learn is (since you have massive programming experience), Play with XCode a while. Create a view based, tabbed, master-view application. See how xcode create the background code etc. Learn Xcode - how Interface builder and storyboard works. How to link UI components with generated class files. 2.1. Learn more about common UIComponents - UIView, Tabbar, TableView, SplitView etc. Syntax of Objective c, message passing, property etc. This tutorial is kinda popular and good, http://www.raywenderlich.com/tutorials Books: To start with UI concept, Beginning iPhone Development is best to me. Further you learn more about objective c in Programming in objective c Apple tutorials on different topics, https://developer.apple.com/videos/wwdc/2010/ https://developer.apple.com/videos/wwdc/2011/ https://developer.apple.com/videos/wwdc/2012/ https://developer.apple.com/videos/wwdc/2013/
[ "math.stackexchange", "0002770215.txt" ]
Q: The meaning of notation $[A : B]$ when $A$ and $B$ are matrices While reading an article [1], I encountered notation that I couldn't decipher: $[A : B]$, where $A$ and $B$ are both $n \times n$ real matrices. The following statement was also given (if that helps): If $[A : B]$ has full rank $a \in \ker A^T$ and $a \in \ker B^T$ implies $a = 0$. What does $[A : B]$ mean? [1]: Jesús Rodríguez and Kristen Kobylus Abernathy: On the solvability of nonlinear boundary value problems A: That's an augmented matrix. It's the $n\times2n$ matrix you get from putting $A$ and $B$ next to one another and interpret it as a single matrix.
[ "mathematica.stackexchange", "0000095434.txt" ]
Q: Problem in solving a simple Laplace equation I am trying to solve the following Laplace PDE in MMA: $$\frac{\partial^2 T}{\partial x^2}+\frac{\partial^2 T}{\partial z^2}=0$$ subject to the boundary conditions: $$\frac{\partial T}{\partial z}|_{z=0}=0,$$ and, at $z=1$ $$-\frac{\partial T}{\partial z}+A=BT,$$ This is my code: DSolve[{D[T[x, z], {x, 2}] + D[T[x, z], {z, 2}] == 0, (D[T[x, z], z] /. {z -> 0}) == 0, -(D[T[x, z], z] /. {z -> 1}) + A == B T[x, 1]}, T[x, z], {x, z}] But it just repeats my equation. Thank you for kindly help in advance! A: There is a problem about your solution, it is that DSolve cannot handle it and, therefore, returns you the input unevaluated, as a signal. So, what you can do, if you do not want to solve it analytically (seems a simple task, does not it?) you might want to solve it numerically, that is, using NDSolve. This, of course, will reguire from you to somehow fix the values of A and B, otherwise, however, it can be solved. Try this: A = 1; B = 2; << NDSolve`FEM` mesh = ToElementMesh[Rectangle[{0, 0}, {1, 1}]]; nv1 = NeumannValue[A - B*T[x, z], z == 1]; nv2 = NeumannValue[0, z == 0]; dc = DirichletCondition[T[x, z] == 1, x == 0]; sl = NDSolve[{D[T[x, z], {x, 2}] + D[T[x, z], {z, 2}] == nv1 + nv2, dc}, T[x, z], {x, z} \[Element] mesh] (* {{T[x, z] -> InterpolatingFunction[{{0., 1.}, {0., 1.}}, <>][x, z]}} *) To have a look at the solution evaluate this: Plot3D[T[x, z] /. sl[[1, 1]], {x, z} \[Element] mesh, ImageSize -> 300] which should look as follows: Take into account that I added a Dirichlet condition dc = DirichletCondition[T[x, z] == 1, x == 0]; otherwise there is nothing to look at in the solution, as it was. Have fun! A: Another problem easy to do by separation of variables. However, BC's on x are definitely required to solve the problem. The assumption of exp[i a x] requires BC's that make sinusoidal solutions in x. pde = D[T[x, z], x, x] + D[T[x, z], z, z] == 0; With the BC's you give I add 2 more for x. The ones I chose will give sinusoidal solutions. You, of course can choose others bc1 = T[0, z] == 0; bc2 = T[1, z] == 0; bc3 = (D[T[x, z], z] /. z -> 0) == 0; bc4 = (D[T[x, z], z] /. z -> 1) == A - B T[x, 1]; Separate T in the form T[x_, z_] = X[x] Z[z]; pde/T[x, z] // Apart (* D[X[x],x,x]/X[x]+D[Z[z],z,z]/Z[z]==0 *) One terms is dependent on x, the other z, so each must be equal to a constant. xeq = D[X[x], x, x]/X[x] == -alpha^2 X[x_] = (X[x] /. DSolve[xeq, X[x], x][[1]]) /. {C[1] -> c1, C[2] -> c2}; zeq = D[Z[z], z, z]/Z[z] == alpha^2 Z[z_] = (Z[z] /. DSolve[zeq, Z[z], z][[1]]) /. {C[1] -> c3, C[2] -> c4} (* c3 E^(alpha z)+c4 E^(-alpha z) *) From the z BC's, it is obvious we want hyberbolics rather than exponentials. (Z[z] // ExpToTrig) // Collect[#, {Sinh[alpha z], Cosh[alpha z]}] & (* (c3-c4) Sinh[alpha z]+(c3+c4) Cosh[alpha z] *) Z[z_] = % /. {c3 - c4 -> c3, c3 + c4 -> c4}; (* c3 Sinh[alpha z] + c4 Cosh[alpha z] *) Apply the BC's bc1 (* c1 (c3 Sinh[\[Alpha] z] + c4 Cosh[\[Alpha] z]) == 0 *) From which c1 = 0 T[x, z] (* c2 Sin[alpha x] (c3 Sinh[alpha z] + c4 Cosh[alpha z])*) Combine constants c2 = 1; bc2 (* Sin[alpha] (c3 Sinh[alpha z] + c4 Cosh[alpha z]) == 0 *) From which alpha = n Pi with n required to be $Assumptions = n \[Element] Integers && n > 0; bc3 (* Pi c3 n Sin[Pi n x]==0 *) From which c3 = 0; bc4 // Simplify (* c4 Sin[Pi n x] (B Cosh[Pi n]+Pi n Sinh[Pi n])==A *) Use orthogonality to solve for c4 Integrate[%[[1]] Sin[n Pi x], {x, 0, 1}] == Integrate[%[[2]] Sin[n Pi x], {x, 0, 1}]; c4 = c4 /. Solve[%, c4][[1]] T[x, z] (*-((2 A ((-1)^n - 1) Sin[Pi n x] Cosh[Pi n z])/(Pi n (B Cosh[Pi n] + Pi n Sinh[Pi n]))) *) The actual T will be an infinite series in n, but obviously from the form of the solution, the even n terms are 0. In order to not compute the 0 terms we can do the following: Tn[x_, z_] = (T[x, z] /. n -> 2 m - 1) /. m -> n // Simplify (*(4 A Sin[Pi (2 n-1) x] Cosh[Pi (2 n-1) z])/(Pi (2 n-1) (B Cosh[Pi-2 Pi n]+Pi (2 n-1) Sinh[Pi (2 n-1)]))*) The general solution is the above summed from n = 1 to infinity. To make a plot: tn = Function[n, #] &@Tn[x, z]; Assign A and B some values. A = 1; B = 2; Tterms[k_] := Compile[{x, z}, #] &@Total@tn@Range[k] T = Tterms[50]; Plot3D[T[x, z], {x, 0, 1}, {z, 0, 1}, AxesLabel -> {"x", "y", "T"}]
[ "stackoverflow", "0027871415.txt" ]
Q: UPU S-10 standard, regular expression for capturing the tracking code from postal companies What's the regular expression that can capture tracking code from postal companies belonging to UPU based on the S-10 standard. A: UPU (Universal Postal Union), and its members uses a tracking code which consists of 3 parts. The first part is Two letters, the first one of them represents the service that is being used. The only acceptable letters are «A» - Mail is not insured (less than 2 kg) «R» - Registered Mail (less than 2 kg) «V» - Registered Mail (Insured)(less than 2 kg) «C» - Ordinary Parcel (more than 2 kg) «L» - Airmail E-packet (less than 2 kg) «E» - Express Mail Service (EMS more than 2 kg) the second letter can be anything from the Latin alphabet. The second part is 9 digits with the last one being the check digit of their algorithm. The third and last part is two letters that correspond to the country based on ISO 3166-1. I was searching high and low to create a regex that will capture this particular string of characters. I making this post for anyone may looking out for it. /(?:^[aArRvVcClLeE][a-zA-Z]\d{9}(A(D|E|F|G|I|L|M|N|O|R|S|T|Q|U|W|X|Z)|B(A|B|D|E|F|G|H|I|J|L|M|N|O|R|S|T|V|W|Y|Z)|C(A|C|D|F|G|H|I|K|L|M|N|O|R|U|V|X|Y|Z)|D(E|J|K|M|O|Z)|E(C|E|G|H|R|S|T)|F(I|J|K|M|O|R)|G(A|B|D|E|F|G|H|I|L|M|N|P|Q|R|S|T|U|W|Y)|H(K|M|N|R|T|U)|I(D|E|Q|L|M|N|O|R|S|T)|J(E|M|O|P)|K(E|G|H|I|M|N|P|R|W|Y|Z)|L(A|B|C|I|K|R|S|T|U|V|Y)|M(A|C|D|E|F|G|H|K|L|M|N|O|Q|P|R|S|T|U|V|W|X|Y|Z)|N(A|C|E|F|G|I|L|O|P|R|U|Z)|OM|P(A|E|F|G|H|K|L|M|N|R|S|T|W|Y)|QA|R(E|O|S|U|W)|S(A|B|C|D|E|G|H|I|J|K|L|M|N|O|R|T|V|Y|Z)|T(C|D|F|G|H|J|K|L|M|N|O|R|T|V|W|Z)|U(A|G|M|S|Y|Z)|V(A|C|E|G|I|N|U)|W(F|S)|Y(E|T)|Z(A|M|W)))$/s More about the S-10 standard can be found here.
[ "stackoverflow", "0059145875.txt" ]
Q: Sidebar nav don't work with angular and materialize css I'm starting with Angular and I want to use SidebarNav and Dropdown to set up a practical and responsive menu but it's not working. I installed and configured angular2-materialize and materialize-css by the CLI. I created a component named "Navbar" to contain the menu and performed the following process: app.module.ts import 'materialize-css'; // import * as M from 'materialize-css/dist/js/materialize'; import { MaterializeModule } from 'angular2-materialize'; @NgModule({ // ... , imports: [ // ... , // M, MaterializeModule ], }) but he keeps returning this error: Uncaught Error: Couldn't find Materialize object on window. It is created by the materialize-css library. Please import materialize-css before importing angular2-materialize. The solutions I found here in the forum were unfortunately not useful to me. A: angular2-materialize use materialize version '0.100.2'. In your package.json change materialize-css to "^0.100.2". Then run npm install.
[ "superuser", "0000983139.txt" ]
Q: Why is FAT32 limited to just under 2^28 clusters? With FAT16 the maximum partition size is 2GB when your maximum cluster size is 32K. This is calculated by multiplying the number of addressable units by the cluster size. (216 Allocation units) * (215 bytes/cluster) = 2 GiB However with FAT32, when I do the same calculation I get a much larger number than the 8 TiB maximum when using 232 clusters. (232 Allocation units) * (cluster size) If I use a cluster size of 512 bytes, I've already arrived at 2 TiB. In an XP TechNet article, Microsoft says The maximum possible number of clusters on a FAT32 volume is 268,435,445, and there is a maximum of 32 KB per cluster, along with the space required for the file allocation table (FAT). This puts the maximum cluster size at 228 - 11. Why is the maximum number of clusters in FAT32 228-11 and not 232, given that it was 216 in FAT16? A: FAT32 only uses 28 bits not 32. Four bits are "reserved for future use". So, a FAT32 partition has a maximum cluster count of 268,435,455 (228-1) Reference Although VFAT was a clever system, it did not address the limitations of FAT16. As a result, a new file system (and not just better FAT management as was the case with VFAT) appeared with Windows 95 OSR2. This file system, called FAT32 uses 32-bit values for the FAT entries. In fact, only 28 bits are used, as 4 bits are reserved for future use. With the appearance of the FAT32 file system, the maximum number of clusters per partition went increased from 65535 to 268,435,455 (228-1). FAT32 thus allows much bigger partitions (up to 8 terabytes). Although the maximum theoretical size of a FAT32 partition is 8 TB, Microsoft has voluntarily limited it to 32 GB on Windows 9x systems to promote NTFS
[ "vegetarianism.stackexchange", "0000001328.txt" ]
Q: Is body building feasible for vegetarians? Every athlete and bodybuilder talks about regimes and diets that are non-vegetarian. Is it possible for vegetarians to beat a non-vegetarian diet? If yes, how? What are the replacements of high-protein foods and supplements that one would use? PS: Thanks everyone for the answers. It would be great if you could suggest me some food. I have tried chickpea, kidney beans, gram and such kind of lentils but I feel gas sometimes. Is there a better option or the way it should be consumed that gas can be prevented? A: You totally can be a vegetarian and a body builder. I am a body builder for 35 years and a vegetarian for about 7 or 8 years. I feel much better meatless and my workouts have never suffered. There are good sources of plant based protein meals out there, like potatoes and corn or rice and black beans. In combination these meals have a complete amino acid profile. Plus you can get extra protein from plant based raw protein powder. I am very happy with the one from Sunwarrior (rice, chia, pea, quinoa and amaranth). Comes as blends or only rice protein. All in raw food quality and sweetened with stevia.
[ "ru.stackoverflow", "0000521702.txt" ]
Q: Как создать данную HTML-таблицу без ошибки валидации? Есть простенькая табличка HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Таблицы</title> <style> table { border: 1px solid #000; border-spacing: 10px; } table td, table th { border: 1px solid #ccc; text-align:center; padding:10px; background-color: #e5e5e5; } </style> </head> <body> <table> <caption>Таблица 5</caption> <tr> <td colspan="4">1</td> </tr> <tr> <td colspan="2">5</td> <td>7</td> <td>8</td> </tr> <tr> <td colspan="2">9</td> <td colspan="2" rowspan="2">11</td> </tr> <tr> <td>13</td> <td>14</td> </tr> </table> </body> </html> Почему валидатор выдаёт ошибку? Помогите разобраться. Error: Table column 4 established by element td has no cells beginning in it. From line 23, column 13; to line 24, column 28 <tr>↩ <td colspan="4">1</td> A: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>!DOCTYPE</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <table border="1" width="90%" style="margin:auto; min-height:400px;"> <tr> <td colspan="6"></td> </tr> <tr> <td colspan="2"></td> <td colspan="2"></td> <td colspan="2"></td> </tr> <tr> <td colspan="6"></td> </tr> </table> </body> </html> вот это прошло валидацию w3.org , Doctype имеет очень большую роль
[ "stackoverflow", "0011302954.txt" ]
Q: Rails layout per controller I have a home controller and a news controller. I want both of these controller to use the application.html.erb layout file and in addition to that, for home, use the home layout and news, use the news layout. and then render a specific view. Is this possible in rails? In other words, I don't want to specify a layout per view, but per controller, both inheriting from application.html.erb layout. What i want to do is remove the redundancy of adding the top navigation bar and including javascript/css in every single layout file. I'd rather include that in one file, and do controller specific layout with another layout, and then finally render the view. Thanks A: You can tell a controller to use a specific layout, eg class HomeController < ApplicationController layout 'home' end class NewsController < ApplicationController layout 'news' end These will expect the layouts in app/views/layouts/home.html.erb etc A: class ProductsController < ApplicationController layout "inventory" #... end http://guides.rubyonrails.org/layouts_and_rendering.html
[ "stackoverflow", "0031771420.txt" ]
Q: Loading another page into DIV Function .load doesn't work on Chrome on localhost (with Xampp). On JsFiddle nothing happens if I run the button. My goal is on load to DIV id="lista_ogol" another page. Is it possible? Thanks for every help, if my code is messy let me know what to change. Here is my html code: <ul> <div id="lista_ogol" class="lista"> <li><a id="rejestracjaID" href="javascript:void(0)" >Rejestracja</a></li> <li><a href="logowanie.php">Logowanie</a></li> </div> </ul> Here is my Js script: jQuery(function(){ jQuery('#rejestracjaID').click(function(){ jQuery('#lista_ogol').load('logowanie.php', function(){alert('Content Successfully Loaded.')} ); }); }) A: You need to include jquery script in your html file. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> Make sure you put this in the <head> of your document, or above the script you use to load the PHP page.
[ "english.stackexchange", "0000359424.txt" ]
Q: What is so bad about puns? Many times I've heard of 'pun intended' or 'pun not intended', which I see as a form of excuse in the English-spoken world. However, I can not wrap my head around why are you constantly excusing/explaning something so innocent(?) as pun. What I am giving off constantly saying 'pun intended'? What's the purpose of constantly saying 'pun (not) intended'? We don't excuse puns in my native language, in my country, we just laugh it off. A: It's not generally to excuse a pun, but to draw attention to it. Sometimes "no pun intended" is an edit, or when the author/speaker realised an accidental pun (and in the case of writing decided to leave it in). In speech sometimes the accidental pun (or indeed any humour) may be inappropriate but it can't be edited out once said. In that case an excuse may be needed. Sometimes puns are regarded as a low form of humour when planned, so "no pun intended" can mean "that just came out by itself" and may not be true. Other times they can be rather subtle and "(no) pun intended" highlights the wordplay and gives a pause to process it. There are some cases in which it is used to excuse a pun: In technical writing the choice of terminology can be very restricted — everyday synonyms can mean completely different things. In this case the best phrasing may well lead to an inadvertent pun that is kept and the reader is asked to ignore it. A: However, I can not wrap my head around why are you constantly excusing/explaning something so innocent(?) as pun. [...] We don't excuse puns in my native language, in my country, we just laugh it off. I think you might be slightly overthinking how much we actually care about puns. You've probably seen references to puns in internet comments, mostly because that's an informal context and because it's easier to make puns using written language. But in "the real world" you won't hear people referring to puns nearly as often as you do on the internet. This is a non-issue for us, just like it's a non-issue in your native language. I will say that this depends entirely on context. Obviously you wouldn't include a bunch of puns in a speech you're giving at a funeral or at an important work meeting, but that's probably true in your native language as well. A: Dispensing with Distraction Mostly I think it is the speaker saying either I’m clever, I spotted the accidental pun or else I’m funny, I made a pun, but there is a possible third reason: distraction. Puns can be distracting, provoking internal questions such as: Was it deliberate or not? Did they realise? Does this guy think he’s funny? If people start thinking about questions like those about the pun, they may become so distracted by that pun that they may then lose the thread of whatever was being discussed. By acknowledging the pun, this gives everyone a chance see, appreciate, and instantly forget it so that everyone can concentrate on the actual substance of whatever is being said.
[ "stackoverflow", "0012435812.txt" ]
Q: ButtonField doesn't appear in HorizontalFieldManager I have added a buttonField into a HorizontalFieldManager in Blackberry app. I added it after adding an EditField. Yet the buttonField doesnt appear. Below is my code HorizontalFieldManager hfm = new HorizontlFieldManager(); BasicEditField edit = new BasicEditField("Label", "UP"); ButtonField button = new ButtonField("Search"); hfm.add(edit); hfm.add(button); add(hfm); A: This answer won't solve your problem, but it is important to note that your code is absolutely fine, and there's nothing wrong with it. HorizontalFieldManager class is full of bugs introduced in OS 5.0 and as for today (latest version are 7.x) RIM has shown no intention whatsoever of fixing it. As a sample, here's a bug issue in BB Developer Issue Tracker and still unresolved. I've had to deal with hfm in my latest project and also faced issues I had to workaround by creating my own manager, in a similar way as Shashank's answer shows. You can find more examples on creating a custom manager in SO. Also here are covered the basics. This is currently the only solution, since RIM is transitioning to BB 10 (C++), and they are dumping the Java API, so don't expect them to fix it anytime soon. Even if they were, it won't be fixed but on the latest OS version, which is useless since BB devices are rarely upgraded.
[ "math.stackexchange", "0001828775.txt" ]
Q: Prove $\forall n \in \mathbb{N}: \int_{0}^{\frac{\pi}{2}} |\frac{\sin(nx)}{x}|dx \geq \frac{2}{\pi}\sum_{k=1}^{n}\frac{1}{k}$ As my further preparation to Putnam competition, I came across such inequality to prove: $$\forall n \in \mathbb{N}: \int_{0}^{\pi} \left|\frac{\sin(nx)}{x}\right|dx \geq \frac{2}{\pi}\sum_{k=1}^{n}\frac{1}{k}$$ The problem is that I got stuck in spite of spending by far 6 days on this problem! Because I got really stuck, I am very determined to see how to prove such inequality. Help very, very appreciated! A: We may start from: $$ A_k = \int_{0}^{\pi}\frac{\sin x}{x+k\pi}\,dx = \int_{0}^{\pi/2}\sin(x)\left(\frac{1}{x+k\pi}+\frac{1}{\pi-x+k\pi}\right)\,dx$$ and notice that $f_k(x)=\frac{1}{x+k\pi}+\frac{1}{\pi-x+k\pi}$ is decreasing on $\left[0,\frac{\pi}{2}\right]$, hence: $$ A_k \geq \int_{0}^{\pi/2} \sin(x)\,f_k\left(\frac{\pi}{2}\right)\,dx = \frac{4}{(2k+1)\pi}\geq \frac{4}{(2k+2)\pi}=\frac{2}{\pi}\cdot\frac{1}{k+1}.$$ Then we may notice that: $$ \int_{0}^{\pi}\left|\frac{\sin(nx)}{x}\right|\,dx = \sum_{k=0}^{n-1}A_k \geq \color{red}{\frac{2}{\pi} H_n} $$ as wanted. My approach indeed proves a slightly stronger inequality, i.e.: $$ \int_{0}^{\pi}\left|\frac{\sin(nx)}{x}\right|\,dx \geq \frac{2}{\pi}\sum_{k=1}^{n}\frac{1}{k\color{red}{-\frac{1}{2}}}.$$ A: We have $$\begin{align} \int_{0}^{\pi}\left|\frac{\sin\left(nx\right)}{x}\right|dx\stackrel{nx=v}{=} & \int_{0}^{n\pi}\left|\frac{\sin\left(v\right)}{v}\right|dv \\ = & \sum_{k=0}^{n-1}\int_{k\pi}^{\left(k+1\right)\pi}\left|\frac{\sin\left(v\right)}{v}\right|dv \\ = & \sum_{k=0}^{n-1}\left(-1\right)^{k}\int_{k\pi}^{\left(k+1\right)\pi}\frac{\sin\left(v\right)}{v}dv \\ \geq & \frac{1}{\pi}\sum_{k=0}^{n-1}\frac{\left(-1\right)^{k}}{k+1}\int_{k\pi}^{\left(k+1\right)\pi}\sin\left(v\right)dv \\ = & \frac{1}{\pi}\sum_{k=0}^{n-1}\frac{\left(-1\right)^{k}\left(-\cos\left(\left(k+1\right)\pi\right)+\cos\left(k\pi\right)\right)}{k+1} \\ = & \frac{2}{\pi}\sum_{k=0}^{n-1}\frac{1}{k+1}. \end{align}$$ Note that the third line is positive since $\sin\left(x\right)<0 $ if $x\in\left(k\pi,\left(k+1\right)\pi\right) $ and $k$ odd. And $$-\cos\left(\left(k+1\right)\pi\right)+\cos\left(k\pi\right)=2\left(-1\right)^{k}. $$
[ "gaming.stackexchange", "0000320132.txt" ]
Q: Minecraft on ARM Chromebook Error: no lwjgl in java.library.path I am trying to run Minecraft on my ARM Asus Chromebook C201 with XFCE Linux. I followed this post and this post (to make the Java Wrapper), and my Minecraft is crashing with this error Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path. Full crash report is: Java HotSpot(TM) Client VM warning: Using incremental CMS is deprecated and will likely be removed in a future release Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867) at java.lang.Runtime.loadLibrary0(Runtime.java:870) at java.lang.System.loadLibrary(System.java:1122) at org.lwjgl.Sys$1.run(Sys.java:72) at java.security.AccessController.doPrivileged(Native Method) at org.lwjgl.Sys.doLoadLibrary(Sys.java:66) at org.lwjgl.Sys.loadLibrary(Sys.java:96) at org.lwjgl.Sys.<clinit>(Sys.java:117) at bib.I(SourceFile:2825) at net.minecraft.client.main.Main.main(SourceFile:38) Java HotSpot(TM) Client VM warning: Using incremental CMS is deprecated and will likely be removed in a future release Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867) at java.lang.Runtime.loadLibrary0(Runtime.java:870) at java.lang.System.loadLibrary(System.java:1122) at org.lwjgl.Sys$1.run(Sys.java:72) at java.security.AccessController.doPrivileged(Native Method) at org.lwjgl.Sys.doLoadLibrary(Sys.java:66) at org.lwjgl.Sys.loadLibrary(Sys.java:96) at org.lwjgl.Sys.<clinit>(Sys.java:117) at bib.I(SourceFile:2825) at net.minecraft.client.main.Main.main(SourceFile:38) And my java_wrapper is: #!/bin/bash ARGS=$@ echo $ARGS > /tmp/args_original #uncomment for debugging JAVA=$HOME/proprietary_java/jdk1.8.0_151/bin/java JAVA_LIB_SETTING="-Djava.library.path=" JAVA_LIB_PATH="$HOME/MC_libs" MC_ORIG_LWJGL="$HOME/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar" MC_ORIG_LWJGL_UTIL="$HOME/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.4-nightly-20150209/lwjgl_util-2.9.4-nightly-20150209.ja$ MC_ARM_LWJGL="$HOME/proprietary_java/MC_libs/lwjgl.jar" MC_ARM_LWJGL_UTIL="$HOME/proprietary_java/MC_libs/lwjgl_util.jar" ARGS=$(echo $ARGS | sed "s|$MC_ORIG_LWJGL|$MC_ARM_LWJGL|g" | sed "s|$MC_ORIG_LWJGL_UTIL|$MC_ARM_LWJGL_UTIL|g" ) ARGS=$(echo $ARGS | sed "s|-Djava.library.path=[a-zA-Z0-9_\/\\\.-]\+|$JAVA_LIB_SETTING$JAVA_LIB_PATH |g") #magic ;-) # the magic seems to eat the space-character though; this is why it's added after JAVA_LIB_PATH (I'm not good at regex) #"[a-zA-Z0-9_\/\\\.-]\+" explained: # match a-z and A-Z and 0-9 and '_' and '/' and '\' and '.' and '-' (this must be at the end it seems). # "\+": escape the '+'; match this pattern multiple times. # (this means: start at "-Djava.library.path=" and stop replacing at the first space that occurs) #echo $ARGS > /tmp/args_modified #uncomment for debugging $JAVA $ARGS ARGS=$@ #echo $ARGS > /tmp/args_original #uncomment for debugging JAVA=/usr/java/jdk1.8.0_151/bin/java JAVA_LIB_SETTING="-Djava.library.path=" JAVA_LIB_PATH="$HOME/MC_libs" Thanks for any help! :) A: You mentioned following the link from forum.lwjgl.org, which mentions that you had to compile an ARM version of that library yourself. Was this successful? Did you have issues at any point in that process? I followed the links on that same site (http://forum.lwjgl.org/index.php?topic=5494.0) down the rabbit hole until I managed to sort-of get it to work in Crouton with XFCE on my ASUS Chromebook. It was painfully slow because there is no hardware acceleration under Crouton. TL;DR: Yes, it probably still can be done if you manage to compile LWJGL for ARM and get the loader to use your version, but it is probably going to be much slower than you think it will be.
[ "stackoverflow", "0037065438.txt" ]
Q: Neo4j session.query throwing NoSuchMethodError I am using neo4j OGM to fire plain CQL queries using the session.query method provided. The code is as follows: String findPersonCql ="MATCH (p:PersonNode) return p"; session = Neo4jOGMSessionFactory.getInstance().getNeo4jSession(); transaction = session.beginTransaction(); session.query(findPersonCql,Collections.EMPTY_MAP); transaction.commit(); An exception is being thrown as follows: Exception in thread "grpc-default-executor-0" java.lang.NoSuchMethodError: org.neo4j.ogm.model.RestModel.getValues()[Ljava/lang/Object; at org.neo4j.ogm.context.RestModelMapper.map(RestModelMapper.java:55) at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.query(ExecuteQueriesDelegate.java:97) at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.query(ExecuteQueriesDelegate.java:76) at org.neo4j.ogm.session.Neo4jSession.query(Neo4jSession.java:313) We are using gradle dependencies as follows: compile 'org.neo4j:neo4j-ogm:2.0.0' compile "org.neo4j:neo4j-ogm-core:2.0.0-M01" compile "org.neo4j:neo4j-ogm-http-driver:2.0.1" Please let me know if I am missing something. Thanks Updated. A: You appear to have various versions included- 2.0.0, 2.0.0-M01 and 2.0.1! There's no more a dependency called neo4j-ogm. Instead, use compile 'org.neo4j:neo4j-ogm-core:2.0.1' and compile 'org.neo4j:neo4j-ogm-http-driver:2.0.1' See http://neo4j.com/docs/ogm/java/stable/#_dependencies_for_the_neo4j_ogm
[ "tex.stackexchange", "0000192735.txt" ]
Q: biblatex: cite without affecting sorting order I want citations in numerical style sorted in order of appeareance, using biblatex. BUT: I want to have citations before the mainmatter, e.g., in nomenclature or on the title back page, without affecting the sort order (meaning my titleback citation should not necessarily be [1]). All citations will appear again in the mainmatter. Can I achieve that with biblatex? For example, with a command that ... allows to cite but is invisible to "order of appearance", or a command to reset the list of citations before the mainmatter? MWE: (citations in the "mainmatter" should be [1] ... [4]) \documentclass{article} \usepackage[ style=numeric, sorting=none ]{biblatex} \addbibresource{biblatex-examples.bib} \begin{document} The title picture shows the original cover of Aristotles' poetics \cite{aristotle:poetics}. \\ Nomenclature: four --- said by Augustine \cite{augustine}. \\ Mainmatter: \\ Aksin~\cite{aksin} says one in his article. Aristotle~\cite{aristotle:poetics} says two in his book. Angenendt~\cite{angenendt} says three in his article. And Augustine \cite{augustine} says four in his book. \printbibliography \end{document} edit: found an ugly hack, but does not really count as solution: I inserted \makeatletter \immediate\write\@mainaux{\@percentchar mainmatterstartshere} \makeatother where the mainmatter starts, and used an external script to kill all \citation{...} commands from the aux file in front of that before running bibtex (except the \citation{biblatex-control} which does not seem like a good idea). A: Here's a solution, and although it requires some manual intervention it is much less hacky than your external script solution. Furthermore, as I show at the end, we can automate it quite easily. The solution involves (ab)using the \mancite command from biblatex, which provides a means for manual citation for schemes using ibid etc. The trick is that if on your first compilation (before running biber) you use \mancite in your front matter, you can then in subsequent compilations redefine it to be \cite and the correct numbers from the main matter will be used. The only downside is remembering to do this, but since this is really something that only matters for the final compilation of your document, it's probably not too much of a problem. Alternatively, you can automate the whole process using arara. \documentclass{article} \usepackage[ style=numeric, sorting=none, ]{biblatex} \let\mancite=\cite % comment this line out for your initial compilation \addbibresource{biblatex-examples.bib} \begin{document} The title picture shows the original cover of Aristotles' poetics \mancite{aristotle:poetics}. Nomenclature: four --- said by Augustine \mancite{augustine}. Mainmatter: Aksin~\cite{aksin} says one in his article. Aristotle~\cite{aristotle:poetics} says two in his book. Angenendt~\cite{angenendt} says three in his article. And Augustine \cite{augustine} says four in his book. \printbibliography \end{document} Automating the solution Through the wonderful automation tool arara it is actually quite easy to make this solution more automatic. We use the technique described in this answer plus arara to change the definition of \mancite on compilations after the first. You need to replace <basename> with the name of your source file (without the .tex extension). Then compile the file using arara. % arara: pdflatex: { files: [ '\def\mmcite{}\input{<basename>}' ] } % arara: biber % arara: pdflatex: { files: [ '\def\mmcite{\let\mancite=\cite}\input{<basename>}' ] } \documentclass{article} \usepackage[ style=numeric, sorting=none, ]{biblatex} \addbibresource{biblatex-examples.bib} \mmcite % this command is defined when pdflatex is invoked \begin{document} The title picture shows the original cover of Aristotles' poetics \mancite{aristotle:poetics}. Nomenclature: four --- said by Augustine \mancite{augustine}. Mainmatter: Aksin~\cite{aksin} says one in his article. Aristotle~\cite{aristotle:poetics} says two in his book. Angenendt~\cite{angenendt} says three in his article. And Augustine \cite{augustine} says four in his book. \printbibliography \end{document} Thanks to Paulo Cereda for helping with the arara code.
[ "judaism.stackexchange", "0000050473.txt" ]
Q: Who wrote the Ritva on Gittin? I've heard many things about the author of "Ritva on Gittin." It might have been the Ritva, it might not have been. There's also the "חידושים מכתב יד," which some ascribe to the Ritva, while others don't. (see, eg, this answer) How have people accurately determined the authorship of these works? A: This is discussed at length in the hakdamah to the Mosad R' Kook Ritva, and in R' Avrohom Shoshana's Ritva published by Ofeq Institute. In brief, the old Ritva acc. to some is ר' כרשכש. The new one acc. to some is Ritva, acc. to R' Shoshanah it's mostly the Ramah with some others. It's more complicated than that, but that's the Cliff Notes answer.
[ "stackoverflow", "0010739093.txt" ]
Q: Jquery: To switch from one page to another on drop-down list click I have one drop down list in my page, which contains two options. What i want is, when user select second value in drop down list, another page should load. that means how to switch page on clicking on of the drop down box values. for help i am putting my html code of drop down list. <select id = "viewList" class="fl width160"> <option>Target</option> <option>Source</option> </select> so now when user click on source option, another js page should open. and how should i write coding for that in a .js file(Jquery). A: Look you need to change your html code like this <select id = "viewList" class="fl width160"> <option value ="Target">Target</option> <option value ="Source">Source</option> </select> $("#viewList").change(function() { if( $("#viewList").val =='Target') { _loadTargetList(); } else { _loadSourceList(); } }); Here _loadTargetList and _loadSourceList both are the functions which will provide the location to load their html file or js files. Here is an example how to load html or js file If you want to call js first then html through js then go for this one codeLoadingMgr.loadInclude( path + '/Target.js', function() { codeLoadingMgr.getHTML(path + '/Target.html', function(html) { }); }); Other wise you can direct load the html also. Hope this helps.
[ "stackoverflow", "0022380876.txt" ]
Q: kineticjs how to use attrs Im very new to kineticjs and js, And i want to know how to use values in the attrs I have this code BubbleLayer.on('mouseover mousemove dragmove', function(evt) { var node = evt.targetNode; console.log(node) if (node) {`enter code here` // update tooltip var mousePos = node.getStage().getPointerPosition(); tooltip.position({x:mousePos.x, y:mousePos.y - 5}); tooltip.getText().text("Project: " + node.id() + ", Hours: " + **need to show hours **()); tooltip.show(); tooltipLayer.batchDraw(); } The console log shows (see image below) I want to dispay the totalHours in the above code tooltip.getText().text("Project: " + node.id() + ", Hours: " + **need to show hours **()); But dont know where to start. Any help would be appreciated A: It's just a javascript object. You should be able to access it with node.attrs.totalHours.
[ "stackoverflow", "0005037239.txt" ]
Q: nested form triggering a 'Can't mass-assign protected attributes warning I've got a multi layer nested form User->Tasks->Prerequisites and in the same form User->Tasks->Location The location form works fine, now I'm trying to specify prerequisites to the current task. The prerequisite is a task_id stored in the :completed_task field. When I submit the form, I get the following error in the output WARNING: Can't mass-assign protected attributes: prerequisite_attributes One warning for each task in the user. I've gone through all the other questions related to this, ensuring that the field name :completed_task is being referenced correctly, adding attr_accessible to my model (it was already there and I extended it). I'm not sure what else i'm supposed to be doing. My models look like class Task < ActiveRecord::Base attr_accessible :user_id, :date, :description, :location_id belongs_to :user has_one :location accepts_nested_attributes_for :location has_many :prerequisites accepts_nested_attributes_for :prerequisites end class Prerequisite < ActiveRecord::Base attr_accessible :completed_task belongs_to :task end the form uses formtastic, and I'm including the form via <%= f.semantic_fields_for :prerequisites do |builder3| %> <%= render 'prerequisite_fields', :f=>builder3 %> <% end %> --- _prerequisite_fields.html.erb ----- < div class="nested-fields" > <%= f. inputs:completed_step %> </div> Any suggestions? A: Add :prerequisite_attributes to attr_accessible in order to mass-assign attr_accessible :user_id, :date, :description, :location_id, :prerequisite_attributes Should get you started.
[ "stackoverflow", "0046090053.txt" ]
Q: Inside loop showing getAttribute(String) is undefined Currently, I am trying to get breadcrumb name and link from a website.I am writing code for getting breadcrumb name and its working perfectly but Inside loop when I try to get the breadcrumb link its show me an error. The method getAttribute(String) is undefined for the type List Html Code is here <div class="breadCrumb listView" itemscope="" itemtype="http://schema.org/BreadcrumbList"> <div itemscope="" itemprop="itemListElement" itemtype="http://schema.org/ListItem"> <span class="separator">/</span> <a href="https://www.flipkey.com/" itemprop="item"> <span itemprop="name">Home</span> </a> </div> <div itemscope="" itemprop="itemListElement" itemtype="http://schema.org/ListItem"> <span class="separator">/</span> <a href="https://www.flipkey.com/vacation-rentals" itemprop="item"> <span itemprop="name">Vacation Rentals</span> </a> </div> <div itemscope="" itemprop="itemListElement" itemtype="http://schema.org/ListItem"> <span class="separator">/</span> <a href="https://www.flipkey.com/united-states-vacation-rentals/g191/" itemprop="item"> <span itemprop="name">United States</span> </a> </div> <div itemscope="" itemprop="itemListElement" itemtype="http://schema.org/ListItem"> <span class="separator">/</span> <a href="https://www.flipkey.com/florida-vacation-rentals/g28930/" itemprop="item"> <span itemprop="name">Florida</span> </a> </div> </div> Here is my Code List<WebElement> Breadcrumblist=driver.findElements(By.xpath(".//*[@class='breadCrumb listView']/div/a/span")); List<WebElement> crumblink=driver.findElements(By.xpath(".//*[@class='breadCrumb listView']/div/a")); for (WebElement Breadcrumb:Breadcrumblist ){ String count=Breadcrumb.getText(); String Crumblinktext=crumblink.getAttribute("href"); System.setOut(myconsole); myconsole.print(""+count+">"); myconsole.print(""+Crumblinktext+","); } Error showing here String Crumblink=crumblink.getAttribute("href"); getAttribute(String) is undefined Not understand why this error showing.Any type of suggesting will appreciated. A: This may be your requirement. List<WebElement> crumblink=driver.findElements(By.xpath(".//*[@class='breadCrumb listView']/div/a")); for (WebElement Breadcrumb:crumblink){ String count=Breadcrumb.findElement(By.tagName("span")).getText(); String Crumblinktext=Breadcrumb.getAttribute("href"); System.setOut(myconsole); myconsole.print(""+count+">"); myconsole.print(""+Crumblinktext+","); }
[ "biology.stackexchange", "0000024559.txt" ]
Q: Anesthetics, specifically inhaled anesthetics I have had a look at previous inhaled anesthetics and many of them appear to be fluorocarbons. What could be the mechanism behind fluorine's anesthetic properties? Is it the specific bonding pattern or the molecules involved? I realize anesthetics are rather unknown I just wondered what people have as a hypothesis? A: The following is one of the many elegant statements in General Anesthetic Actions on GABAA Receptors: It is the fervent view of the authors that general anesthesia is no different from any other pharmacological process: exogenously administered drugs interact with key sites on cellular proteins in the body which results directly in the alteration in the function of these proteins, in the present case, neuronal proteins that control how information is conveyed through the nervous system. Isoflurane, Sevoflurane, and Desflurane, the current inhalation general anesthetics, along with Halothane and the intravenous anesthetics Propofol, Etomidate, Methohexital and Thiopental, enhance the function of GABAA receptors (GABAARs), the most abundant fast inhibitory neurotransmitter receptor in the CNS (ligand-gated chloride ion channels) by increasing the affinity of the receptor for GABA. Since these receptors are abundant in parts of the CNS that process higher-order brain functions, it stands to reason that GABAAR function is central to memory, awareness and consciousness. GABAARs are involved in mediating hypnosis, depression of spinal reflexes, and amnesia, three of the classical components of general anesthesia. Isoflurane, Sevoflurane, and Desflurane enhance the amplitude of responses to low concentrations of GABA and prolong the duration of GABA mediated synaptic inhibition. A very good starting point for your investigations can be found by clicking on the linked article above. Agent-selective effects of volatile anesthetics on GABAA receptor-mediated synaptic inhibition in hippocampal interneurons The sedative component of anesthesia is mediated by GABA(A) receptors in an endogenous sleep pathway
[ "stackoverflow", "0021065094.txt" ]
Q: 2D array declaration on FORTRAN77 I'm very very new to FORTRAN, so it might be a super easy problem, but I wasn't sure after googling it on web... Basically consider I have an input.txt file which has size of the 2D array e.g. input.txt file contains 4 5 So after opening the file and registering the 4 and 5 on variables row and col, I do the following... Since FORTRAN77 has a specific format where you have to declare before statements, I was thinking about using SUBROUTINE Here is the idea of SUBROUTINE SUBROUTINE create(row,col) INTEGER array(row,col) RETURN END I'm not sure if the code is able to run because it has no statements after declaration, but I already get an error saying that Error on line x: Declaration error for array: adjustable dimension on non-argument I'm not sure what's the problem, so I've come down to this I'm not using array declaration properly (i.e. logical error) In FORTRAN you cannot create array custom size (I don't think this will be the case...) Sample codes and links are welcome, but summary of what I should know will be great! In addition, FORTRAN77 will be used to compile my code, so I have to stick with FORTRAN77 style A: This is a problem for at least Fortran 95, not 77. It is year 2014!!! You need to declare the array as allocatable and allocate it using the allocate(array(rows, cols)) after you read the cols and rows from file. That way you d not have to use the subroutine, but can, if the program logical structure supports it. A: It appears you want an allocatable array, which is not valid in FORTRAN77. However, since it's now 2014 and there have been 4 updates since 1977 (1990, 1995, 2003, & 2008, plus a currently on-going meeting for a 2015 update), you have the freedom to avoid FORTRAN77. What you want to do is the following: program array_builder integer, allocatable :: block(:,:) integer :: row, col read(*,*) row, col allocate(block(row, col)) <whatever you need to do> deallocate(block) end program array_builder EDIT As a bit of a hack, one option you could try is the following: Declare a 2D array at least as big as the largest value you expect & initialize it all to zero Read in row and col from the file Only use the array with the specified range: array(1:row,1:col) This would work like so program pre_define_array integer, dimension(50,50) block integer row, col read(*,*) row, col block = 0 call do_stuff(block(1:row,1:col), row, col) end program pre_define_array subroutine do_stuff(in_array, rows, cols) integer rows, cols integer, dimension(rows, cols) in_array <do math here> end subroutine do_stuff
[ "tex.stackexchange", "0000060205.txt" ]
Q: How to get rid of an arrow in tikz? I want to put a crossing on an edge. I do it in the following way: \documentclass{article} \usepackage[utf8]{inputenc} \usepackage[english,russian]{babel} \usepackage{tikz} \usepackage{color} \usetikzlibrary{shapes.misc} \begin{document} \begin{tikzpicture} [-latex,auto, bkeg/.style={draw=red!30}] \draw[bkeg] (0,0) to [bend left] node [black, pos=0.3, auto=false, cross out, draw]{} (4,4); \end{tikzpicture} \end{document} Here I get the crossing : How to get rid of the arrow and in the second line of the crossing? Is it posible to reset this "-latex" option in the slave node? A: Yes, you can just set - (like a line without an arrow) as a node option: \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{tikz} \usepackage{color} \usetikzlibrary{shapes.misc} \begin{document} \begin{tikzpicture} [-latex,auto, bkeg/.style={draw=red!30}] \draw[bkeg] (0,0) to [bend left] node [black, pos=0.3, auto=false, cross out, -, draw]{} (4,4); \end{tikzpicture} \end{document}
[ "stackoverflow", "0037231793.txt" ]
Q: Splitting a string using a Regex with or statements I am trying to split a string using a regex which will ideally split the string on every whitespace character, underscore, and uppercase letter. Currently what I have is: /(\s+|_+|[A-Z]+)/ But I can only get it to split the string on either one of those conditions and not all. Any tips? Thanks in advance. EDIT: The current (now revised) regex above will split a string on uppercase, whitespace, and underscores...however it is splitting it like so: 'hello World Goodbye' = ['hello', 'W', 'orld', 'G', 'oodbye'] I want to split the string on uppercase letters but not after, like so: ['hello', 'World', 'Goodbye'] A: From your comment: My intent is to be able to parse any string with underscores, whitespace, or uppercase letters and place hyphens between those "words". However strings may sometimes come in the form of helloWorldGoodbye, which are clumped together in camel case and harder to separate. To split on a space or an underscore, use a character class [\s_]+. To additionally split before a capital letter, use a look-ahead. Altogether, that would look like: /[\s_]+|(?=[A-Z])/ And you can use it like this: var str = "HelloWorld good_bye"; str = str.split(/[\s_]+|(?=[A-Z])/).join("-"); document.body.innerHTML = str; Regex101 Demo "hello World Goodbye" -> "hello-World-Goodbye" "hello_World_Goodbye" -> "hello-World-Goodbye" "helloWorldGoodbye" -> "hello-World-Goodbye"
[ "stackoverflow", "0012918150.txt" ]
Q: GWT runtime Java emulation I am interesting in GWT implementation JRE libraries emulation technology. How GWT emulate Java library? How effectively implemented HashMap in JavaScript? Is it implemented in pure JavaScript or it is compile as Java source if used in code? I understand some implementation exists in gwt-dev library for development(hosted) mode. Is it same implementation for production code? A: You can check what are the emulated JRE libraries here. For most of them GWT will use the JavaScript counterparts, but there are cases where GWT will have it's own JavaScript implementation version. In HashMaps's case, since the build-in JavaScript versions offers only String->value map, GWT will use it's own implementation that will support Object->Object map. You can find some more details here. Also to understand what are the differences between production (compiled) and development modes (debug), you can check Compile & Debug section. A: You can browse the code online, e.g. HashMap, or more interestingly AbstractHashMap. As you can see, there are some JSNI methods (the ones with the native keyword, and the /*-{ ... }-*/ syntax). But many methods in the emulation code build on top of the JSNI methods: They are written as "higher level" Java methods. This emulation code is really simply GWT code as you would write your own (but of course the percentage of JSNI code is higher, statistically). And it uses the <super-source> mechanism: This way, the client code for the same class can be different in production mode compared to development mode.
[ "stackoverflow", "0010945452.txt" ]
Q: How Django TemplateResponse handle multi templates The Django doc says TemplateResponse.template can be a sequence of template names. Then if there are multi templates, which of the templates will be rendered? In other words, how does TemplateResponse handle multiple templates? A: It should behave the same way as render_to_string(), which is: choose the first that exists.
[ "stackoverflow", "0000716439.txt" ]
Q: multi-factor login with asp.net Has anyone created or read an article on creating a multi-factor login system for asp.net? The ideas would to be a have a security question after the login to validate the user. The security question would be something they would generate. Kinda similiar to the way some online banks do it. A: Well, you wouldn't be able to use the built-in login controls for ASP.NET but rolling your own is easy enough. You would simply delay the call to FormsAuthentication.SetAuthCookie(...); until after the second page.
[ "ru.stackoverflow", "0000442164.txt" ]
Q: Как изменить расстояние между строчками TextView? Всем привет! Есть обычный textview с большим текстом. Как можно изменить расстояние между строчками. Альтернатива в css line-height:. A: lineSpacingExtra или lineSpacingMultiplier в xml.
[ "math.stackexchange", "0003057999.txt" ]
Q: If you flip three fair coins, what is the probability that you'll get two tails and one head in any order? I can't find a solution that doesn't involve listing out all the possible combinations. Is there a way that I can use combinations/permutations to easily calculate this by hand? For example, when I'm solving "If you flip three fair coins, what is the probability that you'll get exactly two tails?" I can use combinations to find how many ways of getting exactly $2$ tails: $(\frac{3!}{2!\times1!})$. Then I can divide the answer by $8$, which is the total number of possible combinations $(2^3)$. A: It's just $$\binom{3}{2}*\dfrac{1}{2^3}=\dfrac{3}{8}$$ Think of it this way. You have 3 slots. $\text{_ _ _}$ I want two of them to be tail out of 3 (hence the $\binom{3}{2}$), and the probability of $2$ tails and $1$ head is basically $\dfrac{1}{2^3}$, as there are $1/2$ probability of head/tail for each toss, and there are 3 tosses. Similarly I can choose 1 head out of 3, so that would make it $\binom{3}{1}$, and nothing else would change.
[ "stackoverflow", "0036139535.txt" ]
Q: SQL Server - Query by Geometry Data Say I have following data in table addresses: physicalState physicalPostalCode geometry ------------------------------------------------------------------------------ PA 15340 0xE6100000010CAC1C5A643B1354C02D431CEBE2264440 OK 74576 0xE6100000010C7DD0B359F50158C079E9263108544140 WV 26033 0xE6100000010CE8D9ACFA5C2554C0273108AC1CEA4340 WV 26033 0xE6100000010C36AB3E575B2554C0C3D32B6519EA4340 I want to select * from addresses where geometry = GEOMETRY::STPointFromText('POINT (40.3038 -80.3005)', 4326) Finding it very difficult to figure this out... A: Try use method [STContains] like this condition: geometry.STContains(GEOMETRY::STPointFromText('POINT (40.3038 -80.3005)', 4326))
[ "math.stackexchange", "0002856681.txt" ]
Q: Prove that $\binom{2n}{n}\equiv (-1)^n \pmod{(2n+1)}$ if and only if $2n+1$ is a prime number. I have conjectured that $$\binom{2n}{n}\equiv (-1)^n \pmod{(2n+1)}$$ if and only if $2n+1$ is a prime number, based on a short program that I wrote verifying this up to $n=100$. I know that by Wilson's Theorem, $(2n)!\equiv -1 \pmod{(2n+1)}$ if and only if $(2n+1)$ is a prime number, which is as close as I can get. Any hints on how to proceed with either direction of the proof would be appreciated as I am rather stuck. Edit: Never mind. The "only if" part is actually false. $n=2953$ is a counterexample A: If $(2n + 1)$ is indeed prime, we are working in a field and can consider $(n!)^2$ directly, since it is invertible. Note that, mod $(2n + 1)$, we have $$ n! = n \times \cdots \times 1 = (-1)^n \times -n \times \cdots \times -1 = (-1)^n \times (n+1) \times \cdots \times 2n, $$ and so $$ (n!)^2 = (-1)^n\times (2n!), $$ which is precisely what you wanted to prove.
[ "stackoverflow", "0014122342.txt" ]
Q: Why use these many macros when it is really not needed When we look at STL header files, we see many macros used where we could instead write single lines, or sometimes single word, directly. I don't understand why people use so many macros. e.g. _STD_BEGIN using ::type_info; _STD_END #if defined(__cplusplus) #define _STD_BEGIN namespace std { #define _STD_END } #define _STD ::std:: A: Library providers have to cope with a wide range of implementations and use case. I can see two reasons for use of macros in this case (and there are probably others I'm not thinking about now): the need to support compilers which don't support namespace. I'm not sure if it would be a concern for a recent implementation, but most of them have a long history and removing such macros even if compilers which don't support namespaces are no more supported (the not protected using ::type_info; hints that it is the case) would have a low priority. the desire to allow customers to use their implementation of the standard library in addition to the one provided by the compiler provider without replacing it. Configuring of the library would then allow to substitute another name for std. A: That #if defined(__cplusplus) in your sample is the key. Further down in your source I would expect to see alternative definitions for the macros. Depending on compilation environment, some constructs may require different syntax or not be supported at all; so we write code once, using macros for such constructs, and arrange for the macros to be defined appropriately depending on what is supported.
[ "stackoverflow", "0033400338.txt" ]
Q: Java proxy for Autocloseable (Jedis resources) I am trying to find out whether it is possible to create Java dynamic proxy to automatically close Autocloseable resources without having to remember of embedding such resources with try-resources block. For example I have a JedisPool that has a getResource method which can be used like that: try(Jedis jedis = jedisPool.getResource() { // use jedis client } For now I did something like that: class JedisProxy implements InvocationHandler { private final JedisPool pool; public JedisProxy(JedisPool pool) { this.pool = pool; } public static JedisCommands newInstance(Pool<Jedis> pool) { return (JedisCommands) java.lang.reflect.Proxy.newProxyInstance( JedisCommands.class.getClassLoader(), new Class[] { JedisCommands.class }, new JedisProxy(pool)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try (Jedis client = pool.getResource()) { return method.invoke(client, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw e; } } } Now each time when I call method on Jedis (JedisCommands) this method is passed to proxy which gets a new client from the pool, executes method and returns this resource to the pool. It works fine, but when I want to execute multiple methods on client, then for each method resource is taken from pool and returned again (it might be time consuming). Do you have any idea how to improve that? A: You would end up with your own "transaction manager" in which you normally would return the object to the pool immediately, but if you had started a "transaction" the object wouldn't be returned to the pool until you've "committed" the "transaction". Suddenly your problem with using try-with-resources turns into an actual problem due to the use of a hand-crafted custom mechanism. Using try with resources pros: Language built-in feature Allows you to attach a catch block, and the resources are still released Simple, consistent syntax, so that even if a developer weren't familiar with it, he would see all the Jedis code surrounded by it and (hopefully) think "So this must be the correct way to use this" Cons: You need to remember to use it Your suggestion pros (You can tell me if I forget anything): Automatic closing even if the developer doesn't close the resource, preventing a resource leak Cons: Extra code always means extra places to find bugs in If you don't create a "transaction" mechanism, you may suffer from a performance hit (I'm not familiar with [jr]edis or your project, so I can't say whether it's really an issue or not) If you do create it, you'll have even more extra code which is prone to bugs Syntax is no longer simple, and will be confusing to anyone coming to the project Exception handling becomes more complicated You'll be making all your proxy-calls through reflection (a minor issue, but hey, it's my list ;) Possibly more, depending on what the final implementation will be If you think I'm not making valid points, please tell me. Otherwise my assertion will remain "you have a 'solution' looking for a problem".
[ "stackoverflow", "0002213589.txt" ]
Q: Xcode print symbol not found for my C function which used in Objective-C method body Xcode build prints this error . Undefined symbols: "EGViewportDimensionMake(unsigned int, unsigned int, unsigned int, unsigned int)", referenced from: -[Renderer render] in Renderer.o ld: symbol(s) not found collect2: ld returned 1 exit status I cannot figure out what's the problem. I'm not good at classic C syntax. These are the function source code files: EGViewportDimension.h #import <Foundation/Foundation.h> struct EGViewportDimension { NSUInteger x; NSUInteger y; NSUInteger width; NSUInteger height; }; typedef struct EGViewportDimension EGViewportDimension; EGViewportDimension EGViewportDimensionMake(NSUInteger x, NSUInteger y, NSUInteger width, NSUInteger height); EGViewportDimension.m #import "EGViewportDimension.h" EGViewportDimension EGViewportDimensionMake(NSUInteger x, NSUInteger y, NSUInteger width, NSUInteger height) { EGViewportDimension dim; dim.x = x; dim.y = y; dim.width = width; dim.height = height; return dim; } I referenced and used this like: Renderer.mm #import "EGViewportDimension.h" //.... many codes omitted. EGViewportDimension vdim = EGViewportDimensionMake(0, 0, backingWidth, backingHeight); A: I solved it by renaming Renderer.mm to Renderer.m. It was used some C++ classes so I made it as Objective-C++ code, but there was some problem. I removed all C++ calls and renamed it to Objective-C code. But I still don't know what's the problem with Objective-C++ with classic C function definition. ----(edit)---- I asked this as another question, and I got an answer. See here: Does it prohibited calling classic C function from Objective-C++ class method body?
[ "stackoverflow", "0023311559.txt" ]
Q: Writing structured binary files in haskell I want to write a structured binary file in Haskell. For example, assume that the first four bytes should be "TEST" (as ASCII), followed by the numbers 1, 2, 3, 4, then 32 bytes each with the value 128 and then the number 2048 in Little Endian format. That means, the created file (as hex) should look like this: 54 45 53 54 01 02 03 04 80 80 [... 30 bytes more ...] 00 08 So basically I have a custom data structure, let's say data MyData = MyData { header :: String -- "TEST" n1 :: Integer -- 1 n2 :: Integer -- 2 n3 :: Integer -- 3 block :: [Integer] -- 32 times 128 offset :: Integer -- 2048 } Now I want to write this data to file. So basically I need to convert this structure into one long ByteString. I could not find out a clean idiomatic way to do this. Ideally I have a function MyDataToByteString :: MyData -> ByteString or MyDataToPut :: MyData -> Put but I could not find out how to create such a function. Background information: I want to write a song in the impulse tracker format (http://schismtracker.org/wiki/ITTECH.TXT), which is the binary format for the schism tracker software. Update 1 For the endian conversion, I guess I can just extract the individual Bytes as follows: getByte :: Int -> Int -> Int getByte b num = shift (num .&. bitMask b) (8-8*b) where bitMask b = sum $ map (2^) [8*b-8 .. 8*b-1] A: You could try this one (not optimal, I am afraid): import qualified Data.List as L import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString as B data MyData = MyData { header :: String -- "TEST" , n1 :: Integer -- 1 , n2 :: Integer -- 2 , n3 :: Integer -- 3 , n4 :: Integer -- 4 , block :: [Integer] -- 32 times 128 , offset :: [Integer] -- 2048 in little endian } deriving (Show) d = MyData "TEST" 1 2 3 4 (L.replicate 32 128) [0, 8] myDataToByteString :: MyData -> B.ByteString myDataToByteString (MyData h n1 n2 n3 n4 b o) = B.concat [ BC.pack h , B.pack (map fromIntegral [n1, n2, n3, n4]) , B.pack (map fromIntegral b) , B.pack (map fromIntegral o) ]
[ "stackoverflow", "0012429088.txt" ]
Q: Retrieve JPG pictures from URL (Python) I'm trying to retrieve JPG images from http ULRs (to display them in a GUI) with the following Python code: import urllib3 from cStringIO import StringIO from PIL import Image conn = urllib3.connection_from_url('http://www.solarspace.co.uk/') img_file = conn.urlopen('GET', 'http://www.solarspace.co.uk/PlanetPics/Neptune/NeptuneAlt1.jpg') image = StringIO(img_file.read()) image.seek(0) resized_image = Image.open(image) However, this gives me this error message: "IOError: cannot identify image file". The reason why I'm using urllib3 is because I need a persistent connection (to send multiple requests), which is not available with urllib/urllib2. Thanks in advance. A: Seems to work if you use img_file.data instead of img_file.read(). img_file.read() is meant to be used when you specify preload_content=False on the request. Now that I think about it, it's not very intuitive, perhaps img_file.read() should be aware of the cached preloaded content, or perhaps it should raise an exception if it has already been consumed. The plan was to make preload_content=False default but turns out there are a lot of edge cases which fall under normal usage that are hard to satisfy. I opened a bug to fix this in the future: https://github.com/shazow/urllib3/issues/102 Anyways, using img_file.data should fix your problem. Sorry for the confusion! :) Also I suggest using conn.request(...) instead of the lower-level conn.urlopen(...), and perhaps use PoolManager if you might be going cross-domain (no reason not to use it, really). Try this: >>> http = urllib3.PoolManager() >>> r = http.request('GET', 'http://www.solarspace.co.uk/PlanetPics/Neptune/NeptuneAlt1.jpg') >>> resized_image = Image.open(StringIO(r.data))
[ "askubuntu", "0001048222.txt" ]
Q: Laptop not compliant with package profiles through Landscape I installed Ubuntu 18.04 on a MacBook Air for testing purposes, and linked it to my free Landscape license, running off AWS. I have installed the third-party drivers in the Ubuntu ISO, and Wi-Fi works on the laptop. Security groups (IP filtering) on the AWS server are set to allow HTTP, HTTPS, ICMP, and SSH from the IP of my router. There are two simple package profiles I have set by default: installation of emacs and the Chromium browser. For some reason, the laptop can't run either of them. Landscape tries and fails. However, it doesn't seem to be the case that it isn't receiving the commands: remote locking of user accounts on the MacBook from Landscape works just fine. And the MacBook can access and download packages and package updates just fine, as well. Can anyone see what I'm missing? I can't. A: It turns out the hash ID database on the server wasn't populated with entries for Ubuntu 18.04 Bionic Beaver. I edited /opt/canonical/landscape/configs/standalone/hash_id_databases.conf and added entries for [bionic] and [bionic-arm], and ran /opt/canonical/landscape/scripts/hash_id_databases.sh, which solved my problem.
[ "softwareengineering.stackexchange", "0000413302.txt" ]
Q: How is design using C different from C++? A employer is looking for C programmers, and I'm told they say that ... Good C design isn't the same as good C++ design ... and so they're looking for candidates experienced with C and not only C++. How is the design of a large C system (hundreds of thousands or millions of lines of code) very different from that of C++? Are the skills required of a developer very different, what differences should an experienced developer expect? I've read Why are most Linux programs written in C? -- including Linus' little "two minute hate" at http://harmful.cat-v.org/software/c++/linus -- but that doesn't answer my question, which might be, "How is a well-designed C system unlike well-designed C++?" Or are they similar, and is Linus' argument all there is to it? I read Lakos' Large-scale C++ Software Design -- is there anything at all like that for C? I'm trying to write this such that it isn't a duplicate of: How is C different from C++? What are the fundamental differences between C and C++? Please assume I already know the differences between the langages. I used C in the early 90s (before C++ became popular on PCs), and for writing device drivers on Windows (in the kernel where the C++ run-time library wasn't supported), and I learned C++ incrementally as a superset of C. IMO there's obvious mapping between C and C++, like what's written in one can be written in the other, for example: C -- a "file pointer" or "file handle", plus an API of related functions which take a handle-or-pointer as a parameter, plus an underlying data structure (possibly hidden/encapsulated) which contains state associated with each handle C++ -- ditto except that "data structure" and "associated functions" and encapsulated in a class, as data members and methods C++ has additional syntactic and type-checking sugar (e.g. templates and operator overloading), and its destructors allow RAII and reference-counting smart pointers, but apart from that ... And C has no first-class/language support for polymorphism, but e.g. a device driver on Windows is an installable plug-in, which has entry points which it exports, more or less like a vtable. A: The differences between C and C++ are so large these days that they are two different languages that require differences in how designs are expressed in those languages. C offers one paradigm, procedural, for writing code where as C++ is multi-paradigm allowing a larger implementation vocabulary for implementing a design. You can use a procedural paradigm or a generative paradigm with templates or object oriented paradigm with classes or a functional paradigm with support from the Standard Template Library. This difference in supported paradigms means that a C programmer often has to write C code in a procedural paradigm when C++ would offer a better and simpler alternative. The C programmer has to know how to translate from the abstract solution domain which may involve non-procedural concepts into the concrete solution domain within the constraints of what the C programming language offers. A knowledgeable and skilled and experienced C programmer is quicker at this transformation and more inclined to use accepted practices and expressions. A knowledgeable and skilled and experienced C programmer is better able to read existing source code with understanding and to make changes that have less chance of introducing a defect. Over the years I have learned from others or developed or found techniques that overcome some of the limitations that C has for large (as in greater than a million lines of source) bodies of source code. However doing so requires knowing C very well and having the experience with the language to work around its deficiencies and experience with other languages to know of those deficiencies in the first place. And often those workarounds provide opportunities for introducing defects by removing compile time checking such as using void * in argument lists. The first thing to remember is that while the C++ standards committee has made great leaps of innovation in C++ between the original ANSI C++ to C++11 to C++17 to C++20, the C standards committee has made small changes. The result is that the kind of well designed and organized standard libraries and capabilities available with C++17 require C programmers to cobble together a collection of third party libraries. And C++20 is coming. The C programming language was not really designed for huge, multi-million lines of source code projects where as C++ is. C was used to write the UNIX operating system yet according to Wikipedia, Unix - Components, The inclusion of these components did not make the system large – the original V7 UNIX distribution, consisting of copies of all of the compiled binaries plus all of the source code and documentation occupied less than 10 MB and arrived on a single nine-track magnetic tape. The printed documentation, typeset from the online sources, was contained in two volumes. The namespace directive was added to C++ in order to meet the need of large bodies of source code to be manageable by partitioning out domains for names of classes, types, functions, etc. I've used struct with function pointers and a global variable as a kind of namespace approach for functions but you still can run into name space collisions with types and definitions. This is why the three letter subsystem acronym prefix naming convention is used with large C source code bodies. C requires much more attention to detail than does modern C++. You can write modern C++ without using pointers and when you do use pointers, you have facilities that make pointers safer than what C offers. The result is that writing large bodies of source code in modern C++ can be much safer than writing in C and the error checking at compile time is better with C++ because the type system is more specific and less loose. C++ offers more modern error handling than C with exceptions. Using exceptions can make error recovery easier and the use of object destructors allows for a more elegant and simpler cleanup in the face of errors. And you aren't required to use exceptions in those places where they don't make sense. Encapsulation is easier and more complete with C++ classes and namespaces which leads to source code with better cohesion and less chance for defects. Class constructors and destructors of C++ provide a capability for a defined starting and ending state that C doesn't have. And the ability to redefine operators allows for the development of true types that provide a straightforward and intuitive expressiveness of C++ source code that C lacks, a lack which requires work arounds and makes more cognitive demands on the C programmer. Templates in C++ provide an immense power lacking in C and the C Preprocessor is in no way comparable to the capabilities of templates. The C Preprocessor is a separate component, a text processor that parses a file looking for text that looks to be a Preprocessor directive generating text which may or may not be C source code. This means that the kind of checking the C++ compiler does with templates is not available with the C Preprocessor and it also means that information available for writing templates is not available to define and Preprocessor macros. A C programmer will have spent much more time with the Preprocessor and its idiosyncrasies than a modern C++ programmer who will rely on the more powerful templates instead. The C++ Standard Library and Standard Template Library makes the C Standard Library look like a barely functional, crippled library. Text string processing in C++ is so much easier and safer than C. C++17 multi-threading support is much better than what C11 offers. A: Look at this Linux kernel code, for an example of well-designed, idiomatic C code. Notice: There is hardly any direct memory allocation or freeing happening in this file. People who are good at object-oriented design but not C design often have malloc and free all over the place because they are not accustomed to minimizing that in their design. These functions are grouped by their semantic meaning. They are the file operations for ext4. People who are good at OO design but not C design tend to create more awkward, syntax-based groupings of functions, like everything that uses a certain type of pointer. The primary data structures in this file are common to all filesystem drivers. People who are good at OO design but not C design tend to create different types for everything, like a struct ext4_inode * instead of just using the struct inode. The data structures are passed into functions. People who are good at OO design but not C design often have difficulty arranging their code so the data flows through the functions like that, without passing everything everywhere. In OO design, classes primarily hold state, not function arguments. There are two virtual function tables at the end of the file, but they are the minimum necessary to provide the abstraction of a filesystem. People who are good at OO design but not C design tend to overuse structures like this, or try to cram a bunch of data in there too, when something simpler will do. I'm not saying you can't be good at both. Obviously, that's not true, but it's also definitely possible to be good at one and not the other. I could make a similar list for people good at C design but not OO design.
[ "superuser", "0001253830.txt" ]
Q: Does Git prevent data degradation I read that ZFS and Btrfs use checksums to prevent data degradation and I read that Git has integrity through hashing essentially everything with each commit. I was going to use a Git server on a Linux NAS with Btrfs RAID 1 for storage, but if Git has integrity I guess this wouldn't be necessary (at least not if preventing data degradation is all I want). Question: So does Git's integrity though hashing essentially everything with each commit prevent or help against bit-rot? A: Git's hashing only happens at the time commits are created, and from there on the hashes are used to identify the commits. This in no way ensures the integrity of the files. Git repos can get corrupted and lose data. In fact, git has a built-in command to detect this kind of loss, git fsck, but as the documentation says, you are responsible for restoring any corrupted data from backups. A: Depends on what you mean by "prevent". (First of all, bit-rot is a term with multiple definitions. This question is not about code becoming unrunnable due to lack of maintenance.) If you mean by "prevent" that it will likely detect corruption by decay of bits, yes, that will work. It will however not help to fix that corruption: the hashes only provide error detection, not correction. This is generally what is meant by "integrity": The possibility to detect unauthorized/unintended manipulation of data, not the possibility to prevent or correct it. You would generally still want a RAID1 together with backups (possibly implemented with ZFS snapshots or similar, I am not familiar with the ZFS semantics on RAID1 + snapshots), for several reasons: if a disk fails fatally, you either need a RAID1 (or a recent backup) to restore your data; no error correction can correct for a whole disk failing, unless it has a full copy of the data (RAID1). For a short downtime, you essentially must have RAID1. if you accidentally delete parts or whole of the repository, you need a backup (RAID1 doesn’t protect you since it immediately reflects the change to all devices) Block-level RAID1 (e.g. via LVM or similar) with only two disks in itself will not protect you against silent decay of data though: the RAID controller cannot know which of the two disks holds the correct data. You need additional information for that, like a checksum over files. This is where the ZSF and btrfs checksums come in: they can be used (which is not to say that they are used in these cases, I don’t know how ZFS or btrfs handle things there) to distinguish which of the two disks holds the correct data.
[ "wordpress.stackexchange", "0000102265.txt" ]
Q: List latest posts with least comments in WP-Admin I want to encourage my authors to provide feedback to new posts that have not received enough exposure. To do this, I want to add a box to WP-Admin that lists the top 3 latest posts (from the past two days) with least comments. In terms of table structure, I'm thinking something like this answer for listing latest posts. All you need is a table with class='widefat' and get_posts(). Then you run through the results (if there are any) and print the table rows. The code works great but his was for listing the latest 10 posts, my question is how to list the latest posts with least comments? A: I managed to figure it out. So, get_posts() uses WP_Query() and we can use the example in the documentation to filter the dates. Now for the comments, that is easy, we just add the parameter 'orderby'=>'comment_count'. Also to note, when filtering get_posts(), we will need to disable suppress_filters. Let's filter the time first: function filter_where( $where = '' ) { // posts in the last 2 days $where .= " AND post_date > '" . date('Y-m-d', strtotime('-2 days')) . "'"; return $where; } And now let's get the posts: add_filter( 'posts_where', 'filter_where' ); $query = get_posts( array ( 'numberposts' => 2, 'orderby'=>'comment_count', 'order'=>'ASC', 'suppress_filters' => false, 'post_type' => array ( 'post' ) ) ); remove_filter( 'posts_where', 'filter_where' ); That will give you the top least commented posts from the past 2 days.