source
sequence
text
stringlengths
99
98.5k
[ "ru.stackoverflow", "0000132322.txt" ]
Q: Не отправляется email Для отправки простейшего сообщения достаточно же использовать функцию mail()? Но почему-то данная функция при проверке возвращает мне false. В чем может быть проблема? mail('gribkovartem@gmail.com', 'Test', 'testtesttest'); A: Пример функции: mail($to, $tema, $text, $header); Где $to - кому, $tema - тема, $text - текст, $header - заголовки Пример заголовков $email_header = "MIME-Version: 1.0 \r\n"; $email_header .= "Content-type: text/html; charset=utf-8 \r\n"; $email_header .= "From: ".$_SERVER['HTTP_HOST']." <admin@".$_SERVER['HTTP_HOST'].">\r\n"; Попробуйте добавить заголовки, возможно, это поможет.
[ "stackoverflow", "0016957812.txt" ]
Q: Functions that do not automatically inherit In c++ i read in bruce eckel that functions that do not automatically inherit are : Constructors Destructors Operator = ( because it does the constructor like thing) but this code says something else #include<iostream> using namespace std;` class A { public: A & operator= (A &a) { cout<<" base class assignment operator called "; return *this; } }; class B: public A { }; int main() { B a, b; a.A::operator=(b); //calling base class assignment operator function // using derived class a = b; // this also works //getchar(); return 0; } Output : base class assignment operator called please explain. A: In fact, it is not correct to say that operator = is not inherited. The problem is that it is hidden by the implicitly-generated operator = for the derived class, so that (for instance), an assignment such as the one in the code below would be illegal: A a; B b; b = a; Since class B does not have any operator = accepting an A, but only an implicitly generated copy-assignment operator with the following signature: B& operator = (B const&) The situation is not different from the case of regular member functions in the derived class hiding member functions with the same name in the base class. And as for regular member functions, you can have a using declaration in your class that makes the base class's operator = available: class B: public A { public: using A::operator =; // ^^^^^^^^^^^^^^^^^^^^ }; This would make the assignment in the previous example compile.
[ "stackoverflow", "0060553710.txt" ]
Q: Retrieving data from polar accesslink via php sdk I am attempting to use the polar php sdk to retrieve data from the polar accesslink api. I am able to get through the Oauth2 workflow but am stuck after receiving the access token. Following the documentation I am attempting to register a user using the following code: $config = Configuration::getDefaultConfiguration()->setAccessToken($this->token); $apiInstance = new UsersApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new \GuzzleHttp\Client(), $config ); $body = new Register(); // \Coachbox\Services\Polar\Models\Register | try { $result = $apiInstance->registerUser($body); print_r($result); } catch (Exception $e) { echo 'Exception when calling UsersApi->registerUser: ', $e->getMessage(), PHP_EOL; } However the sdk throws the following error: [400] Client error: POST https://www.polaraccesslink.com/v3/users resulted in a 400 Bad Request If instead use a curl command as follows (but through php): curl -X POST https://www.polaraccesslink.com/v3/users \ -H 'Content-Type: application/xml' \ -H 'Accept: application/json' \ -H 'Authorization: Bearer {access-token}' Body parameter { "member-id": "User_id_999" } I get an empty response. I feel I must be missing an important step, but I do not know what it is. Any help is greatly appreciated. EDIT: Heard back from Polar Support, there is an error in their API documentation. The -H 'Content-type' should be 'application/json'. But, if I make the change I get a new error: "Unrecognized token 'member': was expecting ('true', 'false' or 'null') at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 8]" EDIT 2: I was able to get the code working through a cURL request (I didn't have my body formatted as json properly). However, I am still unable to get the sdk working. A: Did a bit of debugging on the same issue and it turns out the SDK example misses the vital step of setting the member_id It should be: $body = new Register(); $body->setMemberId($your_member_id);
[ "tex.stackexchange", "0000409222.txt" ]
Q: \setindexprenote justified and index ragged I'm tidying up my book before going into print and have a tiny problem: The index should be \raggedright but the index preamble should be justified. This is what I've got, but for obvious reasons the preamble is ragged as well: \documentclass{scrbook} \usepackage[english]{babel} \usepackage[babel]{microtype} \usepackage{makeidx} \usepackage{idxlayout} \usepackage{blindtext} \makeindex \begin{document} Word\index{Aaaa} \setindexprenote{\blindtext} \footnotesize\begin{flushleft} \printindex \end{flushleft} \blindtext \end{document} A: To print the contents of the index ragged right while keeping the justified index prenote, you can use the option justific=raggedright of the idxlayout package es shown in the following MWE: \documentclass{scrbook} \usepackage[english]{babel} \usepackage[babel]{microtype} \usepackage{makeidx} \usepackage[justific=raggedright]{idxlayout} \usepackage{blindtext} \makeindex \begin{document} Word\index{Aaaa} \setindexprenote{\blindtext} \footnotesize \printindex \blindtext \end{document}
[ "stackoverflow", "0021426241.txt" ]
Q: Entity Framework update query with Unique constraint I wan to ask you what is best way to get this work. I have table with one unique field. public partial class DeviceInstance { public int Id { get; set; } [Required] public int DeviceId { get; set; } [Required] [MaxLength(50)] public string SerialNo { get; set; } <--- This field is unique [Required] public System.DateTime CreationDate { get; set; } } and I have simple method for checking if SerialNo is unique: public bool IsUnique(String value) { if (!String.IsNullOrEmpty(value)) { var No = value.ToString(); var a = db.DeviceInstances.Where(model => model.SerialNo == No).FirstOrDefault(); if (a == null) { return true; } } return false; } And enity framework method to edit records in table: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include="Id,DeviceId,SerialNo,CreationDate")] DeviceInstance deviceinstance) { if (ModelState.IsValid) { if(IsUnique(deviceinstance.SerialNo)) { db.Entry(deviceinstance).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } else { ModelState.AddModelError("", "Numer seryjny nie jest unikalny"); } } ViewBag.DeviceId = new SelectList(db.Devices, "Id", "Name", deviceinstance.DeviceId); ViewBag.Id = new SelectList(db.DeviceUsages, "DeviceInstanceId", "DeviceInstanceId", deviceinstance.Id); return View(deviceinstance); } Now I can't update any record because isUnique always returns that serialNo already exists. What is true . And now my question. Its better modify isUnique method to someway or delete isUnique method and add catch for the dbUpdateException which is thrown when trying to add duplicate? A: It would be more consistent if you would implement constraint on database. In the Entity Framework side, you can catch exception as below: try { using (var context = new YourEntityContext()) { context.DeviceInstance.Add(new DeviceInstance() { /*Properties*/ }); context.SaveChanges(); } } catch (DbUpdateException ex) { var sqlexception = ex.InnerException.InnerException as SqlException; if (sqlexception != null) { if (sqlexception.Errors.OfType<SqlError>().Any(se => se.Number == 2601)) { // Duplicate Key Exception } else { // Sth Else throw; } } } You can find SqlException Numbers in the document: http://msdn.microsoft.com/en-us/library/cc645603.aspx
[ "stackoverflow", "0013660091.txt" ]
Q: Cannot get async javascript to work I'm using node.js, RailwayJS and JugglingDB. I have a model: Model.afterInitialize = function() { var me = this; Sequence.getSequence('forModel', function(sequence) { me.serialId = sequence; }); me.title = 'Hello'; } Once it's all done only the attribute title is set. This isn't surprising but I cannot get it to work. I tried using the async module with no luck. A: Model.afterInitialize is part of an third-party API that I cannot change, so unfortunately there is no way to do this. I was hoping some sort of infinite loop checking for a flag would work but it doesn't and it would be a bodge even if it did work. I ended up hooking into another method Model.beforeSave = function(callback) {};, which requires a callback. FYI I was using https://github.com/1602/jugglingdb
[ "stackoverflow", "0040251417.txt" ]
Q: HTTP error codes when streaming large binary files over http? I have a go server that is reading & returning large datafiles bundled into a tar. I have tested that this works & writes the tar in pieces and when all the data loads, it's all good. The problem is that there can be unexpected errors that break the download. I currently write an HTTP error code & an error message, but the error message just gets put at the end of the stream/file. Is there a good way to communicate that the export failed partway through? Is it possible to do this with HTTP status codes & also providing error messages? I am using the following curl command: curl --insecure https://127.0.0.1/api/export/030e28f3-4ab6-446a-852e-fda0a497ffe2 -o "test.tar" Do I have to change the curl command to detect errors (too)? A: If the download started already, then all the HTTP headers are already sent to the HTTP client. You cannot rewrite the status code anymore (it was on the first line). The only thing you could do is cut the tcp/ip connection. If you used a 'Content-Length' header the client will see that the transfer was incomplete. If you used 'Transfer-Encoding: chunked' the client will see that the end-of-chunks marker was not received. In all cases this will siply invalidate the whole transfer. You could try to play with Range requests and Partial Content responses, and send the content in several HTTP request-response dialogs. But if you manage the big file transmission over a single HTTP dialog the only thing you can do is breaking the transmission, and starting it back completlty. Usually big file transmissions in chunks are managed on the application layer, on top of HTTP. Like in case of uploads a javascript thing will explode the file in chunks, and send it back to a dedicated application server, rebuilding the file, with a dedicated protocol on top of http to ask for missing pieces. This is because in real-life wild HTTP environments, long transmissions are hard, and range/partial content transmissions not very well managed by all potential proxys. On the other Using simple medium size HTTP requests works almost everywhere. So if you control both the client and server side you can build your own dialog on top of HTTP and make your own chunked transmission protocol, with good error management.
[ "stackoverflow", "0026958017.txt" ]
Q: Convert String to ArrayList Thanks in advance for the help, my code below is taken in a Text File and Displaying it in a ListView, i have Name and youtube in one Line inside the text field. but what i am looking at trying to do is get the youtube String inside the text file and pass that to my new Activity class as a webview to play the video just wondering how can this be done, how can i pass this String into my Setters inside my Model class in order to get an Instance of it, do i need to convert String to ArrayListString ? public class menuFragment extends ListFragment { ArrayList<model> songList = new ArrayList<model>(); public String[] listSongs = new String[]{}; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.list_fragment, container, false); loadSongs(); return view; } public void loadSongs() { try { Resources ResFiles = getResources(); InputStream ReadDbFile = ResFiles.openRawResource(R.raw.songs); byte[] Bytes = new byte[ReadDbFile.available()]; ReadDbFile.read(Bytes); String DbLines = new String(Bytes); listSongs = DbLines.split(","); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listSongs); setListAdapter(adapter); } catch (Exception e) { } } @Override public void onListItemClick(ListView l, View v, int position, long id) { Intent i = new Intent(getActivity(), playVid.class); model selectedSong = MainController.getInstance().getSongs().get(position); i.putExtra("selectedSong", selectedSong); startActivity(i); } public class model implements Serializable { private String name; private String url; public model(String name, String url) { this.name=name; this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl(){ return url; } public void setUrl(String url){ this.url = url; } public class MainController { private static MainController instance; private ArrayList<model> songList; private MainController() { this.songList = new ArrayList<model>(); } public static MainController getInstance() { if(instance == null) { instance = new MainController(); } return instance; } public void addFlight(String name, String singer, String url) { model f = new model(name,singer,url); this.songList.add(f); } public ArrayList<model> getSongs() { return this.songList; } A: Suggestion class name should be start with capital - Model. You have only three variables to pass to another activity, so you can have three putExtra with your intent no need for ArrayList, Sir. Model selectedSong = MainController.getInstance().getSongs().get(position); i.putExtra("name", selectedSong.getName()); i.putExtra("singer", selectedSong.getSinger()); i.putExtra("url", selectedSong.getUrl()); startActivity(i); And inside onCreate of another Activity, we can access these three values like this way, Intent mIntent = getIntent(); String name = mIntent.getStringExtra("name"); String singer = mIntent.getStringExtra("singer"); String url = mIntent.getStringExtra("url");
[ "stackoverflow", "0011385314.txt" ]
Q: cannot load such file -- devise/schema (LoadError) After I added the devise_rpx_connectable gem to my Gemfile, I cannot run rails server anymore or migrate to add a column to my Users table. I'm trying to follow the railscast example here: http://railscasts.com/episodes/233-engage-with-devise?view=comments I have tried several things over the last two days to try getting this thing to work. I've tried creating the migration file myself but when I run 'rake db:migrate --trace' the error I get is "rake aborted! cannot load such file -- devise/schema" and a lot of errors underneath starting with: C:/.../devise/ruby/1.9.1/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251 in 'require' I have tried googling this question and only found a handful of people with the same issue, none of which had their questions answered. Seems other people with 'cannot load such file' errors were told their versions of certain gems weren't compatible so I'll provide that info here: Gemfile: gem 'rails', '3.2.6' gem 'devise', '2.1.2' gem 'devise_rpx_connectable', '0.2.2' Also my bundler version is 1.1.4 and my ruby version is 1.9.3 The only thing that stands out to me is that the version of ruby in the devise folder seems to be 1.9.1 and mine is 1.9.3 but I would like to know the possible consequences of downgrading to 1.9.1. Any input would be greatly appreciated! Thanks A: So we decided to delete the contents of the schema.rb file that "require 'devise/schema.rb'" was in and our app magically worked! I had no idea the implications of this so i did some more research and found this- https://github.com/nbudin/devise_cas_authenticatable/commit/44aacb23fb5b4cc9d22434c952b9d1d88fe28e88#commitcomment-1555733 turns out that with the newer version (> 2.1) of devise, the contents of this file aren't necessary. hope this solves a lot of other peoples issues, especially if they decide to update the devise gem and continue to use devise_rpx_connectable.
[ "stackoverflow", "0021021488.txt" ]
Q: Deleting completely a html element I am aware of .remove() , I am using it and its working fine, I mean its removing the element which I want. But I think it doesn't removes it permanently. On right clicking in browser window selecting View page source I am still able to see those removed elements. I want to remove them completely or say permanently. Please help. A: .remove() removes them completely. The reason you still seem then in the view page source is because the page source does not change based on javascript. The page source shows how the page originally looked when it was first loaded, not how it currently is. If you look in the developers console, you will see that they are no longer there. Likewise, if you dynamically add a new element with javascript/jquery, it will not show that element in the page source.
[ "stackoverflow", "0035410724.txt" ]
Q: Repeating the same statement using loop This is the same statement for 3 times. how to do this with loop. Here, the matrix G1 dimension is 3*10. so in each part i am taking different column. G2 = f_range_m(1:8:length(timeline_ms),:); %%%% measured range G1 = OrgiRange(1:8:end,:); M1 = G1(:,1); dist11 = abs(bsxfun( @minus,G2,M1)); [~,col1] = min(dist11,[],2); Result_1 = diag(G2(:,col1)); M2 = G1(:, 2); dist22 = abs(bsxfun(@minus,G2, M2)); [~,col2] = min(dist22,[],2); Result_2 = diag(G2(:,col2)); M3 = G1(:, 3); dist33 = abs(bsxfun(@minus,G2, M3)); [~,col3] = min(dist33,[],2); Result_3 = diag(G2(:,col3)); I am trying this way. However not getting desired output. Result dimension should be 13*3. obj = 3; for ix = 1:obj M = G1(:,ix); dist = abs(bsxfun(@minus,G2,M)); [~,col] = min (dist,[],2); Result = diag(G2(:,col)); end A: With your updated code you nearly solved it. Everything which remains is writing to the columns of Result instead of overwriting it in each iteration. obj = 3; Result=nan(size(G1,1),obj); for ix = 1:obj M = G1(:,ix); dist = abs(bsxfun(@minus,G2,M)); [~,col] = min (dist,[],2); Result(:,ix) = diag(G2(:,col)); end
[ "stackoverflow", "0019476541.txt" ]
Q: CSS Changing background-color with input type="color"? I'm trying to do a webpage that at least has one color input and each time that color is changed, the background-color changes to that same color, live, without refreshing the page. A: Try this: JS: $("#color").change(function(){ var clr = $(this).val(); $("body").css("background-color",clr); }); HTML: <input type="color" id="color"/> Here is the fiddle.
[ "stackoverflow", "0024899575.txt" ]
Q: Using stopwatch in java to record elapsed time of a drawing I'm having trouble with a part of my assignment. I've done the first part with no trouble, but when I try and record the time I can't seem to get it to work. In the assignment it states "The circle drawing code shall be enclosed by elapsed time measurement using the StopWatch class provided." Here is the circle code and the stopwatch class that was provided can anyone educate me as to how I can use this with the circle code? import java.awt.*; import java.awt.geom.GeneralPath; import javax.swing.*; public class DrawCircle extends JPanel { Point[] points; GeneralPath circle; final int INC = 5; public DrawCircle() { initPoints(); initCircle(); } private void initPoints() { int numberOfPoints = 360/INC; points = new Point[numberOfPoints]; double cx = 200.0; double cy = 200.0; double r = 100.0; // Dimension variables int count = 0; for(int theta = 0; theta < 360; theta+=INC) { int x = (int)(cx + r * Math.cos(Math.toRadians(theta))); int y = (int)(cy + r * Math.sin(Math.toRadians(theta))); points[count++] = new Point(x, y); } } private void initCircle() { circle = new GeneralPath(); for(int j = 0; j < points.length; j++) { if(j == 0) circle.moveTo(points[j].x, points[j].y); else circle.lineTo(points[j].x, points[j].y); } circle.closePath(); } protected void paintComponent(Graphics g) { // fill and color super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.red); g2.fill(circle); g2.setPaint(Color.red); Point p1 = points[0]; for(int j = 1; j <= points.length; j++) { Point p2 = points[j % points.length]; g2.drawLine(p1.x, p1.y, p2.x, p2.y); // Line coordinates p1 = p2; } } public static void main(String[] args) { //Main functions JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setContentPane(new DrawCircle()); f.setSize(400,400); // Frame f.setLocation(200,200); // Center f.setVisible(true); } } Here is the stopwatch class I was provided with. public class StopWatch { private final long before; StopWatch() { before = System.currentTimeMillis(); //before = System.nanoTime(); } public long elapsedTime() { long after = System.currentTimeMillis(); //long after = System.nanoTime(); return after - before; } } A: The timing code should be placed within the actual drawing code of your component. Java Swing does its rendering in a separate thread so timing it from the main thread would simply measure the amount of time taken to initialize swing. The constructor is also executed on the main thread, so timing it does not measure the drawing time. The drawing of the circle would be queued into a separate thread. The actual drawing is done by the paintComponent method which fires in the aforementioned thread: protected void paintComponent(Graphics g) { // fill and color super.paintComponent(g); StopWatch sw = new StopWatch(); // <-- HERE Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.red); g2.fill(circle); g2.setPaint(Color.red); Point p1 = points[0]; for(int j = 1; j <= points.length; j++) { Point p2 = points[j % points.length]; g2.drawLine(p1.x, p1.y, p2.x, p2.y); // Line coordinates p1 = p2; } long time = sw.elapsedTime(); // <-- HERE System.out.println("Circle took " + time + "ms to draw."); } Note that super must be the first method called so it can not be included in the measurement (nor should it be).
[ "stackoverflow", "0015449773.txt" ]
Q: Special character from FTP directory i´m using the black raccoon class for ftp sessions. getting the content of a FTP directory like this arrayHelper.FTPFileName = [file objectForKey:(id)kCFFTPResourceName] and writing into nsmutablearray i have some folders with special character like this on the ftp share: "Heino - Mit Freundlichen Gr\U00b8ssen (Deluxe Edition) (2013) - 320" How can i convert the string? i´ve try´ed the following: NSString *uncodedName = [file objectForKey:(id)kCFFTPResourceName]; NSLog(@"Uncoded Name is %@",uncodedName); arrayHelper.FTPFileName = [NSString stringWithCString:[uncodedName cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding]; NSLog(@"Coded Name is %@",arrayHelper.FTPFileName); but returns nil... NSLog: [7344:c07] Uncoded Name is Heino - Mit Freundlichen Gr¸ssen (Deluxe Edition) (2013) - 320 [7344:c07] Coded Name is (null) A: One can see in the source code of CFFTPStream.c that CFFTPStream interprets all file names on the FTP server in the "Mac OS Roman" encoding. Your FTP server seems to use Windows encoded file names, which are therefore wrongly converted to Unicode in CFFTPStream. But you can reverse the process with NSString *uncodedName = [file objectForKey:(id)kCFFTPResourceName]; NSData *data = [uncodedName dataUsingEncoding:NSMacOSRomanStringEncoding]; arrayHelper.FTPFileName = [[NSString alloc] initWithData:data encoding:NSWindowsCP1252StringEncoding];
[ "english.stackexchange", "0000317132.txt" ]
Q: I am looking for alternatives to the phrase "way too" or "far too" as in "Way too often..." I am editing a work written for professions and have come across a sentence beginning "Way too often I encounter ..." First, this seems very colloquial. In doing some research on google ([alternative to "way too"], [alternatives to saying "way too", grammar girl and grammarist, which did not not pull anything, I came here. Urban Dictionary states: A phrase originating from Welland, Ontario, Canada. The phrase means to do/be something to a great extent. The alternatives are professional than what I am starting with: [urban dictionary.com]. Any help appreciated. This is the first question I've posted; Apologize for posting errors. A: "Much too" is a more "professional" way of saying "way too."
[ "webmasters.stackexchange", "0000023340.txt" ]
Q: How can I replicate Google Page Speed's lossless image compression as part of my workflow? I love that Google's Page Speed is able to losslessly compress a lot of my images, but I'd love to make it part of my workflow, prior to uploading a site and making it live. Is there anything I can run locally to give me the same lossless compression? I currently export images from Export For Web from Photoshop, and use a little application called PNGCrusher to reduce file size of PNGs. I'd love to find a faster way though than saving out and replacing the individual images from Page Speed's results. A: For MacOSX ImageOptim optimizes the images. Internally it uses the same tools used by google page speed. http://imageoptim.com A: You could try http://www.smushit.com/ysmush.it/ Click "Uploader" and select all images that needs to be "smushed". Your files will be uploaded to their server, become optimized without quality loss, and you will then be able to download all images in a zip file. A: If you're using the Google Page Speed extension for Firefox, then a copy of the optimized images (as well as JavaScript and CSS files) are put in a temporary folder. http://code.google.com/speed/page-speed/docs/using_firefox.html#advanced You can then take these out, cleanup the file names, and reuse them. Download Google Page Speed extension for Firefox
[ "stackoverflow", "0002959515.txt" ]
Q: Pound symbol not displaying on web page I have a mysql database table to store country name and currency symbol - the CHARSET has correctly set to UTF8. This is example data inserted into the table insert into country ( country_name, currency_name, currency_code, currency_symbol) values ('UK','Pounds','GBP','£'); When I look in the database - the pound symbol appears fine - but when I retrieve it from the database and display it on the website - a weird square symbol shows up with a question mark inside instead of the pound symbol. Edit In my.cnf - the characterset was set to latin1 - I changed it to utf8 - then I Logged in as root and ran \s - it returned Server characterset: utf8 Client characterset: utf8 Collations -- Database SELECT default_collation_name FROM information_schema.schemata WHERE schema_name = 'swipe_prod'; THIS DOES NOT RETURN ANYTHING -- Table SELECT table_collation FROM information_schema.tables WHERE TABLE_NAME = 'country'; THIS RETURNS utf8_general_ci -- Columns SELECT collation_name FROM information_schema.columns WHERE TABLE_NAME = 'country'; THIS RETURNS 7 ROWS but all have either null or utf8_general_ci PHP CODE <?php $con = mysql_connect("localhost","user","123456"); mysql_select_db("swipe_db", $con); $result = mysql_query("SELECT * FROM country where country_name='UK'"); while($row = mysql_fetch_array($result)) { echo $row['country_name'] . " " . $row['currency_symbol']; } mysql_close($con); ?> Please advice Thanks A: When you see that "weird square symbol with a question mark inside" otherwise known as the REPLACEMENT CHARACTER, that is usually an indicator that you have a byte in the range of 80-FF (128-255) and the system is trying to render it in UTF-8. That entire byte-range is invalid for single-byte characters in UTF-8, but are all very common in western encodings such as ISO-8859-1. When I view your page and manually switch the character encoding from UTF-8 to ISO-8859-1 (in Firefox with View >> Character Encoding >> Western (ISO-8859-1)) then the POUND SIGN displays properly. So, what's wrong then? It's hard to say - there are dozens of places where this can be fouled up. But most likely it's at the database level. Setting the CHARSET on the table to UTF8 is generally not enough. All of your charsets and collations need to be in order before characters will move around the system properly. A common pitfall is improperly set connection charsets, so I'd start there. Let me know if you need more guidance. EDIT To check what bytes are actually stored for that value, run this query. SELECT hex( currency_symbol ) FROM country WHERE country_name = 'UK' If you see A3 then you know the character is stored as ISO-8859-1. This means the problem occurs during or before writing to the DB. If you see C2A3 then you know the character is stored as UTF-8. This means the problem occurs after reading from the DB and before writing to the browser. EDIT 2 -- Database SELECT default_collation_name FROM information_schema.schemata WHERE schema_name = 'your_db_name'; -- Table SELECT table_collation FROM information_schema.tables WHERE TABLE_NAME = 'country'; -- Columns SELECT collation_name FROM information_schema.columns WHERE TABLE_NAME = 'country'; A: Chipping in my 2 pence. I use utf8_encode() to output the data from the database. This seems to take care of other characters as well.
[ "mathematica.stackexchange", "0000161951.txt" ]
Q: Plot with two scales for X axis I want to do something similar to 1 Plot, 2 Scale/Axis but for the X-axis. The aim is to have physical units below, but array indices at the top for easy access to the discrete data range. So far I tried: XY = Table[{i, Sin[i]}, {i, -10, 10, 0.5}]; DoubleXAxisPlotExample[XY : {{_?NumberQ, _?NumberQ} ..}] := Overlay[{ ListLinePlot[XY, ImagePadding -> 25, Frame -> True, FrameTicks -> {{All, None}, {All, None}}, PlotRange -> All], ListLinePlot[Transpose[{Range[Length[XY]], Part[XY, All, 2]}], ImagePadding -> 25, Frame -> True, FrameTicks -> {{All, None}, {None, All}}, PlotRange -> All] }]; DoubleXAxisPlotExample@XY returns: However, with: XY = Table[{i, 100000*Sin[i]}, {i, -10, 10, 0.5}]; DoubleXAxisPlotExample@XY returns: -> the left ticks have been truncated I understand that ImagePadding -> 25 is there to let enough arbitrary space on the left, however in my code this is a fixed absolute value. To solve the problem, I think that this value should be computed according to the actual plot Y-range, but I do not know how to do that. Any idea? A: You can use my function GraphicsInformation to obtain this information (I think GraphicsInformation is more reliable than Image + BorderDimensions). Install the paclet/function: PacletInstall[ "GraphicsInformation", "Site"->"http://raw.githubusercontent.com/carlwoll/GraphicsInformation/master" ]; Then, load it: <<GraphicsInformation` For your example: plots = { ListLinePlot[ XY, Frame -> True, FrameTicks -> {{All, None}, {All, None}}, PlotRange -> All ], ListLinePlot[Transpose[{Range[Length[XY]], Part[XY, All, 2]}], Frame -> True, FrameTicks -> {{All, None}, {None, All}}, PlotRange -> All ] }; padding = "ImagePadding" /. GraphicsInformation[plots] {{{44., 1.5}, {17., 0.5}}, {{44., 1.5}, {1.5, 16.}}} This gives the actual ImagePadding used in the two plots. You can use MapThread to come up with the total ImagePadding that is needed: MapThread[Max, padding, 2] {{44., 1.5}, {17., 16.}} I will leave it to you to include GraphicsInformation in your DoubleXAxisPlotExample function.
[ "stackoverflow", "0030593240.txt" ]
Q: Comparing INT_MAX and long giving wrong result I am getting long from user input (with fgets() and converting to long with strtoul()), but when testing it to convert into integer giving wrong result. Declarations: char buf[BUFSIZE]; unsigned char input[80]; int done = 0; int i, val; long valPrimary; char *ptr; Code: // gets the max first 79 characters, whichever comes first if (fgets(input, INPUTSIZE, stdin) != NULL) { printf("Input ok\n"); } else { printf("Input not ok\n"); return 0; } // get unsigned long from input valPrimary = strtoul(input, &ptr, 10); // Check if any character was converted if (ptr == input) { fprintf(stderr, "Can't convert string to number\n"); return 0; } if ((valPrimary == LONG_MAX || valPrimary == LONG_MIN) && errno== ERANGE) { fprintf(stderr, "Number out of range for LONG\n"); return 0; } printf("valPrimary: %lu\n", valPrimary); printf("Max Int: %i\n", INT_MAX); printf("Min Int: %i\n", INT_MIN); printf("Long size: %lu\n", sizeof(long)); // Check overflows and if long is convertable to int if ( (valPrimary > INT_MAX) || (valPrimary < INT_MIN) ) { fprintf(stderr, "Number out of range for INT\n"); return 0; } else { val = (int) valPrimary; } For example if I enter some a very big number, I am getting this kind of stdout: valPrimary: 18446744073709551615 Max Int: 2147483647 But error message is not displayed and conversion still happens. A: Incorrect mixing of signed long and strtoul(). Use strtol(). @Quentin strtoul("18446744073709551615",...) --> ULONG_MAX and that converted to long likely becomes -1. long valPrimary; ... // valPrimary = strtoul(input, &ptr, 10); valPrimary = strtol(input, &ptr, 10); ... if ((valPrimary == LONG_MAX || valPrimary == LONG_MIN) && errno== ERANGE) { fprintf(stderr, "Number out of range for LONG\n");
[ "askubuntu", "0000983917.txt" ]
Q: LTS after 5 years of support Ubuntu 16.04 have support until April 2021. So in 2021 will i have to reinstall whole system or will be asked to update system by"system update like on windows" without formating hdd and losing all my preferences? Like every 5 years have to reinstall everything? Sorry to ask silly questions. I'm newcomer to Linux and I just want to use pc for daily things and don't want using terminal at all. Thank you A: LTS releases occur every 2 years, so from 16.04, you will have opportunities to upgrade directly to 18.04 in April 2018, and then to 20.04 in April 2020. It will be generally expected that you would have upgraded to a newer release by then. You will be able to upgrade to 18.04 still at that point though. You can also re-install a fresh new version at that time if you need to (you may very well have a new PC by then), but it will not be necessary. However, if you do not upgrade by that point, you will no longer be running a supported system, and you may become susceptible to security problems if new ones are discovered in the versions included in the no-longer-supported version of Ubuntu. A: You can stay on an LTS release for 5 years and continue to receive updates. After 5 years you will not be forced to upgrade. If you don't, you'll simply stop receiving updates, and thus your system can be considered to be unsupported. Your options at that point would be Continue running an unsupported release. Security issues may not be fixed and you can't receive support from Ubuntu (or this site). It is considered irresponsible, even harmful, to run a Linux distribution that is unsupported due to the potential for security problems to impact others. Upgrade to the immediate next LTS release using an in-place upgrade, in your case 18.04. That will then ensure you are supported until April 2023. You can then upgrade immediately to 20.04, or wait until April 2023 to do so. Upgrade to any release by reinstalling.
[ "stackoverflow", "0056626150.txt" ]
Q: How to upload a pdf file and an image file to different upload folders in flask? I was hoping someone could adjust my code so that it could upload a pdf and image file at once on the same page. Below is the html part <form method="post" enctype="multipart/form-data"> Profile Image: <br> <input type="file" name="img-file" class="bg-warning" style="padding:10px" required> <br><br> Pdf: <br> <input type="file" name="pdf-file" class="bg-warning" style="padding:10px" required> <h6 class="text-success">{{ msg_name }}</h6> <br><br> <input type="submit" name="submit" value="UPLOAD" class="btn btn-outline-warning"> </form> next is the flask code. I havent included the upload of pdf file cause the below worked with image files UPLOAD_FOLDER = 'C:\\Users\\...\\static\\image\\' ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/imageUpload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'img-file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['img-file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('uploads')) return render_template('upload-image.html') I tried doubling everything to see if that would work. didn't work. Any help will be appreciated A: Your HTML form should have an action where to post the data. <form method="post" enctype="multipart/form-data" action="localhost:3000/up"> Profile Image: <br> <input type="file" name="img-file" class="bg-warning" style="padding:10px" required> <br><br> Pdf: <br> <input type="file" name="pdf-file" class="bg-warning" style="padding:10px" required> <h6 class="text-success">{{ msg_name }}</h6> <br><br> <input type="submit" name="submit" value="UPLOAD" class="btn btn-outline-warning"> </form> Your FLASK code would be pretty much the same, you just have to check for the file-names and based on file-names you can do your work. UPLOAD_FOLDER = 'C:\\Users\\...\\static\\' ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'img-file' not in request.files: flash('No img file') return redirect(request.url) if 'pdf-file' not in request.files: flash('No pdf file') return redirect(request.url) img_file = request.files['img-file'] pdf_file = request.files['pdf-file'] # if user does not select file, browser also # submit an empty part without filename if img_file.filename == '': flash('No image file selected') return redirect(request.url) if pdf_file.filename == '': flash('No pdf file selected') return redirect(request.url) if img_file and allowed_file(img_file.filename): filename = secure_filename(img_file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'] + "\image\" , filename)) if pdf_file and allowed_file(pdf_file.filename): filename = secure_filename(pdf_file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'] + "\pdf\" , filename)) return redirect(url_for('uploads')) return render_template('upload-image.html')
[ "stackoverflow", "0019631506.txt" ]
Q: finding a neon instruction corresponding to sse instruction I want to know what is the equivalent instruction/code to SSE instruction in Neon instruction. __m128i a,b,c; c = _mm_packs_epi32(a, b); Packs the 8 signed 32-bit integers from a and b into signed 16-bit integers and saturates. I checked the equivalent instruction on ARM site but I didn't find any equivalent instruction. http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0204j/Bcfjicfj.html A: There is no instruction that directly does what you want, but all the building blocks to build one are there: The saturation/narrow instruction is: int16x4_t vqmovn_s32 (int32x4_t) This intrinsic saturates from signed 32 bit to signed 16 bit integers, returning the four narrowed integers in a 64 bit wide variable. Combining these into your _mm_packs_epi32 is easy: Just do it for a and b, and combine the results: int32x4_t a,b; int16x8_t c; c = vcombine_s16 (vqmovn_s32(a), vqmovn_s32(b)); You may have to swap the order of the vcombine_s16 arguments.
[ "gamedev.stackexchange", "0000114891.txt" ]
Q: How do I make Unity halt on exceptions? I'm trying to debug a Unity project using the Unity Editor and Visual Studio. A runtime exception keeps popping up, but the debugger doesn't halt when an exception occurs, making it impossible to debug my code efficiently. In Visual Studio, I've gone into Tools -> Options -> Tools For Unity and set "Exception Support" to "True". I've also enabled all types of exceptions in the Exception Settings panel. I am connecting the debugger to Unity using the "Attach to Unity" button. Breakpoints are working, but the debugger isn't halting on Exceptions. What do I need to do to get Unity/VS to actually halt on Exceptions? Note: I've tried closing and re-opening both Unity and VS many times but that doesn't make any difference. A: This documentation on the 2.0 Unity tools preview for VS implies you have to both enable Unity exception support via Tools -> Options -> Tools For Unity (setting "exception support" to true, as you've done) and enable the appropriate CLR exception masks in Visual Studio's built-in exception settings window (check the box next to "Common Language Runtime Exceptions"). For best result you may want to check and then un-check the CLR exceptions tick, as that will ensure all the exception subtypes are enabled to get started with. A: You may need to do a couple more things to get this working. In my case, I wanted Unity's built-in Assertions to raise exceptions that would be caught by VS. I had to do the following to make this happen. Configure Unity's Assert class to raise exceptions via Assert.raiseExceptions=true Add the specific type of Exception to VS's exception settings window. (Right click, select Add, and input UnityEngine.Assertions.AssertionException)
[ "stackoverflow", "0033623263.txt" ]
Q: How to update 3D arrow animation in matplotlib I am trying to reproduce the left plot of this animation in python using matplotlib. I am able to generate the vector arrows using the 3D quiver function, but as I read here, it does not seem possible to set the lengths of the arrows. So, my plot does not look quite right: So, the question is: how do I generate a number of 3D arrows with different lengths? Importantly, can I generate them in such a way so that I can easily modify for each frame of the animation? Here's my code so far, with the not-so-promising 3D quiver approach: import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d ax1 = plt.subplot(111,projection='3d') t = np.linspace(0,10,40) y = np.sin(t) z = np.sin(t) line, = ax1.plot(t,y,z,color='r',lw=2) ax1.quiver(t,y,z, t*0,y,z) plt.show() A: As Azad suggests, an inelegant, but effective, solution is to simply edit the mpl_toolkits/mplot3d/axes3d.py to remove the normalization. Since I didn't want to mess with my actual matplotlib installation, I simply copied the axes3d.py file to the same directory as my other script and modified the line norm = math.sqrt(u ** 2 + v ** 2 + w ** 2) to norm = 1 (Be sure to change the correct line. There is another use of "norm" a few lines higher.) Also, to get axes3d.py to function correctly when it's outside of the mpl directory, I changed from . import art3d from . import proj3d from . import axis3d to from mpl_toolkits.mplot3d import art3d from mpl_toolkits.mplot3d import proj3d from mpl_toolkits.mplot3d import axis3d And here is the nice animation that I was able to generate (not sure what's going wrong with the colors, it looks fine before I uploaded to SO). And the code to generate the animation: import numpy as np import matplotlib.pyplot as plt import axes3d_hacked ax1 = plt.subplot(111,projection='3d') plt.ion() plt.show() t = np.linspace(0,10,40) for index,delay in enumerate(np.linspace(0,1,20)): y = np.sin(t+delay) z = np.sin(t+delay) if delay > 0: line.remove() ax1.collections.remove(linecol) line, = ax1.plot(t,y,z,color='r',lw=2) linecol = ax1.quiver(t,y,z, t*0,y,z) plt.savefig('images/Frame%03i.gif'%index) plt.draw() plt.ioff() plt.show() Now, if I could only get those arrows to look prettier, with nice filled heads. But that's a separate question... EDIT: In the future, matplotlib will not automatically normalize the arrow lengths in the 3D quiver per this pull request.
[ "stackoverflow", "0031218528.txt" ]
Q: custom dropdown slide up if I interact into jquery datepicker The issue here is, the div that has a class of filter_sub (the custom menu dropdown) is sliding up (hide thing when click anywhere other than this element and its descendants) when I interact into the jquery ui date picker. Any ideas, clues, help, suggestions, recommendations to fix my issue? I want the custom menu dropdown (the one that has a class of filter_sub) to not slide up when I interact into the jquery ui date picker or to be sharpen other that jquery ui datepicker and the custom dropdown menu, when click anywhere then the jquery ui date picker will be hidden as well as the custom dropdown menu will slide up (hide). $(document).ready(function(){ $(".thehide").hide(); $( ".datepicker" ).datepicker({ dateFormat: "yy-mm-dd" }); //when authorized person clicks on the attendance menu $(".filter_pages").unbind().click(function(e){ $(this).next(".filter_sub").slideToggle(); e.preventDefault(); }); $(document).mouseup(function(e) { var container = $(".filter_sub"); var calendar = $(".ui-datepicker"); if (!container.is(e.target) // if the target of the click isn't the container... && container.has(e.target).length === 0) // ... nor a descendant of the container { container.slideUp(); } }); }); .filter .filter_has_sub{ padding: 0px; margin: 0px; float: left; margin-left: 7px; } .filter_pages{ display: table; font: normal 12px 'mpregular', san-serif; padding: 7px; color: #7e7e7e; margin-top: 4px; } .filter_pages span, .filter_sub a span{ float: left; display: block; } .filter_pages span:first-child, .filter_sub a span:first-child{ margin-right: 6px; } .filter_pages span:last-child{ font-size: 8px; padding-top: 3px; } .filter_has_sub:first-child .filter_sub{ margin-left: -100px; width: 170px; } .filter_has_sub:first-child .filter_sub .filter_datepicker{ border: 1px solid #ccc; display: table; margin: 5px auto; } .filter_has_sub:first-child .filter_sub .filter_datepicker span{ display: block; margin: 0px 5px 0px 0px; float: left; font-size: 20px; padding: 5px 0px 0px 5px; color: #7e7e7e; } .filter_has_sub:first-child .filter_sub .datepicker{ padding: 5px; border: none; margin: 0px; display: block; float: left; width: 120px; } .filter_sub{ background: #fff; position: absolute; z-index: 99999999; width: 100px; margin-left: -30px; padding: 10px 5px; margin-top: 5px; -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.15); -moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.15); box-shadow: 0 1px 5px rgba(0, 0, 0, 0.15); } .filter_sub a{ clear: both; float: none; display: block; padding: 5px 10px; font: normal 14px 'mplight', sans-serif; color: #555; text-transform: uppercase; } .filter_sub a:hover{ color: #555; } .thehide{dsiplay: none;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet"/> <script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <div class="filter_has_sub extend data_filter" style="display: table; margin: 0px auto;"> <a href="#" class="btn btn-default filter_pages"><span>Filter Data</span><span class="ion-chevron-down"></span></a> <div class="filter_sub thehide" id="pagesfilter"> <div class="extend clear" style="height: 5px;"></div> <div class="filter_datepicker extend clear"> <span class="ion-calendar"></span><input class="form-control datepicker extend" name="from_what_date" placeholder="From what date" required/> </div> <div class="filter_datepicker extend clear"> <span class="ion-calendar"></span><input class="form-control datepicker extend" name="to_what_date" placeholder="To what date" required/> </div> <button class="btn btn-default center display_table" id="date_filter_button">Go</button> </div> </div> A: I think you are almost there. Here is what you can do: In your if clause inside mouseup function, add another condition: calendar.has(e.target).length===0. Which does the same thing as the other similar condition i.e. to make sure that the current target is not a descendant of the ui-datepicker element. Also, I noticed that your slideToggle inside click event and your slideUp inside your mouseup event were executing one after another if you clicked on filter_has_sub element to hide the inner elements. Easy fix is to add a stop(true) right before sliding to both slideToggle and slideUp calls. JS: $(document).ready(function () { $(".thehide").hide(); $(".datepicker").datepicker({dateFormat: "yy-mm-dd"}); $(".filter_pages").unbind().click(function (e) { $(this).next(".filter_sub").stop(true).slideToggle(); e.preventDefault(); }); $(document).mouseup(function (e) { var container = $(".filter_sub"); var calendar = $(".ui-datepicker"); if (!container.is(e.target) && calendar.has(e.target).length === 0 && container.has(e.target).length === 0) { container.stop(true).slideUp(); } }); }); Hope this helps.
[ "stackoverflow", "0000173813.txt" ]
Q: Should exceptions be in a different project When structuring a visual studio solution I tend to structure it so that various components are in different project (As I would assume most people do) I tend to have a bunch of User defined exceptions. The Question is should these exceptions be in a separate project to the (for example) Model classes? I tend to put them in a sub-namespace of the model, and organise them in a directory within the Model project. but should they be in a separate project all together? A: It depends on how you imagine them being used and how you deploy your application. As a rule of thumb - never create more packages/assemblies than needed. There's one strong case for putting Exceptions and Interface classes in their own assembly and that's when they're supposed to be shared among clients that not necesarily need to "full" package, one common scenario is when using remoting another is when building plugin architechtures.
[ "stackoverflow", "0033045517.txt" ]
Q: Use ServiceWorker cache only when offline I'm trying to integrate service workers into my app, but I've found the service worker tries to retrieve cached content even when online, but I want it to prefer the network in these situations. How can I do this? Below is the code I have now, but I don't believe it is working. SW Install code is omitted for brevity. var CACHE_NAME = 'my-cache-v1'; var urlsToCache = [ /* my cached file list */ ]; self.addEventListener('install', function(event) { // Perform install steps event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); /* request is being made */ self.addEventListener('fetch', function(event) { event.respondWith( //first try to run the request normally fetch(event.request).catch(function() { //catch errors by attempting to match in cache return caches.match(event.request).then(function(response) { // Cache hit - return response if (response) { return response; } }); }) ); }); This seems to lead to warnings like The FetchEvent for "[url]" resulted in a network error response: an object that was not a Response was passed to respondWith(). I'm new to service workers, so apologies for any mistaken terminology or bad practices, would welcome any tips. Thank you! A: Without testing this out, my guess is that you're not resolving respondWith() correctly in the case where there is no cache match. According to MDN, the code passed to respondWith() is supposed to "resolve by returning a Response or network error to Fetch." So why not try just doing this: self.addEventListener('fetch', function(event) { event.respondWith( fetch(event.request).catch(function() { return caches.match(event.request); }) ); }); A: Why don't you open the cache for your fetch event? I think the process of a service worker is : Open your cache Check if the request match with an answer in your cache Then you answer OR (if the answer is not in the cache) : Check the request via the network Clone your answer from the network Put the request and the clone of the answer in your cache for future use I would write : self.addEventListener('fetch', event => { event.respondWith( caches.open(CACHE_NAME).then(cache => { return cache.match(event.request).then(response => { return response || fetch(event.request) .then(response => { const responseClone = response.clone(); cache.put(event.request, responseClone); }) }) } ); }); A: event.respondWith() expects a promise that resolves to Response. So in case of a cache miss, you still need to return a Response, but above, you are returning nothing. I'd also try to use the cache first, then fetch, but in any case, as the last resort, you can always create a synthetic Response, for example something like this: return new Response("Network error happened", {"status" : 408, "headers" : {"Content-Type" : "text/plain"}});
[ "stackoverflow", "0013113349.txt" ]
Q: checkbox won't enable/disable until control loses focus I’m working on an ASP.net page that displays a datagrid with a checkbox and a dropdownlist in each row. To continue on to the next step, each row must either have a check or an option selected, but never both. I am attempting to disable the dropdownlist if the checkbox is checked, and to disable the checkbox if any option except “Select a Reason” is selected. I’m trying to do everything client side, using jquery 1.4 (I know its old, but that’s the UI leads decision). My code works fine in Chrome and IE8, but when I use Firefox 16 the checkbox does not disable upon selection change, until the user clicks outside the grid. Then the box disables. I want to get rid of the extra click. Here is the grid markup: <asp:GridView ID="gvApps" runat="server" CssClass="sGrid" HorizontalAlign="Center" AutoGenerateColumns="False" EmptyDataText="No Data" PageSize="3" ShowHeaderWhenEmpty="True" > <Columns> <asp:TemplateField HeaderText="Select"> <itemtemplate> <asp:checkbox id = "gvCheckbox" runat="server" onclick="RowCheckChanged(this)" /> </itemtemplate> </asp:TemplateField> <asp:BoundField datafield="FiscalYear" HeaderText="Year" /> <asp:TemplateField HeaderText="Reason"> <itemtemplate> <asp:DropDownList id = "ddlReason" Viewstate="true" DataSource="<%# ReasonsList %>" runat="server" /> </itemtemplate> </asp:TemplateField> </Columns> <emptydatatemplate> <p class="norecords">There are currently no Records </p> </emptydatatemplate> </asp:GridView> Here is my OnReady: <script type="text/javascript"> $(function () { $("select").change(function () { $(IndexChanged(this)); }); }) </script> Here are the IndexChanged and RowCheckChanged functions: <script type="text/javascript"> function RowCheckChanged(objRef) { var row = objRef.parentNode.parentNode; if (objRef.checked) { $(row).find("select").attr("selectedIndex", 0); $(row).find("select")[0].disabled = true; } else { $(row).find("select")[0].disabled = false; } } function IndexChanged(objRef) { //toggle chkb enabled-ness var row = objRef.parentNode.parentNode; if ($(row).find("select option:selected").text() == "Select a Reason") { //both objects should be enabled $(row).find(":checkbox").attr("disabled", false); } else { //a selection has been made, disable checkbox. $(row).find(":checkbox").attr("disabled", true); } } </script> Any Ideas? Edit: here is the markup generated by the grid client side (per firebug): <select id="MainContent_wiz_IntraAppYears1_gvApps_ddlReason_0" viewstate="true" name="ctl00$MainContent$wiz$IntraAppYears1$gvApps$ctl02$ddlReason" disabled=""> <option value="Select a Reason" selected="selected">Select a Reason</option> <option value="Tax Exempt">Tax Exempt</option> <option value="Out of Business">Out of Business</option> <option value="Worked under Another Authority">Worked under Another Authority</option> </select> A: A friend pointed me to the .click event for FF and IE, and it seems to be working great. I no longer need the dropdown list to lose focus before the event fires. it seems chrome doesn't like .click, so I have to link the event conditionally. Here is my new OnReady: if ($.browser.webkit) { $("select").change(function () { $(IndexChanged(this)); }); } else { $("select").click(function () { $(IndexChanged(this)); }); } Thanks to charlietfl for the help and advice!
[ "stackoverflow", "0018322102.txt" ]
Q: hadoop connection refused on port 9000 I want to setup a hadoop-cluster in pseudo-distributed mode for development. Trying to start the hadoop cluster fails due to refused connection on port 9000. These are my configs (pretty standard): site-core.xml: <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000</value> </property> <property> <name>hadoop.tmp.dir</name> <value>~/hacking/hd-data/tmp</value> </property> <property> <name>fs.checkpoint.dir</name> <value>~/hacking/hd-data/snn</value> </property> </configuration> hdfs-site.xml <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> <property> <name>dfs.name.dir</name> <value>~/hacking/hd-data/nn</value> </property> <property> <name>dfs.data.dir</name> <value>~/hacking/hd-data/dn</value> </property> <property> <name>dfs.permissions.supergroup</name> <value>hadoop</value> </property> </configuration> haddop-env.sh - here I changed the config to IPv4 mode only (see last line): # Set Hadoop-specific environment variables here. # The only required environment variable is JAVA_HOME. All others are # optional. When running a distributed configuration it is best to # set JAVA_HOME in this file, so that it is correctly defined on # remote nodes. # The java implementation to use. Required. export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64 # Extra Java CLASSPATH elements. Optional. # export HADOOP_CLASSPATH= # The maximum amount of heap to use, in MB. Default is 1000. # export HADOOP_HEAPSIZE=2000 # Extra Java runtime options. Empty by default. # export HADOOP_OPTS=-server # Command specific options appended to HADOOP_OPTS when specified export HADOOP_NAMENODE_OPTS="-Dcom.sun.management.jmxremote $HADOOP_NAMENODE_OPTS" export HADOOP_SECONDARYNAMENODE_OPTS="-Dcom.sun.management.jmxremote $HADOOP_SECONDARYNAMENODE_OPTS" export HADOOP_DATANODE_OPTS="-Dcom.sun.management.jmxremote $HADOOP_DATANODE_OPTS" export HADOOP_BALANCER_OPTS="-Dcom.sun.management.jmxremote $HADOOP_BALANCER_OPTS" export HADOOP_JOBTRACKER_OPTS="-Dcom.sun.management.jmxremote $HADOOP_JOBTRACKER_OPTS" # export HADOOP_TASKTRACKER_OPTS= # The following applies to multiple commands (fs, dfs, fsck, distcp etc) # export HADOOP_CLIENT_OPTS # Extra ssh options. Empty by default. # export HADOOP_SSH_OPTS="-o ConnectTimeout=1 -o SendEnv=HADOOP_CONF_DIR" # Where log files are stored. $HADOOP_HOME/logs by default. # export HADOOP_LOG_DIR=${HADOOP_HOME}/logs # File naming remote slave hosts. $HADOOP_HOME/conf/slaves by default. # export HADOOP_SLAVES=${HADOOP_HOME}/conf/slaves # host:path where hadoop code should be rsync'd from. Unset by default. # export HADOOP_MASTER=master:/home/$USER/src/hadoop # Seconds to sleep between slave commands. Unset by default. This # can be useful in large clusters, where, e.g., slave rsyncs can # otherwise arrive faster than the master can service them. # export HADOOP_SLAVE_SLEEP=0.1 # The directory where pid files are stored. /tmp by default. # export HADOOP_PID_DIR=/var/hadoop/pids # A string representing this instance of hadoop. $USER by default. # export HADOOP_IDENT_STRING=$USER # The scheduling priority for daemon processes. See 'man nice'. # export HADOOP_NICENESS=10 # Disabling IPv6 for HADOOP export HADOOP_OPTS=-Djava.net.preferIPv4Stack=true /etc/hosts: 127.0.0.1 localhost zaphod # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters But at the beginning after calling ./start-dfs.sh following lines are in the log files: hadoop-pschmidt-datanode-zaphod.log 2013-08-19 21:21:59,430 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: STARTUP_MSG: /************************************************************ STARTUP_MSG: Starting DataNode STARTUP_MSG: host = zaphod/127.0.1.1 STARTUP_MSG: args = [] STARTUP_MSG: version = 0.20.204.0 STARTUP_MSG: build = git://hrt8n35.cc1.ygridcore.net/ on branch branch-0.20-security-204 -r 65e258bf0813ac2b15bb4c954660eaf9e8fba141; compiled by 'hortonow' on Thu Aug 25 23:25:52 UTC 2011 ************************************************************/ 2013-08-19 21:22:03,950 INFO org.apache.hadoop.metrics2.impl.MetricsConfig: loaded properties from hadoop-metrics2.properties 2013-08-19 21:22:04,052 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source MetricsSystem,sub=Stats registered. 2013-08-19 21:22:04,064 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: Scheduled snapshot period at 10 second(s). 2013-08-19 21:22:04,065 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: DataNode metrics system started 2013-08-19 21:22:07,054 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source ugi registered. 2013-08-19 21:22:07,060 WARN org.apache.hadoop.metrics2.impl.MetricsSystemImpl: Source name ugi already exists! 2013-08-19 21:22:08,709 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 0 time(s). 2013-08-19 21:22:09,710 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 1 time(s). 2013-08-19 21:22:10,711 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 2 time(s). 2013-08-19 21:22:11,712 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 3 time(s). 2013-08-19 21:22:12,712 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 4 time(s). 2013-08-19 21:22:13,713 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 5 time(s). 2013-08-19 21:22:14,714 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 6 time(s). 2013-08-19 21:22:15,714 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 7 time(s). 2013-08-19 21:22:16,715 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 8 time(s). 2013-08-19 21:22:17,716 INFO org.apache.hadoop.ipc.Client: Retrying connect to server: localhost/127.0.0.1:9000. Already tried 9 time(s). 2013-08-19 21:22:17,717 INFO org.apache.hadoop.ipc.RPC: Server at localhost/127.0.0.1:9000 not available yet, Zzzzz... hadoop-pschmidt-namenode-zaphod.log 2013-08-19 21:21:59,443 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: STARTUP_MSG: /************************************************************ STARTUP_MSG: Starting NameNode STARTUP_MSG: host = zaphod/127.0.1.1 STARTUP_MSG: args = [] STARTUP_MSG: version = 0.20.204.0 STARTUP_MSG: build = git://hrt8n35.cc1.ygridcore.net/ on branch branch-0.20-security-204 -r 65e258bf0813ac2b15bb4c954660eaf9e8fba141; compiled by 'hortonow' on Thu Aug 25 23:25:52 UTC 2011 ************************************************************/ 2013-08-19 21:22:03,950 INFO org.apache.hadoop.metrics2.impl.MetricsConfig: loaded properties from hadoop-metrics2.properties 2013-08-19 21:22:04,052 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source MetricsSystem,sub=Stats registered. 2013-08-19 21:22:04,064 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: Scheduled snapshot period at 10 second(s). 2013-08-19 21:22:04,064 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: NameNode metrics system started 2013-08-19 21:22:06,050 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source ugi registered. 2013-08-19 21:22:06,056 WARN org.apache.hadoop.metrics2.impl.MetricsSystemImpl: Source name ugi already exists! 2013-08-19 21:22:06,095 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source jvm registered. 2013-08-19 21:22:06,097 INFO org.apache.hadoop.metrics2.impl.MetricsSourceAdapter: MBean for source NameNode registered. 2013-08-19 21:22:06,232 INFO org.apache.hadoop.hdfs.util.GSet: VM type = 64-bit 2013-08-19 21:22:06,234 INFO org.apache.hadoop.hdfs.util.GSet: 2% max memory = 17.77875 MB 2013-08-19 21:22:06,235 INFO org.apache.hadoop.hdfs.util.GSet: capacity = 2^21 = 2097152 entries 2013-08-19 21:22:06,235 INFO org.apache.hadoop.hdfs.util.GSet: recommended=2097152, actual=2097152 2013-08-19 21:22:06,748 INFO org.apache.hadoop.hdfs.server.namenode.FSNamesystem: fsOwner=pschmidt 2013-08-19 21:22:06,748 INFO org.apache.hadoop.hdfs.server.namenode.FSNamesystem: supergroup=hadoop 2013-08-19 21:22:06,748 INFO org.apache.hadoop.hdfs.server.namenode.FSNamesystem: isPermissionEnabled=true 2013-08-19 21:22:06,754 INFO org.apache.hadoop.hdfs.server.namenode.FSNamesystem: dfs.block.invalidate.limit=100 2013-08-19 21:22:06,768 INFO org.apache.hadoop.hdfs.server.namenode.FSNamesystem: isAccessTokenEnabled=false accessKeyUpdateInterval=0 min(s), accessTokenLifetime=0 min(s) 2013-08-19 21:22:07,262 INFO org.apache.hadoop.hdfs.server.namenode.FSNamesystem: Registered FSNamesystemStateMBean and NameNodeMXBean 2013-08-19 21:22:07,322 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: Caching file names occuring more than 10 times 2013-08-19 21:22:07,326 INFO org.apache.hadoop.hdfs.server.common.Storage: Storage directory /home/pschmidt/hacking/hadoop-0.20.204.0/~/hacking/hd-data/nn does not exist. 2013-08-19 21:22:07,329 ERROR org.apache.hadoop.hdfs.server.namenode.FSNamesystem: FSNamesystem initialization failed. org.apache.hadoop.hdfs.server.common.InconsistentFSStateException: Directory /home/pschmidt/hacking/hadoop-0.20.204.0/~/hacking/hd-data/nn is in an inconsistent state: storage directory does not exist or is not accessible. at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverTransitionRead(FSImage.java:291) at org.apache.hadoop.hdfs.server.namenode.FSDirectory.loadFSImage(FSDirectory.java:97) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.initialize(FSNamesystem.java:379) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.<init>(FSNamesystem.java:353) at org.apache.hadoop.hdfs.server.namenode.NameNode.initialize(NameNode.java:254) at org.apache.hadoop.hdfs.server.namenode.NameNode.<init>(NameNode.java:434) at org.apache.hadoop.hdfs.server.namenode.NameNode.createNameNode(NameNode.java:1153) at org.apache.hadoop.hdfs.server.namenode.NameNode.main(NameNode.java:1162) 2013-08-19 21:22:07,331 ERROR org.apache.hadoop.hdfs.server.namenode.NameNode: org.apache.hadoop.hdfs.server.common.InconsistentFSStateException: Directory /home/pschmidt/hacking/hadoop-0.20.204.0/~/hacking/hd-data/nn is in an inconsistent state: storage directory does not exist or is not accessible. at org.apache.hadoop.hdfs.server.namenode.FSImage.recoverTransitionRead(FSImage.java:291) at org.apache.hadoop.hdfs.server.namenode.FSDirectory.loadFSImage(FSDirectory.java:97) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.initialize(FSNamesystem.java:379) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.<init>(FSNamesystem.java:353) at org.apache.hadoop.hdfs.server.namenode.NameNode.initialize(NameNode.java:254) at org.apache.hadoop.hdfs.server.namenode.NameNode.<init>(NameNode.java:434) at org.apache.hadoop.hdfs.server.namenode.NameNode.createNameNode(NameNode.java:1153) at org.apache.hadoop.hdfs.server.namenode.NameNode.main(NameNode.java:1162) 2013-08-19 21:22:07,332 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: SHUTDOWN_MSG: /************************************************************ SHUTDOWN_MSG: Shutting down NameNode at zaphod/127.0.1.1 ************************************************************/ After reformatting the hdfs following output is displayed: 13/08/19 21:50:21 INFO namenode.NameNode: STARTUP_MSG: /************************************************************ STARTUP_MSG: Starting NameNode STARTUP_MSG: host = zaphod/127.0.0.1 STARTUP_MSG: args = [-format] STARTUP_MSG: version = 0.20.204.0 STARTUP_MSG: build = git://hrt8n35.cc1.ygridcore.net/ on branch branch-0.20-security-204 -r 65e258bf0813ac2b15bb4c954660eaf9e8fba141; compiled by 'hortonow' on Thu Aug 25 23:25:52 UTC 2011 ************************************************************/ Re-format filesystem in ~/hacking/hd-data/nn ? (Y or N) Y 13/08/19 21:50:26 INFO util.GSet: VM type = 64-bit 13/08/19 21:50:26 INFO util.GSet: 2% max memory = 17.77875 MB 13/08/19 21:50:26 INFO util.GSet: capacity = 2^21 = 2097152 entries 13/08/19 21:50:26 INFO util.GSet: recommended=2097152, actual=2097152 13/08/19 21:50:27 INFO namenode.FSNamesystem: fsOwner=pschmidt 13/08/19 21:50:27 INFO namenode.FSNamesystem: supergroup=hadoop 13/08/19 21:50:27 INFO namenode.FSNamesystem: isPermissionEnabled=true 13/08/19 21:50:27 INFO namenode.FSNamesystem: dfs.block.invalidate.limit=100 13/08/19 21:50:27 INFO namenode.FSNamesystem: isAccessTokenEnabled=false accessKeyUpdateInterval=0 min(s), accessTokenLifetime=0 min(s) 13/08/19 21:50:27 INFO namenode.NameNode: Caching file names occuring more than 10 times 13/08/19 21:50:27 INFO common.Storage: Image file of size 110 saved in 0 seconds. 13/08/19 21:50:28 INFO common.Storage: Storage directory ~/hacking/hd-data/nn has been successfully formatted. 13/08/19 21:50:28 INFO namenode.NameNode: SHUTDOWN_MSG: /************************************************************ SHUTDOWN_MSG: Shutting down NameNode at zaphod/127.0.0.1 ************************************************************/ Using netstat -lpten | grep java : tcp 0 0 0.0.0.0:50301 0.0.0.0:* LISTEN 1000 50995 9875/java tcp 0 0 0.0.0.0:35471 0.0.0.0:* LISTEN 1000 51775 9639/java tcp6 0 0 :::2181 :::* LISTEN 1000 20841 2659/java tcp6 0 0 :::36743 :::* LISTEN 1000 20524 2659/java Using netstat -lpten | grep 9000 returns nothing, assuming that there is no application bound to this designated port after all. What else can I look for to get my hdfs up and running. Don't hesitate to ask for further logs and config files. Thanks in advance. A: Use absolute path for this and make sure the hadoop user has permissions to access this directory:- <property> <name>dfs.data.dir</name> <value>~/hacking/hd-data/dn</value> </property> also make sure you format this path like # hadoop namenode -format
[ "stackoverflow", "0008621971.txt" ]
Q: Rails routing two controllers Firstly, I want to tell you that I am a novice in rails and I have a stupid question. I want to make an application where I should post news and every new will have have a category. So I create a controller about categories. Now, I add, edit and delete categories and I should create a controller about news but how should I connect news with categories in routes? I hope you understand my question. Thanks in advance! A: Assuming a story can only have one category, the model would be: class Category < ActiveRecord::Base has_many :stories end class Story < ActiveRecord::Base belongs_to :category end From the routing point of view, you can nest the resources: resources :categories do resources :stories end or not: resources :categories resources :stories This choice is up to you :) See Nested resources
[ "stackoverflow", "0040912345.txt" ]
Q: Are class generation functions allowed in ES6? I need to create classes by some parameters. I want to do it with a function. I tried it using node.js v7.0 it looks working well but I'm wondering whether it's allowed by es6 specification. For example: const MyClassGenerator = (something) => { return class GeneratedClass { get type() { return something; } } } class MyInheritedClass extends MyClassGenerator('foo') { ... } new MyInheritedClass().type // => 'foo' A: Yes, class syntax can be used both for declarations and as expressions, in any scope - it doesn't need to be (module-) top-level. A function that returns classes is very well possible and does, as you experienced, work as expected. However, it often is a bad ida: the generated classes are usually quite similar to each other, yet they are lacking a common superclass if used in an extends clause, it often introduces an unnecessary level of inheritance. To counter point 1, you can let all generated classes extend a shared one: class Base { get type() { return this.constructor.type; } } const MyClassGenerator = (something) => { class GeneratedClass extends Base {} GeneratedClass.type = something; return GeneratedClass } (not too useful in this case, but often a good approach) To counter point 2, you usually don't want to use extends for mixing generated stuff into your class. Rather use a decorator! function myClassDecorator = (something, constructor) => { Object.defineProperty(constructor.prototype, "type", { get() { return something; }, configurable: true }); return constructor; } let MyInheritedClass = myClassDecorator('foo', class { ... });
[ "stackoverflow", "0025788773.txt" ]
Q: How to delay the mousemove detection for 30 seconds I have this detector script in order to detect if user/mouse is leaving from the page (exit trap). Its working well except script is too fast, sometimes it detects when mouse is initially coming into page from the adress bar. How to delay it for 30 seconds so that check is done only if user has stayed 30 secs on page? jQuery(document).ready(function($) { jQuery(document).setTimeout(function(f) { jQuery(document).mousemove(function(e) { if (e.pageY - jQuery(document).scrollTop() <= 7) if ( document.referrer == null { USER LEAVING !!! } }); , 2000); }); A: The simplest way I can think of is to grab a timestamp when the page loads, then check it every time mousemove fires. Basically: var movementThreshold = 0; $(document).ready(function () { movementThreshold = new Date().getTime() + 30000; // Get the current time, add 30s }); $(document).mousemove(function (e) { if (new Date().getTime() > movementThreshold) { // process the event, at least 30s has passed } });
[ "stackoverflow", "0060894425.txt" ]
Q: Django 3 - CreateView with initial ForeignKey field I am trying to create a "restaurant rating" app on Django 3. I have set up the following models: # Table storing the different restaurants class Restaurant(models.Model): restaurant_name = models.CharField(max_length=200, unique=True) restaurant_address = models.CharField(max_length=200) restaurant_street_number = models.CharField(max_length=10) restaurant_city = models.CharField(max_length=200) restaurant_cuisine_type = models.CharField(max_length=200) def __str__(self): return self.restaurant_name + ' - ' + self.restaurant_city class UserReview(models.Model): # Defining the possible grades Grade_1 = 1 Grade_2 = 2 Grade_3 = 3 Grade_4 = 4 Grade_5 = 5 # All those grades will sit under Review_Grade to appear in choices Review_Grade = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5') ) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) user_review_grade = models.IntegerField(default=None, choices=Review_Grade) # default=None pour eviter d'avoir un bouton vide sur ma template user_review_comment = models.CharField(max_length=1500) def get_absolute_url(self): return reverse('restaurants:reviews', args=[self.id]) This is the form I am using: # Form for user reviews per restaurant class UserReviewForm(forms.ModelForm): class Meta: model = UserReview # restaurant = forms.ModelChoiceField(queryset=Restaurant.objects.filter(pk=id)) fields = [ 'restaurant', 'user_review_grade', 'user_review_comment' ] widgets = { 'restaurant': forms.HiddenInput, 'user_review_grade': forms.RadioSelect, 'user_review_comment': forms.Textarea } labels = { 'user_review_grade': 'Chose a satisfaction level:', 'user_review_comment': 'And write your comments:' } Here are my URLs: app_name = 'restaurants' urlpatterns = [ # ex: /restaurants/ path('', views.index, name='index'), # ex: /restaurants/15 path('<int:restaurant_id>/', views.details, name='details'), # ex: /restaurants/test path('<int:restaurant_id>/test', views.Test.as_view(), name='test') ] Template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TEST</title> </head> <body> <h1>Write a review for this restaurant:</h1> <form method="post"> {% csrf_token %} <input type="Hidden" name="restaurant" value="{{restaurant.restaurant_id}}"> {{ form.as_p }} <br> <input type="submit" value="Submit"> </form> </body> </html> And finally my view: # Test class to be renamed posts reviews as it should class Test (CreateView): template_name = 'restaurants/TEST.html' form_class = UserReviewForm # Get the initial information needed for the form to function: restaurant field def get_initial(self, restaurant_id, *args, **kwargs): initial = super(Test, self).get_initial(**kwargs) initial['restaurant'] = 9 return initial() # Post the data into the DB def post(self, request, *args, **kwargs): form = UserReviewForm(request.POST) if form.is_valid(): review = form.save() print(review) # Print so I cna see in cmd prompt that something posts as it should review.save() return render(request, 'restaurants/reviews.html', {'form': form}) I am facing an issue as when I define initial as an integrer (let's say 9 - as I put it to test if my form was actually posting) it posts with no issue the review in the DB for restaurant that holds id=9 However I can't get it to have the restaurant_id automatically populated depending on which restaurant's page we're visiting. I tried the following as well as few other 'tricks' found here and there but nothing seems to do the cut... # Test class to be renamed later IF it works... class Test (CreateView): template_name = 'restaurants/TEST.html' form_class = UserReviewForm # Get the initial information needed for the form to function: restaurant field def get_initial(self, restaurant_id, *args, **kwargs): restaurant = get_object_or_404(Restaurant, pk=restaurant_id) initial = super(Test, self).get_initial(**kwargs) initial['restaurant'] = self.request.restaurant.pk return initial() # Post the data into the DB def post(self, request, *args, **kwargs): form = UserReviewForm(request.POST) if form.is_valid(): review = form.save() print(review) # Print so I cna see in cmd prompt that something posts as it should review.save() return render(request, 'restaurants/reviews.html', {'form': form}) Any help would be appreciated to point me in the right direction :) A: You can obtain the restaurant_id in the url parameters with self.kwargs['restaurant_id']. So you can ue: class Test(CreateView): def get_initial(self, *args, **kwargs): initial = super(Test, self).get_initial(**kwargs) initial['restaurant'] = self.kwargs['restaurant_id'] return initial # … That being said, it is rather odd to store this in a form anyway. You can simply set this when the form is valid. So we define the form without a restaurant: class UserReviewForm(forms.ModelForm): class Meta: model = UserReview fields = [ 'user_review_grade', 'user_review_comment' ] widgets = { 'user_review_grade': forms.RadioSelect, 'user_review_comment': forms.Textarea } labels = { 'user_review_grade': 'Chose a satisfaction level:', 'user_review_comment': 'And write your comments:' } and in the CreateView, we then set the restaurant of that instance: class Test(CreateView): template_name = 'restaurants/TEST.html' model = UserReview form_class = UserReviewForm success_url = … def form_valid(self, form): form.instance.restaurant_id = self.kwargs['restaurant_id'] super().form_valid(form) You here need to specify a success_url to which it will redirect in case the submission is succesful. In case a POST is successful, you need to make a redirect to implement the Post/Redirect/Get pattern [wiki].
[ "stackoverflow", "0056396515.txt" ]
Q: Grid shows up for split second and then immediately disappears I'm making a small project with wxpython and I'm having some trouble with wx.grid.Grid. The grid is nested in a sizer which is nested in another sizer (here's a photo). However, when it's like that, the grid shows up for a split second and disappears. It didn't disappear when it was just inside one sizer. I've tried changing the sizer type and various properties of the sizer and the grid with no avail. I've also tried changing parts of code but realized that it has nothing to do with it since the grid doesn't even show inside wxGlade. Here's a part of .py generated by wxGlade: class frameRozvrh(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: frameRozvrh.__init__ kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.SetSize((640, 480)) self.statusbar = self.CreateStatusBar(1) self.buttonPrev = wx.Button(self, wx.ID_ANY, "<<") self.dateWeek = wx.adv.DatePickerCtrl(self, wx.ID_ANY, style=wx.adv.DP_DEFAULT) self.buttonNext = wx.Button(self, wx.ID_ANY, ">>") self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(1, 1)) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: frameRozvrh.__set_properties self.SetTitle("Rozvrh hodin") self.statusbar.SetStatusWidths([-1]) # statusbar fields statusbar_fields = [u"Aktuální týden"] for i in range(len(statusbar_fields)): self.statusbar.SetStatusText(statusbar_fields[i], i) self.dateWeek.Enable(False) self.gridRozvrh.CreateGrid(0, 0) self.gridRozvrh.EnableEditing(0) self.gridRozvrh.EnableDragColSize(0) self.gridRozvrh.EnableDragRowSize(0) self.gridRozvrh.EnableDragGridSize(0) self.gridRozvrh.SetFocus() # end wxGlade def __do_layout(self): # begin wxGlade: frameRozvrh.__do_layout sizer = wx.BoxSizer(wx.VERTICAL) sizer_2 = wx.BoxSizer(wx.VERTICAL) sizer_1 = wx.GridBagSizer(0, 0) sizer_1.Add(self.buttonPrev, (0, 0), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5) sizer_1.Add(self.dateWeek, (0, 1), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5) sizer_1.Add(self.buttonNext, (0, 2), (1, 1), wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 5) sizer_1.AddGrowableCol(0) sizer_1.AddGrowableCol(1) sizer_1.AddGrowableCol(2) sizer.Add(sizer_1, 0, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 10) sizer_2.Add(self.gridRozvrh, 0, wx.ALL | wx.EXPAND, 5) sizer.Add(sizer_2, 0, wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, 10) self.SetSizer(sizer) self.Layout() I'd like the grid to stay visible, not disappear. A: There are two problems in your code Problem 1 is in this line: self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(1, 1)) With this line your creating a grid with 1 pixel wide and 1 pixel height. Change it to: self.gridRozvrh = wx.grid.Grid(self, wx.ID_ANY, size=(100, 100)) or any other size. Problem 2 is in this line: self.gridRozvrh.CreateGrid(0, 0) With this line you are creating a grid with 0 rows and 0 columns. Change this to: self.gridRozvrh.CreateGrid(10, 10) or any other numbers as needed.
[ "aviation.stackexchange", "0000056912.txt" ]
Q: Can a private pilot refuel his small private airplane internationally without passing through immigration or customs? I've been a private pilot for many years, but I have never flown internationally in small private aircraft. I'm about to buy a tiny, high-tech, super-efficient 2-seat airplane that has extended range fuel tanks that make it possible to fly 8000km == 5000 miles without refueling (24+ hours). The longest flights necessary to cross the south-pacific in hops is 4000km (about 16 hours of flight at 250kph). Such long range makes it possible for this tiny aircraft to fly anywhere on earth. Nonetheless, I'd have to be nuts not to stop more often than every 16 hours when that is possible: for a meal, potty stop, walk around and stretch body & legs... and eventually sleep! This raises the asked question. Can a pilot, with or without one passenger, stop in other nations JUST to refuel without needing to go through immigration (and get a visa for that nation)... just to land, pull up to the gasoline pumps, fill them up, get back into the airplane, then fly away? Note that this is NOT a question about flying in a commercial airplane on a conventional scheduled airplane flight. I also presume the stop will not involve going inside any building or leaving the refueling area within the private aircraft portion of the airport. It will involve getting out of the airplane, because refueling of diverse small private airplanes is generally done by hand by pilots, not by the huge trucks that fuel jet airplanes. Typically small airplanes just pull up to a pump much like you'd see at any gasoline station, insert credit card, pump fuel into the wings, then fly away. When I get the airplane, after a month or two of getting used to it in north america, I plan to flying down to Chile with 1, 2, 3, 4, 5 stops between (depending on these rules), then fly to dozens of islands in the south pacific (and land many places and islands that have airstrips, but no buildings (or at least no legal/government buildings). In the later cases (south-pacific islands with tiny populations), I suspect nobody bothers or cares, because they assume all air traffic is strictly local. But flying down through (or 20 miles offshore) of Mexico through central America then Columbia, Ecuador, Peru and then finally into northern Chile (where I intend to spend a great deal of time) may be another matter entirely. A: While it depends on the country, expect to have mandatory immigration checks on first port of entry in most countries. I know this to be true for the US, Canada, Britain, Russia and the EU (Schengen area). Usually only emergency landings are exempt. But they may lead to investigations so not really an alternative to declare one in each and every country. Usually it's best to hire a service provider to prepare all the paperwork for your trip. While their main business is to prepare commercial flights (non airliner), most also accept private pilots as clients, a few even welcome them. They will not just plan your journey regarding visas, landing and crossing permits (some countries do require preregistration for each and every flight into their territory), but also make sure to pick only airports with the right fuel available, or making it available. Selecting and booking hotels can be included as well. Anyone I know, who ever tried to fly further than the next door country, sooner or later took such service as it makes a huge difference. Well, some had to make the experiance to get stuck for a week at some border first :))
[ "tex.stackexchange", "0000444734.txt" ]
Q: How to put the amsthm title right of text How can I put the title of a theorem environment right of the text. Example: \begin{definition}[Titel] Some Text \end{definition} The result should look like this. Where the tile is Strukturbaum and is placed right of the definition. A: With amsthm you can define a style that's the same as the standard except for the treatment of the optional argument. \documentclass{article} \usepackage{amsmath,amsthm} \newtheoremstyle{arweddefinition} {\topsep} % ABOVESPACE {\topsep} % BELOWSPACE {\upshape} % BODYFONT {0pt} % INDENT (empty value is the same as 0pt) {\bfseries} % HEADFONT {.} % HEADPUNCT {5pt plus 1pt minus 1pt} % HEADSPACE % CUSTOM-HEAD-SPEC follows {% \if\relax\detokenize{#3}\relax % no optional argument \else \makebox[0pt][l]{\hspace{\textwidth}\hspace{\marginparsep}\normalfont\itshape#3}% \fi \thmname{#1}\thmnumber{ #2}% } \theoremstyle{arweddefinition} \newtheorem{definition}{Definition}[section] \begin{document} \section{Test} \begin{definition}[Foo] A \emph{foo} is something very useful. We will use foos all the time in this paper. This should be enough to wrap. \end{definition} \begin{definition} A \emph{baz} is not very useful so we don't set it in the margin. We will not be using any baz in the paper. This should be enough to wrap. \end{definition} \end{document} Use a smashed \parbox in order to accommodate longer titles. \documentclass{article} \usepackage{amsmath,amsthm} \newtheoremstyle{arweddefinition} {\topsep} % ABOVESPACE {\topsep} % BELOWSPACE {\upshape} % BODYFONT {0pt} % INDENT (empty value is the same as 0pt) {\bfseries} % HEADFONT {.} % HEADPUNCT {5pt plus 1pt minus 1pt} % HEADSPACE % CUSTOM-HEAD-SPEC follows {% \if\relax\detokenize{#3}\relax % no optional argument \else \makebox[0pt][l]{% \hspace{\textwidth}\hspace{\marginparsep}\normalfont\itshape \smash{\parbox[t]{\marginparwidth}{\raggedright#3}}% }% \fi \thmname{#1}\thmnumber{ #2}% } \theoremstyle{arweddefinition} \newtheorem{definition}{Definition}[section] \begin{document} \section{Test} \begin{definition}[Foo] A \emph{foo} is something very useful. We will use foos all the time in this paper. This should be enough to wrap. \end{definition} \begin{definition} A \emph{baz} is not very useful so we don't set it in the margin. We will not be using any baz in the paper. This should be enough to wrap. \end{definition} \begin{definition}[Strongly typed principal foo] A \emph{strongly typed principal foo} is not very useful, but we set it in the margin just by way of example. We will not be using themin the paper. This should be enough to wrap. \end{definition} \end{document}
[ "stackoverflow", "0007993059.txt" ]
Q: Page navigation in WP7 Mango? Looking for comments on the following scheme for handling page navigation. Using the Mvvm Light Messenger sends messages in a broadcast manner so if all ViewModels in a multi page solution listen to same type of message, every one will receive all messages. Filtering out the ones the current ViewModel needs to handle is done by HandleIncomingMessage() Also I wonder where to store "globalish" data that flow through the app, have used static properties defined in App.xaml.cs so far for currentCustomerId etc. But should I also put the object graph with all person data from the database here? An alternative would be to extend or overload the PageTransitionMessageType() and provide properties to send specific messages to each page. In this way you would not have to worry about Filtering of incoming messages described above. Any comments appreciated! // In ViewModelLocator public static readonly Uri Page1Uri = new Uri("/Views/Page1.xaml", UriKind.Relative); public static readonly Uri Page2Uri = new Uri("/Views/Page2.xaml", UriKind.Relative); public static readonly Uri Page3Uri = new Uri("/Views/Page3.xaml", UriKind.Relative); // create similar page def for Page2 public partial class Page1 : PhoneApplicationPage { public Page1() { InitializeComponent(); Messenger.Default.Register<PageTransitionMessageType>(this, (action) => NavigationHandler(action)); } private void NavigationHandler(PageTransitionMessageType action) { NavigationService.Navigate(action.PageUri); } } // create similar VM for Page3 public class Page2ViewModel : ViewModelBase { public Page2ViewModel () { Messenger.Default.Register<PageTransitionMessageType>(this, (s) => HandleIncomingMessage(s)); } private void HandleIncomingMessage(PageTransitionMessageType s) { // check for page2 message if (s.PageUri == ViewModelLocator.Page2Uri) { // do cunning page2 stuff... } } } // create similar VM for Page2 public class Page1ViewModel : ViewModelBase { public RelayCommand GotoPage2Cmd { get; private set; } public Page1ViewModel() { GotoPage2Cmd = new RelayCommand(() => ExecuteGoToPage2(), () => CanExecuteGoToPage2()); } private void ExecuteGoToPage2() { var message = new PageTransitionMessageType() { PageUri = ViewModelLocator.Page2Uri }; Messenger.Default.Send<PageTransitionMessageType>(message); } } public class PageTransitionMessageType { public Uri PageUri { get; set; } // e.g. put props with data you'd like to pass from one page to another here } A: I would recommend saving "globalish" variables in an IsolatedStorage
[ "stackoverflow", "0017498556.txt" ]
Q: C preprocessor __TIMESTAMP__ in ISO 8601:2004 How can I have a __TIMESTAMP__ replacement in ISO 8601:2004? __TIMESTAMP__ Sat Jul 6 02:50:06 2013 vs __TIMESTAMP_ISO__ 2013-07-06T00:50:06Z A: Oh ye optimist! You wouldn't really expect one standard to pay attention to another, would you? The __TIMESTAMP__ define is not in standard C, just so as you are aware. It would be great to have a format like your proposed __TIMESTAMP_ISO__ (would you always want Zulu time, or would it be better to have the local time zone offset?), but frankly, the easiest way to get it added might be a patch to GCC and Clang and so on. You can try monkeying with asctime() as suggested by user1034749's answer, but I'd rather not try that. In the GCC 4.8.1 manual, there's an interesting warning suppression: -Wno-builtin-macro-redefined Do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of __TIMESTAMP__, __TIME__, __DATE__, __FILE__, and __BASE_FILE__. This suggests you could try: gcc ... -Wno-builtin-macro-redefined -D__TIMESTAMP__=$(date +'"%Y-%m-%dT%H:%M:%S"') ... (Note the hieroglyphics necessary to get the string from date surrounded by double quotes.) However, some earlier versions of GCC do not support the option; I don't recall seeing it before. You can still redefine __TIMESTAMP__: $ gcc -std=c99 -Wall -Wextra -O xx.c -o xx $ ./xx Fri Jul 5 19:56:25 2013 $ gcc -std=c99 -Wall -Wextra -D__TIMESTAMP__=$(date +'"%Y-%m-%dT%H:%M:%S"') -O xx.c -o xx <command-line>: warning: "__TIMESTAMP__" redefined $ ./xx 2013-07-05T20:10:28 $ Not very pretty, but it works... Oh, and just for the record, the source code was (trivial): #include <stdio.h> int main(void) { printf("%s\n", __TIMESTAMP__); return 0; }
[ "stackoverflow", "0050835434.txt" ]
Q: How do I create a SAS data view from an 'Out=' option? I have a process flow in SAS Enterprise Guide which is comprised mainly of Data views rather than tables, for the sake of storage in the work library. The problem is that I need to calculate percentiles (using proc univariate) from one of the data views and left join this to the final table (shown in the screenshot of my process flow). Is there any way that I can specify the outfile in the univariate procedure as being a data view, so that the procedure doesn't calculate everything prior to it in the flow? When the percentiles are left joined to the final table, the flow is calculated again so I'm effectively doubling my processing time. Please find the code for the univariate procedure below proc univariate data=WORK.QUERY_FOR_SGFIX noprint; var CSA_Price; by product_id; output out= work.CSA_Percentiles_Prod pctlpre= P pctlpts= 40 to 60 by 10; run; A: In SAS, my understanding is that procs such as proc univariate cannot generally produce views as output. The only workaround I can think of would be for you to replicate the proc logic within a data step and produce a view from the data step. You could do this e.g. by transposing your variables into temporary arrays and using the pctl function. Here's a simple example: data example /view = example; array _height[19]; /*Number of rows in sashelp.class dataset*/ /*Populate array*/ do _n_ = 1 by 1 until(eof); set sashelp.class end = eof; _height[_n_] = height; end; /*Calculate quantiles*/ array quantiles[3] q40 q50 q60; array points[3] (40 50 60); do i = 1 to 3; quantiles[i] = pctl(points[i], of _height{*}); end; /*Keep only the quantiles we calculated*/ keep q40--q60; run; With a bit more work, you could also make this approach return percentiles for individual by groups rather than for the whole dataset at once. You would need to write a double-DOW loop to do this, e.g.: data example; array _height[19]; array quantiles[3] q40 q50 q60; array points[3] _temporary_ (40 50 60); /*Clear heights array between by groups*/ call missing(of _height[*]); /*Populate heights array*/ do _n_ = 1 by 1 until(last.sex); set class end = eof; by sex; _height[_n_] = height; end; /*Calculate quantiles*/ do i = 1 to 3; quantiles[i] = pctl(points[i], of _height{*}); end; /* Output all rows from input dataset, with by-group quantiles attached*/ do _n_ = 1 to _n_; set class; output; end; keep name sex q40--q60; run;
[ "askubuntu", "0000319551.txt" ]
Q: Installing Linux without affecting Window 7 I have Window 7 installed on my laptop and I can install Linux (Ubuntu). I just wanted to install it with the following conditions: At the time of booting I get option for both OS, but if I delete Linux OS it should not affect the booting process of Windows. May be it automatically gain Windows bootloader or if its Grub, its OK. I am not aware of what is "sda" at the time of installation. Can I create "sdb" without destroying Windows partitions and install Linux in this "sdb"? I got free space in my system. A: Answer to question1: if you delete Linux and want to not affect the windows bootloader then the Windows bootloader would have to manage both OSs. Question2: sda, sdb, sdc ... you see a pattern? Everyone is a separate partition, and this is their name. In windows you have C, D, E ... To make what you are asking I would do like this: Enter in Linux and do 4 partitions: sda formatted as ext4 sdb formatted as linux-swap (with the space double of your ram in the system) sdc formatted as ntfs sdd formatted as ntfs First instal Ubuntu, when you install you select the mout point / in the sda and then the sdb as swap partition and you install. Then, install Windows 7 and you will see you have 4 partition in which 2 as ntfs and and probably two unrecognised. In Windows you will have the C drive where the Windows is and the second where you put your data. Since the Windows 7 is installed secondly and because Windows does what it wants, it will put its bootloader over the Linux one. Now I have not done lately this (2-3 years ago), and I may not be the best practice, but you get the point.
[ "stackoverflow", "0009329986.txt" ]
Q: Javascript jQuery post()/get() JSON object as closure function before document ready I'm trying to figure out what the best way to handle a JSON object that I need to post/get when the document is ready so I can then run over another function that builds out the DOM based on said JSON object. This object is also something that updates every 30 seconds to a minute. My initial thought was to build it out as a closure. i.e.: var myJSONobject = $.post(uri, function(data){return data;}); however the function I run when the for document ready, and functions I base on click events don't recognize the object as being valid. It returns a JSON object, and I've used jsonlint.com to confirm that the object format is valid. So I am thinking its in how I am handling the string of events. Where the object though it may be legit is being rendered after the document ready thus breaking the functionality in a sense. Cause if I take the same object it spits out and hard code it in as a variable. the code I've been working on works fine. So now I am trying to figure out whats my best approach to handling this so one, my script doesn't break prematurely. and two find out if trying to adapt this as a closure the way I am is the right way? Whats a good practice logic in this type of scenario? Should I load the JSON object into a hidden div somewhere or text area and pass it through that or what? A: $.post function does not actually return the return value of the success function, so you cannot just assign myJSONobject to it. What you really want to do is var myJSONobject; $.post(uri, function(data){ myJSONobject = data; // OR work with data here }); // You cannot use myJSONobject right away But be careful, you can't access myJSONobject right after calling $.post, you need to wait until the ajax call succeded.
[ "stackoverflow", "0059912701.txt" ]
Q: DIV positioning in footer I tried to create a homepage but can't manage to place a div in the footer. It's always displayed above. Can anybody give me a hint why it is displayed that way? Here is my code: * { color: #000000; background-color: #FFFFFF; font-family: "Arial", "Sans serif", "Roboto", "ApexNew"; padding: 0; margin: 0; } html { color: #000000; background-color: #FFFFFF; scroll-behavior: smooth; overflow-x: hidden; width: 100%; height: 100%; } body { color: #000000 !important; background-color: #FFFFFF !important; font-family: "Arial", "Sans serif", "Roboto", "ApexNew" !important; width: 100%; height: 100%; } #footer { width: 100%; height: 520px; color: #FFFFFF; background-color: #000000; } /* --Footer-- */ .ovfl { width: 200px; height: 200px; } <!doctype html> <html lang="en-US"> <head> <!-- CSS --> <link rel="stylesheet" href="../assets/css/pages/index.css"> </head> <body id="page-top" class="body"> <header id="header" class="header"> <nav id="navbar" class="navbar"> </nav> </header> <main id="main" class="main"> <div id="hero" class="hero"> </div> <div id="newsletter" class="newsletter"> </div> </main> <footer id="footer" class="footer"> <div> <a href="#" id="ovfl-link" class="ovfl-link"><img src="../../../Pictures/JPG/gred.jpg" alt="Ovabis" id="ovfl" class="ovfl"></a> </div> </footer> </body> </html> This is what it looks like. The image is displayed above the footer :-( Many Thanks astroship A: You have the impression that the image is not in the footer because its background color is not black but white. But this is the behavior that you attribute in your css with * {}. Just remove the background-color of * and you will see that the image is actually in your footer: *{ color: #000000; /* This rule color your #ovfl image background*/ /*background-color: #FFFFFF;*/ font-family: "Arial", "Sans serif", "Roboto", "ApexNew"; padding: 0; margin: 0; } html{ color: #000000; background-color: #FFFFFF; scroll-behavior: smooth; overflow-x: hidden; width: 100%; height: 100%; } body{ color: #000000 !important; background-color: #FFFFFF !important; font-family: "Arial", "Sans serif", "Roboto", "ApexNew" !important; width: 100%; height: 100%; } #footer{ width: 100%; height: 520px; color: #FFFFFF; background-color: #000000; } /* --Footer-- */ .ovfl{ width: 200px; height: 200px; } <!doctype html> <html lang="en-US"> <head> <!-- CSS --> </head> <body id="page-top" class="body"> <header id="header" class="header"> <nav id="navbar" class="navbar"> </nav> </header> <main id="main" class="main"> <div id="hero" class="hero"> </div> <div id="newsletter" class="newsletter"> </div> </main> <footer id="footer" class="footer"> <div> <a href="#" id="ovfl-link" class="ovfl-link"> <img src="https://www.google.fr/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Ovabis" id="ovfl" class="ovfl"> </a> </div> </footer> </body> </html>
[ "gis.stackexchange", "0000332466.txt" ]
Q: Show/mark not visible labels (colliding labels) If "show all labels, also colliding" is not active, some colliding labels will not show up. So far so good, but I would like to know, how often and where this happens and maybe why. Something like a red dot where the invisible label is, would satisfy me. Any ideas? A: This functionality is being introduced in QGIS 3.10 (and is currently available in the "nightly" beta releases)
[ "arduino.stackexchange", "0000053419.txt" ]
Q: Why can't my bluetooth receive serial data from my android phone, but can send serial data from my bluetooth to my android phone? I can receive serial data from my phone but I can't send serial data to the arduino using bluetooth. I can see my input from serial monitor to my Android but not the other way. I'm using ARF7044A bluetooth module if that matters. Any help would be appreciated please. Arduino to Android: Working Android to Arduino: Not working. Here is the wiring: Here is the code: char state; void setup() { pinMode(8, OUTPUT); Serial.begin(9600); } void loop() { if(Serial.available()) { state = Serial.read(); Serial.println(state); } if (state == 'a') { digitalWrite(8, HIGH); } else if(state == 'b') { digitalWrite(8,LOW); } } A: Your erroneous level shifting attempt from Bluetooth TX to Arduino RX is the root of your problem. Pins 0 and 1 are also connected to the on-board USB interface chip via a pair of 1kΩ resistors. These resistors serve two purposes: To "weaken" the drive of the USB chip's UART interface (actually only needed on the USB chip's TX -> Arduino RX connection), and To protect both the USB chip and the main MCU from damage should two connected pins be set to opposing levels, which would cause high currents to flow through both output drivers. The TX pin of the USB chip is actively driven HIGH all the time when idle (stupid design by Arduino, it should be Hi-Z when the port is not open), and the RX pin is pulled up by the internal pullup resistor in the USB chip. Further, when the Arduino's Serial is in use the TX pin of the Arduino is actively driven HIGH when idle (or LOW when transmitting a "1" bit). The actual circuit you have looks more like this: simulate this circuit – Schematic created using CircuitLab Transmitting from the Arduino to the BT module is straight forward enough - the "high" point of the circuit is the Arduno's TX pin at 5V when idle. Current flows through R2 to the USB RX pin, and through R5 to the BT RX pin, with a portion split off to ground, which is what you want for your level shifting. Communication in the other direction, however, is different, because you have two balanced "high" points in your circuit - one at the USB TX and one at the Bluetooth TX - and the fact you have 1kΩ resistors in both branches means that neither transmitter is "stronger" than the other. This means that when the BT TX is LOW (0V) you have around 2.5V at the Arduino RX pin (5V over two 1kΩ resistors = 2.5V in the center tap - see here). Since 2.5V is neither within the Arduino's HIGH nor LOW voltage ranges (which are more than 3.5V for HIGH and less than 1.5V for LOW when running from 5V) the input is completely ignored. The 3.3V transmitted by the Bluetooth module is a little under the official threshold for a HIGH signal on an Arduino, but in practice, it usually is detected fine. So remove the resistor network from the Bluetooth's TX pin and connect it directly to the Arduino. Since the input threshold voltage is a function of the supply voltage (0.7 * Vcc) it depends very much on your power supply as to whether it will work reliably or not. If you find it doesn't, you should use some upward level shifting. There are simple MOSFET based bi-directional level shifters available cheaply that are a better solution than resistors, and will allow proper operation in both directions, shifting a high voltage to a low one and a low voltage to a high one. These are good for lower frequency communications such as UART. If you should need higher frequency, or you find a simple MOSFET based shifter isn't working for you then a 74HCT08 or similar chip (be sure to use the HCT range not the HC range) or a dedicated level shifting chip may be in order.
[ "stackoverflow", "0017220355.txt" ]
Q: how to make yahoo like newsfeed that is on yahoo's front page with jQuery? I'm tying to make identical or very similar to yahoo newsfeed that is present on it's front page. I have put the image below my website is java based, Spring and Jsf 2.0 and primefaces. A: this has exactly what I was looking for. http://www.agilecarousel.com/flavor_2.htm
[ "stackoverflow", "0058876545.txt" ]
Q: spring boot webflux login with username or email address I am new to spring boot webflux, and am using Cassandra as my database. I can't figure it out how to login with username or email. I have three tables user table Create Table user ( userid bigint, username text, password text, name text, email text, phone text, birthday text, biography text, PRIMARY KEY (userid) ) user_username table Create Table user ( username text, userid bigint, password text, name text, email text, phone text, birthday text, biography text, PRIMARY KEY (username) ) user_email table Create Table user ( email text, username text, userid bigint, password text, name text, phone text, birthday text, biography text, PRIMARY KEY (email) ) @PostMapping("/signin") public Mono<ResponseEntity<?>> login(@RequestBody AuthLoginRequest authLoginRequest) { return userService.findByUsernameOrEmail(authLoginRequest.getUsernameOrEmail()).map((user) -> { if(passwordEncoder.encode(authLoginRequest.getPassword()).equals(user.getPassword())) { return ResponseEntity.ok(new ApiResponse(tokenProvider.generateToken(user))); }else { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } }.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()); } This is where the issues comes in how will i return a user mono Mono . if they login with their username i have to query the user_username table or if they login with their email address i have to query the user_email table. @Service public class UserService() { public Mono<User> findByUsernameOrEmail(String usernameOrEmail) { } } Do i need to zip the user_username and user_email class? Please i need a solution i haven't seen any related issue concerning this. please i need a working solution. Based on your answer @NikolaB i have edited this question to show what i have done so far public Mono<User> findByUsernameOrEmail(String usernameOrEmail) { return userUsernameRepository.findById(usernameOrEmail) .map(userUsername -> { System.out.println("Checking name "+userUsername.getName());// i printed out the name of the user return new User(userUsername); }).switchIfEmpty(userEmailRepository.findById(usernameOrEmail) .map(userEmail -> { System.out.println("Checking name " +userEmail.getName());// i printed out the name of the user return new User(userEmail); })); } Everything works well... My user table public class User { //My Constructors public User(UserUsername userUsername) { System.out.println("Userid " + userUsername.getUserId());/I am getting the userId User user = new User(); BeanUtils.copyProperties(userUsername, user); System.out.println("New Userid " + user.getUserId()); //I am getting the userId } public User(UserEmail userEmail) { System.out.println("Userid " + userEmail.getUserId()); /I am getting the userId User user = new User(); BeanUtils.copyProperties(userEmail, user); System.out.println("New Userid " + user.getUserId()); /I am getting the userId } } My post mapping Here the User is empty @PostMapping("/signin") public Mono<ResponseEntity<?>> login(@RequestBody AuthLoginRequest authLoginRequest) { return userService.findByUsernameOrEmail(authLoginRequest.getUsernameOrEmail()).map((user) -> { if(passwordEncoder.encode(authLoginRequest.getPassword()).equals(user.getPassword())) { return ResponseEntity.ok(new ApiResponse(tokenProvider.generateToken(user))); }else { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } }.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()); } A: You need to query the user_username table and if there is an entry, map it to User class and return it. If there isn't you need to query the user_email table and map it to UserUsername class if an entry exists. Easiest way to do it would be with repositories: public interface UserUsernameRepository extends ReactiveCassandraRepository<UserUsername, String> { } public interface UserEmailRepository extends ReactiveCassandraRepository<UserEmail, String> { } Here is the usage: @Service public class UserService() { @Autowired private UserUsernameRepository userUsernameRepository; @Autowired private UserEmailRepository userEmailRepository; public Mono<User> findByUsernameOrEmail(String usernameOrEmail) { return userUsernameRepository.findById(usernameOrEmail) .switchIfEmpty(userEmailRepository.findById(usernameOrEmail) .map(userEmail -> new UserUsername(userEmail))) // or some other way to map properties to UserUsername class .map(userUsername -> new User(userEmail)) // or some other way to map properties to wanted User class } } If both queries returned no results (empty) then service method would return Mono.empty() which is exactly what you need. Note that you have to implement property mapping in new UserUsername and new UserUsername constructors. Edit Ok I think I know where the problem is, in the User constructors you are creating a new User instance and mapping UserUsername/UserEmail instance properties to that instantiated User instance when in fact that instance is not tied to instance which is returned by the constructor. Either set the fields manually in those constructors like this: public User(UserUsername userUsername) { System.out.println("Userid " + userUsername.getUserId()); //I am getting the userId this.email = userUsername.getEmail(); this.username = userUsername.getUsername(); ... } or in the service method map with BeanUtils: public Mono<User> findByUsernameOrEmail(String usernameOrEmail) { return userUsernameRepository.findById(usernameOrEmail) .map(userUsername -> { System.out.println("Checking name "+userUsername.getName());// i printed out the name of the user User user = new User(); BeanUtils.copyProperties(userUsername, user); return user; }).switchIfEmpty(userEmailRepository.findById(usernameOrEmail) .map(userEmail -> { System.out.println("Checking name " +userEmail.getName());// i printed out the name of the user User user = new User(); BeanUtils.copyProperties(userEmail, user); return user; })); }
[ "stackoverflow", "0030145939.txt" ]
Q: Batch modify text files I have a million markdown files spread across several sub-directories files with different titles where I want to change: # A Markdown title to --- title: "A Markdown title" --- …while keeping the rest of the file intact. Any ideas? OS X solutions prefered. A: You could use sed -i 's/^# \(.*\)$/---\ntitle: \"\1\"\n---/' *. The * means apply to all files in the current directory. Alternatively search for files using Unix find. An example usage: find . -type f -name "*.java" -exec sed 's/^# \(.*\)$/---\ntitle: \"\1\"\n---/' "{}" > "{}.bak" \; -exec mv "{}.bak" "{}" \; This looks for all files with a java extension (in this directory and sub directories) and performs the substitution. It first stores the content in a file with a .bak extension and later moves it to the original file. You can adjust the depth to search for the files using find's -maxdepth and -mindepth options.
[ "stackoverflow", "0031951479.txt" ]
Q: Chaning return key into tab function I have a client who wants the Enter/Return key to perform the same function as the tab key on form fields. Here's my code so far. It won't work. Anyone know why? <script> $('input, select').live('keydown', function(e) { if (e.keyCode === 13) { if (e.shiftKey) { var focusable = form.find('input,a,select,button,textarea').filter(':visible'); focusable.eq(focusable.index(this)-1).focus(); } else { var focusable = form.find('input,a,select,button,textarea').filter(':visible'); focusable.eq(focusable.index(this)+1).focus(); return true; } } }); </script> A: You'll want to prevent the default behavior of the enter key with preventDefault(); You put form.find in there, but I don't see form set anywhere. Maybe try $('form')? I've set up a basic js fiddle for you to check out. Is this the functionality you were going for? $('input, select').on('keydown', function (e) { if (e.keyCode === 13) { e.preventDefault(); if (e.shiftKey) { var focusable = $('form').find('input,a,select,button,textarea').filter(':visible'); focusable.eq(focusable.index(this) - 1).focus(); } else { var focusable = $('form').find('input,a,select,button,textarea').filter(':visible'); focusable.eq(focusable.index(this) + 1).focus(); return true; } } }); Note that .live() is deprecated and you could just use .on()
[ "stackoverflow", "0024846434.txt" ]
Q: Where does user order get recorded in OpenCart? I'm trying to find the controller responsible for saving orders to the user's record after checking out. Which one would that be? A: Orders are first added to the database in the file /catalog/model/checkout/order.php. This is called by the final page of the checkout, which is /catalog/controller/checkout/confirm.php on the default checkout. However, this just sets up what's referred to as a 'missing order' which is an order where the order_status_id value is set to 0 - due to the order not currently marked as paid. Once the customer pays, the payment gateway used will update the order setting the correct order status. You can find all of the payment gateways in /catalog/controller/payment/
[ "stackoverflow", "0006690780.txt" ]
Q: CALayer with rotation animation I have masked an image like this: UIView *maskImage; maskImage = [[UIView alloc] init]; maskImage.backgroundColor = UIColorFromRGB(FTRMaskColor); maskImage.frame = newFrame; CALayer *theLayer = [CALayer layer]; theLayer.contents = (id)[[UIImage imageNamed:@"image.png"] CGImage]; theLayer.frame = newFrame; maskImage.layer.mask = theLayer; It works fine but the main problem is if I want to rotate the my Ipad, the rotation animation of the view or the layer (I'm not very sure) doesn't work. It rotates without animation. Could you help, please? A: To rotate a CALayer: NSNumber *rotationAtStart = [myLayer valueForKeyPath:@"transform.rotation"]; CATransform3D myRotationTransform = CATransform3DRotate(myLayer.transform, myRotationAngle, 0.0, 0.0, 1.0); myLayer.transform = myRotationTransform; CABasicAnimation *myAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; myAnimation.duration = kMyAnimationDuration; myAnimation.fromValue = rotationAtStart; myAnimation.toValue = [NSNumber numberWithFloat:([rotationAtStart floatValue] + myRotationAngle)]; [myLayer addAnimation:myAnimation forKey:@"transform.rotation"]; myRotationAngle should be in radians. Use negative values for counter-clockwise rotation and positive values for clockwise.
[ "stackoverflow", "0041875395.txt" ]
Q: docker networking: How to know which ip will be assigned? Trying to get acquainted with docker, so bear with me... If I create a database container (psql) with port 5432 exposed, and then create another webapp which wants to connect on 5432, they get assigned some ip addresses on the bridge network from docker... probably 172.0.0.1 and 172.0.0.2 respectively. if I fire up the containers, inspect their ips with docker network inspect <bridge id> if I then take those ips and plug in the port on my webapp settings, everything works great... BUT I shouldn't have to run my webapp, shell into it, change settings, and then run a server, I should be able to just run the container... So what am I missing here, is there a way to have these two containers networked without having to do all of that? A: Use a Docker network docker create network myapp docker run --network myapp --name db [first-container...] docker run --network myapp --name webapp [second-container...] # ... and so on Now you can refer to containers by their names, from within other containers. Just like they were hostnames in DNS. In the application running in the webapp container, you can configure the database server using db as if it is a hostname.
[ "stackoverflow", "0016462567.txt" ]
Q: MS Analysis Cube - one-to-many joins I am building an OLAP cube in MS SQL Server BI Studio. I have two main tables that contain my measures and dimensions. One table contains Date | Keywords | Measure1 where date-keyword is the composite key. One table contains looks like Date | Keyword | Product | Measure2 | Measure3 where date-keyword-product is the composite key. My problem is that there can be a one-to-many relationship between date-keyword's in the first table and date-keyword's in the second table (as the second table has data broken down by product). I want to be able to make queries that look something like this when filtered for a given Keyword: Measure1 Measure2 Measure3 ============================================================ Tuesday, January 01 2013 23 19 18 ============================================================ Bike 23 Car 23 16 13 Motorcycle 23 Caravan 23 2 4 Van 23 1 1 I've created dimensions for the Date and ProductType but I'm having problems creating the dimension for the Keywords. I can create a Keyword dimension that affects the measures from the second table but not the first. Can anyone point me to any good tutorials for doing this sort of thing? A: Turns out the first table had one row with all null values (a weird side effect of uploading an excel file straight into MS SQL Server db). Because the value that the cube was trying to apply the dimension to was null in this one row, the whole cube build and deploy failed with no useful error messages! Grr
[ "ru.stackoverflow", "0000807833.txt" ]
Q: Где разместить логику перед выводом шаблона страницы (Drupal 8)? Заходим в тему default-theme > templates > page.html.twig, вижу структуру twig с некоторым количеством простых условий по типу if page.highlighted. А если нужно более сложную логику организовать, например между загрузкой страницы и выводом информации из этой страницы через шаблон page.html.twig разместить контроллер, который сделает некоторые манипуляции и после этого уже запустит этот шаблон. Как в данном случае поступают в Drupal 8? A: Логика получения данных должна быть в сервисах. Writing your first Drupal service Symfony и Drupal 8 не являются традиционными реализациями архитектуры MVC, так как нет отдельного слоя модели, например как в CodeIgniter. Одной из наиболее важных функций Symfony и Drupal являются сервисы, которые есть (или должны быть) независимыми и многоразовыми реализациями различных функций. Поэтому, если вам нужна логика выборки данных, вы можете создать свой собственный сервис, который делает это, и использовать эту службу в своем контроллере, вместо того, чтобы загрязнять его лишней логикой. Еще отдельно в Drupal есть огромное количество хуков, посмотрите например на function THEME_NAME_preprocess_node(&$variables) { // your code } по нему можно понять общий принцип. Можно помещать логику в эти хуки, но мне больше нравяться тонкие хуки и логику все таки переносить в сервисы. А в хуках просто использовать их.
[ "stackoverflow", "0041432673.txt" ]
Q: How to decrease prod bundle size? I have a simple app, initialized by angular-cli. It display some pages relative to 3 routes. I have 3 components. On one of this page I use lodash and Angular 2 HTTP modules to get some data (using RxJS Observables, map and subscribe). I display these elements using a simple *ngFor. But, despite the fact my app is really simple, I get a huge (in my opinion) bundle package and maps. I don't talk about gzip versions though but size before gzipping. This question is just a general recommendations inquiry. Some tests results: ng build Hash: 8efac7d6208adb8641c1 Time: 10129ms chunk {0} main.bundle.js, main.bundle.map (main) 18.7 kB {3} [initial] [rendered] chunk {1} styles.bundle.css, styles.bundle.map, styles.bundle.map (styles) 155 kB {4} [initial] [rendered] chunk {2} scripts.bundle.js, scripts.bundle.map (scripts) 128 kB {4} [initial] [rendered] chunk {3} vendor.bundle.js, vendor.bundle.map (vendor) 3.96 MB [initial] [rendered] chunk {4} inline.bundle.js, inline.bundle.map (inline) 0 bytes [entry] [rendered] Wait: 10Mb vendor bundle package for such a simple app? ng build --prod Hash: 09a5f095e33b2980e7cc Time: 23455ms chunk {0} main.6273b0f04a07a1c2ad6c.bundle.js, main.6273b0f04a07a1c2ad6c.bundle.map (main) 18.3 kB {3} [initial] [rendered] chunk {1} styles.bfdaa4d8a4eb2d0cb019.bundle.css, styles.bfdaa4d8a4eb2d0cb019.bundle.map, styles.bfdaa4d8a4eb2d0cb019.bundle.map (styles) 154 kB {4} [initial] [rendered] chunk {2} scripts.c5b720a078e5464ec211.bundle.js, scripts.c5b720a078e5464ec211.bundle.map (scripts) 128 kB {4} [initial] [rendered] chunk {3} vendor.07af2467307e17d85438.bundle.js, vendor.07af2467307e17d85438.bundle.map (vendor) 3.96 MB [initial] [rendered] chunk {4} inline.a345391d459797f81820.bundle.js, inline.a345391d459797f81820.bundle.map (inline) 0 bytes [entry] [rendered] Wait again: such a similar vendor bundle size for prod? ng build --prod --aot Hash: 517e4425ff872bbe3e5b Time: 22856ms chunk {0} main.95eadabace554e3c2b43.bundle.js, main.95eadabace554e3c2b43.bundle.map (main) 130 kB {3} [initial] [rendered] chunk {1} styles.e53a388ae1dd2b7f5434.bundle.css, styles.e53a388ae1dd2b7f5434.bundle.map, styles.e53a388ae1dd2b7f5434.bundle.map (styles) 154 kB {4} [initial] [rendered] chunk {2} scripts.e5c2c90547f3168a7564.bundle.js, scripts.e5c2c90547f3168a7564.bundle.map (scripts) 128 kB {4} [initial] [rendered] chunk {3} vendor.41a6c1f57136df286f14.bundle.js, vendor.41a6c1f57136df286f14.bundle.map (vendor) 2.75 MB [initial] [rendered] chunk {4} inline.97c0403c57a46c6a7920.bundle.js, inline.97c0403c57a46c6a7920.bundle.map (inline) 0 bytes [entry] [rendered] ng build --aot Hash: 040cc91df4df5ffc3c3f Time: 11011ms chunk {0} main.bundle.js, main.bundle.map (main) 130 kB {3} [initial] [rendered] chunk {1} styles.bundle.css, styles.bundle.map, styles.bundle.map (styles) 155 kB {4} [initial] [rendered] chunk {2} scripts.bundle.js, scripts.bundle.map (scripts) 128 kB {4} [initial] [rendered] chunk {3} vendor.bundle.js, vendor.bundle.map (vendor) 2.75 MB [initial] [rendered] chunk {4} inline.bundle.js, inline.bundle.map (inline) 0 bytes [entry] [rendered] So a few questions for deploying my app on prod: Why are the vendor bundles so huge? Is tree shaking properly used by angular-cli? How to improve this bundle size? Are the .map files required? Are the testing features included in bundles? I don't need them in prod. Generic question: what are the recommanded tools to pack for prod? Maybe angular-cli (using Webpack in the background) is not the best option? Can we do better? I searched many discussions on Stack Overflow, but I haven't found any generic question. A: Update February 2020 Since this answer got a lot of traction, I thought it would be best to update it with newer Angular optimizations: As another answerer said, ng build --prod --build-optimizer is a good option for people using less than Angular v5. For newer versions, this is done by default with ng build --prod Another option is to use module chunking/lazy loading to better split your application into smaller chunks Ivy rendering engine comes by default in Angular 9, it offers better bundle sizes Make sure your 3rd party deps are tree shakeable. If you're not using Rxjs v6 yet, you should be. If all else fails, use a tool like webpack-bundle-analyzer to see what is causing bloat in your modules Check if you files are gzipped Some claims that using AOT compilation can reduce the vendor bundle size to 250kb. However, in BlackHoleGalaxy's example, he uses AOT compilation and is still left with a vendor bundle size of 2.75MB with ng build --prod --aot, 10x larger than the supposed 250kb. This is not out of the norm for angular2 applications, even if you are using v4.0. 2.75MB is still too large for anyone who really cares about performance, especially on a mobile device. There are a few things you can do to help the performance of your application: 1) AOT & Tree Shaking (angular-cli does this out of the box). With Angular 9 AOT is by default on prod and dev environment. 2) Using Angular Universal A.K.A. server-side rendering (not in cli) 3) Web Workers (again, not in cli, but a very requested feature) see: https://github.com/angular/angular-cli/issues/2305 4) Service Workers see: https://github.com/angular/angular-cli/issues/4006 You may not need all of these in a single application, but these are some of the options that are currently present for optimizing Angular performance. I believe/hope Google is aware of the out of the box shortcomings in terms of performance and plans to improve this in the future. Here is a reference that talks more in depth about some of the concepts i mentioned above: https://medium.com/@areai51/the-4-stages-of-perf-tuning-for-your-angular2-app-922ce5c1b294 A: Use latest angular cli version and use command ng build --prod --build-optimizer It will definitely reduce the build size for prod env. This is what the build optimizer does under the hood: The build optimizer has two main jobs. First, we are able to mark parts of your application as pure,this improves the tree shaking provided by the existing tools, removing additional parts of your application that aren’t needed. The second thing the build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decrease the size of your JavaScript bundles, and increase the boot speed of your application for your users. Note : One update for Angular 5 and up, the ng build --prod automatically take care of above process :) A: Lodash can contribute a bug chunk of code to your bundle depending on how you import from it. For example: // includes the entire package (very large) import * as _ from 'lodash'; // depending on your buildchain, may still include the entire package import { flatten } from 'lodash'; // imports only the code needed for `flatten` import flatten from 'lodash-es/flatten' Personally I still wanted smaller footprints from my utility functions. E.g. flatten can contribute up to 1.2K to your bundle, after minimization. So I've been building up a collection of simplified lodash functions. My implementation of flatten contributes around 50 bytes. You can check it out here to see if it works for you: https://github.com/simontonsoftware/micro-dash
[ "stackoverflow", "0059108723.txt" ]
Q: Postgresql - How to get numeric value from the end of string and string without end numeric value I have the following usernames in Postgresql user table. **username** test 123test 123test456 test123 test45test test55test55 So I am trying to get the string without end numeric value and end numeric value seperately. I am expecting following output str num ---------------- test 0 123test 0 123test 456 test 123 test45test 0 test55test 55 How to write a Postgresql query that will return the above result? A: You could use regexp_replace() and substring(): select regexp_replace(username, '\d+$', '') str, coalesce(substring(username from '\d+$')::int, 0) num from mytable Demo on DB Fiddlde: with mytable as ( select 'test' username union all select '123test' union all select '123test456' union all select 'test123' union all select 'test45test' union all select 'test55test55' ) select regexp_replace(username, '\d+$', '') str, coalesce(substring(username from '\d+$')::int, 0) num from mytable str | num :--------- | --: test | 0 123test | 0 123test | 456 test | 123 test45test | 0 test55test | 55
[ "stackoverflow", "0014486611.txt" ]
Q: For how long before standardisation was `string` available? C++ was formally standardised in 1998, but how far back can we find a class named string that looks like std::string does in C++2003 in a pre-standard C++ implementation? I ask because CString, as part of MFC, has been "out there" since 1992 and I'm trying to determine whether it was first seen before or after what eventually became std::string. A: Well before. In 1992 everybody was still rolling their own string classes. Remember that std::string was originally terrible, and then it became terrible and an STL-style container- but that was very late in the process, as the Committee delayed the first Standard for two years to fit in the STL and everything Stepanov needed. So std::string wasn't finalized until fairly late.
[ "stackoverflow", "0004885815.txt" ]
Q: Changing state specific mxml parts in AS3 I'm using something like this in my MXML file: <s:label id='mxml_label' text.state1='test' text.state2='test 2' /> Now i would like to change the state1 text from as3 on runtime. Anyone any suggestions? thx. A: You could bind the text for state1 to a bindable string variable that you will then update whenever you want. [Bindable] private var state1TextString:String = "test"; Then your expression becomes : text.state1="{state1TextString}"
[ "stackoverflow", "0031122008.txt" ]
Q: Keeping focus on cells in Excel using C# I am creating a spreadsheet that collects data from a site and inserts the data into excel. For no reason other than a way for me to follow the data as it fills the sheet with information, is there a way to keep focus on the current cell to force the sheet to scroll (as if clicking the down arrow on the scroll bar) along with the data entry? My current code is as follows: else if (driver.FindElements(By.XPath("//table[7]/tbody /tr/td[11]")).Count > 0) { activesheet.Range["D" + n].Value = driver.FindElement(By.XPath("//table[7]/tbody/tr/td[11]")).Text; activesheet.Range["A" + n].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen); activesheet.Range["B" + n].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen); activesheet.Range["C" + n].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen); activesheet.Range["D" + n].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen); activesheet.Range["E" + n].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen); } I am sure it's very simple, I just have not been able to find this information/command, nor am I sure I am wording my searches correctly or if one even exists. A: Use the ScrollRow property of the ActiveWindow. If you just want to "hit the down arrow" you can increment. //app is a valid reference to a Microsoft.Office.Interop.Excel.Application instance app.ActiveWindow.ScrollRow++; Reference: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.window.scrollrow.aspx
[ "stackoverflow", "0039642803.txt" ]
Q: PHP how to detect chrome on IOS, Android, and Windows? eregi is an older code and works when I load chrome for chrome specific functions. I have seen Java tutorials on detection for iOS, Android, and windows, but for PHP it seems limited. preg_match seemed to give me issues on how this was used. How would you detect it on all 3 so you get the correct browser? This is what I currently use: function is_chrome() { return(eregi("chrome", $_SERVER['HTTP_USER_AGENT'])); //return(preg_match(“/applewebkit/i”, $_SERVER[‘HTTP_USER_AGENT’])); } if(is_chrome()) { // code for Chrome Browser here echo $chrome = 'You are using Google Chrome Browser.'; } else{ echo $chrome = 'hide'; } A: You could use some 3rd party library to detect browsers, e.g. Browser.php Typical Usage: $browser = new Browser(); if( $browser->getBrowser() == Browser::BROWSER_CHROME && $browser->getPlatform() == Browser::PLATFORM_WINDOWS ) { echo 'Chrome on Windows'; }
[ "stackoverflow", "0016229663.txt" ]
Q: Will the DOM structure vary for same HTML based on the browser Is the DOM structure is browser dependent for the base HTML files. If not then will the structure vary when the applications uses some java script libraries (Jquery/Extjs/etc) for the UI elements ? A: There are some situtaions where the dom structure can be different in different browsers. An element is supported by one browser, but it is not in another (especiall very old) browser The same applies to CSS attached to elements Javascript libraries are free to act differently on different browsers, so there is no guarantee that the dom tree will be the same. But in practice I've never enountered problems which were caused by differing DOM structures.
[ "stackoverflow", "0062410380.txt" ]
Q: std::bad_cast vs NULL, what's the difference? Why we need std::bad_cast when It returns Null when it fails? I learnt that when dynamic_cast fails it returns Null So I could check if Null was returned it means an error happened. But why std::bad_cast exception was added to C++? A: Because you can't have a null reference. A dynamic_cast<T*> can return nullptr as a failure but dynamic_cast<T&> can't, since you're returning a reference to the object. For that case you need an exception to know that the cast failed.
[ "stackoverflow", "0012894898.txt" ]
Q: IIS take long time to first run I have a big website and we converted it to a web application. then again we published the application and get the result files in to another web application and do our own development on top of that. above steps are taken to reduce the build time. it reduced the build time but take long time to the first run. our site containing large number of files. is there any suggessions to reduce the run time. after each and every change we have to wait 5-10 minutes to load the site. A: I think Application Initialization Module will be usefull for you ;) EDIT Adding following code solved the problem, <compilation optimizeCompilations="true" /> Optional Boolean attribute Specifies whether dynamic compilation will recompile an entire site if a top-level file is changed. Top-level files include the Global.asax file and all files in the Bin and App_Code folders. If True, only changed files are recompiled.The default is False. For more information, see Understanding ASP.NET Dynamic Compilation.
[ "stackoverflow", "0043179021.txt" ]
Q: How do I make a command line program using click in python that takes separates command parameters that run different scripts? I have the following code: import click @click.group() def cli(): pass @click.command() def initdb(): click.echo('Initialized the database') @click.command() def dropdb(): click.echo('Dropped the database') cli.add_command(initdb) cli.add_command(dropdb) At the command line I want to be able to do something like the following: python clicktest.py cli initdb and have the following happen echo at the terminal: Initialized the database Or to enter into the terminal: python clicktest.py cli dropdb and have the following happen on the terminal: Dropped the database My problem is currently when I do this at the terminal: python clicktest.py cli initdb Nothing happens at the terminal, nothing prints when I think something should, namely the 'Initialized Database' echo. What am i doing wrong?? A: First, you should use it in command line like: python clicktest.py initdb python clicktest.py dropdb And in your clicktest.py file, place these lines at the bottom of your code: if __name__ == '__main__': cli() Unless, your code won't get work. EDIT: If you really want to use it in a way python clicktest.py cli initdb, then you have another choice: @click.group() def main(): pass @click.group() def cli(): pass @click.command() def initdb(): click.echo('Initialized the database') @click.command() def dropdb(): click.echo('Dropped the database') cli.add_command(initdb) cli.add_command(dropdb) main.add_command(cli) if __name__ == '__main__': main() Or even better (Using decorators instead): @click.group() def main(): pass @main.group() def cli(): pass @cli.command() def initdb(): click.echo('Initialized the database') @cli.command() def dropdb(): click.echo('Dropped the database') if __name__ == '__main__': main()
[ "stackoverflow", "0032384652.txt" ]
Q: How to capture the active control in Firemonkey? I am migrating a VCL application to FMX. I need to know the class of a control that has focus. The application works with various dynamically created frames with numerous input controls. In VCL I use the VCL.Forms.TScreen.OnActiveControlChange as this is the one place to consistently capture the active control. This event is not available in FMX.Forms.TScreen. What would be an alternative approach in FMX? A: The most similar approach in FMX would be to listen to the TForm.OnFocusChanged event. From within the event handler you could then look up theTForm.Focused property.
[ "stackoverflow", "0028082331.txt" ]
Q: Implement HTML syntax highlighting into a textarea for writing code I have a problem that seems simple but I fear that it is too complicated for just myself to implement. I'm trying to implement a textarea into a webpage where a user can write html code, press a button, and the interpreted html page shows up in a div next to the code. Very similar to w3schools "try it" sections. So far, I have everything implemented, and it works almost as intended, the code renders properly in the right place when you press a button. The next step is to implement syntax highlighting in the textarea such that it will recolor the text based on what tag or attribute is typed. Basically, I'd like the behavior to be exactly like what notepad++ does when you write html code. text turns blue, attribute="" text turns red, etc. My thinking is that I need to somehow read what's in the textarea word by word, test against all possible tag and attribute names, and repopulate the textarea with colored text. From what I've seen, I don't think this is possible with a traditional textarea, and I might have to implement a specialized applet in place of the textarea. Does anyone know what the least painful way of accomplishing this would be? I'm a computer science major just about to complete my degree, but my knowledge of web programming is very limited and I've only started delving into jquery and jsp, though I have a good amount of experience with HTML/CSS/Javascript. A: I had a similar requirement in the past. I found an awesome Javascript-based code editor that you can embed in your web-application. Click here to view the demo: Code Mirror HTML editor demo Click here to download Code Mirror: Code Mirror home/download User Manual: Code Mirror user-manual The editor supports syntax-highlighting, automatic indentation, intellisence auto suggestion, etc. Using it is as simple as importing the script: <script src="codemirror.js"></script> <link rel="stylesheet" href="codemirror.css"> And replacing the text-area with the code-mirror editor: var myCodeMirror = CodeMirror(function(elt) { myTextArea.parentNode.replaceChild(elt, myTextArea); }, {value: myTextArea.value}); If you are using JQuery, you can do it like this: var myCodeMirror = CodeMirror(function(elt) { $('#my-code-input').replaceWith(elt); }, {value: $('#my-code-input').val()});
[ "stackoverflow", "0040257684.txt" ]
Q: php get data from one to many tables I have 2 tables A & B Table A ID NAME 1 John 2 Jack 3 Mark Table B ID phone UserID s1 4586 1 s2 6996 1 s3 9654 2 they are one to many relation (John has 2 phone on Table 2) my sql query $sql = 'SELECT * FROM A Join B ON B.USER_ID = A.ID WHERE A.ID=:ID'; my PHP foreach($vars['GROUPS'] as $row) { <tr><th>Name</th><td><?=$row['Name']?></td></tr> <tr><th>phone</th><td><?=$row['phone']?></td></tr> } I want to show the phones number for this user John name then show all his details from table 2 . as it now loop for me A: You have 2 options: Use group_concat() function in sql to concatenate all telephone numbers a user has into a single string and use pretty much the same loop in php as you use now. select a.id, a.name, group_concat(b.phone) as phone from a inner join b on a.id=b.user_id group by a.id, a.name Leave your current sql query intact, but change the php loop displaying the table. In this case only print out a name with all the corresponding phone numbers after looping through all the records returned from the query. Just concatenate all phone numbers in the loop.
[ "stackoverflow", "0003816370.txt" ]
Q: C# Wrapping a primitive I known that deriving a class from a primitive is not possible, however, I would like my class to 'seem' like it's a primitive without casting. In this case, my class would operate much like a Decimal: public interface IFoo { static explicit operator Decimal(IFoo tFoo); } public class Foo: IFoo { private Decimal m_iFooVal; public Decimal Value { get { return m_iFooVal; } set { m_iFooVal= value; } } static explicit operator Decimal(IFoo tFoo) { return (tFoo as Foo).Value; } } The above code doesn't work because the explicit operator cannot be defined in an interface. My code deals with interfaces and I would like to keep it like that. Is it possible to convert IFoo to a Decimal? Any alternatives are welcome. Example: IFoo tMyFooInterfaceReference = GetFooSomehow(); Decimal iVal = tMyFooInterfaceReference; A: Why not just add another method to your IFoo interface called ToDecimal() and call that when needed? public interface IFoo { decimal ToDecimal(); } public class Foo : IFoo { public decimal Value { get; set; } public decimal ToDecimal() { return Value; } } Your code wouldn't be that much more complicated: IFoo tMyFooInterfaceReference = GetFooSomehow(); decimal iVal = tMyFooInterfaceReference.ToDecimal();
[ "stackoverflow", "0012743804.txt" ]
Q: Filter files using a wildcard character (java) Using a wildcard character I want to process files in a directory. If a wildcard character is specified I want to process those files which match the wildcard char else if not specified I'll process all the files. Here's my code List<File> fileList; File folder = new File("Directory"); File[] listOfFiles = folder.listFiles(); if(prop.WILD_CARD!=null) { Pattern wildCardPattern = Pattern.compile(".*"+prop.WILD_CARD+"(.*)?.csv",Pattern.CASE_INSENSITIVE); for(File file: listOfFiles) { Matcher match = wildCardPattern.matcher(file.getName()); while(match.find()){ String fileMatch = match.group(); if(file.getName().equals(fileMatch)) { fileList.add(file); // doesn't work } } } } else fileList = new LinkedList<File>( Arrays.asList(folder.listFiles())); I'm not able to put the files that match wildcard char in a separate file list. Pls help me to modify my code so that I can put all the files that match wildcard char in a separate file list. Here I concatenate prop.WILD_CARD in my regex, it can be any string, for instance if wild card is test, my pattern is .test(.)?.csv. And I want to store the files matching this wildcard and store it in a file list. A: I just tested this code and it runs pretty well. You should check for logical errors somewhere else. public static void main(String[] args) { String WILD_CARD = ""; List<File> fileList = new LinkedList<File>(); File folder = new File("d:\\"); File[] listOfFiles = folder.listFiles(); if(WILD_CARD!=null) { Pattern wildCardPattern = Pattern.compile(".*"+WILD_CARD+"(.*)?.mpp",Pattern.CASE_INSENSITIVE); for(File file: listOfFiles) { Matcher match = wildCardPattern.matcher(file.getName()); while(match.find()){ String fileMatch = match.group(); if(file.getName().equals(fileMatch)) { fileList.add(file); // doesn't work } } } } else fileList = new LinkedList<File>( Arrays.asList(folder.listFiles())); for (File f: fileList) System.out.println(f.getName()); } This returns a list of all *.mpp files on my D: drive. I'd also suggest using for (File file : listOfFiles) { Matcher match = wildCardPattern.matcher(file.getName()); if (match.matches()) { fileList.add(file); } }
[ "stackoverflow", "0013208352.txt" ]
Q: jQuery multiple if else statements stuck at second condition Someone please tell me why the following script only works to the first “else if” statement? Even if the width is below 800px I still get the 900px settings. Here is the live code http://jsbin.com/iranof/2/ <script type='text/javascript'> $(document).ready(function(){ var window_width = $(window).width(); if (window_width >= 900){ $('#adSize').attr('id','largeRectangle'); } else if (window_width <= 800) { $('#adSize').attr('id','mediumRectangle'); } else if (window_width <= 700) { $('#adSize').attr('id','square'); } else if (window_width <= 600) { $('#adSize').attr('id','smallSquare'); } else if (window_width <= 480) { $('#adSize').attr('id','mediumRectangle'); } }); </script> A: 700 <= 800. If window_width is less than 800, the first else if check will return true - and so its body will be invoked; all the other else if will be ignored. Rebuild your code so that <= checks deal with increasing numbers: else if (window_width <= 480) { ... } else if (window_width <= 600) { ... } else if (window_width <= 700) { ... } else if (window_width <= 800) { ... }
[ "stackoverflow", "0012731020.txt" ]
Q: How to have sub ordered lists correctly I'm not sure I understand the logistics of this. Basically I wanted to make a simple listing on a web blog that looks like: 1. item1 a. item2 2. item3 a. item4 b. item5 3. item6 And so on, basically a master list ordered numerically, with child lists under each master item that are lower-alpha ordered. I achieved this effect by using this HTML markup: <ol> <li>item1</li> <ol> <li>item2</li> </ol> <li>item3</li> <ol> <li>item4</li> <li>item5</li> </ol> <li>item6</li> </ol> With this small CSS rule: ol ol { list-style-type: lower-alpha; } /* sub ordered lists */ This issue I had was that according to the w3c validator: Element ol not allowed as child of element ol in this context. I think this problem ought have a very simple solution, I wasn't able to find one, and I'm not sure I follow why ol cannot be a child of ol. A: You do it like this: <ol> <li>item1 <ol> <li>item2</li> </ol> </li> </ol> You need to put the sublist inside the list item for the top level. A: There are several ways to control your sub-ordered list, either with CSS, or HTML. You almost were achieving the effect you want, to get something like this: 1. item1 a. item2 2. item3 a. item4 b. item5 3. item6 Your HTML should look like this: <ol> <li>item1 <ol> <li>item2</li> </ol> </li> <li>item3 <ol> <li>item4</li> <li>item5</li> </ol> </li> <li>item6</li> </ol> And your CSS should look like this: ol li{ list-style-type:decimal; } /* sub ordered lists level 1 */ ol li ol li { list-style-type: lower-alpha; } /* sub ordered lists level 2 */ You can also read more about a similar question here
[ "stackoverflow", "0029152648.txt" ]
Q: Python: How can I rename a dictionary item and still use it as case statement option? I am using a dictionary as a case statement in my application. I have the need to rename a dictionary item but still use the dictionary as a case statement. To illustrate what I am trying to do I create this example. def venus(): print 'Venus' def mars(): print 'Mars' def earth(): print 'Earth' def pluto(): print 'Pluto' options = { '1': venus, '2': mars, '3': earth} options['1']() options['2']() options['3']() options['1'] = 'pluto' options['1']() If you run it will print out the following: Venus Mars Earth Traceback (most recent call last): File "dict.py", line 22, in <module> options['1']() TypeError: 'str' object is not callable Before you ask, no I cannot just add another entry to the dictionary to catch the Pluto option. How can I rename a dictionary item and still use it as case statement option? A: Don't pass it in as a string. You need to change the dictionary reference to the object pluto which is your function... not the string 'pluto' options['1'] = pluto
[ "stackoverflow", "0005324868.txt" ]
Q: Propel case-insensitive order by usage problem I have been looking around for days and couldnt find anything helpfull. my problem is; I couldn't set criteria case-insensitive ORDER (A a b B D d). Because when I try to fetch my records from DB, its not ordering properly since ascii problems (A B C a b c ) I want to set my ORDER criteria like this; Criterias::setCriterias(Array('ORDER' => 'UPPER(name)')); But propel doesnt let me to use UPPER in setting criterias. So I have to set it like this; Criterias::setCriterias(Array('ORDER' => 'name')); I found something that may help, this function is doing what i want; setIgnoreCase(true) A new problem is coming with this function. If I set ORDER criteria without WHERE, it will working like a charm. But if I set 'WHERE' and 'ORDER' together, propel will giving me error. Fatal error: Uncaught exception 'PropelException' with message 'Unable to execute SELECT statement [] [wrapped: Cannot fetch TableMap for undefined table: ]' in /usr/local/share/pear/propel/query/ModelCriteria.php:1153 Stack trace: #0 /usr/local/share/pear/propel/query/ModelCriteria.php(1019): ModelCriteria->getSelectStatement(NULL) Thanks. A: This is fixed in Propel 1.6.x. I pushed a few tests to prove that: https://github.com/propelorm/Propel/commit/3fc74ccffb05931ec3187b0dcff77dce732ef325
[ "stackoverflow", "0009222401.txt" ]
Q: iphone:Display JSON data in uitableviewcell I used the following code: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { // cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } if (indexPath.row == 0) { CGRect myImageRect = CGRectMake(120.0f, 5.0f, 70.0f, 55.0f); UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect]; [myImage setImage:[UIImage imageNamed:@"logo.png"]]; [cell.contentView addSubview:myImage]; } else { int arrayIndex = [indexPath row]-1 ; mdict = [mmenuitems objectAtIndex:arrayIndex]; [mdict retain]; cell.textLabel.text =[mdict objectForKey:@"name"]; I got correct JSON parsed message in mmenuitems,and used indexPath.row = 0 to display a logo. But the problem is I didn't get the last item in tableview. Also when I scrolls the tableview the data reloads randomly and same gets repeated. A: I can gusse that you need to add 1 to your number of rows method: - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [mmenuitems count]+1//add 1 for the logo cell } So your rows count will be all the objects in the mmenuitems array + 1 cell for the logo. But a better way will be to add your logo to the table view header view and not to the table view rows, you can do it in your view did load after the table view is loaded: CGRect myImageRect = CGRectMake(120.0f, 5.0f, 70.0f, 55.0f); UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect]; [myImage setImage:[UIImage imageNamed:@"logo.png"]]; [self.tableView.tableHeaderView addSubview:myImage]; It will add your logo to a view on top of the first table row and won't mix in your table rows. I believe it will resolve your repetition problem. Good luck
[ "stackoverflow", "0049407143.txt" ]
Q: How to exclude results within this MySQL query I'm setting up a toxi tagging system for some articles, and am using this query as a starting point for testing... SELECT a.* FROM tagmap at, articles a, tag t, userExcludedArticles uea WHERE at.tag_id = t.tag_id AND (t.name IN ('bookmark', 'webservice', 'semweb')) AND a.id = at.articleID GROUP BY a.id If I have a table called userExcludedArticles (id, userID, articleID), which stores the id of articles a user has flagged as not wanting to see, how do I include that in the above query? For testing, I have two articles in total stored in my articles table, and added both of their ids to the userExcludedArticles for userID 1 - ie this user has effectively said they don't want to be shown those two articles. I added the following line to the query... AND (uea.userID='1' AND a.id <> uea.articleID) To give... SELECT a.* FROM tagmap at, articles a, tag t, userExcludedArticles uea WHERE at.tag_id = t.tag_id AND (t.name IN ('bookmark', 'webservice', 'semweb')) AND a.id = at.articleID AND (uea.userID='1' AND a.id <> uea.articleID) GROUP BY a.id But both articles appear when searching, instead of no articles. How do I get it to return all articles that match the included tags, while excluding any articles the user has flagged as not wanting to see? Thanks for your time and help. A: First, don't use GROUP BY when you don't use aggregates in the results. MySQL allows you to use it without aggregates, but it produces random results. I assume you're using it here because including userExcludedArticles table gave you duplicates of the rows. That's not the proper way to handle it. As your query is now written it will check every row in userExcludedArticles against every row in articles/tag/tagmap and if there is a row which doesn't have the article id it can be shown. This is why the articles aren't hidden. You need to use NOT EXISTS clause to check for this: SELECT a.* FROM tagmap at, articles a, tag t WHERE at.tag_id = t.tag_id AND (t.name IN ('bookmark', 'webservice', 'semweb')) AND a.id = at.articleID AND NOT EXISTS (SELECT 1 from userExcludedArticles WHERE userID='1' AND a.id = articleID) Now you don't need GROUP BY since there aren't multiple results per article and the articles are hidden if the userExcludedArticles contains a row with the article's id regardless of any other rows. Also would be better to use JOIN syntax for the tables rather than multiple in the FROM section.
[ "engineering.meta.stackexchange", "0000000212.txt" ]
Q: What will be the difference between the aerospace engineering and aircraft design tags? The aircraft-design and aerospace-engineering tags have seen a decent amount of use so far. I created aerospace-engineering1 as a more general term that could be applied to rockets and spacecraft (and, or course, spaceplanes). At the moment, though, they're being used rather interchangeably, as this question seems to show. How should we differentiate between the two? For what it's worth, here are the tag wiki excerpts: aircraft-design: For questions about how certain features of an aircraft affect its performance and function, such as engine type or wing configuration aerospace-engineering: Aerospace engineering is the primary branch of engineering concerned with the research, design, development, construction, and testing of aircraft and spacecraft. Here's a paragraph from the Wikipedia page on aerospace engineering: Aeronautical engineering was the original term for the field. As flight technology advanced to include craft operating in outer space, the broader term "aerospace engineering" has largely replaced it in common usage. Aerospace engineering, particularly the astronautics branch, is often referred to colloquially as "rocket science", such as in popular culture. 1I love being able to say, "I created aerospace engineering"! A: I prefer aerospace-engineering because it matches the convention we started out with, where disciplines of engineering get tagged "something-engineering." (Oversimplification; we may want to revisit tagging conventions at a future date, but not in this discussion.) I dislike aircraft-design because using "design" in tags runs the risk of inviting too-broad questions. Design is an involved and usually complex process, which we are not prepared to support here except by answering specific technical questions. Most of the questions that have been asked so far are related to the design process in one way or another; we don't need to be reminded of that. If more specific tags are needed for questions in aerospace-engineering, I can imagine many that seem like they would be appropriate for the right question. Rocketry, gliders, jet-propulsion, and so on. These focus in on specific technologies that users can be experts in; "design" doesn't achieve that in a tag. A: One tag is much more specific than the other. Great to have both in my opinion, just as we have a 'mechanical-engineering' and 'fluid-mechanics'. I recommend that the aerospace-engineering tag wiki includes the synonym aeronautical engineering in its tag wiki. A: Aircraft design is a subset of aerospace engineering. Calling it a "primary pursuit" is incorrect. Equally important are spacecraft design, launch vehicle design, and so on. Not all of aerospace engineering is aircraft design. Both tags should remain, and should not be synonymized.
[ "mathematica.stackexchange", "0000128101.txt" ]
Q: Controlling speed of frames for animated gif How can I control the speed of the animation? I would like the frames to pass one value per second, in others words, one frame per second. Is there any function that controls this output? g = Graphics[Table[{ Text[ Style[#, FontSize -> 40, Bold, Red], {0, 0}]}, 1]] & /@ Range[10] Export["C:\\Users\\JohnPeter\\Desktop\\Count.gif", g] A: Based on the JasonB comment One frame in $0,5sec$: g = Graphics[ Table[{Text[Style[#, FontSize -> 40, Bold, Red], {0, 0}]}, 1]] & /@ Range[10] Export["C:\\Users\\Leandro\\Documents\\Wolfram Mathematica\\1 - \ NB\\anima.gif", g, "DisplayDurations" -> 0.5] One frame in $1sec$: g = Graphics[ Table[{Text[Style[#, FontSize -> 40, Bold, Red], {0, 0}]}, 1]] & /@ Range[10] Export["C:\\Users\\Leandro\\Documents\\Wolfram Mathematica\\1 - \ NB\\anima.gif", g, "DisplayDurations" -> 1]
[ "stackoverflow", "0009894407.txt" ]
Q: Ruby Net::SFTP transfer interrupt handling How to handle Ruby Net::SFTP transfer interruption like network disconnection? When I run my example code and the network is disconnected during the transfer, application stays running. require 'net/sftp' Net::SFTP.start("testing","root",:timeout=>1) do |sftp| begin sftp.download!("testfile_100MB", "testfile_100MB") rescue RuntimeError =>e puts e.message end end A: You can create another thread to watch the downloading progress and crash the application if the download appears unresponsive. Since Net::SFTP allows you to pass in a custom handler to the download! method, you can set up the watcher thread like this: class CustomHandler def extend_time @crash_time = Time.now + 30 end # called when downloading has started def on_open(downloader, file) extend_time downloader_thread = Thread.current @watcher_thread = Thread.new{ while true do if Time.now > @crash_time downloader_thread.raise "Downloading appears unresponsive. Network disconnected?" end sleep 5 end } end # called when new bytes are downloaded def on_get(downloader, file, offset, data) extend_time end # called when downloading is completed def on_close(downloader, file) @watcher_thread.exit end end And don't forget to pass in the custom handler like this: sftp.download!(remote_path, local_path, :progress => CustomHandler.new)
[ "stackoverflow", "0046135457.txt" ]
Q: call callback with reference to field Consider such code: trait OnUpdate { fn on_update(&mut self, x: &i32); } struct Foo { field: i32, cbs: Vec<Box<OnUpdate>>, } impl Foo { fn subscribe(&mut self, cb: Box<OnUpdate>) { self.cbs.push(cb); } fn set_x(&mut self, v: i32) { self.field = v; //variant 1 //self.call_callbacks(|v| v.on_update(&self.field)); //variant 2 let f_ref = &self.field; for item in &mut self.cbs { item.on_update(f_ref); } } fn call_callbacks<CB: FnMut(&mut Box<OnUpdate>)>(&mut self, mut cb: CB) { for item in &mut self.cbs { cb(item); } } } If I comment variant 2 and uncomment variant 1, it doesn't compiles, because of I need &Foo and &mut Foo at the same time. But I really need function in this place, because of I need the same code to call callbacks in several places. So do I need macros here to call callbacks, or may be another solution? Side notes: in real code I use big structure instead of i32, so I can not copy it. Also I have several methods in OnUpdate, so I need FnMut in call_callbacks. A: An important rule of Rust's borrow checker is, mutable access is exclusive access. In variant 2, this rule is upheld because the reference to self.field and to mut self.cbs never really overlap. The for loop implicitly invokes into_iter on &mut Vec, which returns a std::slice::IterMut object that references the vector, but not the rest of Foo. In other words, the for loop does not really contain a mutable borrow of self. In variant 1, there is a call_callbacks which does retain a mutable borrow of self, which means it cannot receive (directly on indirectly) another borrow of self. In other words, at the same time: It accepts a mutable reference to self, which allows it to modify all its fields, including self.field. It accepts a closure that also refers to self, because it uses the expression self.field. Letting this compile would allow call_callbacks to mutate self.field without the closure being aware of it. In case of an integer it might not sound like a big deal, but for other data this would lead to bugs that Rust's borrow checker is explicitly designed to prevent. For example, Rust relies on these properties to prevent unsafe iteration over mutating containers or data races in multi-threaded programs. In your case it is straightforward to avoid the above situation. set_x is in control both of the contents of the closure and of the mutation to self.field. It could be restated to pass a temporary variable to the closure, and then update self.field, like this: impl Foo { fn subscribe(&mut self, cb: Box<OnUpdate>) { self.cbs.push(cb); } fn set_x(&mut self, v: i32) { self.call_callbacks(|cb| cb.on_update(&v)); self.field = v; } fn call_callbacks<OP>(&mut self, mut operation: OP) where OP: FnMut(&mut OnUpdate) { for cb in self.cbs.iter_mut() { operation(&mut **cb); } } } Rust has no problem with this code, and effect is the same. As an exercise, it is possible to write a version of call_callbacks that works like variant 2. In that case, it needs to accept an iterator into the cbs Vec, much like the for loop does, and it must not accept &self at all: fn set_x(&mut self, v: i32) { self.field = v; let fref = &self.field; Foo::call_callbacks(&mut self.cbs.iter_mut(), |cb| cb.on_update(fref)); } fn call_callbacks<OP>(it: &mut Iterator<Item=&mut Box<OnUpdate>>, mut operation: OP) where OP: FnMut(&mut OnUpdate) { for cb in it { operation(&mut **cb); } }
[ "math.stackexchange", "0000355187.txt" ]
Q: How is the Power set without the original set a partial order? This is a past exam question. Let S = {a,b,c} Define $\mathcal{P}(S)$ as the power set of S. Consider $\mathcal{P}(S)\setminus S$ Explain how this structure illustrates the concepts of partial order and maximal element. - Generalising, let the relation $R_p$ be defined such that apb $\Longleftrightarrow b = \mathcal{P}(A)\setminus A$ Of course, a partial order is a relation on a set (in this case, I think it'd be the theoretical universal set U s.t. all sets $A \in U$), which is reflexive, antisymmetric and transitive. However, I don't understand how this relation is reflexive. Taking the example of S={a,b,c}, $\mathcal{P}(S)\setminus S = \{\emptyset, \{a\},\{b\},\{c\},\{a,b\},\{a,c\}, \{b,c\}\}$ Clearly, by definition, $S \notin \mathcal{P}(S)\setminus S$. Defining the relation to be subset inclusion also does not make it reflexive. I can't think of any appropriate relationship that would be reflexive. I can see that the question wants me to show that it is a partial order, and then discuss how there is no unique maximal element - since {a,b}, {a,c} and {b,c} are all maximal. However, I feel like I must be missing something here - how can it be that a partial order exists between S and $\mathcal{P}(S)\setminus S$, when $\mathcal{P}(S)\setminus S$ seems to contradict the definition of reflexivity? (partial-order may be an appropriate tag, but I can't add it myself) A: The partial order is set inclusion. It is reflexive as (for example) $\{a\} \subseteq \{a\}$. It is not a partial order batween $S$ and $\mathcal{P}(S)\setminus S$, it a partial order within $\mathcal{P}(S)\setminus S$.
[ "gis.stackexchange", "0000023087.txt" ]
Q: AttributeError: MapDocObject: Unable to save on mxd.save/saveACopy? I'm trying to use arcpy to save an .mxd and am having an issue. It doesn't matter if I use mxd.save or mxd.saveACopy I get the same error. I know it doesn't look like I am doing anything w/ it here, but it's just a portion of my code: import arcpy import arcpy.mapping as map arcpy.env.overwriteOutput = True env.workspace = r"C:\MGIS\FinalProject2.gdb mxd = map.MapDocument(r"C:\MGIS\Finalproject2.mxd") df = map.ListDataFrames(mxd)[0] for df in map.ListDataFrames(mxd): df.scale = 2000000 #Add layers into map document addLayer = map.Layer(OKXcounties) addLayer1 = map.Layer(contourLabelText) addLayer2 = map.Layer(contoursClipLyr) addLayer3 = map.Layer(clipOKXLyr) map.AddLayer(df, addLayer, "AUTO_ARRANGE") map.AddLayer(df, addLayer1, "AUTO_ARRANGE") map.AddLayer(df, addLayer2, "AUTO_ARRANGE") map.AddLayer(df, addLayer3, "AUTO_ARRANGE") # Add contour Labels for lyr in map.ListLayers(mxd): if lyr.name == "contourLabelText": lyr.showLabels = True if lyr.name == "Contour Features": lyr.transparency = 100 mxd.saveACopy(mxd) I get the following error: Traceback (most recent call last): File "C:\Python26\ArcGIS10.0\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, in RunScript exec codeObject in __main__.__dict__ File "C:\MGIS\geog485\FinalProject2\mxdtest.py", line 7, in <module> mxd.saveACopy(mxd) File "C:\Program Files\ArcGIS\Desktop10.0\arcpy\arcpy\utils.py", line 181, in fn_ return fn(*args, **kw) File "C:\Program Files\ArcGIS\Desktop10.0\arcpy\arcpy\_mapping.py", line 668, in saveACopy self._arc_object.saveACopy(file_name) AttributeError: MapDocObject: Unable to save. Check to make sure you have write access to the specified file and that there is enough space on the storage device to hold your document. Space is not the issue, I have 60 GB of free space and I've checked the windows properties of the .mxd file. Read-only box is unchecked and I've "allowed" all permissions for all groups: Does anyone have any idea how if this is a bug or how I can fix this? I'm using ArcInfo 10.0 SP4. A: My guess is that you cannot save "over" a file. Does it work if there is no file of that name already on disk? Try deleting the existing file before the save.
[ "stackoverflow", "0036141269.txt" ]
Q: How to login with Account Number-Java Hi guys so I am trying to login using my Account Number which is stored in an arraylist, I am unable to match the user input with the Account Number.My code is below : Login Method-Main Class private void Login (){ int UserInput; Scanner option = new Scanner (System.in); Account Account = new Account(); ArrayList<Client> customers = bank.getCustomers(); //Gets Customer Info from Bank System.out.println("What is your Account Number?"); UserInput = option.nextInt(); if(UserInput==Account.getAccountNumber()){ Menu(); int choice = UserInput(); performAction(choice); //system.out.println(i+1 + ")" + customers.get(i).BasicInfo()); } else { System.out.println("Invalid Account Number"); } } ArrayList - Bank Class public class Bank { ArrayList<Client> customers = new ArrayList<Client>(); //Adds customer details in this void addCustomer(Client customer) { // TODO Auto-generated method stub customers.add(customer);//Adds customer from Menu to ArrayList } Client getCustomer(int account) { // TODO Auto-generated method stub return customers.get(account); //Returns Customer detail from ArrayList } ArrayList <Client> getCustomers (){ return customers; //Returns customers } } Hi guys what I am trying to do is make the userInput in the main class be able to match the AccountNumber from the 'GetMethod" I believe it is stored in an araylist in the 'Bank' class. If it does match the Account number then the other methods function within the if statement. Right now when I enter the AccountNumber it just goes to the else statement and displays "Invalid AccountNumber". I apologise if this doesnt make sense. A: From your code, I think you are saving account number of user somewhere else. The account number you get from the Account class is the next account number available to assign.As when you initialize the Account class, inside the Account constructor it increases the account number. That number is returned from Account.getAccountNumber(). There is no way this can be an account number of an existing user. Solution: You didn't post your customer class here. But you must have a account_number variable inside you customer class.you can set a getter for account number. Inside the bank you have list customer's. you will need to iterate through each customer and match the input account number with the account number of those customers.Your loop inside bank class could look like this: for(int i=0;i<customers.size();i++){ if(inputAccountNumber == customers.get(i).getAccountNumber()) { return true; } } This is not a scalable solution. You can set a hashmap for customer with account number as key and value as the instance of customer class for that customer. Hope this solves your problem.
[ "stackoverflow", "0023068069.txt" ]
Q: Will I be able to train the neural network with negative values in feature vector? I am working on handwritten character recognition . I have extracted certain features of a image to feed it to neural network. But , some of these values are negative. Can I feed these values to train the neural network? A: Short but precise: Yes, you may feed the network negative input values.
[ "stackoverflow", "0010774399.txt" ]
Q: How can I use in my project some classes from other project? I have an android project and I want to use some classes from another android project. How can I do that? In my project I draw the road between 2 points. From the new project I want to use some classes that help me draw more points on the map and tooltips with information for they. A: Create a library project containing the common part for the two projects. Make the two projects reference this Android library project.
[ "stackoverflow", "0005110807.txt" ]
Q: Python - invalid mode('w') or filename I've encountered a very odd error. I have this code as part of many of my functions in my python script: url=['http://agecommunity.com/query/query.aspx?name=', name, '&md=user'] url=''.join(url) file = open("QueryESO.xml", "w") filehandle = urllib.urlopen(url) for lines in filehandle.readlines(): file.write(lines) file.close() When I run in IDLE, everything works great. If I run it with Python (Command Line) then it gives me this error: [Errno 22] invalid mode('w') or filename: 'QueryESO.xml' Here's where it starts to get weird: Weird #1: I have the exact same code in different functions in my script, but the error only occurs for one of them. Weird #2: If I change the code to this, it works fine: url=['http://agecommunity.com/query/query.aspx?name=', name, '&md=user'] print url url=''.join(url) file = open("QueryESO.xml", "w") filehandle = urllib.urlopen(url) for lines in filehandle.readlines(): file.write(lines) file.close() I also tried moving the print url to after I joined the list, which didn't work, and I just tried print "", which also got the previously mentioned error. So I guess I've found a solution... but can anyone explain this behavior? Am I doing something wrong? (And do you need me to post the entire script so you can mess with it?) EDIT: Here is the entire code: import urllib from Tkinter import * import tkFont master = Tk() QUERY_ESO = "QueryESO.xml" def QueryXML(xml, attribute): x = ["<", attribute, ">"] x=''.join(x) z = xml.split(x, 1) x = ["</", attribute, ">"] x=''.join(x) z=z[1] z=z.split(x, 1) return z[0] def AddFriend(): nfentry = nfe2 name=nfentry.get() url=['http://agecommunity.com/query/query.aspx?name=', name, '&md=user'] url=''.join(url) file = open("QueryESO.xml", "w") filehandle = urllib.urlopen(url) for lines in filehandle.readlines(): file.write(lines) file.close() f = open(QUERY_ESO, "r") xml = f.readlines() f.close() xml=''.join(xml) f = open("Friends.txt", "r") filestring = f.read() f.close() fs = filestring.split('\n') if name in fs: print "Friend Already Added" elif xml == "<?xml version='1.0' encoding='utf-8'?><error>Failed to find user</error>": print "User does not exist" else: fs.append(name) fs = '\n'.join(fs) f = open("Friends.txt", "w") f.write(fs) f.close() nfe2.set("") nfentry = nfe2 def DeleteFriend(): ofentry = ofe2 name=ofentry.get() f = open("Friends.txt", "r") filestring = f.read() f.close() fs = filestring.split('\n') if name in fs: fs.remove(name) fs = '\n'.join(fs) f = open("Friends.txt", "w") f.write(fs) ofe2.set("") ofentry = ofe2 def IsOnline(name): url=['http://agecommunity.com/query/query.aspx?name=', name, '&md=user'] print url url=''.join(url) file = open("QueryESO.xml", "w") filehandle = urllib.urlopen(url) for lines in filehandle.readlines(): file.write(lines) file.close() f = open(QUERY_ESO, "r") xml = f.readlines() f.close() xml=''.join(xml) if xml == "<?xml version='1.0' encoding='utf-8'?><error>Failed to find user</error>": print "User does not exist" else: datetime = QueryXML(xml, "LastUpdated") datetime = datetime.split('T', 1) time = datetime[1].split('Z', 1) date = datetime[0] print "User", name, "is", QueryXML(xml, "presence"), "as of", date, "at", time[0] return QueryXML(xml, "presence") def FriendCheck(): f = open("Friends.txt", "r") filestring = f.read() f.close() fs = filestring.split('\n') Laonline = Label(lowerframe, text="") Laonline.grid(column=0, row=0) Laonline.grid_forget() x=0 while x <= (len(fs)-1): if IsOnline(fs[x]) == "online": Laonline = Label(lowerframe, text=fs[x]) Laonline.grid(column=0, row=x) x=x+1 def RunTwo(Function1, Function2): Function1() Function2() def DeleteAllFriends(): fs = "<?xml version='1.0' encoding='utf-8'?>\n<friends>\n</friends>" f = open("Friends.txt", "w") f.write(fs) f.close() FriendCheck() def DAFPop(): DAFpopup = Toplevel() DAFframe = Frame(DAFpopup) DAFframe.grid(columnspan=4, column=0, row=0) F1 = DeleteAllFriends F2 = DAFpopup.destroy Q1 = lambda: RunTwo(F1, F2) DAFL1 = Label(DAFframe, text="This delete all of your friends. Are you sure you wish to continue?") DAFL1.grid() DAFOK = Button(DAFpopup, width=10, text="Yes", command=Q1) DAFOK.grid(column=1, row=1) DAFNO = Button(DAFpopup, width=10, text="No", command=DAFpopup.destroy) DAFNO.grid(column=2, row=1) frame = Frame(master, bd=5) frame.grid() friendlist = Frame(frame, bd=5, width=150, height=400) friendlist.grid(column=0, row=0, rowspan=15) lon = Frame(friendlist, bd=2, width=150, height=10) lon.grid() Lonline = Label(lon, text="Friends Online") Lonline.grid(column=0, row=1) underlined = tkFont.Font(Lonline, Lonline.cget("font")) underlined.configure(underline=True) Lonline.configure(font=underlined) lowerframe = Frame(friendlist, bd=2, width=150, height=390) lowerframe.grid() lowerframe.grid_propagate(0) newfriendframe = Frame(frame, bd=2) newfriendframe.grid(column=1, row=0) nfe2 = StringVar() nfentry = Entry(newfriendframe, width=12, textvariable=nfe2) nfentry.grid() nfe2.set("") nfentry = nfe2.get() newfriend = Button(newfriendframe, text="Add Friend", width=10, command=AddFriend) newfriend.grid(column=0, row=1) oldfriendframe = Frame(frame, bd=2) oldfriendframe.grid(column=1, row=1) ofe2 = StringVar() ofentry = Entry(oldfriendframe, width=12,textvariable=ofe2) ofentry.grid() ofe2.set("") ofentry = ofe2.get() oldfriend = Button(oldfriendframe, text="Delete Friend", width=10, command=DeleteFriend) oldfriend.grid(column=0, row=1) rof = Button(frame, text="Reset List", width=10, command=DAFPop) rof.grid(column=1, row=2) update = Button(frame, text="Refresh", width=10, command=FriendCheck) update.grid(column=1, row=3) close = Button(frame, text="Exit", width=10, command=master.destroy) close.grid(column=1, row=4) master.mainloop() And the function that isn't working is IsOnline(), although I have left print url in there for the code I posted, which seems to keep it running without error 90% of the time, whereas without it it gets the error 100% of the time. It also has a dependency text file, Friends.txt: zorc17 WilliamWallace30 Sir_Constantin jerom_the_brave elvarg_flame refinedchaos Metis Lancener Neverseperat musketeer925 maxulino Zack_iz_Weird StormComing It seems to create QueryESO.xml just fine for me even if it isn't there (when it doesn't get the error, of course). If this isn't the case for you, a blank file called QueryESO.xml will work fine, as it gets its content from a webpage. The 'Refresh' button is the one that has the error in it. A: Some observations: (1) If the problem was invalid characters in the actual file name, it would be obvious from the error message; see below: >>> open('fu\x01bar', 'w') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 22] invalid mode ('w') or filename: 'fu\x01bar' (2) You say that you are using a global constant for the file name, but there are TWO occurrences of the literal text (in functions AddFriend and IsOnline) -- it helps if you make sure that the code that you post is actually what you have been running. (3) One cause of this "works 90% of the time" behaviour is an extension (e.g. tkinter) not processing an exception, which then pops up later when something else does check for an error. Note that for errorno 22, Windows just reports "something evil has happened" and Python has to issue the "oh, in that case the mode must be wrong, or the filepath must be wrong" error message. (4) I'm not one to walk away from a puzzle, but: in two places you get the results from the web, write them to this file, and read them back -- WHY?? Why don't you just use the web result in memory?
[ "stackoverflow", "0031934224.txt" ]
Q: GCC optimizes sinl and cosl to sincosl I'm seeing behaviour when compiling with GCC that implies GCC is smart enough to optimize calls in the same "scope" (I use the term loosely here as the scope is wider than what C++ strictly refers to as a scope) to sin and cos into a single call to sincos. Specifically, for a long double x, sinl(x) and cosl(x) get optimized to a sincosl(x, x) call. I'm pretty sure this is what's happening as I can comment out either sin or cos and get a call to just cos or sin respectively. Similarly if I change the parameter then, again, I get separate sin and cos calls. This is an issue for me as the C library I'm linking against doesn't implement sincosl. So I really do want the individual functions. Is my assertion correct? Can someone point me to documentation for this behaviour? Can it be disabled? FYI I'm using: i686-nacl-gcc.exe --version x86_64-nacl-gcc (GCC) 4.4.3 20141209 (Native Client r14192, Git Commit 7faaabb9f10e6dcae5f2b799da43e236e65cda95) Copyright (C) 2010 Free Software Foundation, Inc. however I don't expect this to be version specific. Likely generic GCC behaviour (possibly arch/target specific I guess). A: See the comments to my original post fo some background on the answer. Seemingly the best "fix" was to use a Bionic type workaround: https://github.com/android/platform_bionic/blob/master/libm/sincos.c
[ "math.stackexchange", "0002483648.txt" ]
Q: 'Minimal σ-field' in probability I'm new to the subject and there's something I'm not so sure of. I do think I understand what 'σ-field' is, but then I ran into 'minimal σ-field'. Suppose that one gets $500 if heads in coin flipping. If the coin is tossed twice, then the Sample Space would be Ω={0,500,100}. If I'm understanding the concept of σ-field correctly, the Power Set is a σ-field, and the subsets of the Power Set that satisfies the conditions are also σ-field. Then would {∅,P(S)} be the 'minimal σ-field' or does this term have some kind of another definition? Thanks in advance. A: If you have some collection of sigma fields $\sigma_i$ then $\cap \sigma_i$ is a sigma field. If you have some sets $S_j \subset \Omega$ then the minimal sigma field containing $S_j$ is $\cap \sigma_i$ where $\sigma_i$ contains all $S_j$.
[ "stackoverflow", "0038277489.txt" ]
Q: Using custombox plugin in asp.net mvc? How can I use custombox plugin to render actions in asp.net mvc? With modal boostrap, I use the following code, but the same code gives error with custombox: BUTTON <a class="btnModal btn btn-primary" href="javascript:;" data-href="@Url.Action("Create")">New</a> VIEW <div class="modal fade" id="myModal" tabindex="-1"></div> JS $(".btnModal").click(function () { $("#myModal").load($(this).attr("data-href")); $("#myModal").modal({ backdrop: 'static', keyboard: false }); }); A: You can't use the same code to open both a bootstrap modal popup and a custombox.They are two different plugins.To launch a custombox popup you can use the code below: <script src="~/scripts/custombox.js"></script> <link href="~/css/custombox.css" rel="stylesheet" /> <script type="text/javascript"> $(function () { $(".btnModal").click(function () { $("#modalBody").load($(this).attr("data-href")); Custombox.open({ target: '#myModal', zIndex: 'auto' }); }); }); </script> <a class="btnModal btn btn-primary" href="javascript:;" data-href="@Url.Action("Create")">New</a> <div id="myModal" style="width:200px;height:200px;background-color:#fff;"> <div id="modalBody"> </div> </div>
[ "stackoverflow", "0003391464.txt" ]
Q: Best way to create a numeric pad as seen in Apples telephone app What is the best way to create a numeric pad like the one Apple uses in the telephone app? A: I would say just create an array of UIButton objects so that you can utilize UIControlStateSelected and the other button states by using different images for different states. Another idea is to create something similar to that entire keypad in Photoshop, and then tile it into 12 images using http://www.mikelin.ca/blog/2010/06/iphone-splitting-image-into-tiles-for-faster-loading-with-imagemagick/ That would take some of the work out of get all the images to flow nicely together. By the way, I just forgot about these until just a minute ago... they have some of the UI graphics from the iPhone and iPad in high res PSD file: http://www.teehanlax.com/blog/2010/02/01/ipad-gui-psd/ and http://www.teehanlax.com/blog/2010/08/12/iphone-4-gui-psd-retina-display/ and http://www.teehanlax.com/blog/2010/06/14/iphone-gui-psd-v4/ A: I implemented a KeypadView, that is customizable via a delegate. This github repository has the KeypadView and a delegate-implementation. As I am still beginner in the field of iOS development I would appreciate, if you share your thoughts with me.
[ "superuser", "0000811374.txt" ]
Q: Installing newer version of linux over an older version on a windows dual boot laptop? I have an Asus laptop, with a recovery partition and windows 7 installed. I installed Linux Mint 13 on it, dual-booting it with Win 7. Now I want to remove Linux mint and on the same partition space install the latest Ubuntu distribution. I am not too knowledgeable about boot records and Grub. I want some advice about how do I proceed such that my recovery partition and Windows installation are not screwed up. A: Install Ubuntu like you normally would but opt for the manual partitioning tool when Ubuntu asks you how you want to install. From here you can either format the partition Mint was on or tell Ubuntu to install over it. Grub will be automatically installed to /dev/sda during the installation process.
[ "stackoverflow", "0055118027.txt" ]
Q: Design a O(|V | + |E|) time algorithm that finds a root vertex (or reports that none exists) of a directed graph Given a directed graph G = (V, E). A root vertex in G is a vertex v such that any other vertex u in G is reachable from v through a directed path. How to design a O(|V| + |E|) time algorithm that finds a root vertex (or reports that none exists). A: Here`s O(|V| + |E|) approach: First we can join all nodes that belong to same SCC (Strongly Connected Component) to super-nodes and build new graph based on that, let's call it SCC-graph (it's also known as condensation graph, can be done with Kosaraju algorithm in O(|V| + |E|)) Because SCC-graph cannot have cycles by definition it`s a DAG For every node in SCC-graph we can calculate it's in-degree (number of edges directed to it) Now if there's more than 1 node in SCC-graph with in-degree of 0 there's no root If there is only one node in SCC-graph with in-degree of 0 then any node from original graph that's part of SCC-graph node with 0 in-degree can be a root
[ "askubuntu", "0000166777.txt" ]
Q: How can you make a .sh file come on at startup in Lubuntu 12.04? Running lubuntu desktop on samsung N145 netbook. I got so far as /etc/xdg/lxsession/Lubuntu/autostart and added the line @home/magpie/touchpad_settings.sh Where the name of my file is touchpad_settings.sh and it does execute and work if clicked then executed. This meant I could no longer login and get my panels though, so I undid it with my USB booter and came here to see if anyone could clarify. Lubuntu does not use a startup manager and this is a home-made file so it won't be in Desktop session settings either. As suggested in answers below I tried #!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. /bin/sh /home/magpie/touchpad_settings.sh exit 0 I also tried the lines: /bin/bash /home/magpie/touchpad_settings.sh and sh /home/magpie/touchpad_settings.sh which did not work. A: In the file manager, go to /usr/share/applications. Open it with root access (Tools -> Open Current Folder as Root) In your root access file manager window, create a new file (File -> Create New -> Blank File) Name the new file touchpad.desktop. Find your newly created file, right-click it, edit it with leafpad. In leafpad, paste the following: [Desktop Entry] Name=Touchpad Autostart Exec=/home/magpie/touchpad_settings.sh Type=Application Terminal=false Save it. If you can't save it, you are not in the window with root access. Start over again and follow the directions really carefully. Again, find your file in the root access file manager window. Right-click and copy. Now navigate your root window to the autostart folder: /etc/xdg/autostart/ Finally, paste in your desktop file you created earlier. If you did everything correctly, you should see a lot of other autostart files, but you will also see the file, "Touchpad Autostart" This is not the fastest way to do things, but you seemed to be struggling with a lot of steps in the other answers, so I wanted to take it slow with a lot of details. If your script is still not running after rebooting (do not simply logout and back in), it's a problem with your script. Maybe double check? A: Open /etc/rc.local in your editor with root permission and add the command you want to execute at startup before the line exit 0 in that file. In your case it is sh home/magpie/myfile.sh
[ "stackoverflow", "0045825449.txt" ]
Q: HTML default image size I'm displaying 3 pictures on my code. The pictures have different size (width and height). <div class="row"> <div class="col-lg-12"> <h2 class="page-header">Gallery</h2> </div> <div class="col-md-4 col-sm-6"> <a > <img class="img-responsive img-portfolio img-hover" src="../../imgVideos/test/1/pictureGallery1.jpg" alt=""> </a> </div> <div class="col-md-4 col-sm-6"> <a > <img class="img-responsive img-portfolio img-hover" src="../../imgVideos/test/1/pictureGallery2.jpg" alt=""> </a> </div> <div class="col-md-4 col-sm-6"> <a > <img class="img-responsive img-portfolio img-hover" src="../../imgVideos/test/1/pictureGallery3.jpg" alt=""> </a> </div> </div> It loads and displays the pictures, but the sizes of the images are different. How can I set the height and width to have a default value? Thanks A: Use the height and width attributes on the image tag: <div class="row"> <div class="col-lg-12"> <h2 class="page-header">Gallery</h2> </div> <div class="col-md-4 col-sm-6"> <a> <img height="100" width="100" class="img-responsive img-portfolio img-hover" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg" alt=""> </a> </div> <div class="col-md-4 col-sm-6"> <a> <img height="100" width="100" class="img-responsive img-portfolio img-hover" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg" alt=""> </a> </div> <div class="col-md-4 col-sm-6"> <a> <img height="100" width="100" class="img-responsive img-portfolio img-hover" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg" alt=""> </a> </div> </div> Or use some CSS by setting the width and height rules and linking it to the images you want to affect: #myImage { width: 100px; height: 100px; } <div class="row"> <div class="col-lg-12"> <h2 class="page-header">Gallery</h2> </div> <div class="col-md-4 col-sm-6"> <a> <img id="myImage" class="img-responsive img-portfolio img-hover" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg" alt=""> </a> </div> <div class="col-md-4 col-sm-6"> <a> <img id="myImage" class="img-responsive img-portfolio img-hover" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg" alt=""> </a> </div> <div class="col-md-4 col-sm-6"> <a> <img id="myImage" class="img-responsive img-portfolio img-hover" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg" alt=""> </a> </div> </div> Another thing : in the above code, if the images you're using are not squares you might want to use width: auto or height: auto. Look below: /* sets the width to 100px and the height will be calculate automatically to respect the dimensions */ #myImage1 { width: 100px; height: auto; } /* sets the height to 100px and the width will be calculate automatically to respect the dimensions */ #myImage2 { width: auto; height: 100px; } <div class="row"> <div class="col-lg-12"> <h2 class="page-header">Gallery</h2> </div> <div class="col-md-4 col-sm-6"> <a> <img id="myImage1" class="img-responsive img-portfolio img-hover" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg" alt=""> </a> </div> <div class="col-md-4 col-sm-6"> <a> <img id="myImage2" class="img-responsive img-portfolio img-hover" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg" alt=""> </a> </div> </div>
[ "security.stackexchange", "0000128294.txt" ]
Q: How to brute force this token in php, if it is possible it is possible to brute-force this token (MD5 Hash) of the following script (PHP) in a realistic time (0,5h - 24h)? If the answer is YES, how could I do it, for example with PHP or Python? $time = microtime(); $secret = MD5('$time' . rand(1, 100)); A: As written, it is quite easy, because PHP will not expand variables inside single quotes. So '$time' is the five constant characters '$', 't', 'i', 'm', 'e', instead of a very long, increasing number. So this might have been a trick question, to lead someone to say "it's very difficult" when actually it is not. Supposing it was written md5("{$time}".rand(1, 100)); then much would depend on the actual timer precision of the attacked platform. microtime() will return a time with microseconds, but it does so by calling gettimeofday. You might therefore only have 100,000 attempts in a single second timespan. So you need to crack ten million MD5 hashes for every second in your timespan. If you know that the hash was generated in a given hour (today between 15:30 and 16:30), that's 36 000 000 000 attempts you need to run. On a good hardware you can get about 2-8 million MD5s per second, which means that your cracking needs to run for a time 1-10 times as long as the timespan you need to crack. Of course, using multiple computers would proportionally decrease the time required. In the worst case (true microsecond resolution) you need about one day for every hour of timespan. If you know that a hash has been generated between 15:30:00 and 15:30:15 today (15 seconds), you can crack it in about six minutes. Update From your comment, if this is for your site's security, then I'd strongly suggest you switch to bcrypt hashes (also, check out the link and the documentation it references). Then, to confirm that such a token is secure, you can send a token built like this: $secret = 'YourSiteVerySecretPassword'; $date = date('YmdHis'); // Put whatever you want in the $token. $token = "{$username}:{$date}"; $send = $token . '-' . $bcrypt->hash($secret . $token); The user will send you back a link which you can explode('-') in two parts separated by a dash: list($token, $hash) = explode('-', $receivedToken); if ($bcrypt->verify($secret . $token, $hash)) { // Token is valid. You can further explode it using ':', // and for example extract the date and time and verify that // it is within 24 hours of the current timestamp. Otherwise // the token is valid, yes, but it is "stale". }
[ "stackoverflow", "0005433595.txt" ]
Q: android http post response format type different than specified in query string I am sending post request from android to the url using httpclient like this one below - String url = "http://www.myurl.com/test.php?format=json"; Now I am getting response back in form of plist instead of json, which is default type of response from php file if no format query string is described in url. Can we specify query string in url while posting? It looks like php file is not getting format query string. List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("method", "add")); nameValuePairs.add(new BasicNameValuePair("device_id", "123")); nameValuePairs.add(new BasicNameValuePair("device_token", "3221")); nameValuePairs.add(new BasicNameValuePair("session_id", "1212")); nameValuePairs.add(new BasicNameValuePair("event_id","12345" )); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.addHeader("Content-Type","application/x-www-form-urlencoded"); httppost.addHeader("Accept","application/json"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httppost); /* Checking response */ if (response != null) { InputStream in = response.getEntity().getContent(); String a = convertStreamToString(in); Log.i("Read from Server "+response.getStatusLine().getStatusCode(), a); }else{ Log.i("response is ", "null"); } Thanks A: It's impossible to know without seeing your server code, but your server may not like that you're combining HTTP POST parameters in your request body with GET parameters in the URL. Try putting nameValuePairs.add(new BasicNameValuePair("format","json" )); into the section where you're building up the request parameters instead and see what happens.
[ "stackoverflow", "0019514488.txt" ]
Q: Constant defined inside function is not acceible via class name please see code here the constant is dynamically defined inside the function and i am unable to access it with class name any help i want to make it accessible via class name. my constants in functions are coming from Db and i am generating constant from db and i want to access them with class name please tell me what do i do with "define" to make Constants available or class as well class MyClass { public function getsettings(){ define('myconstant','values'); } } echo MyClass::myconstant; A: Function define() will define constant for global scope, no matter where you've called it - it has nothing to do with any class or it's context. To define class constant, you should use const keyword: class MyClass { const myconstant = 'values'; //.. }
[ "stackoverflow", "0000171490.txt" ]
Q: Getting 256 colors out of ruby-ncurses I've got 256 colors working great in my terminal (test scripts here), but it stops working when I use ncurses (via Ruby-ncurses). Printing the escape sequences given on that page works fine, but when I initialize ncurses 'puts' stops working and I can't output the colors with any of the various ncurses color changing/string output functions I've found. What gives? A: I am not sure if this would be all the story, but make sure your terminal capabilities do indeed provide for the 256 colors description. What is the TERM environment variable value? Try setting it to xterm-256color and rerun it. ncurses should then get the proper color escape sequences. You can also test the terminal capabilities and terminal color output with the program we use at SXEmacs development: http://www.triatlantico.org/tmp/tty-colors.c Compile with gcc -o tty-colors tty-colors.c -lncurses EDIT: Note that just because the scripts that are found on the net output the 256 colors, that is not "all set". Curses programs rely on terminfo and termcap and the TERM environment variable to find out how to interact with the terminal. So in order for a curses app to be able to use the 256 colors one should set the TERM variable to an existing terminal name which supports 256 colors. The C program above will show you what ncurses thinks about your terminal, not just output the xterm sequences like most scripts do [even the one from X.org] A: njsf: You were partially right here, and after tinkering a lot more I eventually got it to work. Thanks for your help. The story: XTerm (and rxvt, and Eterm) support 256 colors via escape sequences (what I was seeing) but 'tput colors' will say '8' and ncurses won't be able to get at them, because ncurses is playing nice and attempting to access via terminfo. For the benefit of anyone with similar pain: I found I need to install the ncurses-term (Ubuntu) package to get /lib/terminfo/x/xterm-256color and other 256-color terminfo files. Then I set my TERM to xterm-256color and added the line '*customization: -color' to my ~/.Xdefaults, ran 'xrdb -merge ~/.Xdefaults' to load it, and from then on I have proper 256 color support in new xterms.
[ "stackoverflow", "0007894494.txt" ]
Q: Size of Subclass If I have a classes A_1, ... A_m extending a class B, then the size of an object of A_i is at least the size of an object of B. If I now declare an array B collB[] = new B[1]; then how much space is allocated? Thank you A: That's creating an array with one element. It'll probably be about 20 bytes, and will vary depending on the JVM you're using (e.g. 32-bit vs 64-bit). It won't vary at all by the number of fields in B, or A, or anything like that - because you're not actually creating any instances of B. You're only creating an array, whose sole element will be a null reference initially.
[ "stats.stackexchange", "0000288844.txt" ]
Q: Deleting Null Values in data analysis Python I have recently been looking through an Ipython notebook that analyzes the Iris dataset. At one point in the notebook I read the following: I'm confused about this statement. Why would delteing these 5 rows bias our results, and how would mean imputation help with this? Thanks A: It could bias the analysis in the sense that the other columns (which are not null) would be taken away from statistics, since all the rows would be deleted. Since it is clear that the NaN entries affect all Iris-Setosa rows, it would make no sense to sacrifice all the other columns because one of the does not apply for this qualitative class. A better approach is to change all NaN entries for Iris-Setosa rows with the mean for that column (a.k.a Mean Inputation), which has the consequence of not changing the mean for that column, preserving the statistic for the other rows.
[ "stackoverflow", "0062252083.txt" ]
Q: Creating a new column based on a window and a condition in Spark INITIAL DATA FRAME: +------------------------------+----------+-------+ | Timestamp | Property | Value | +------------------------------+----------+-------+ | 2019-09-01T01:36:57.000+0000 | X | N | | 2019-09-01T01:37:39.000+0000 | A | 3 | | 2019-09-01T01:42:55.000+0000 | X | Y | | 2019-09-01T01:53:44.000+0000 | A | 17 | | 2019-09-01T01:55:34.000+0000 | A | 9 | | 2019-09-01T01:57:32.000+0000 | X | N | | 2019-09-01T02:59:40.000+0000 | A | 2 | | 2019-09-01T02:00:03.000+0000 | A | 16 | | 2019-09-01T02:01:40.000+0000 | X | Y | | 2019-09-01T02:04:03.000+0000 | A | 21 | +------------------------------+----------+-------+ FINAL DATA FRAME: +------------------------------+----------+-------+---+ | Timestamp | Property | Value | X | +------------------------------+----------+-------+---+ | 2019-09-01T01:37:39.000+0000 | A | 3 | N | | 2019-09-01T01:53:44.000+0000 | A | 17 | Y | | 2019-09-01T01:55:34.000+0000 | A | 9 | Y | | 2019-09-01T02:00:03.000+0000 | A | 16 | N | | 2019-09-01T02:04:03.000+0000 | A | 21 | Y | | 2019-09-01T02:59:40.000+0000 | A | 2 | Y | +------------------------------+----------+-------+---+ Basically, I have a Timestamp, a Property, and a Value field. The Property could be either A or X and it has a value. I would like to have a new DataFrame with a fourth column named X based on the values of the X property. I start going through the rows from the earliest to the oldest. I encounter a row with the X-property, I store its value and I insert it into the X-column. IF I encounter an A-property row: I insert the stored value from the previous step into the X-column. ELSE (meaning I encounter an X-property row): I update the stored value (since it is more recent) and I insert the new stored value into the X column. I keep doing so until I have gone through the whole dataframe. I remove the rows with the X property to have the final dataframe showed above. I am sure there is some sort of way to do so efficiently with the Window function. A: create a temp column with value X's value, null if A. Then use window to get last not-null Temp value. Filter property "A" in the end. scala> val df = Seq( | ("2019-09-01T01:36:57.000+0000", "X", "N"), | ("2019-09-01T01:37:39.000+0000", "A", "3"), | ("2019-09-01T01:42:55.000+0000", "X", "Y"), | ("2019-09-01T01:53:44.000+0000", "A", "17"), | ("2019-09-01T01:55:34.000+0000", "A", "9"), | ("2019-09-01T01:57:32.000+0000", "X", "N"), | ("2019-09-01T02:59:40.000+0000", "A", "2"), | ("2019-09-01T02:00:03.000+0000", "A", "16"), | ("2019-09-01T02:01:40.000+0000", "X", "Y"), | ("2019-09-01T02:04:03.000+0000", "A", "21") | ).toDF("Timestamp", "Property", "Value").withColumn("Temp", when($"Property" === "X", $"Value").otherwise(null)) df: org.apache.spark.sql.DataFrame = [Timestamp: string, Property: string ... 2 more fields] scala> df.show(false) +----------------------------+--------+-----+----+ |Timestamp |Property|Value|Temp| +----------------------------+--------+-----+----+ |2019-09-01T01:36:57.000+0000|X |N |N | |2019-09-01T01:37:39.000+0000|A |3 |null| |2019-09-01T01:42:55.000+0000|X |Y |Y | |2019-09-01T01:53:44.000+0000|A |17 |null| |2019-09-01T01:55:34.000+0000|A |9 |null| |2019-09-01T01:57:32.000+0000|X |N |N | |2019-09-01T02:59:40.000+0000|A |2 |null| |2019-09-01T02:00:03.000+0000|A |16 |null| |2019-09-01T02:01:40.000+0000|X |Y |Y | |2019-09-01T02:04:03.000+0000|A |21 |null| +----------------------------+--------+-----+----+ scala> val overColumns = Window.orderBy("TimeStamp").rowsBetween(Window.unboundedPreceding, Window.currentRow) overColumns: org.apache.spark.sql.expressions.WindowSpec = org.apache.spark.sql.expressions.WindowSpec@1b759662 scala> df.withColumn("X", last($"Temp",true).over(overColumns)).show(false) +----------------------------+--------+-----+----+---+ |Timestamp |Property|Value|Temp|X | +----------------------------+--------+-----+----+---+ |2019-09-01T01:36:57.000+0000|X |N |N |N | |2019-09-01T01:37:39.000+0000|A |3 |null|N | |2019-09-01T01:42:55.000+0000|X |Y |Y |Y | |2019-09-01T01:53:44.000+0000|A |17 |null|Y | |2019-09-01T01:55:34.000+0000|A |9 |null|Y | |2019-09-01T01:57:32.000+0000|X |N |N |N | |2019-09-01T02:00:03.000+0000|A |16 |null|N | |2019-09-01T02:01:40.000+0000|X |Y |Y |Y | |2019-09-01T02:04:03.000+0000|A |21 |null|Y | |2019-09-01T02:59:40.000+0000|A |2 |null|Y | +----------------------------+--------+-----+----+---+ scala> df.withColumn("X", last($"Temp",true).over(overColumns)).filter($"Property" === "A").show(false) +----------------------------+--------+-----+----+---+ |Timestamp |Property|Value|Temp|X | +----------------------------+--------+-----+----+---+ |2019-09-01T01:37:39.000+0000|A |3 |null|N | |2019-09-01T01:53:44.000+0000|A |17 |null|Y | |2019-09-01T01:55:34.000+0000|A |9 |null|Y | |2019-09-01T02:00:03.000+0000|A |16 |null|N | |2019-09-01T02:04:03.000+0000|A |21 |null|Y | |2019-09-01T02:59:40.000+0000|A |2 |null|Y | +----------------------------+--------+-----+----+---+
[ "stackoverflow", "0008867648.txt" ]
Q: How to keep focus on Spark TextInput after setting StageWebView source I have a mobile application that has a Text Input used for searching. Below the search TextInput is a StageWebView. When I set the source of the StageWebView using loadURL() the key input is shifted to the StageWebView. How can I prevent this? A: I think I figured out the problem. When you set the stage property (which is basically setting the visibility to true) that's when it steals the focus. I was showing and hiding the web view depending on if the text input had any text (I was updating the webview source on text change). The fix was to set the web view to visible before putting the cursor in the Text Input. As long as the visibility doesn't change the focus stays in the text input.