source
sequence
text
stringlengths
99
98.5k
[ "drupal.stackexchange", "0000025586.txt" ]
Q: What's the best way to create a booking form? I need to create a booking form for an event. This form will contain normal text field plus one drop down list with the number of tickets. There will be a prefilled field with the price of the single ticket that user can modify. After the field with the price of the single ticket there will be an other field with the total price of the tickets and when they select the number of the tickets automatically the total price will be updated and stored in the database after the form is submitted. After the submit I need to send an email, I can use mime-mail but let me know if I need to change method due the live field of the prices. There is not online payment expected. Let me know if everything is clear. A: If you're new to Drupal, I would first try the webform module. This is a very popular, well tested module that often gets security fixes which less commonly used modules may not get. It has all the basic functions you need for creating the options for the form and can easily be configured to send an e-mail upon submission. It will also leave a record of all submitted data in the Drupal database. To be honest, off the top of my head I'm not sure if webform can do the computation you request or not. However, for that there is the computed field module, which will allow you to write a simple function in PHP to compute the value. Alternately, you could use the rules module's "on node save" event with the action "compute data value" to calculate the total price. There are a number of other approaches as well but these are commonly used Drupal modules with fairly good documentation and thus are, I think, a good place to start.
[ "stackoverflow", "0012656617.txt" ]
Q: PHP PDO Username Availability Checker I'm building a registration page that uses JQuery's validator plugin to validate the form. For the username, i used the remote method. So here's my jquery+html code: fiddle And here's Available.php: <?php $usr = $_POST['username']; $link = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***'); $usr_check = $link->prepare("SELECT * FROM Conference WHERE Username = :usr"); $usr_check->bindParam(':usr', $usr); $usr_check->execute(); if($usr_check->rowCount()>0) echo false; else echo true; ?> So I have a test account in my database with the username: user. When I tried to submit my form with the same username, it didn't display the error saying "username taken" which means the php isn't correct. Any ideas where I went wrong? Thanks Edit: Ran the website with chrome's inspector open. When the user name is entered it DOES try to get Available.php but it says "500 internal server error". Here's what it looks like: A: Alright, after chatting with you for a while, here's what we found: 1- $_POST should be $_GET, since you're using a remote method from jQuery.validate. 2- Your code was calling bindParam() on $link instead of $usr_check, which is correct in your question. Another thing, your code also needs to print out strings for true and false. Wrap those in quotes.
[ "stackoverflow", "0052144163.txt" ]
Q: EF Core Seed Migrations: reseeding I am familiar with, and have been using EF Core 2.1 Migrations and seeding. However, I am unclear about how to migrate seeds to a new (changed) version. So in version 1 of the app I have: modelBuilder.Entity<Category>().HasData( new Category[] { new Category() { Id = 1, Name = "Category A" }, new Category() { Id = 2, Name = "Category B" }, new Category() { Id = 3, Name = "Category C" } }); Users have been adding items under these categories, i.e. public class Category { public List<UserItem> Items {get; set;} } And FYI: Xamarin Forms - so the database is a Sqlite db on each user's device. Now I am releasing version 2, and the categories have changed, but I don't want to lose any of the existing user data. The category seed data now looks like: modelBuilder.Entity<Category>().HasData( new Category[] { new Category() { Id = 1, Name = "Category A" }, new Category() { Id = 2, Name = "Category B has a new name" }, // Category C has been merged with Category B }); Category A is unchanged, B has a new name, and C has been removed and C items need to now be under category B. How is this achieved in EF Core migration to persist the existing UserItems data under the new categories (noting that as each user has their own db I can only migrate using the EF run-time context.Migrate()) ? A: The changes for Category A and Category B should be handled by just adding a new migration after making the changes in your HasData() parameters. Moving sub-entities from Category C to Category B, however, will require manually editing the migration after it has been added.
[ "stackoverflow", "0024231793.txt" ]
Q: How to change the order of elements in an array using a pointer? For example, I have an array: int Arr[10]={1,2,3,4,5,6,7,8,9,10}; How to change its order of elements using a pointer to receive the following array: Arr={10,9,8,7,6,5,4,3,2,1} to change the order odd and even using a pointer I've found this: But I need only to reverse an array (without replacing odd and even) #include <iostream> using namespace std; int main (const int& Argc, const char* Argv[]){ const int Nelem=10; int Arr[]={1,2,3,4,5,6,7,8,9,10}; int *begAr=&Arr[0]; int *endAr=&Arr[Nelem]; int *itrAr=begAr; int *tmpValAr=new int(0); cout<<"Before\t1 2 3 4 5 6 7 8 9 10"<<endl; while(itrAr<endAr){ *tmpValAr=*itrAr; *itrAr=*(itrAr+1); *(itrAr+1)=*tmpValAr; itrAr+=2; } cout<<"After\t"; for(int i=0; i<Nelem; ++i)cout<<Arr[i]<<" "; cout<<endl; system("pause"); return 0; } A: Ok, a C-style approach using pointers to reverse an array? That shouldn't be too hard to figure out. Here's one approach: int main ( void ) { int i,//temp var arr[10]= {1,2,3,4,5,6,7,8,9,10};//the array int *start = &arr[0],//pointer to the start of the array *end = &arr[9];//pointer to the last elem in array //print out current arr values for (i=0;i<10;++i) printf("arr[%d] = %d\n", i, arr[i]); do {//simple loop i = *start;//assign whatever start points to to i *start = *end;//assign value of *end to *start *end = i;//assign initial value of *start (stored in i) to *end } while ( ++start < --end);//make sure start is < end, increment start and decrement end //check output: for (i=0;i<10;++i) printf("arr[%d] = %d\n", i, arr[i]); return 0; } As you can see here, this reverses the array just fine.
[ "apple.stackexchange", "0000219251.txt" ]
Q: After restore, WhatsApp does't show photo anymore After the restore from backup of my iPhone 4S I realised that photos in my Whatsapp chats are not present. Moreover, instead of each photos preview there are a question mark as in the photo reported here below: I tried to solve the problem with: a reset of the phone; a battery pull; But nothing change. Someone know how can I solve this problem? Thanks. A: I solve this problem with an iTunes restore. In particular, using an older backup that was previous the one used having found this problem. In this manner, all the WhatsApp photo were present.
[ "stackoverflow", "0017842435.txt" ]
Q: How can I make an android application unremovable? How can I make an android application non-removable? No one can uninstall it from Application Manager. A: Unless it's a system app that is pre-installed with the ROM on the phone, you can't do that. A: You would have to make the application a System Application. You cannot do this unless you have a rooted device and third party software or as others have stated, the app came preinstalled on the phone.
[ "stackoverflow", "0029547094.txt" ]
Q: Echo only the day number This is my code right now: echo"<tr> <td>{$row['game_release']}</td> </tr>"; How do I echo only the day? For example 2015-05-06 should echo as only '6'? This is the code I found on Stackoverflow, but couldn't get it to work: $string = "2010-11-24"; $date = DateTime::createFromFormat("Y-m-d", $string); echo $date->format("d"); A: This should work for you: Here I just create a new DateTime object, where I then simply format it with the format which you want. echo"<tr> <td>" . (new DateTime($row['game_release']))->format("j") . "</td> </tr>";
[ "stackoverflow", "0028628018.txt" ]
Q: Load Open layers 3 jsonp vector layer with bounding box strategy? I have problem with loading features from geoserver to a vector layer using OpenLayers3 and bounding box strategy. I tried to find how I can load more than one layer using bounding box strategy, but without success. The only example which I found is with one layer and using global functions, which in my case is not applicable (http://acanimal.github.io/thebookofopenlayers3/chapter03_08_loading_strategies.html). The problem is that the function, which is loading the response, is not defined globally - if so I'll have to create such function for every single layer, which I want to load, right? This is an example url address for requesting features: http://192.168.1.10/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typename=ubutrusty:places&outputFormat=text/javascript&format_options=callback:success&srsname=EPSG:32635&bbox=161473.81383919955,4698323.564696768,234672.52335922938,4767981.6354873795,EPSG:32635 You can see that format_options parameter is set to callback:success and I'm sure this is the problem, but I'm struggling with setting the correct callback function. My knowledge in javascript is not so good, so the question is not an easy one for me. This is how I'm trying to create a new vector layer: var layer = { name: 'ubutrusty:places', title: 'Позиции', source: createVectorLayer(layer), type: 'operational', visible: true, style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#800000', width: 2 }) }) } This function is called for every layer I want to add to the map - it returns ol.source.ServerVector object: MyApp.prototype.createVectorLayer = function(layerData){ var vectorSource = new ol.source.ServerVector({ format: new ol.format.GeoJSON(), loader: function(extent, resolution, projection) { extent = ol.proj.transformExtent(extent, projection.getCode(), ol.proj.get(layerData.srcEPSG).getCode()); var url = config.proxyUrl + layerData.url + '?service=WFS&' + 'version=1.1.0&request=GetFeature&typename=' + layerData.name + '&' + 'outputFormat=text/javascript' + '&format_options=callback:success&srsname=' + layerData.srcEPSG + '&bbox=' + extent.join(',') + ',' + layerData.srcEPSG; $.ajax({ url: url, dataType: 'jsonp', success: function(data) { this.addFeatures(this.readFeatures(data)); }, error: function (e) { var wtf = e.status; } }); }, strategy: ol.loadingstrategy.bbox, projection: layerData.srcEPSG }) return vectorSource; } MyApp.map.addLayer(new ol.layer.Vector(layer); The question is, is it possible to define one function for loading features from more than one layer and if yes, how I can do this? If I don't specify the callback function, then the default one is used (for geoserver it is parseResponse) which is also not defined. If more information is needed I can give additional parameters or code examples. Thanks A: In your URL, you already define the name of the callback function. It is success, and is defined by '&format_options=callback:success&srsname='. If you want to use your createVectorLayer function for multiple layers, you will want to change that to '&format_options=callback:success.' + layerData.name.replace(':', '_') + '&srsName='. Then you can create a registry of functions in the global object literal success, which you define once: window.success = {}; You can then add the following code to your createVectorLayer function, which will create a callback function for each of your layers: success[layerData.name.replace(':', '_')] = function(response) { vectorSource.addFeatures(vectorSource.readFeatures(response)); };
[ "stackoverflow", "0033460033.txt" ]
Q: How can I make colores to be changed according to the value of scope variable? I have this element: <a class="btn btn-default btn-xs" ui-sref="sites.edit({siteId: site.Id})" ng-click="$event.stopPropagation()"> <i class="glyphicon glyphicon-info-sign"></i> </a> If this value: $scope.IsValid = true; I want the element to be in green color. If this value: $scope.IsValid = false; I want the element to be in red color. How can I make colres to be changed according to the value of $scope.IsValid variable? A: You can use ng-class assigning the right class (btn-green, btn-red): <a class="btn btn-default btn-xs" ng-class="{'btn-green': isValid, 'btn-red': !isValid}" ui-sref="sites.edit({siteId: site.Id})" ng-click="$event.stopPropagation()"> <i class="glyphicon glyphicon-info-sign"></i> </a> Check the classes you assign are present, this is only an example.
[ "stackoverflow", "0051335967.txt" ]
Q: TextView is not showing proper text from string resources. I have below string resources in my android studio project. <string name="not_registered">Haven&#39;t registered yet?</string> I set the string into TextView with following code:- android:text="@string/not_registered" It show proper text in xml preview window as expected:- Haven't registered yet? But when i run the project then it doesn't show the text after special char " ' ". It only show Haven I am not able to understand why it is not showing full string. A: First, change into your string resource. <string name="not_registered">Haven\'t registered yet?</string> And set the string into TextView with following code:- android:text="@string/not_registered" A: Use <string name="not_registered">Haven\'t registered yet?</string> instead of <string name="not_registered">Haven&#39;t registered yet?</string>
[ "stackoverflow", "0006779225.txt" ]
Q: Crystal Report Licence Question I was checking out the crystal report website and I'm wondering if I purchase it, would it be a license per machine or per user name (use it on another computer but not at the same time)? just wanted to clarify... this is their statement Report Design Licensing SAP Crystal Reports is licensed on a named-user basis for report design. if anyone could help me clarify this, that would be great. Thanks! A: SAP Crystal report is free to download from below link http://www.businessobjects.com/jump/xi/crvs2010/default.asp this is the free version of Crystal report for Visual Studio 2010 Please read the comment at the bottom of the page for given link...
[ "stackoverflow", "0025003424.txt" ]
Q: Displaying Images from file using OpenCV VideoCapture, and C++ vectors I am reading in an image sequence from a file using an OpenCV VidoeCapture - I believe I am doing this part correctly - and then putting them in a c++ vector, for processing at a later point. To test this, I wrote the following that would read in images, put them in a vector, and then display those images from the vector one by one. However, when I run this, no images appear. What's wrong? I am using a raspberry pi, I don't know if that makes any difference. #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <vector> #include <iostream> using namespace cv; using namespace std; vector<Mat> imageQueue; int main(int argc, char** argv) { string arg = ("/home/pi/pictures/ceilingSequence/%02d.jpg"); VidoeCapture sequence(arg); if(!sequence.isOpened()) { cout << "Failed to open image sequence" << endl; return -1; } Mat image; for(;;) { sequence >> image; if(image.empty()) { cout << "End of sequence" << endl; break; } imageQueue.push_back(image); } for(int i = 0; i < 10; i++) { //display 10 images Mat readImage; readImage = imageQueue[i]; namedWindow("Current Image", CV_WINDOW_AUTOSIZE); imshow("Current Image", readImage); sleep(2); } return 0; } A: please replace the sleep(2) with a waitKey(2000). // assuming you want to wait for 2 seconds even if you're not interested in keypresses in general, it is needed to update the opencv / highgui graphics loop correctly.
[ "gis.stackexchange", "0000356632.txt" ]
Q: How to correctly create a polygon from an extent? I'm tying to create a new polygon based on some calculated extent. I'm doing this way, as suggested by documentation: let newPolygon = new Polygon().fromExtent(newExtent); let newFeature = new Feature({ geometry: newPolygon, }); This is giving me an error in the new Polygon() line: Cannot read property 'length' of undefined. newExtent is an array and is in accordance with the documentation as well. A: The syntax is import {fromExtent} from 'ol/geom/Polygon'; let newPolygon = fromExtent(newExtent);
[ "stackoverflow", "0038437674.txt" ]
Q: Need hours difference in SQL query Looking for a query which can retrieve the time difference of two times. Below is the example: EmpID EmpOnTime EmpOffTime 1 2:45 3:00 2 1:00 4:00 3 1:35 2:55 4 2:45 3:20 Result should be: For EmpID 1 Time diffrence: 0:15 For EmpID 2 Time diffrence: 3:00 For EmpID 3 Time diffrence: 1:20 For EmpID 4 Time diffrence: 0:35 I am using the following query which giving wrong result Query: select offTime, onTime, (strftime('%s',offTime) - strftime('%s',onTime)) / 60 AS diffrence from emplyoee; A: This one was trickier than initially thought. Here is the SQL you will need, however your input data will need to be formatted differently to get it to work. select EmpId, offTime, onTime, time(((strftime('%s', offTime) - strftime('%s', onTime)) / 60), 'unixepoch') as difference from employee; I had to store the data in the YYYY-MM-DD HH:MM:SS: 2019-07-18 03:00:00 Otherwise SQLite gets confused if you mean am or pm, and the %s cannot calculate since it returns the number of seconds since 1970-01-01.
[ "gis.stackexchange", "0000312232.txt" ]
Q: Prevent user from creating self intersected polygons i'm working on a project in QGIS 3.4.1 Madeira. I want to prevent users from creating polygons with errors (like self intersection). When I digitize a polygon in QGIS i get a mark where the polygon self-intersects (see image), but I can continue and save my polygon without any further warning. Is there an option to prevent that and not ignore the topological error so that the user can redo his digitalization (e.g. pop up)? A: In Layer Properties, Digitizing tab, tick on Is Valid Geometry check. https://docs.qgis.org/testing/en/docs/user_manual/working_with_vector/vector_properties.html#digitizing-properties
[ "stackoverflow", "0041610515.txt" ]
Q: Edit RecyclerView item programatically in Android So I have this app in which I have to make a RecyclerView which contains a list of items that can be deleted/edited e.t.c. I followed a tutorial on youtube and I made a custom CardView item on another layout and a custom adapter for that item. Thing is, depending on the state of the item, I have to change something(ex. background color or text color). When I do that in the RecyclerView activity I get NullPointerException even if I have the id's. How can I edit those TextViews inside the programmatically generated list of items in the moment I make the Retrofit call? boolean isEnded; if(!endedAt.equals("null")) { endedAt = endedAt.substring(endedAt.indexOf("T") + 1, endedAt.lastIndexOf(":")); isEnded=true; } else { endedAt="ongoing"; isEnded=false; } item.timeDifference=createdAt+" - "+endedAt; if(externalSystem.equals("null")) { item.externalSystem=""; } else { item.externalSystem = externalSystem; } Log.i("attr",externalSystem); items.add(item); itemAdapter=new ItemAdapter(getApplicationContext(), items); recyclerView.setAdapter(itemAdapter); if(isEnded) { error-> externalSystemView.setTextColor(Color.BLACK); } The app is rather big, but I think you can get the idea from this piece of code. Here is the error: Attempt to invoke virtual method 'void android.widget.TextView.setTextColor(int)' on a null object reference public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder>{ private Context context; private ArrayList<Item> itemList; public ItemAdapter(Context context, ArrayList<Item> itemList) { this.context=context; this.itemList=itemList; } @Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext()); View view=layoutInflater.inflate(R.layout.item_layout,parent,false); ItemViewHolder itemViewHolder=new ItemViewHolder(view); return itemViewHolder; } @Override public void onBindViewHolder(ItemViewHolder holder, int position) { Item item=itemList.get(position); holder.timeDifference.setText(item.timeDifference); holder.title.setText(item.title); holder.timeCounter.setText(item.timeCounter); holder.externalSystem.setText(item.externalSystem); holder.type.setText(item.type); holder.project.setText(item.project); MY IDEA "holder.timeDifference.setTextColor(Color.parseColor(item.color));" } @Override public int getItemCount() { if(itemList!=null) return itemList.size(); else return 0; } public static class ItemViewHolder extends RecyclerView.ViewHolder { public CardView cardViewItem; public TextView title; public TextView project; public TextView externalSystem; public TextView timeDifference; public TextView timeCounter; public TextView type; public ItemViewHolder(View itemView) { super(itemView); cardViewItem=(CardView)itemView.findViewById(R.id.card_view_item); title=(TextView)itemView.findViewById(R.id.title); project=(TextView)itemView.findViewById(R.id.project); externalSystem= (TextView)itemView.findViewById(R.id.external_system); timeDifference= (TextView)itemView.findViewById(R.id.time_difference); timeCounter=(TextView)itemView.findViewById(R.id.time_counter); type=(TextView)itemView.findViewById(R.id.type); } EDIT: I think I found a way, but I don't know if it's the best one A: The solution would involve changing your Item class a little. Your problem is that you're not passing over the boolean trigger to your RecyclerView.Adapter from your Activity properly. E.g. isEndedBoolean's value to know what state the item is in. You have the right idea in the use of all three classes. What I would suggest do is create a constructor in your Item class passing the values from your Activity to be used in your adapter. I feel it's easier to use getters and setters rather than assigning the variables straight from code like you have. So let's begin, boolean isEnded; if(!endedAt.equals("null")) { endedAt = endedAt.substring(endedAt.indexOf("T") + 1, endedAt.lastIndexOf(":")); isEnded=true; } else { endedAt="ongoing"; isEnded=false; } String timeDifference = createdAt+" - "+endedAt; if(externalSystem.equals("null")) { externalSystem=""; } else { externalSystem = externalSystem; } Log.i("attr",externalSystem); items.add(new ItemModel(isEnded, timeDifference, externalSystem); itemAdapter=new ItemAdapter(this, items); recyclerView.setAdapter(itemAdapter); itemAdapter.notifyDataSetChanged(); You'll notice how I'm adding a new ItemModel for each row of variables inside the RecyclerView to the array and then passing it that array to the Adapter. This is so that it's easier to know what variables are being passed to the Model and thus the corresponding row at the position inside the Adapter. An example of the ItemModel class would look something like: public class ItemModel { // Getter and Setter model for recycler view items private boolean isEnded; private String timeDifference; private String externalSystem; //other variables, title etc etc public ItemModel(boolean isEnded, String timeDifference, String externalSystem) { this.isEnded = isEnded; this.timeDifference = timeDifference; this.externalSystem = externalSystem; //only pass to the model if you can access it from code above otherwise to assign the variables statically like you have. } public boolean getIsEnded() {return isEnded;} public String getTimeDifference() {return timeDifference;} public String getExternalSystem() { return externalSystem; } } The information above is just a guideline for you to create a more efficient model framework to pass the data rather than using static variables. Now to solve your problem you need to check if (item.getIsEnded()) and then change the text color corresponding to that if condition. RecyclerView.Adapter onBindViewHolder would look like: @Override public void onBindViewHolder(ItemViewHolder holder, int position) { ItemModel item =itemList.get(position); holder.timeDifference.setText(item.getTimeDifference()); holder.title.setText(item.title); holder.timeCounter.setText(item.timeCounter); holder.externalSystem.setText(item.getExternalSystem()); holder.type.setText(item.type); holder.project.setText(item.project); if (item.getIsEnded() { holder.timeDifference.setTextColor(item.color); } else { holder.timeDifference.setTextColor(item.color); } } The purpose of the Adapter is to inflate a layout, bind components to that layout and perform functionality to the items corresponding to the layout at the dedicated position. You need to know which item in your list is in which state, you won't be able to do that from your Activity alone. Be mindful of how useful the Adapter is in keeping the code from your Activity separate from the actual activity of your RecyclerView.
[ "wordpress.stackexchange", "0000033121.txt" ]
Q: Get avatar of the logged-in user in Wordpress How can I get a user avatar to display in the header of my WordPress site? I've tried: <a href="<?php echo get_author_posts_url($post->post_author); ?>" title="<?php the_author_meta( 'display_name', $post->post_author ); ?>"> <?php if( get_the_author_meta( 'user_custom_avatar', $post->post_author ) != '' ) { ?> <img src="<?php the_author_meta( 'user_custom_avatar', $post->post_author ); ?>" alt="" /> <?php echo $curauth->display_name; ?> <?php } else { ?> <?php echo get_avatar( get_the_author_meta( 'user_email', $post->post_author ), '80' ); ?> <?php } ?> </a> but every time the logged-in user goes to a different authors post, the avatar changes to that authors avatar. I want it to be that when a user logs in, his/her avatar stays on the top of the page all the time. Can this be done? A: All you need to do is pass the current users email address into the get_avatar() function. <?php $current_user = wp_get_current_user(); if ( ($current_user instanceof WP_User) ) { echo get_avatar( $current_user->user_email, 32 ); } ?> Here are some links for specifics: get_avatar(); wp_get_current_user(); A response to your new problem in the comments below: <?php echo '<img src="'. get_the_author_meta( 'user_custom_avatar', $current_user->ID, 32 ) .'" />'; ?> I had one too many semicolons in that there code I gave you before, this ought to work. EDIT This will make it 10X easier for you. I dont know why I didnt do it this way to begin with. - I'll just add it into your example snippet the way you want it. The Real Answer: <a href="<?php echo get_author_posts_url($post->post_author); ?>" title="<?php the_author_meta( 'display_name', $post->post_author ); ?>"> <?php if( get_the_author_meta( 'user_custom_avatar', $post->post_author ) != '' ) { ?> <img src="<?php the_author_meta( 'user_custom_avatar', $post->post_author ); ?>" alt="" /> <?php echo $curauth->display_name; ?> <?php } else { $current_user = wp_get_current_user(); echo get_avatar( $current_user->user_email, $post->post_author ), '80' ); } ?> </a> Sorry about that.
[ "stackoverflow", "0042407514.txt" ]
Q: How do I make html or javascript open and display .swf files from the file system on a button click I've looked all over the place and here is the fullest extent of what I found: <!DOCTYPE html> <html> <body> <input name="PickedFile" type="file" accept=".swf"> <object width="550" height="400"> <param name="movie" value="PickedFile"> <script type="text/javascript" src="/path/to/swfobject.js"></script> <script type="text/javascript"> function loadSWF(url) { swfobject.embedSWF(url, "flashcontent", "550", "400", "7"); } </script> <p><a href="PickedFile" onclick="loadSWF(PickedFile); return false;"> Click here to load the SWF! </a></p> <div id="flashcontent"></div> </object> </body> </html> I'd prefer it to be in html so it can be downloaded for offline use A: @AHBagheri, You can display a SWF loaded from outside the server, I just verified using Chrome. I was very surprised it worked. @Ben, you have multiple flaws in your code. There are a number of reasons why your code wasn't working; the SWFObject tutorial you based your SWF loading code on (from LearnSWFObject) was not written with a file input in mind. Here is updated code that I verified in Chrome (macOS). Be sure to point the SWFObject <script> to your copy of SWFObject. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Local SWF Test</title> </head> <body> <div> <input id="PickedFile" type="file" accept="application/x-shockwave-flash"/><br/> <button id="btn_load">Load the SWF!</button> </div> <div id="flashcontent"></div> <script src="swfobject.js"></script> <script> var loadSWF = function (){ var file = document.querySelector("#PickedFile"); if(file && file.files[0]){ swfobject.embedSWF(file.files[0].name, "flashcontent", "550", "400", "7"); } else { alert("You need to pick a file first."); } }; document.querySelector("#btn_load").addEventListener("click", loadSWF); </script> </body> </html> The primary problems with your code: You placed everything inside an <object> element. Not only is this incorrect, the <object> element was not needed at all -- this is not how SWFObject works. I removed the <object> and related <param> nodes. The "accept" attribute for the input needs to specify the MIME type, not the file extension. I changed it to application/x-shockwave-flash. The "PickedFile" input had a name but no ID. I removed the name attribute and added the ID attribute as this is the common practice when using JavaScript to find an element (in this case document.querySelector). See the examples at https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications When you're using a file input, the value of the input is an array of files, and each item in the array is actually an object containing details about the file, including name and file path. Since you are only expecting one file in the file input, you need to grab the first array item (files.file[0]), which you can then use to access the file's name (files.file[0].name).
[ "stackoverflow", "0002707467.txt" ]
Q: Groovlet not working in GWT project, container : embedded Jetty in google plugin I am working on a GWT application which uses GWT-RPC. I just made a test groovlet to see if it worked, but ran into some problems here's my groovlet package groovy.servlet; print "testing the groovlet"; Every tutorial said we don't need to subclass anything, and just a simple script would act as a servlet. my web.xml looks like this - <!-- groovy --> <servlet> <servlet-name>testGroovy</servlet-name> <servlet-class>groovy.servlet.testGroovy</servlet-class> </servlet> <servlet-mapping> <servlet-name>testGroovy</servlet-name> <url-pattern>*.groovy</url-pattern> </servlet-mapping When I Run as -> web application, i get the following error from jetty : [WARN] failed testGroovy javax.servlet.UnavailableException: Servlet class groovy.servlet.testGroovy is not a javax.servlet.Servlet at org.mortbay.jetty.servlet.ServletHolder.checkServletType(ServletHolder.java:377) at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:234) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:616) at org.mortbay.jetty.servlet.Context.startContext(Context.java:140) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1220) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:513) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448) at com.google.gwt.dev.shell.jetty.JettyLauncher$WebAppContextWithReload.doStart(JettyLauncher.java:447) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.handler.RequestLogHandler.doStart(RequestLogHandler.java:115) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:222) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39) at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:543) at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:421) at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1035) at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:783) at com.google.gwt.dev.DevMode.main(DevMode.java:275) What did I miss ? A: You're building a new class there, not extending the HttpServlet class (or the groovy.servlet.GroovyServlet either). GroovyServlet is the servlet, that then interprets your groovy script. To set it up in web.xml you use <servlet> <servlet-name>GroovyServlet</servlet-name> <servlet-class>groovy.servlet.GroovyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GroovyServlet</servlet-name> <url-pattern>*.groovy</url-pattern> </servlet-mapping> And then in a file named something.groovy somwhere under your web root you can write out.println 'testing the groovlet' The objects request, response, session, params and others are also present at your disposal. So that you for instance can write out.println "Hello ${params['name']}" More info at http://groovy.codehaus.org/Groovlet
[ "stackoverflow", "0058408161.txt" ]
Q: Split File based on date prefix? I have this file.log Sep 16 16:18:49 abcd 123 456 Sep 16 16:18:49 abcd 123 567 Sep 17 16:18:49 abcd 123 456 Sep 17 16:18:49 abcd 123 567 I want to split based on date partition so I get, Sep_16.log Sep 16 16:18:49 abcd 123 456 Sep 16 16:18:49 abcd 123 567 Sep_17.log Sep 17 16:18:49 abcd 123 456 Sep 17 16:18:49 abcd 123 567 I search in the forum, that it's supposed to be using csplit and regex ^.{6}, but the answer that I got only for the regex to be used as delimiter, which is not what I intended. Also, I want to split 10k rows per date partition, so the filename will be something like Sep_17_part001.log, which will then using something like prefix and suffix option. Does anybody know the full command for doing this? And if I do this one time thing on one log, how can I make it to run daily, without csplit overwrite previous days? A: So in the end, I decided to create a simple Python script after searching through csplit documentation and find nothing that suitable to my needs. Something like, with open(args.logfile) as f: for line in f: timef = datetime.strptime(str(datetime.utcnow().year) + line[:6], '%Y%b %d').strftime('%Y%m%d') t_dest_path = os.path.join(date_path, timef + '-browse.log') with open(t_dest_path, "a") as fdest: fdest.write(line)
[ "chemistry.stackexchange", "0000032551.txt" ]
Q: How to get a precise reading from pipette? While doing titrations, we are instructed to use pipette and they demonstrated how to use a pipette. But still after all this, we face difficulties of how to take precise reading from pipette. Example- Due to the concave water meniscus, until where to take the reading ? Is it really important to take every single drop of solution from pipette ? as while putting solution in beaker we see little bit drop left inside pipette. And what's the best way to hold pipette to avoid breaking it and easy to see the reading which we are taking ? A: The bottom of the meniscus (in the middle) is your measurement point and should lie on the line that you are trying to read. This is completely dependent on the type of pipette that you are using. Some pipettes are designed so that you just leave the last drop and some you are supposed to just touch the tip of the pipette to the surface of what you've dispensed already to get the last bit. TD pipettes stand for "to deliver" (leave the last bit). TC pipettes stand for "to contain" (take the last bit out). Again, this is dependent on the pipette. If you have a classic bulb pipette then you shouldn't hold it by the bulb as it is the weakest part and that's how you end up with glass in your hand.
[ "stackoverflow", "0009856214.txt" ]
Q: Adding a static library to an XCode console application I'm having trouble adding a static library from another Xcode project (CloudApp API) to my Xcode project. My project has two targets -- a prefpane bundle, and a console application. I want to add the static library to the console application. Here's what I've done so far: Created a new workspace Added the CloudApp project to my workspace Added the libcloud.a file to my "Link Project Binaries" list for the target binary Added -ObjC to the "Other Linker Flags" setting for the target binary Added $(BUILD_PRODUCTS_DIR) to the "User Header Search Paths" setting for the target binary Copied all the relevant headers from the CloudApp project into my project (without adding them to the target) so that I don't get errors from any #import statements Edited the scheme for the target binary to require compiling CloudApp first Added relevant frameworks to the target (Cocoa, Foundation, CoreFoundation) Doing all this worked fine when I just had a single Cocoa target (not a console application). But now I'm getting errors in the CloudApp header files I included. Basically things like this: In CLWebItem.h: Unknown type name 'NSImage' Any ideas? A: Create a prefix-header.pch and #import <Cocoa/Cocoa.h> inside. Make sure to compile the prefix header in your settings.
[ "stackoverflow", "0061356979.txt" ]
Q: How to get a list of all documents from SharePoint using PowerShell? I want to retrieve all documents from SharePoint using PowerShell, but at the moment I can only retrieve documents for a particular site. This is the code I am using: #Load SharePoint CSOM Assemblies Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" #Set Parameters $SiteURL="https://xxx.sharepoint.com/sites/CRMDevelopment" $LibraryName="Documents" $ReportOutput = "C:\users\xxx\downloads\VersionHistory.csv" Try { #Setup Credentials to connect $Cred= Get-Credential $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password) #Setup the context $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) $Ctx.Credentials = $Credentials #Get the web & Library $Web=$Ctx.Web $Ctx.Load($Web) $List = $Web.Lists.GetByTitle($LibraryName) $Ctx.ExecuteQuery() #Get All Files of from the document library - Excluding Folders $Query = New-Object Microsoft.SharePoint.Client.CamlQuery $Query.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq></Where><OrderBy><FieldRef Name='ID' /></OrderBy></Query></View>" $ListItems=$List.GetItems($Query) $Ctx.Load($ListItems) $Ctx.ExecuteQuery() $VersionHistoryData = @() #Iterate throgh each version of file Foreach ($Item in $ListItems) { ##more code goes here. } } A: Demo to iterate all site collections by PnP PowerShell and SharePoint online management shell, if you want to access the library in all site collections, the account need access to all site collections(admin not has permissions to all site collections by default). #region Variables $AdminName = "[email protected]" $Password = "password" #endregion Variables #region Credentials [SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force $credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $AdminName, $(convertto-securestring $Password -asplaintext -force) #endregion Credentials #Config Parameters $AdminSiteURL="https://xxx-admin.sharepoint.com" #$ReportOutput = "C:\users\xxx\downloads\VersionHistory.csv" #Connect to SharePoint Online Admin Center Connect-SPOService -Url $AdminSiteURL –Credential $credentials #Get All site collections $SiteCollections = Get-SPOSite -Limit All Write-Host "Total Number of Site collections Found:"$SiteCollections.count -f Yellow #Loop through each site collection and retrieve details Foreach ($Site in $SiteCollections) { #Test for specific site #if($Site.URL -eq "https://xxx.sharepoint.com/sites/lee"){ Write-Host "Processing Site Collection :"$Site.URL -f Yellow Connect-PnPOnline -Url $Site.URL -credentials $credentials $items=Get-PnPListItem -List Documents -Query "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq></Where><OrderBy><FieldRef Name='ID' /></OrderBy></Query></View>" Foreach ($Item in $items) { Write-Host $Item.FieldValues["FileRef"] } #} } Write-Host "--"
[ "stackoverflow", "0038054246.txt" ]
Q: Django Heroku - Dropdown not working in bootstrap I made a Django project and a page has side menu, whenever the side menu is selected a dropdown appears. This is happening when I run it locally, whereas its not working from heroku. The dropdown code is as follows: <li class="panel panel-default" id="dropdown"> <a data-toggle="collapse" href="#dropdown-lvl4"> <span class="glyphicon glyphicon-menu-down"></span> Day 4 <span class="caret"></span> </a> <!-- Dropdown level 1 --> <div id="dropdown-lvl4" class="panel-collapse collapse"> <div class="panel-body"> <ul class="nav navbar-nav"> <li><a href="/python_course/day4/reg_expressions">Regular Expressions</a></li> <li><a href="/python_course/day4/data_scraping">Data Scraping</a></li> </ul> </div> </div> </li> The website link is here. Kindly help me with this. I an new to heroku and Django. A: You are trying to load an unencrypted (http) resource from a secure (https) page. You will notice that if you check your page using http it will work. Change the following line <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> to <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> Note the lack of protocol string (http:) in the URL.
[ "stackoverflow", "0010277220.txt" ]
Q: how to draw a square in to a PictureBox? I have a problem with my C# Windows-Forms project. I am trying to draw a square and I want to display the square inside a picture-box. How can I do that? This is my function for drawing the square: public void DrawingSquares(int x, int y)//the function gets x and y to know where to print the square. { Graphics graphicsObj; graphicsObj = this.CreateGraphics(); Pen myPen = new Pen(Color.Black, 5); Rectangle myRectangle = new Rectangle(x, y, 100, 100); graphicsObj.DrawRectangle(myPen, myRectangle); } A: using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.pictureBox1.Image = this.Draw(this.pictureBox1.Width, this.pictureBox1.Height); } public Bitmap Draw(int width, int height) { var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); var graphics = Graphics.FromImage(bitmap); graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.FillRectangle(new SolidBrush(Color.Tomato), 10, 10, 100, 100); return bitmap; } } } this is my Form1.cs you should have something simillar
[ "stackoverflow", "0010913080.txt" ]
Q: Python : How to insert a dictionary to a sqlite database? I have a sqlite database with a table with following columns : id(int) , name(text) , dob(text) I want to insert following dictionary to it : {"id":"100","name":"xyz","dob":"12/12/12"} Dictionary keys are the column names. How can i achieve it ? A: Looking at the documentation here you can add a single row: c.execute("INSERT INTO stocks VALUES (?,?,?)", [dict["id"], dict["name"], dict["dob"]]) Or you can use a list and add multiple rows in one go: # Larger example that inserts many records at a time purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) A: Here's a way which preserves parameter safety. (Might need polishing in the tablename department) def post_row(conn, tablename, rec): keys = ','.join(rec.keys()) question_marks = ','.join(list('?'*len(rec))) values = tuple(rec.values()) conn.execute('INSERT INTO '+tablename+' ('+keys+') VALUES ('+question_marks+')', values) row = {"id":"100","name":"xyz","dob":"12/12/12"} post_row(my_db, 'my_table', row) A: If, for example, c = conn.cursor(), and your dictionary is named dict and your table tablename, then you can write c.execute('insert into tablename values (?,?,?)', [dict['id'], dict['name'], dict['dob']]) Which will insert the elements of the dictionary into the table as you require.
[ "meta.stackexchange", "0000301642.txt" ]
Q: If I worked out a problem I coudn't find answered directly, how do I post my solution? I had a MySQL problem I was trying to solve, had a hard time figuring out how to frame a question, got close, but never asked a question and I never did find my exact situation addressed. After a bunch of searching, I figured out the answer by patching together parts of other answers and researching elements that turned out to be part of the solution. I think it's a good solution, and both the solution and suggestions about how to frame the question might be useful to users. So how do I post that? A: If you have what you think is a unique problem and you've already solved it, you can actually ask and answer a question simultaneously. Generally, what I recommend is writing the question as if you don't know the answer at all. Phrase it precisely and explain it in such a way that it's clear and obvious that the existing questions and their solutions are different. Then, before submitting the question, click the tick box next to the text that reads Answer your own question – share your knowledge, Q&A-style Here, post your solution. Explain how you found it, link to the other answers that you used to solve your problem and explain it as if you're answering someone else's question. Submit them both. You may still get other answers - perhaps your solution isn't the perfect one or other people figured it out in a different way. That's OK. You may also get some commentary on your solution and whether it's a good one or not. It's important, however, that you explain the question thoroughly enough that other people can write answers. Don't write half a question because you already know the answer. In fact, because you already know the answer, you should probably be better able to write a useful question. Some users aren't big fans of these types of question/answer posts but they are definitely allowed and part of the way the site works.
[ "diy.stackexchange", "0000049752.txt" ]
Q: What is considered "over a tub or shower" for a bathroom fan? I'm going to add a fan to my currently unvented bathroom. The fan installation instructions include the text "if this unit is to be installed over a tub or shower, it must be marked as appropriate for the application and be conencted to a GFCI-protected branch circuit." The fan is marked as such, but my question is: what is technically "over" the bath? The fan is not directly above the bath. If I were to draw an imaginary line from the top of the shower curtain rod to the ceiling, the fan would be about 4" outside of this line. Does that mean I do not have to put the fan on a GFCI circuit? A: Let's get one thing straight. Ground-Fault Circuit Interrupter protection for personnel is designed and intended to protect a human (or any animal I guess), from being electrocuted (killed) due to an electrical fault. In most situations, the grounding system will handle any direct faults to ground. A GFCI devices is there to protect you, if you happen to come into contact with an energized conductor. Let's also be clear that a GFCI device may not protect you from a shock, but should protect you from death (electrocution). Examples: You grab hold of the ungrounded "hot" conductor. In this situation, the GFCI device should disconnect the circuit before you are killed. The frame of a device is energized, and for some reason the grounding system has not performed its job, and you come into contact with the energized frame of the device. In this situation, the GFCI device should disconnect the circuit before you are killed. A GFCI device is there to protect you, from death. But why does it seem like codes tend to require GFCI protection in locations where there is water, like bathrooms and kitchens? The simple answer is that when your skin is wet, it's a better conductor. Because of this, you could potentially provide a fairly good path to ground. It's also important to provide this protection in bathrooms and kitchens, because it's common for plumbing in homes to be grounded. Let's say you're washing your face in the sink. The water is running, as you reach for a towel. You reach with one hand to turn the water off, while the other fumbles for the towel. While you're still holding the faucet with one hand, the other hand accidentally finds the non-GFCI protected receptacle. The electricity races through your wet hand, across your body, and out your other hand into the well grounded faucet. While crossing your body, the electricity ran right through your heart causing it to stop. Now, you're dead. If it was a GFCI protected receptacle, you would have gotten a bit of a shock and a scare. But you'd still be alive. As for the question asked... Put an imaginary box around the tub/shower, and extend it all the way up to the ceiling. If any part of the exhaust fan is within the box, you should GFCI protect the fan as per the installation instructions. If it makes you feel safer, then by all means GFCI protect the fan.
[ "stackoverflow", "0063065975.txt" ]
Q: why this.key is not working properly in javacript? let student = { fname: "Carlos", lname: 'Dubón', sayHi(){ alert(`Hi my name is ${this.fname}`); }, sayBye: function() { alert(`Bye ${this.fname}`); }, sayHiAgain: ()=> { alert(`Hi my name is ${this.fname}`); } } student.sayHiAgain(); I'm new to OOP in Javascript, I understand that the 3 ways in which I wrote a method work exactly the same. student.sayHi(); works and shows up the alert => "Hi my name is Carlos" but student.sayHiAgain(); shows up the alert => "Hi my name is undefined" What am I missing? A: When using arrow functions, it uses lexical scoping meaning that it refers to it's current scope and no further past that, i.e., binds to the inner-function and not to the object itself. An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[ "askubuntu", "0000533186.txt" ]
Q: Disconnecting wifi every few minutes I'm new in Ubuntu and I have some small problem with my wifi. I manage to connect it after an hour of using this forum, however now whatever I'm doing I'm loosing the connection every few minutes. I think it started when I've installed dropbox and all of the software required for it. I have to turn off and again on network to get it for next few minutes. - Ubuntu version 14.04 - asus x550L - belkin f7d2301 v1 I have logged to another account and everything was fine before I have installed dropbox. Any ideas how to fix it? I have such a limited knowledge about this system that I don't even know where to start. Edit: I have blocked IPv6 and worked without dropbox, problem still occur. I have noticed that it's more likely to appear if I open 2-3 tabs at the same moment, or download update and at the same moment open tab; watch playlist on youtube so it download all the time.. Any ideas how to fix it? I can't believe I have such a problems with linux from the very beginning. Edit2: should I maybe change my router settings? I have almost default from benkin. Dynamic connection on channel 10, bandwidth 20/40, 802.11e/WMM QoS on; wpa-psk+wpa2+psk. Edit3: I had enough of it so I have reinstalled system. Same story, installed dropbox which was updating something, using internet and crash after 20sec. Edit4: I tried to play with MTU, no idea how to change it on my router but I learned that I should have 1472 (+28 = 1500). I added to /etc/dhcp/dhclient.conf two lines: default interface-mtu 1500; supercede interface-mtu 1500; It didn't change anything. It seems like I'm trying to use too much internet (?). I made limit 1024 kb/s on dropbox and it works. However when I try to update information in "incomplete language support" it crushes.. A: I had an issue with either my ISP or my router - don't really care which it was. Ipv6 was not being handled well, and causing periodic disconnects. I disabled ipv6 according to instructions I found on itsfoss.com - The following lines are added to /etc/sysctl.conf net.ipv6.conf.all.disable_ipv6 = 1 net.ipv6.conf.default.disable_ipv6 = 1 net.ipv6.conf.lo.disable_ipv6 = 1 This is best done from a terminal: press alt+ctrl+t to open a terminal window, and enter the command sudo nano /etc/sysctl.conf to start an editor with the file open. Add the lines by typing them, or copying them from here (shift+ctrl+v to paste), and press ctrl+o to write the file, and ctrl+x to exit the editor. You will need to reboot for the changes to take effect. Because I seem to be a little OCD, I also set IPV6 to IGNORE in the NM applet
[ "tex.stackexchange", "0000342279.txt" ]
Q: Section/chapter title in landscape mode How could I write the title of a section or of a chapter in landscape mode? I mean without rotating the document. What I need to have, to explain me better, is this: Do't mind about the plot, I already created a page with the landscape mode for the plot and it's awesome. What I miss is the "title of this section" in landscape mode, above the plot. Thank you!! I already inserted the plot with the cose \begin{sidewaysfigure}[ht] \centering \includegraphics[scale=2.5]{E1-ExpLog-LogLogPlot.eps} \end{sidewaysfigure} What I need is the title in section mode above the plot, in landscape mode. Let's pretend I have to write "TITILE OF THE PLOT" as I wrote in the paper. A: Is it something like this you want? \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{graphicx, rotating, caption, lscape, threeparttable}% \usepackage{amsmath} \begin{document} \begin{landscape} \section{About Piero di Cosimo} \vfill \begin{measuredfigure} \includegraphics[height=10cm]{SanRomano} % \caption{The Battle of San Romano} \end{measuredfigure} \vfill \end{landscape} \end{document}
[ "german.stackexchange", "0000027941.txt" ]
Q: How to use “seit” and “vor” with “verschwinden” The questions are on these sentences, where (a) is lifted out of this older post, and (b) is from a vocabulary workbook. I made up (c) and (d); so they may have problems. (a) Ich lebe seit einem Monat in Graz. (b) Unsere Katze ist seit Tagen verschwunden. (c) Unsere Katze verschwand vor Tagen. (d) Unsere Katze ist vor Tagen verschwunden. Basically I am trying to understand how seit and vor may interact with grammatical aspect. Feel free to answer in German. Questions Am I OK to assimilate (b) to (a) as follows? lebe in (a) denotes what is true (in progess) for the whole time between a month ago and now. ist verschwunden in (b) is not a substitute for Präteritum. It is a true Perfekt. The "present result of the past event" is what is true for the whole time between days ago and now. We may say that the "present" (imperfect, progressive) aspect of lebe and the "present" component of the resultative aspect of ist verschwunden respectively satisfy the aspectual requirement of seit. Is (d) grammatical and idiomatic? If yes to 2, am I OK to understand (d) this way? Because vor requires a verb denoting an event (viz. a verb in the "aorist" aspect), ist verschwunden is now a substitute for Präteritum. That is, (d) now means the same thing as (c). Unlike (b), you can say (d) even if the cat has come back subsequently. Background I tried to get something like (b) with vorbeigehen, but Er ist seit Tagen an unserem Hause vorbeigegangen didn’t seem to work. I think there is no sense of ist vorbeigegangen that is comparable to ist verschwunden, something that can remain and persist (be in progress). A: The sentence Die Katze ist verschwunden has two different interpretations: On the one hand, ist can be the auxiliary used when forming the perfect tense. In that case, verschwunden is part of the perfect form and the sentence is analogous to Der Mann ist gestorben or Der Hahn hat (!) gekräht; it indicates that an event (disappearance of the cat) happened in the past. On the other hand, ist can be the present-tense copula. In that case, verschwunden is used as an adjective, analogous to Der Mann ist tot or Der Hahn ist wach; it indicates a current state, namely that the whereabouts of the cat are unknown. This ambiguity is only possible because verschwinden belongs to the group of verbs that form the perfect tense with sein instead of haben. Adding a time specification like in your sentences (b) and (d) resolves the ambiguity because vor drei Tagen etc. only makes sense in connection with a past event, whereas seit drei Tagen only works in connection with a state that persists. Applied to the structurally analogous sentences I introduced above, this means that you can use only one of these constructions for each sentence: Der Mann ist vor drei Tagen gestorben. Der Hahn hat vor einer Stunde gekräht. Der Mann ist seit drei Tagen tot. Der Hahn ist seit einer Stunde wach. (Der Hahn hat seit einer Stunde gekräht is in fact possible, but would mean that the cock crowed continuously or repeatedly over the course of the last hour.) Now to your questions: In (b), ist (verschwunden) is not perfect but present tense (not of verschwinden, but of sein). That’s why it can’t be replaced with a preterite. Whether (d) is grammatical and idiomatic … mostly yes, but I hesitate to “approve” of it because of vor Tagen. As Crissov already mentioned in a comment, vor Tagen sounds strange except in specific contexts; schon vor Tagen will often work, and vor zwei Tagen (or any number) is fine. Yes, (c) and (d) are equivalent, and both can be said – unlike (b) – when the cat has since reappeared: Unsere Katze ist vor drei Tagen verschwunden. Heute früh ist sie endlich wieder aufgetaucht.
[ "physics.stackexchange", "0000371902.txt" ]
Q: Why nuclear fusion deliver energy instead of taking? In nuclear physics, when you break eg. a nucleus of Uranium, some neutrons are liberated, and the original atom degrades to a lighter element. The energy that was used to keep these subatomic particles together is liberated (strong interaction), and a small part of the mass is converted to energy (E=MC^2) so you get a lot of energy with a small amount of atoms. So why nuclear fusion (the opposite operation) could even liberate MUCH more energy? I would naively expect it to take a lot of energy, not liberate it. I'm not a physician nor a student, just interested in physics, and this has always been a mystery to me. EDIT: actually, both of your answers are great and cristal-clear. That makes perfect sense and is exactly what I was looking for. I wish I could accept both answers, but the one with the graphic was a bit more complete. But thank you two! A: Good question. To think of it in that way can be very confusing. Every atom wants to reach the least energetic state it possibly can. This is what happens in fission, as you explain, and the uranium nucleus gives out energy after it splits into other nuclei, as those daughter nuclei have lost energy in order to reach that state, lost the energy which we use. Why do they lose energy though? This is where binding energy comes in. Binding energy is defined as the energy required to split a given nucleus into it's individual protons and neutrons. Rephrased, it is the energy released when protons or neutrons come together to form an nucleus. Now the binding energy is not what determines the stability, but the binding energy per nucleon (protons and neutrons are collectively called nucleons, as they constitute the nucleus) that determines it. For example, if one man has a 100 dollars, and a family of 10 has 500 dollars, the family has more money collectively, however, individualy, the man has more money. In the same way, it is the binding energy per nucleon , that determines the stability. The graph of binding energy per nucleon vs the elements is given- You can see that iron, has the highest binding energy, which makes it the most stable element. Now every atom wants to attain this stability that iron has. Uranium, on the right side of the graph, should split in order to come closer to the binding energy per nucleon value that iron has, whereas light elements like hydrogen need to fuse in order to gain iron's stability. You can see that hydrogen is way below iron in the graph, which is also why fusion releases a lot more energy than fission. I hope you understood, have a great day! A: The answer comes down to the relative strength and mechanism of the strong nuclear force and the electromagnetic force. Up to a certain point, the mass-energy of a larger nucleus is lower than the separate smaller nuclei that fuse to it. For example, two hydrogen nuclei + two neutrons separate from each other weigh more than a helium nucleus. Since the lower energy state is favorable, the four particles will fuse if they are brought together and release the extra energy. Of course the electromagnetic repulsion must be overcome for that to happen, which is why fusion requires high temperature to get started, but once conditions exists, fusion is favorable because the strong force overcomes the electromagnetic force to bind the nucleons. This process occurs spontaneously up to iron, after which it is no longer energetically favorable to fuse - larger nuclei are the product of endothermic, rather than exothermic, fusion reactions generally only occurring during supernovae and similar catastrophic events. In a very large nucleus like Uranium however, there are a large number of protons, which repel electromagnetically. But unlike the smaller nuclei, the strong force cannot reliably bind the nucleus due to its short range. Protons on opposite sides of the nucleus experience electromagnetic repulsion on par with the nuclear binding forces and sometimes will break off. In this case the fission is energetically favorable, bringing the nuclei closer to lower energy state of an iron atom, where the nucleus is small enough to be kept together be the nuclear forces. So there's a saddle point at iron where the energy is most favorable, so fusing up from smaller nuclei releases energy due to strong force binding and fissing (is that a word?) down to it is favorable due to electromagnetic repulsion.
[ "stackoverflow", "0017076168.txt" ]
Q: How to flatten with ng-repeat I have: businesses: [ {businessName: 'A', "address":[loc1, loc2, loc3]}, {businessName: 'B', "address":[loc1, loc2]}, {businessName: 'C', "address":[loc1]} }; I want to ng-repeat this object with output: A | street, city, zip, state A | street, city, zip, state A | street, city, zip, state B | street, city, zip, state B | street, city, zip, state C | street, city, zip, state In other words, i want to display this object as flat in a table with ng-repeat. Do i have to flatten it myself, or does ng-repeat have the power to do this? Ideally i could just do something like ng-repeat business in businesses business.businessName | business.address.City | business.address.State By specifying address, it should know i want them all. Otherwise, how do i flatted an object like this one? Thanks! A: Seems like you could process it a bit, something like: var flatBusinesses = []; for (business in businesses) { for (address in business.addresses) { flatBusinesses.push ({name: business.name, address: address.City, state: address.State} } } And then just repeat on flatBusinesses in the view A: The underscore library has a number of functions for dealing with javascript arrays and objects that work well as a complement to angular: http://underscorejs.org/ You would need to download the library and add it to your project. Then you could write: var flatBusinesses = _.flatten(_.pluck(businesses, 'address')); You should be able to add the underscore library to the scope: $scope._ = _; And then add this directly to your template: <div ng-repeat="business in _.flatten(_.pluck(businesses, 'address'))"> {{business.businessName}} | {{business.address.City}} | {{business.address.State}} </div> EDIT: So, I didn't read your questions carefully enough, and flatten and pluck aren't going to cut it in your case. I put together a fiddle playing around with underscore to make it work, but the final result is not an improvement over rquinn's response. Anyways, here is the fiddle if you want to look at it: http://jsfiddle.net/pna7f5h3/
[ "stackoverflow", "0030825382.txt" ]
Q: gitlab: Windows: How to use chmod and fix "Get Permission denied (publickey). fatal: Could not read from remote repository" I have gone through many other posts about the above error, but they all seem to be for a different OS, or for some different reason. I am running Windows 8.1. I have git installed (I am very new to git), and have signed up to gitlab, create a project there, created and added the key (as per instructions), however when I try and do a push, I get the Pushing to [email protected]:myusername/Test1.git Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Now when I created my ssh key using ssh-keygen -t rsa -C "[email protected] it did create the files in the local project folder, and not under C:\Users\Peter (my home folder) So, copied the single file (known_hosts) I deleted the existing .ssh folder, and created using bash, and then copied in the above together with the created id_rsa.pub and idrsa.key files. From Git Gui, if I go to Help | Show SSH Key is reports "Found a public key in ~/.ssh/id_ras.pub From bash, my permissions on the folder are. drwxr-xr-x 1 Peter Administ 0 Jun 14 09:35 .ssh and the permissions on the files within are.. $ ls .ssh -l total 2 -rw-r--r-- 1 Peter Administ 403 Jun 13 18:26 id_rsa.pub -rw-r--r-- 1 Peter Administ 1766 Jun 13 18:26 idrsa.key -rw-r--r-- 1 Peter Administ 184 Jun 13 18:11 known_hosts I am assuming I need to fix the permissions here? So I go into the .ssh folder and try a chmod 777 * But then when I use ls -l to see the permissions they have not changed Likewise when I try that on the actual directory .ssh, permissions stay as they are So, the questions are Am I on the right track here, is it the permissions of the folder/files that are the problem If so, how can I fix this (on Windows 8.1) I am at a complete loss of what to try next Thanks in advance for any help! A: Am I on the right track here, is it the permissions of the folder/files that are the problem Not really: "permission denied" is sent back by the GitLab server, as it doesn't recognize your ssh public key. Firstly, as mentioned in GitLab ssh keys doc page: Copy-paste the key (id_rsa.pub content) to the 'My SSH Keys' section under the 'SSH' tab in your user profile. Please copy the complete key starting with ssh- and ending with your username and host. Secondly, ssh will locally look for the private and public keys in %HOME%. And %HOME% isn't defined by default in Git, unless you launch git-cmd.exe or git-bash.exe packaged with the latest Git for Windows 2.4.x+. So: make sure to grep PortableGit-2.4.3.1-2nd-release-candidate-64-bit.7z.exe, and unzip it anywhere you want (for example in: c:\prgs\git\PortableGit-2.4.3.1-2nd-release-candidate-64-bit) Don't intall the old obsolete msysgit 1.9.5 from git-scm.com. As I explained, it will soon be phased out. add c:\prgs\git\PortableGit-2.4.3.1-2nd-release-candidate-64-bit\usr\bin to your %PATH% (it includes ssh.exe) launch c:\prgs\git\PortableGit-2.4.3.1-2nd-release-candidate-64-bit\git-cmd.exe, and see that %HOME% is define (set HOME). It should be defined to your %USERPROFILE% by default (c:\Users\<yourLogin>) generate your ssh keys (or copy your existing one in %HOME%\.ssh). Don't worry about chmod or rights. make sure your ssh public key is copied in your GitLab ssh key page. Then, test if ssh works: ssh -Tv [email protected] Now you can start pushing.
[ "stackoverflow", "0054898748.txt" ]
Q: What powershell verb suits reloading a users profile? I have a commandlet in my profile that reloads my user profile. Whenever I edit my profile VSCode warns me that the name I use—Reload-Profile—uses an unapproved verb. While Reload seems like a sane, obvious and easily searchable verb to describe reloading a resource, I'd like to know what I should be using to keep PS happy. None of the candidates on the list of approved verbs seem to describe anything like reloading. Here's the code BTW (I got it from this answer) function Reload-Profile { @($Profile.AllUsersAllHosts, $Profile.AllUsersCurrentHost, $Profile.CurrentUserAllHosts, $Profile.CurrentUserCurrentHost ) | ForEach-Object { if(Test-Path $_){ Write-Host "Running $_" -foregroundcolor Magenta . $_ } } } A: I'd go with Invoke. Running a command is Invoke-Command, running a expression is Invoke-Expression, running pester is Invoke-Pester, and when Pester wants to run a mock, it's with Invoke-Mock, etc. Invoke is the goto verb for asking something to execute.
[ "stackoverflow", "0011604896.txt" ]
Q: smooth curve of scatter data frame data in R and add confedence interval I have many data.frame and each one contains many columns. Say my first data.frame col1=a, col2=b,col3=c I want to plot x-axis=b/a and y-axis=a. I managed to plot them (scatter plot) plot (dataframe$b/dataframe$a, dataframe$a, xlim=...,ylim=..) Now, I need to get the pattern for the scatter data ( I don't want linear regression as both of x and y are changing). I did use the command loess(..) and I was able to show the pattern. lo_smooth<-loess(x,y, f=number, iter=number) How I can add the confidence intervals (CI) to the graph? My goal is to check if two data.frame are within each other CI or not. A: A solution that uses your attempt (Well done!) plus your clarification Some dummy data dppm <- data.frame(a = runif(100, 1, 100), b = runif(100,1, 100)) dppm_2 <- data.frame(a = runif(100, 1, 75), b = runif(100,1,75)) dppm_3 <- data.frame(a = runif(100, 1,50), b = runif(100,1,50)) Using reshape2 to melt these data into a single data frame library(reshape2) data_list <- list(dppm1 = dppm, dppm2 = dppm_2, dppm3 = dppm_3) all_data <- melt(data_list, id.vars = c('a','b')) This single data frame has a column L1 that is the identifier (the name of the list component in data_list. head(all_data) a b L1 ## 1 83.202896 36.94026 dppm1 ## 2 42.618987 11.23863 dppm1 ## 3 29.505029 11.91742 dppm1 ## 4 63.569487 59.07395 dppm1 ## 5 94.499772 47.32779 dppm1 ## 6 4.535389 64.11570 dppm1 We can then plot this combined data set and colour by this identifier. We also set the fill for the smooth to the same identifier so that the CIs will be coloured in the same way. ggplot(all_data,aes(x = b/a, y = a, colour = L1)) + geom_point() + stat_smooth(method = "loess", se = TRUE,level = 0.90, aes(fill = L1))+ coord_cartesian(ylim = c(0, 100))
[ "stackoverflow", "0001995440.txt" ]
Q: NHibernate Filter as a row level security layer I would like to use NHibernate Filters to hide some rows from users, according to different permission sets. Can I call a stored procedure from the filter? Are there any scenarios in which a filter won't filter records, or will cause an error? Thanks! A: No you can't. The filter is translated into part of the WHERE clause of a SQL statement. Not sure what you mean - if the filter is correct and is applied it will work, it's not a half-baked feature...
[ "stackoverflow", "0019173931.txt" ]
Q: htaccess rewrite acting funny Here is my redirect rule to redirect inside a public/ directory. File inside site (example directory) RewriteCond %{REQUEST_URI} ="" RewriteRule ^.*$ public/index.php [NC,L] RewriteCond %{REQUEST_URI} !^public/.*$ RewriteRule ^(.*)$ public/$1 RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^.*$ - [NC,L] RewriteRule ^public/(.*)$ public/index.php?r=$1 [NC,L] What this does is create a funky effect. site/a/b/c --> site/a/b/c/b/c // ^ b/c is repeated and the params are a/b/c Inside a public directory .htaccess file has RewriteEngine On If I remove this line, r gets public/index.php not a/b/c. Why is this happening? A: Try this code: RewriteEngine On RewriteRule ^$ public/index.php [NC,L] RewriteCond %{REQUEST_URI} !^/public/ RewriteRule ^(.+)$ public/index.php?r=$1 [L,QSA]
[ "stackoverflow", "0047097156.txt" ]
Q: PDO postgresql last inserted id return 'false' or -1 I have code $dbh = new PDO("pgsql:host=localhost; port=5432; dbname=gpd; user=postgres; password=postgres"); $sth = $dbh->prepare("INSERT INTO res (res_name, res_order) VALUES ('London', 1)"); $sth->execute(); $id = $dbh->lastInsertId(); echo $id; Record insert, but $id is empty. I try execure query INSERT INTO res (res_name, res_order) VALUES ('London', 1) RETURNING id and received a value "-1" A: Going home, I myself understood what must to do $dbh = new PDO("pgsql:host=localhost; port=5432; dbname=gpd; user=postgres; password=postgres"); $sth = $dbh->prepare("INSERT INTO res (res_name, res_order) VALUES ('London', 1)"); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); echo "ID - ". $result["id"]; It's simple
[ "stackoverflow", "0012684989.txt" ]
Q: accessing array and objects I have a problem with printing my data. In my program, i get the data which was in object and put in an array. say array1[$id] = dataobject. the whole array1 then will be put to array2['list'] like array2['list'] = array1; the problem is how do i get the data such as the id, name and description.. here's the print_r of the whole array: this is actually the result of the array, i am not sure how to access this. i want to foreach and get the name and print them: Array ( [list] => Array ( [0] => Array ( [0] => stdClass Object ( [id] => 1 [name] => harry potter 4 [description] => harry potter and the goblet of fire book by j.k. rowling [unit_price] => 300.99 ) ) [1] => Array ( [0] => stdClass Object ( [id] => 4 [name] => lipton tea [description] => yellow label tea [unit_price] => 15.00 ) ) [2] => Array ( [0] => stdClass Object ( [id] => 9 [name] => tisyu [description] => tissue twenty pieces [unit_price] => 20.00 ) ) ) ) A: You would have to access them something like the following: foreach($array['list'] as $array_item){ $object = $array_item[0]; echo $object->id."<br />"; echo $object->name."<br />"; echo $object->description."<br />"; echo $object->unit_price."<br />"; } This would yield: 1 harry potter 4 harry potter and the goblet of fire book by j.k. rowling 300.99 4 lipton tea yellow label tea 15.00 9 tisyu tussue twenty pieces 20.00 You can access an objects properties using the -> operator, followed by the property you wish to access.
[ "superuser", "0000101972.txt" ]
Q: Max Usable Memory - Windows 7 Pro 64-bit Specs beforehand (Upgraded HP m8530f): AMD Phenom X4 9550 @ 2.20 GHz / HIS 256MB Radeon HD4350 GDDR2 PCI-E / 6.0 GB PC2-6400 DDR2 RAM / 750GB SATA Seagate Barracuda HDD / ASUS M2N78-LA / CoolerMaster 500W PSU So, this computer comes stock with 5.0 GB of RAM. So in the four slots, there is a 1 GB - 1 GB - 2 GB - 1 GB configuration. Today, though, I got another 2GB stick, so now I have a configuration of 1 GB - 1 GB - 2 GB - 2 GB. However, after I booted up... I went to Computer Properties and it says that I only have 5.0 GB Usable memory. However, I checked online and for Windows 7 Pro 64-bit, the max supported memory should be much much more. Any ideas? Are there questions like this already? (oops) EDIT1: for Sim... A: Have you upgraded the BIOS? There is a BIOS update for your model (HP m8530f) on the HP website that might do the trick M2N78-LA Motherboard BIOS update improves security support, and fixes incorrect memory size being reported in Vista when 4GB or more is installed. There is a good page on the HP Site that walks you through upgrading to Windows 7 and covers know issues and solutions etc.
[ "stackoverflow", "0003704522.txt" ]
Q: Is there any kind of idiots guide to deploying your ASP.NET MVC website in one click? I'm about to begin building a website using the ASP.NET MVC framework and I'm trying to find a good solution to 1)Source Control Management and 2)Deployment. For the SCM, I'm probably going to use SourceGear since it integrates into Visual Studio nicely, but for deployment, I don't even know where to start. Up until know, most websites that I've built were very static and every time I had to update the site, I would use an FTP program and just drag and drop the files to the server. But now that I'm going to be building a much more dynamic web application, this approach feels dangerous (which, oddly enough, is also my middle name). Does there exist some kind of idiots guide or tutorial that explains a good way to deploy an update to your website? Thanks so much in advance for all your help! A: Source Control For source control, I like to use SubVersion at home. I would recommend using VisualSVN Server to install the server - it's free and ridiculously easy to use. On the client side of things, I use TortoiseSVN (for shell integration) and VisualSVN (for Visual Studio integration). The small ammount of money for VisualSVN is well worth it, but there is a free open source equivilent AnkhSVN. That's just what I use and there are many alternatives out there. Deployment I would definitely recommend using Microsoft Web Deploy. Scott Gu just blogged today about it - Automating Deploy with Microsoft Web Deploy. There there is also Scott Hanselman's guide - Web Deployment Made Awesome: If You're Using XCopy, You're Doing It Wrong. I recently came across a couple of posts by Jon Torresdal using Team Foundation Server (SCM), TeamCity (CI), and Web Deploy to implement a 'no-click' web deployment. They make for very interesting reading but they're definitely not what you'd consider idiots guide material. No-Click Web Deployment – Part 1 No-Click Web Deployment – Part 2 – Web Deploy (a.k.a. msdeploy) HTHs, Charles
[ "math.stackexchange", "0001756524.txt" ]
Q: Can we have a diffeomorphism from a subset of $\Bbb R^2$ into a subset of $\Bbb R^3$? In a lecture, our professor defined an allowable surface patch for a surface $S \subset \Bbb R^3$ to be a diffeomorphic surface patch of $S$. But is is possible to have a diffeomorphism between an open subset of $\Bbb R^2$ and an open subset of $\Bbb R^3$? If $f: U \subset \Bbb R^2 \to V \subset \Bbb R^3$ is a diffeomorphism, meaning that $f$ is a differentiable invertible map with a differentiable inverse, then the differential of $f$ at some point $x_0 \in U$ is a linear map $Df(x_0): \Bbb R^2 \to \Bbb R^3$, and it is invertible as its inverse is given by the differential of $f^{-1}$ at $f(x_0)$, hence there would be an isomorphism between $\Bbb R^2$ and $\Bbb R^3$, which is impossible. Isn't this right? A: Indeed, an open subset of $\mathbb{R}^2$ cannot be diffeomorphic to an open subset of $\mathbb{R}^3$, for the reason you outlined. In fact there cannot even be a homeomorphism, by invariance of domain. But a surface is not an open subset of $\mathbb{R}^3$. Consider the standard sphere $$S^2 = \{ (x,y,z) \in \mathbb{R}^3 \mid x^2+y^2+z^2=1 \}.$$ Hopefully you agree that it is a surface, and indeed $S^2$ is locally diffeomorphic to an open subset of $\mathbb{R}^2$. But $S^2 \subset \mathbb{R}^3$ is not open.
[ "stackoverflow", "0023550953.txt" ]
Q: Call to undefined method PDO::execute(), previous answers doesn't solve the error I'm trying to make a CSV import function via php, which stores the information in a MySQL database, but for some reason, it gives the below error :- Fatal error: Call to undefined method PDO::execute() in /home/a/public_html/admin/admin_import_product.php on line 25 <?php session_start(); include '../inc/inc.functions.php'; include '../dbconnector.php'; include '../dbpdo.php'; include '../inc/inc.config.php'; if((isset($_SESSION['admin'])) && ($_SESSION['admin'] == 1)) { $adminusername = $_SESSION['username']; $date=date('Y-m-d'); if ($_FILES[csv][size] > 0) { //get the csv file $file = $_FILES[csv][tmp_name]; $handle = fopen($file,"r"); //prepare the statement for the insertion of the record via PDO try{ global $conn; $statement = $conn->prepare("INSERT INTO products(category,productname,baseprice,basepricewd,basepricenw,addedby,addedon) VALUES (?,?,?,?,?,?,?)"); //loop through the csv file and insert into database do { if ($data[0]) { $statement=$conn->execute(array( $data[0], $data[1], $data[2], $data[3], $data[4], $adminusername, $date)); } } while ($data = fgetcsv($handle,5000,",","'")); // }//try catch(PDOException $e) { echo $e->getMessage(); } //redirect // header('Location: admin_importproducts_home.php?success=1'); die; echo "Products imported successfully"; } } else { header('Location:http://a.co.uk/' . $config["admindir"] . '/adminlogin'); } ?> Any suggestions are helpful. A: You are calling execute() from the wrong object/resource (whatever PDO is): // this is the proper chain of calls as stated in the documentation $statement = $conn->prepare(); $execute_result = $statement->execute(); // execute() returns a boolean so you can use an if/else block to know if your query is hunky-dory if($execute_result) { // yay the query had no errors! } else { // aww snap, you messed up now! } http://www.php.net/manual/en/pdostatement.execute.php
[ "stackoverflow", "0056050322.txt" ]
Q: Why is valarray so slow on Visual Studio 2015? To speed up the calculations in my library, I decided to use the std::valarray class. The documentation says: std::valarray and helper classes are defined to be free of certain forms of aliasing, thus allowing operations on these classes to be optimized similar to the effect of the keyword restrict in the C programming language. In addition, functions and operators that take valarray arguments are allowed to return proxy objects to make it possible for the compiler to optimize an expression such as v1 = a * v2 + v3; as a single loop that executes v1[i] = a * v2[i] + v3[i]; avoiding any temporaries or multiple passes. This is exactly what I need. And it works as described in the documentation when I use the g++ compiler. I have developed a simple example to test the std::valarray performance: void check(std::valarray<float>& a) { for (int i = 0; i < a.size(); i++) if (a[i] != 7) std::cout << "Error" << std::endl; } int main() { const int N = 100000000; std::valarray<float> a(1, N); std::valarray<float> c(2, N); std::valarray<float> b(3, N); std::valarray<float> d(N); auto start = std::chrono::system_clock::now(); d = a + b * c; auto end = std::chrono::system_clock::now(); std::cout << "Valarr optimized case: " << (end - start).count() << std::endl; check(d); // Optimal single loop case start = std::chrono::system_clock::now(); for (int i = 0; i < N; i++) d[i] = a[i] + b[i] * c[i]; end = std::chrono::system_clock::now(); std::cout << "Optimal case: " << (end - start).count() << std::endl; check(d); return 0; } On g++ I got: Valarr optimized case: 1484215 Optimal case: 1472202 It seems that all operations d = a + b * c; are really placed in one cycle, which simplifies the code while maintaining performance. However, this does not work when I use Visual Studio 2015. For the same code, I get: Valarr optimized case: 6652402 Optimal case: 1766699 The difference is almost four times; there is no optimization! Why is std::valarray not working as needed on Visual Studio 2015? Am I doing everything right? How can I solve the problem without abandoning std::valarray? A: Am I doing everything right? You're doing everything right. The problem is in the Visual Studio std::valarray implementation. Why is std::valarray not working as needed on Visual Studio 2015? Just open the implementation of any valarray operator, for example operator+. You will see something like (after macro expansion): template<class _Ty> inline valarray<_Ty> operator+(const valarray<_Ty>& _Left, const valarray<_Ty>& _Right) { valarray<TYPE> _Ans(_Left.size()); for (size_t _Idx = 0; _Idx < _Ans.size(); ++_Idx) _Ans[_Idx] = _Left[_Idx] + _Right[_Idx]; return (_Ans) } As you can see, a new object is created in which the result of the operation is copied. There really is no optimization. I do not know why, but it is a fact. It looks like in Visual Studio, std::valarray was added for compatibility only. For comparison, consider the GNU implementation. As you can see, each operator returns the template class _Expr which contains only the operation, but does not contain data. The real computation is performed in the assignment operator and more specifically in the __valarray_copy function. Thus, until you perform assignment, all actions are performed on the proxy object _Expr. Only once operator= is called, is the operation stored in _Expr performed in a single loop. This is the reason why you get such good results with g++. How can I solve the problem? You need to find a suitable std::valarray implementation on the internet or you can write your own. You can use the GNU implementation as an example.
[ "stackoverflow", "0012167108.txt" ]
Q: using Oracle JDBC driver implicit caching feature I am pretty sure that somebody else already asked this question, but I still couldn't find a satisfactory answer to it. So, here is my scenario: I want to use the Oracle's JDBC driver implicit statement caching (documented here: http://docs.oracle.com/cd/B28359_01/java.111/b31224/stmtcach.htm#i1072607) I need to use the connections from a 3rd party JDBC pool provider (to be more specific, Tomcat JDBC) and I have no choice there. The problem is that the way to enable the implicit caching is a two-step process (accordingly to the documentation): 1. Call setImplicitCachingEnabled(true) on the connection or Call OracleDataSource.getConnection with the ImplicitCachingEnabled property set to true. You set ImplicitCachingEnabled by calling OracleDataSource.setImplicitCachingEnabled(true) 2. In addition to calling one of these methods, you also need to call OracleConnection.setStatementCacheSize on the physical connection. The argument you supply is the maximum number of statements in the cache. An argument of 0 specifies no caching. I can live with 1 (somehow I can configure my pool to use the OracleDataSource as a primary connection factory and on that I can set the OracleDataSource.setImplicitCachingEnabled(true)). But at the second step, I already need the connection to be present in order to call the setStatementCacheSize. My question is if there is any possibility to specify at the data source level a default value for the statementCacheSize so that I can get from the OracleDataSource connections that are already enabled for implicit caching. PS: some related questions I found here: Oracle jdbc driver: implicit statement cache or setPoolable(true)? Update (possible solution): Eventually I did this: Created a native connection pool using oracle.jdbc.pool.OracleDataSource. Created a tomcat JDBC connection pool using org.apache.tomcat.jdbc.pool.DataSource that uses the native one (see the property dataSource). Enabled via AOP a poincut so that after the execution of 'execution(public java.sql.Connection oracle.jdbc.pool.OracleDataSource.getConnection())' I pickup the object and perform the setting I wanted. The solution works great; I am just unhappy that I had to write some boilerplate to do it (I was expecting a straight-forward property). A: The white paper Oracle JDBC Memory Management says that The 11.2 drivers also add a new property to enable the Implicit Statement Cache. oracle.jdbc.implicitStatementCacheSize The value of the property is an integer string, e.g. “100”. It is the initial size of the statement cache. Setting the property to a positive value enables the Implicit Statement Cache. The default is “0”. The property can be set as a System property via -D or as a connection property via getConnection.
[ "stackoverflow", "0015563526.txt" ]
Q: What does hbase returns when get is called for either row key, Column Family , Column Qualifier What does hbase returns when get is called for either row key, Column Family , Column Qualifier When Called with get ( ROW_KEY1 ) what does it returns, does it returns all the CFs and then respective CQs When Called with get ( ROW_KEY, CF) does it returns all the CQs .... A: For (1), it will return all the column families and column qualifiers. For (2), it will return all the column qualifiers for the specified column family.
[ "stackoverflow", "0038647882.txt" ]
Q: Read a File Object with nodejs Is it possible to read a file object in nodejs? This is an example of an object that I'm talking about "attachment1" : { "data" : [ 37, 80, 68, 70, ... ], "encoding" : "7bit", "mimetype" : "application/pdf", "name" : "Dalliny_Coelho_A_Ferreira.pdf", "size" : 6427, "truncated" : false } My dream would be able to read it's contents as if it was HTML, since it's a PDF A: I figured out afterwards that the data attribute was a ArrayBuffer of the file content, and that is basically what needs to be read. It's also what is returned when you read a file with the HTML 5 native file input
[ "stackoverflow", "0014718428.txt" ]
Q: MongoDb reads happening from a secondary in RECOVERY state I have a replica set in which a new secondary node is added. That node status is in "RECOVERING". When I try to execute java driver client with Nearest as ReadPreference, some reads are going to the secondary which is syncing and throwing exception. Should driver be intelligent enough not to make read requests to secondaries that are in "Recovering" state? or am I missing something. A: Indeed the driver should not be sending requests to a node in a RECOVERING state. I've created a Jira ticket to track this bug: https://jira.mongodb.org/browse/JAVA-753
[ "stackoverflow", "0016227597.txt" ]
Q: Autopair and Python strings I use autopair-mode globally for intelligent quote/paren/bracket pairing. It helps in most situations, except one. It's kind of a pain in the ass using Python's multi-quote strings. Typing quote once gives me "|", another quote gets me ""|, a third quote gets me """|", a fourth quote gies """"|, a fifth quote gives me """""|, and a sixth quote finally gets me to """"""|. At which point I need to hop back three spaces to get what I actually wanted the whole time, which is """|""". Is there a pre-built (or easy) way of getting autopair to have the behavior that hitting quote three times automatically gives me """|""" instead of the quote-shuffle described above? A: Adding the following to my .emacs gave me the desired behavior: (add-hook 'python-mode-hook #'(lambda () (setq autopair-handle-action-fns (list #'autopair-default-handle-action #'autopair-python-triple-quote-action)))) Found in the More Tricks section of the documentation linked by immerrr in their comment.
[ "gaming.meta.stackexchange", "0000014762.txt" ]
Q: Is it OK to tell a user to install mods/community patches to fix problems with old games? Not all of the games available on the internet can run on recent versions of Windows, and because of this, mods created by the community usually appear attempting to fix the problems that the game has and/or make it run on recent versions of operating systems. Is OK to tell a user to install mods/community patches to fix problems with old games? Some examples: grand-theft-auto-san-andreas internal timings on missions like the Dancing and Low Rider challenges can be fixed by installing SilentPatch the-simpsons-hit-and-run does not allows the use of non 4:3 resolutions, but this can be bypassed by using Lucas' Simpsons Hit & Run Mod Launcher A: Abso-lutely. Mods are perfectly acceptable as an answer in pretty much every use case, and in situations like this, where they might be the only solution, they're all the more appropriate.
[ "unix.stackexchange", "0000259901.txt" ]
Q: Change dir colour in bash output Under Mac OSX, I am trying to change the dir colour when ls outputs in the bash shell. So I placed this line at the end of my .bashrc file and reloaded. LS_COLORS=$LS_COLORS:'di=0;32:' ; export LS_COLORS . ~/.bashrcc The output of echo "$LS_COLORS" is :di=0;35::di=0;35::di=0;32: But I am not getting the light green I am expecting. Thanks A: Mac uses BSD ls. See man ls for details. The format of LS_COLORS is different. Specifically, see LESS='+/^[[:space:]]*LSCOLORS' man ls The variable name isn't even LS_COLORS, it's LSCOLORS. The links I found that were most helpful in figuring this out were this blog post, and this article which was linked to from the blog post. The default value for LSCOLORS is exfxcxdxbxegedabagacad. To leave everything at its default color except for directories, and make those green instead of blue, put the following in your ~/.bash_profile: export LSCOLORS=cxfxcxdxbxegedabagacad You will also need to either set the CLICOLOR variable (with export CLICOLOR=) or alias ls to ls -G. But in your screenshot above you do have color output, so I'm assuming you've done one of those already. Original Answer: On Mac OS, ls takes the -G option to colorize output. From man ls on a Mac: -G Enable colorized output. This option is equivalent to defining CLICOLOR in the environment. (See below.) Run ls -G and you'll get color output. I also recommend adding: alias ls='ls -GF' to your ~/.bash_profile. That's the alias I have there. The -F option adds the / after directory names, * after executables, etc.
[ "stackoverflow", "0022146205.txt" ]
Q: grab frame NTSCtoUSB dongle, opencv2, python wrapper Context: I have been playing around with python's wrapper for opencv2. I wanted to play with a few ideas and use a wide angle camera similar to 'rear view' cameras in cars. I got one from a scrapped crash car (its got 4 wires) I took an educated guess from the wires color codding, connect it up so that I power the power and ground line from a usb type A and feed the NTSC composite+ composite- from an RCA connector. I bought a NTSC to usb converter like this one. It came with drivers and some off the shelf VHStoDVD software. the problem: I used the run of the mill examples online to trial test it like this: import numpy as np import cv2 cam_index=0 cap=cv2.VideoCapture(cam_index) print cap.isOpened() ret, frame=cap.read() #print frame.shape[0] #print frame.shape[1] while (cap.isOpened()): ret, frame=cap.read() #gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break #release and close cap.release() cv2.destroyAllWindows() this is the output from shell: True Traceback (most recent call last): File "C:/../cam_capture_.py", line 19, in <module> cv2.imshow('frame', frame) error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow >>> key Observations: SCREENSHOTS in control panel the usb dongle is shown as 'OEM capture' in Sound Video & Game controllers . So it's not seen as a simple plug and play Webcam in 'Imaging devices' If I open the VHStoDVD software I need to configure 2 aspects: set as Composite set enconding as NTSC then the camera feed from the analog camera is shown OK within the VHStoDVD application When I open the device video channel in FLV (device capture). The device stream is just a black screen but IF i open the VHStoDVD software WHILE flv is streaming I get the camera's feed to stream on FLV and a black screen is shown on the VHStoDVD feed. Another important difference is that there is huge latency of aprox 0.5sec when the feed is in FLV as opposed to running in VHStoDVD. When running "cam_capture.py" as per the sample code above at some put during runtime i will eventually get a stop error code 0x0000008e: detail: stop: 0x0000008E (0xC0000005, 0xB8B5F417, 0X9DC979F4, 0X00000000 ) ks.sys - Address B8B5F417 base at B8B5900, Datestamp... beg mem dump phy mem dump complete 5.if i try to print frame.shape[0] or frame.shape[1] I get a type error say I cannot print type None 6.if try other cam_index the result is always false TLDR: In 'control panel' the camera device is under 'sound video & game controllers' not under 'imaging devices'; The cam_index==zero; The capture.isOpened()=True; The frame size is None; If VHStoDVD is running with composite NTSC configured the camera works , obviously you cant see the image with printscreen in attachment but trust me ! ;) Is there any form of initialisation of the start of communication with the dongle that could fix this i.e. emulate VHStoDVD settings (composite+NTSC)? I thought I could buspirate the start of comms between VHStoDVD and the dongle but it feels like I am going above and beyond to do something I thought was a key turn solution. Any constructive insights, suggestion , corrections are most welcome! Thanks Cheers A: Ok , so after deeper investigation the initial suspicion was confirmed i.e. because the NTSC dongle is not handled as an imaging device (it's seen as a Video Controller , so similar to an emulation of a TV Tuner card ) it means that although we are able to call cv2.VideoCapture with cam_index=0 the video channel itself is not transmitting because we are required to define a bunch of parameters encoding frame size fps rate etc The problem is because the device is not supported as an imaging device calling cv2.VideoCapture.set(parameter, value) doesn't seem to change anything on the original video feed. I didn't find a solution but I found a work around. There seems to be quite a few options online. Search for keywords DV to webcam or camcorder as a webcam. I used DVdriver (http://www.trackerpod.com/TCamWeb/download.htm) (i used the trial because I am cheap!). Why does it work? As much as I can tell DVdriver receives the data from the device which is set as a Video controller (similar to a capture from "Windows Movie Maker" or ffmpeg) and then through "fairydust" outputs the frames on cam_index=0 (assumed no other cam connected) as an 'imaging device' webcam. Summary TLDR use DVdriver or similar. I found a workaround but I would really like to understand it from first principles and possible generate a similar initialisation of the NTSC dongle from within python, without any other software dependencies but until then, hopefully this will help others who were also struggling or assuming it was a hardware issue. I will now leave you with some Beckett: Ever tried. Ever failed. No matter. Try again. Fail again. Fail better. (!)
[ "meta.stackoverflow", "0000329526.txt" ]
Q: Beautification and simplification I would like to submit a working code snippet to ask for feedback on how to simplify and/or make the code more readable. Is there a tag or method for this? A: There's no tag for this, but an entire site: Code Review. Their tagline matches your request perfectly: We're working together to improve the skills of programmers worldwide by taking working code and making it better. Before asking your question, make sure to read their help center to make sure your question is well-received.
[ "stackoverflow", "0010515369.txt" ]
Q: multiple markers resolving I was testing the first app (see http://developer.android.com/training/basics/firstapp/starting-activity.html) at a point,I stuck.. it shows: Multiple markers at this line - MyFirstActivity cannot be resolved to a variable - EXTRA_MESSAGE cannot be resolved or is not a field (see heading DISPLAY THE MESSAGE) // I FOUND THE ABOVE GIVEN ERROR MESSAGE HERE String message = intent.getStringExtra(MyFirstActivity.EXTRA_MESSAGE); HOW CAN I RESOLVE THIS? THANK YOU A: You haven't defined MyFirstActivity and EXTRA_MESSAGE. Did you add public final static String EXTRA_MESSAGE = "com.example.myapp.MESSAGE"; as it says in the tutorial? Check that MyFirstActivity is the name of your activity as well.
[ "stackoverflow", "0063405338.txt" ]
Q: Firebase .httpsCallable functions always returning "Maximum call stack size exceeded" I'm not sure I'm 100% on await and promise chaining, but I cannot for the life of me understand why any time I try to pass data to a httpsCallable function I get a "Maximum call stack size exceeded" error without the function ever being called. I'm just trying to pass the user object returned from signInWithEmailAndPassword to my httpsCallable but cannot figure out how to without said error. Any pointers appreciated <3 const importFirebase = () => import(process.env.VUE_APP_MODE === 'web' ? 'firebase' : 'nativescript-plugin-firebase/app') const firebase = await importFirebase() firebase .auth() .signInWithEmailAndPassword(signInData.email, signInData.password) .then((user) => { return firebase.functions().httpsCallable('doSomething')(user) }) A: The error typically means you're trying to serialize an object with internal circular references. The first thing you should try is any object other than user. Then, try composing an object based on what you pull out of user. Just don't pass user itself, since it might not be safe to serialize in the default manner.
[ "stackoverflow", "0061446883.txt" ]
Q: sender not recieving message sent on socker.io I am working on a node project using socket.io but when a message is emitted it goes to the sender only and not to other connected clients. please what could I be doing wrong? this my socket server and client code below. node - index.js ... io.on("connection", (socket) => { //When a new user join socket.on("joined", (data) => { socket.emit("welcome", "Welcome to test"); }); //on send socket.on("send_message", (data) => { const {name, message} = data; socket.emit("recieve_message", {name, message}); }); }); ... client - socket.html ... <body> <form action=""> <input id="name" autocomplete="off" /> <input id="message" autocomplete="off" /><button>Send</button> </form> <ul id="messages"></ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.0/socket.io.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> <script> var socket = io.connect('http://localhost:3005'); $('form').submit(function () { socket.emit('send_message', {name: $('#name').val(), message: $('#message').val()}); $('#message').val(''); return false; }); socket.emit('joined'); socket.on('welcome', function (msg) { $('#messages').append($('<li>').text(msg)); }); socket.on('recieve_message', function (msg) { $('#messages').append($('<li>').text(`${msg.name} - ${msg.message}`)); }); </script> </body> ... A: To send to everyone in the channel use socket.broadcast.emit() this will broadcast the message. Use this cheatsheet for reference next time. https://socket.io/docs/emit-cheatsheet/
[ "stackoverflow", "0036709996.txt" ]
Q: how to update ng-model of textarea after manual insert of some text into it I have this code which takes input from an input area and inserts the text at the caret position inside a text area, the insert part is working accurately but ng-model of text area fails to update the same. here is the code var app = angular.module('plunker', []); app.controller('MyCtrl', function($scope, $rootScope) { $scope.items = []; $scope.add = function() { $scope.items.push($scope.someInput); $rootScope.$broadcast('add', $scope.someInput); } }); app.directive('myText', ['$rootScope', function($rootScope) { return { link: function(scope, element, attrs) { $rootScope.$on('add', function(e, val) { var domElement = element[0]; if (document.selection) { domElement.focus(); var sel = document.selection.createRange(); sel.text = val; domElement.focus(); } else if (domElement.selectionStart || domElement.selectionStart === 0) { var startPos = domElement.selectionStart; var endPos = domElement.selectionEnd; var scrollTop = domElement.scrollTop; domElement.value = domElement.value.substring(0, startPos) + val + domElement.value.substring(endPos, domElement.value.length); domElement.focus(); domElement.selectionStart = startPos + val.length; domElement.selectionEnd = startPos + val.length; domElement.scrollTop = scrollTop; } else { domElement.value += val; domElement.focus(); } }); } } }]) <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link href="style.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-controller="MyCtrl"> <input ng-model="someInput"> <button ng-click="add()">Add</button> <p ng-repeat="item in items">Created {{ item }}</p> </div> <p>add some text and change caret position and insert test using input area above</p> <textarea my-text="" ng-model="textarea"> </textarea> <p>{{textarea}}</p> </body> </html> A: The quickest fix to your code that I can think of is added below. Basically, require the ng-model controller into your directive, and inform it when the value has changed. A little off-topic, but having your myText directive be controlled via global scope (in the form of $rootScope.$on) smells bad to me. var app = angular.module('plunker', []); app.controller('MyCtrl', function($scope, $rootScope) { $scope.items = []; $scope.add = function() { $scope.items.push($scope.someInput); $rootScope.$broadcast('add', $scope.someInput); } }); app.directive('myText', ['$rootScope', function($rootScope) { return { require: '^ngModel', // request our containing ng-model controller link: function(scope, element, attrs, ngModelCtrl) { // DI $rootScope.$on('add', function(e, val) { var domElement = element[0]; if (document.selection) { domElement.focus(); var sel = document.selection.createRange(); sel.text = val; domElement.focus(); } else if (domElement.selectionStart || domElement.selectionStart === 0) { var startPos = domElement.selectionStart; var endPos = domElement.selectionEnd; var scrollTop = domElement.scrollTop; domElement.value = domElement.value.substring(0, startPos) + val + domElement.value.substring(endPos, domElement.value.length); domElement.focus(); domElement.selectionStart = startPos + val.length; domElement.selectionEnd = startPos + val.length; domElement.scrollTop = scrollTop; } else { domElement.value += val; domElement.focus(); } // inform ng-model that the value has changed ngModelCtrl.$setViewValue(domElement.value); }); } } }]) <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link href="style.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-controller="MyCtrl"> <input ng-model="someInput"> <button ng-click="add()">Add</button> <p ng-repeat="item in items">Created {{ item }}</p> </div> <p>add some text and change caret position and insert test using input area above</p> <textarea my-text="" ng-model="textarea"> </textarea> <p>{{textarea}}</p> </body> </html>
[ "stackoverflow", "0010265893.txt" ]
Q: how do you get sbt web plugin to work with a .scala config I'm currently getting the error Plugin classpath does not exist for plugin definition at file:/C:/project_root/project/ from the below files. Does anyone know how to configure the web plugin properly for a lift project with .scala config? plugin/Build.scala: import com.github.siasia.PluginKeys._ import com.github.siasia.WebPlugin._ import sbt._ import Keys._ object BuildSettings { val buildOrganization = "dualitystudios" val buildVersion = "0.1" val buildScalaVersion = "2.9.1" val buildSettings = Defaults.defaultSettings ++ Seq ( organization := buildOrganization, version := buildVersion, scalaVersion := buildScalaVersion ) } object Dependencies { val liftVersion = "2.4" val logbackVer = "0.9.26" val lift_webkit = "net.liftweb" %% "lift-webkit" % liftVersion % "compile" val lift_mapper = "net.liftweb" %% "lift-mapper" % liftVersion % "compile" //val jetty = "org.mortbay.jetty" % "jetty" % "6.1.26" % "test" val junit = "junit" % "junit" % "4.7" % "test" val testing_tools = "org.scala-tools.testing" %% "specs" % "1.6.9" % "test" val logbackclassic = "ch.qos.logback" % "logback-classic" % logbackVer val dbConnector = "com.h2database" % "h2" % "1.2.147" val selenium = "org.seleniumhq.selenium" % "selenium-java" % "2.21.0" val mysql = "mysql" % "mysql-connector-java" % "5.1.19" val jetty = "org.mortbay.jetty" % "jetty" % "6.1.22" % "test" val liftAuth = RootProject(uri("git://github.com/keynan/LiftAthentication.git")) } object Resolvers { val scala_testing = "Scala Testing" at "http://mvnrepository.com/artifact" def resolve_all = Seq(scala_testing) } object LiftProject extends Build { import Dependencies._; import BuildSettings._; import Resolvers._; lazy val JavaNet = "Java.net Maven2 Repository" at "http://download.java.net/maven/2/" //lazy val sbtWeb = uri("git://github.com/siasia/xsbt-web-plugin") lazy val main = Project ( "xxxxxx", file ("."), settings = buildSettings ++ Seq ( resolvers := resolve_all, libraryDependencies ++= Seq( lift_webkit, lift_mapper, jetty, junit, testing_tools, logbackclassic, dbConnector, selenium, mysql ) ) ++ webSettings ) dependsOn(liftAuth) } project/project/Build.scala: import sbt._ import Keys._ object PluginDef extends Build { val jetty = "org.mortbay.jetty" % "jetty" % "6.1.22" override lazy val projects = Seq(root) lazy val root = Project( "plug", file("."), settings = Seq( libraryDependencies ++= Seq(jetty)) ) dependsOn( sbtWeb ) lazy val sbtWeb = uri("git://github.com/siasia/xsbt-web-plugin") } A: Replace your ./project/project/Build.scala with ./project/plugins.sbt containing: libraryDependencies <+= sbtVersion(v => "com.github.siasia" %% "xsbt-web-plugin" % (v+"-0.2.11"))
[ "electronics.stackexchange", "0000331423.txt" ]
Q: Avoiding opamp saturation - working with apd i have avalanche photo diode with which i am trying to digitalize the current from TIA through a comparator, the diode biased using a HVDCDC the source is being a 20ns laser with a PRF of 3Khz the circuit is as below simulate this circuit – Schematic created using CircuitLab the output of opamp for an high intensity light is like above, we can see the opamp fully saturated, but i am clue less about the over shoot and ringing effect, this happened when i have put my bias voltage 300V, i am not able to stop the opamp to enter in to saturation. even if i see the datasheet of DC-DC CA05N, it can maximum source 2mA of current, and the peak current of didoe is only 0.25mA, so i understood the dcdc current is exceeding 2mA so to avoid the opamp going in to saturation i tried to use a 300K in series with the source but still the opamp went to saturation, it evident that in order to make the opamp not to go in to saturation, the only way i can try is to reduce the bias voltage to as less as possible, so i operated it at 70V for which the response is as below. reasons are unknow for the expansion of 20ns pulse to 100ns even through the APD is having a BW of 70MHz, so in order to operate the APD properly, i understood i have to bias with higher voltage to see proper response for low light, but at the same time i have to avoid saturation. i feel limiting the current to the TIA will solve problem, kindly suggest some ways to bypass the excess current which is to the opamp. Kindly throw some light on behaviour of APD in saturation also EDIT: as the answers suggested to go for a unity gain stable equivalent, i went for changing my opamp to LTC6269 which is 400Mhz unity gain stable below is the result i got with photo diode polarity inversed, so you may see a inverted output, but effect persists the analog support was suggesting me also on using a subber at the photo diode bias so i used a 20ohm in series with 100p cap thinking this disturbance is due to the power supply i am using, frankly i am clueless how to tweak a snubber please help me in identifying the problems rootcause **EDIT2:**i have to tweak my Cf accordingly i feel, to avoid this, i dont think this is ringing, i feel i have solved my problem , will comeback with results shortly EDIT3 : replacing Cf with 4pF given me a clean pulse with out any ringing Thanks for the help EDIT4: But after few experiments i identified that i am not saturating the photodiode/opamp completely, so i have increase the pulse width and pulse power on photo diode with which my response turned like below A: The amplification and reaction speed of an APD depend on the current through it. It's a bad habit of the physics community to use APDs with a voltage source and a series resistor for biasing. As you have witnessed, this fails in high dynamic range applications. I suggest you change your biasing circuit to provide a constant current instead of constant voltage. The ringing you see is from your opamp. You are using a variant that is not unity gain stable. The -10 in the part number denotes that it's a decompensated opamp for a gain of at least 10 (Linear's opamp numbering convention). But for this kind of circuit to work, you need unity gain stability. I suggest you have a look at Linear Appnote 92 which discusses a few circuits for APDs.
[ "gaming.stackexchange", "0000018263.txt" ]
Q: How can I predict how much money I will lose if I lose a battle? If I lose a battle (i.e. all 6 of my pokemon faint), how much money will I lose? A: The amount of money you will lose since FireRed and LeafGreen (with the exception of Emerald) is determined by: Money = Level * Base Payout Level is the highest level pokemon of yours and the base payout is based on the number of badges you have. Badges/Payout 0/8 1/16 2/24 3/36 4/48 5/60 6/80 7/100 8/120 For example, if you have 5 gym badges and your top level pokemon is 30, your money lost for defeat would be 30 * 60 = 1800. Source (bulbapedia) While it is possible the bulbapedia article is outdated given the site's recent downtime, serebii's battle changes page lists no change to the payout system in gen V.
[ "mathoverflow", "0000051950.txt" ]
Q: Derivation of von Neumann algebra which is zero on MASA Are there any example of $II_1$-factor $M$ with maximal abelian von Neumann subalgebra $A$ and non-zero derivation $\delta:M\rightarrow B(H)$ such that $\delta(a)=0$ for every $a\in A$? A: Let $M= L \mathbb F_2$ and $H = \ell^2 \mathbb F_2$, where $\mathbb F_2 = \langle a,b \rangle$ is the free group on two generators and $B(H)$ is a bimodule via the left and right multiplication with the left-regular representation $\lambda \colon L \mathbb F_2 \to B(\ell^2 \mathbb F_2)$. Define $\delta(x) = [x,\lambda(a)]$. Then, $\lambda(a^{\pm1})'' \subset L \mathbb F_2$ is a MASA (as can be shown) and $\delta$ vanishes on it. However, $\delta(\lambda(b)) \neq 0$ so that $\delta$ does not vanish on $L \mathbb F_2$.
[ "space.stackexchange", "0000045461.txt" ]
Q: Were these Apollo 14 and 15 recovery images taken (by a Navy frogman) using an underwater camera? These images were taken after the flotation collar was mounted and inflated by the frogmen. Also the raft was inflated. The divers jumped off a helicopter before, no rescue ship was present. Camera position was directly above the water surface. So the camera had to survive the jump of the diver photographer from the helicopter down to the water. The camera should be small, lightweight, compact and robust and to be used under and above water. Conventional cameras within a special underwater case would have been too heavy and bulky. So I guess the Navy frogmen used a Nikonos underwater camera for 35 mm film? Images from ALSJ. A: The answer is on this National Geographic page about the best pictures from NASA's official photographer Bill Ingalls: If you love space, odds are you’ve admired the work of Bill Ingalls. He has been NASA’s senior contract photographer for 30 years, a job that has taken him across the world—but not yet beyond it—to cover major moments in space exploration. His stash includes two Nikonos underwater cameras, which, Taub told Ingalls, "were used by frogmen during Apollo splashdown recoveries." In this DOD Pdf about Apollo Recovery Operational Procedures equipment furnished by NASA is mentioned. Underwater cameras, 1 or 2 per recovery diver team and 3 per primary recovery ship. Nikonos model II image from this Nikonos Story page. The size of the camera was: 129 mm × 99 mm × 47 mm (5.1 in × 3.9 in × 1.9 in), the weight 495 g (17.5 oz). The Nikonos was marketed as an all-weather camera. Photos below and above the water's surface are possible, also in heavy rain. An Apollo 12 image ap12-S69-22265 from ALSJ: A Navy diver helps Al Bean into the recovery raft. Pete Conrad is at the far right and Dick Gordon is at the center. Note the diver in the water to the left of the raft taking pictures. Photographs are also being taken from the helicopter. 24 November 1969. Scan by Ed Hengeveld. So at least two divers were equipped with Nikonos cameras, the diver shown with camera and the diver who has taken the image. Taking pictures by Navy divers during recovery has a tradition: Navy divers prepare to retrieve the Gemini 6A crew on16 December 1965. Green dye was released by the spacecraft on splashdown, making it easier to spot them from the air. Credit: Courtesy of NASA Image and text from amateurphotographer. But the Nikonos I was introduced in 1963, so it might have been used only for the last Mercury flight. Bold font enhancement within block quotes by me.
[ "stackoverflow", "0017998417.txt" ]
Q: Swipe Gestures in SurfaceView for mediaplayer display I'm developing a movie player for android. I want to implement mx player like gestures to my surfaceView (left side up/down swipe, right side up/down swipe, right/left swipe). How can i do it?? A: Inspired by Android: How to handle right to left swipe gestures, but modified to not get deprecated warnings: MainActivity.java: private SurfaceView surfaceView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); surfaceView = new SurfaceView(this); surfaceView.setOnTouchListener(new OnSwipeTouchListener(this) { public void onSwipeTop() { Toast.makeText(MainActivity.this, "top", Toast.LENGTH_SHORT).show(); } public void onSwipeRight() { Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show(); } public void onSwipeLeft() { Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show(); } public void onSwipeBottom() { Toast.makeText(MainActivity.this, "bottom", Toast.LENGTH_SHORT).show(); } }); setContentView(surfaceView); } OnSwipeTouchListener.java public class OnSwipeTouchListener implements OnTouchListener { private final GestureDetector gestureDetector; public OnSwipeTouchListener(Context ctx) { gestureDetector = new GestureDetector(ctx, new GestureListener()); } public boolean onTouch(final View view, final MotionEvent motionEvent) { return gestureDetector.onTouchEvent(motionEvent); } private final class GestureListener extends SimpleOnGestureListener { private static final int SWIPE_THRESHOLD = 100; private static final int SWIPE_VELOCITY_THRESHOLD = 100; @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { boolean result = false; try { float diffY = e2.getY() - e1.getY(); float diffX = e2.getX() - e1.getX(); if (Math.abs(diffX) > Math.abs(diffY)) { if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (diffX > 0) { onSwipeRight(); } else { onSwipeLeft(); } } } else { if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) { if (diffY > 0) { onSwipeBottom(); } else { onSwipeTop(); } } } } catch (Exception exception) { exception.printStackTrace(); } return result; } } public void onSwipeRight() { } public void onSwipeLeft() { } public void onSwipeTop() { } public void onSwipeBottom() { } }
[ "stackoverflow", "0030880912.txt" ]
Q: Bower: Install package that doesn't have bower.json file I'm trying to get Bower to install this javascript: https://github.com/markmalek/Fixed-Header-Table I use: bower install [email protected]:markmalek/Fixed-Header-Table.git --save It installs the package into bower-components, and even adds it to my project's bower.json, but it doesn't add the to my html. I'm guessing it's because that particular git repo doesn't contain a bower.json telling my project which js file is the main one. So how do I install this package? Thanks! A: This answer takes your assumption that your HTML is picking up scripts loaded via Bower using the bower.json file as correct. There are two options. The quickest is to fork the repo yourself, and in the main directory use the command bower init to create your own bower.json file in your forked version of the repo. Then, change the github url to the repo to your forked version rather than the original you have above. The second option is to submit a pull request to the package owner adding a bower.json file so that you can continue to pull directly from his repo. There are probably more options like manually loading the script outside of pulling from a bower.json file but the two above seem simplest.
[ "stackoverflow", "0047673108.txt" ]
Q: Recovering implicit information from existentials in Coq Suppose we have something like this: Suppose x is a real number. Show that if there is a real number y such that (y + 1) / (y - 2) = x, then x <> 1". If one formulates it in an obvious way: forall x : R, (exists y, ((y + 1) * / (y - 2)) = x) -> x <> 1, one runs into an issue very soon. We have an assumption of existence of y such that ((y + 1) * / (y - 2)) = x). Am I wrong to assume that this should also imply that y <> 2? Is there a way to recover this information in Coq? Surely, if such y exists, then it is not 2. How does one recover this information in Coq - do I need to explicitly assume it (that is, there is no way to recover it by existential instantiation somehow?). Of course, destruct H as [y] just gives us ((y + 1) * / (y - 2)) = x) for y : R, but now we don't know y <> 2. A: Am I wrong to assume that this should also imply that y <> 2? Yes. In Coq, division is a total, unconstrained function: you can apply it to any pair of numbers, including a zero divisor. If you want to assume y <> 2, you need to add that as an explicit assumption to your lemma. You may find this scary: how could we be allowed to divide something by zero? The answer is that it doesn't matter, as long as you do not try to argue that 0 * (x / 0) = x. This question discusses the issue in more detail. A: The real numbers in Coq are defined axiomatically, i.e. they are just names associated with types, there are no definitions attached to the names. There are basic numbers (R0, R1) and operations on reals (Rplus, Rmult, etc.) which do not get executed, i.e. operations are not functions. In a sense one just builds real numbers by constructing them out of those operations just like with data constructors (but we cannot pattern-match on reals). The above means that, e.g. 1/0 is a valid real number. It's just the premises of the axioms for real numbers prohibit some simplifications involving expressions like that: we cannot rewrite expressions like 1/0 * 0 to 1 (though, we can rewrite it to 0). Here is how we can show that we cannot derive y <> 2 from an expression like (y + 1) / (y - 2) = x because we are allowed to use "strange" real numbers: From Coq Require Import Reals. Open Scope R. Goal ~ (forall x y : R, (y + 1) / (y - 2) = x -> y <> 2). unfold "_ - _"; intros contra; specialize (contra ((2+1)/0) 2). rewrite Rplus_opp_r in contra. intuition. Qed.
[ "stackoverflow", "0006567467.txt" ]
Q: Human readable form of DNS lookup I have got a very simple idea in mind that i want to try out. Say i have a browser, chrome for instance, and i want to search for the ip of the domain name, say www.google.com. I use windows 7 and i have set the dns lookup properties to manual and have given the address 127.0.0.1 where my server (written in Python is running). I started my server and i could see the dns query but it was very weird as in it is showing faces like this: WAITING FOR CONNECTION......... .........recieved from : ('127.0.0.1', 59339) 'V"\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06teredo\x04ipv6\tmicrosoft\x03com\x00\x00\x01\x00\x01' The waiting for connection and the received from is from my server. How do i get a breakdown form(a human readable form) of this message?? This is my server code(quiet elementary but still): Here is the code: from time import sleep import socket host='' port=53 addr_list=(host,port) buf_siz=1024 udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) udp.bind(addr_list) while True: print 'WAITING FOR CONNECTION.........' data,addr = udp.recvfrom(buf_siz) print '.........recieved from : ',addr sleep(3) print data A: If you want to analyse the query data using python, I recommend the excellent scapy library (http://www.secdev.org/projects/scapy/) It's got decoding (and building!) routines for many network protocols including DNS. Here's your original program with the scapy decoding added: from time import sleep import socket from scapy.all import DNS #Bring in scapy's DNS decoder host='' port=53 addr_list=(host,port) buf_siz=1024 udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) udp.bind(addr_list) while True: print 'WAITING FOR CONNECTION.........' data,addr = udp.recvfrom(buf_siz) print '.........recieved from : ',addr sleep(3) #Decode the DNS data decoded = DNS(data) #Print the decoded packet decoded.show() For the raw packet in your question this prints: ###[ DNS ]### id = 22050 qr = 0L opcode = QUERY aa = 0L tc = 0L rd = 1L ra = 0L z = 0L rcode = ok qdcount = 1 ancount = 0 nscount = 0 arcount = 0 \qd \ |###[ DNS Question Record ]### | qname = 'teredo.ipv6.microsoft.com.' | qtype = 12288 | qclass = 256 an = None ns = None ar = None ###[ Raw ]### load = '\x01' Scapy installation instructions are here: http://www.secdev.org/projects/scapy/doc/installation.html#installing-scapy-v2-x If you use ubuntu, just sudo apt-get install python-scapy Enjoy!
[ "math.stackexchange", "0001159436.txt" ]
Q: Proving subspace conditions from subsets of vector spaces Let n>=2. Which of the conditions defining a subspace are satisfied for the following subsets of the vector space Mnxn(R) of real (nxn)-matrices? (Proofs of counterexamples needed). U={A is an element of Mnxn(R) such that rank(A)<=1} V={A is an element of Mnxn(R) such that det(A)=0} W={A is an element of Mnxn(R) such that trace(A)=0} For this I started by stating the 3 conditions for a subspace V to hold: i. the subspace is non-empty ii. for all u and v in V, u+v is also in V iii. for all u in V and t in R, tu is also in V For U For i I acknowledged that if rank(A)<=1, then it is linearly dependant and is non empty as there is an c1x1+c2x2+...+cnxn=d in the matrix. For ii, I let u=(c1x1,c2x2,...,cnxn) and this is where I started to get stuck. As rank(A)<=1, can I take v=(0x1,0x2,...,0xn) so u+v=((c1+0)x1,...,((c1+0)xn))? I'd assume this is just the same as u so this property doesn't hold. For iii, as it is linearly dependant there exists rows that are (0x1,0x2,...,0xn) so that multiplication by the scalar holds, but would it still apply that tu=u which is an element of V? For V On this question I acknowledged that if det(A)=0, then the matrix is linearly dependant and also has a row of zero vectors (at least). For i can you state that the matrix Mnxn can contain any element and still be non empoty? i.e. isn't this just trivial? For ii, can you do something similar to U part ii where you just take your row of zero vectors and add them on? A: For both $U$ and $V$, consider $$\begin{bmatrix} 1 & 0 \\ 0 & 0 \\ \end{bmatrix} +\begin{bmatrix} 0 & 0 \\ 0 & 1 \\ \end{bmatrix}$$ For $W$, consider what adding and scalar multiplication does to the trace. You will find that this is indeed a subspace. So all three conditions are satisfied for $W$. As for condition 1), the n-by-n zero matrix is a member of $U$, $V$, and $W$, so that is satisfied for all three. As for condition 2), the counterexample I gave shows that is not satisfied in $U$ or $V$. It is satisfied for $W$. I gave you a hint on proving that. As for condition 3), that is satisfied for all of $U$, $V$, and $W$. For $U$, multiplying a matrix by a non-zero scalar does not change its rank. You can show that any linear combination of rows in a matrix such as $au+bv$ is equal to a linear combination in the multiplied matrix: $\frac at(tu)+\frac bt(tv)$. Multiplying a matrix by the zero scalar reduces its rank to zero, which means it remains in $U$. For $V$, use the theorem that $\operatorname{det}(tA)=t^n\cdot \operatorname{det}(A)$. So if $\operatorname{det}(A)=0$, we also have $\operatorname{det}(tA)=t^n\cdot \operatorname{det}(A)=t^n\cdot 0=0$. I gave you a hint in proving condition 3) for $W$.
[ "beer.stackexchange", "0000006715.txt" ]
Q: Why does my slice/wedge of lime go up and down in my glass of Gin and Tonic? I was sitting watching my G&T which had a slice of lime in it, when I noticed that the lime sank to the bottom of the glass, and then rose to the top again, it then continued to repeat this cycle for some time. What is causing this behavior? A: Pieces of lime are slightly denser than a mixture of water and alcohol, and so they will naturally sink at first. However, they also encourage carbon dioxide gas to come out of solution and form bubbles by making the liquid around the fruit more acidic (and thereby reduce the amount of dissolved CO2 that it can hold). Unlike bubbles that form on the side of a glass and then detach, these bubbles will stick to the fruit and cause it to float to the surface. When sufficient bubbles have burst, the fruit sinks to the bottom again, and the cycle is repeated until no more CO2 will come out of solution.
[ "tex.stackexchange", "0000278587.txt" ]
Q: How to override the \vec{} command so that we have an underline? I have been using the \vec{} command for specifying vectors in this paper I am writing, but I would like to denote vectors with just an underline, and I would like to keep using the \vec{} command, so that I don't need to change it everywhere. How can I override \vec{} so that I obtain a underline instead of a left-to-right arrow above the letter? A: If this is really necessary, use a redefinition of \vec to apply \underline. I am pretty sure, there's a better version of \underline in math mode. Edit Another way of \underline: Use \ushortw from the ushort package. \documentclass{article} \usepackage{mathtools} \renewcommand{\vec}{\underline} \begin{document} $\vec{A}$ \end{document}
[ "stackoverflow", "0005170794.txt" ]
Q: Click Listener on ListView I have modified this example from the SDK pages to grab all the Contact Groups from the phone and display them. I cannot, however, figure out how to click one of them and then use the Groups._ID to do something else. Can someone teach me how to get a click/select listener on this list? MyListAdapter.java package com.example.simplelist; import android.app.ListActivity; import android.database.Cursor; import android.os.Bundle; import android.provider.Contacts.Groups; import android.widget.ListAdapter; import android.widget.SimpleCursorAdapter; public class MyListAdapter extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.custom_list_activity_view); Cursor mCursor = this.getContentResolver().query(Groups.CONTENT_URI, null, null, null, null); startManagingCursor(mCursor); ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, mCursor, new String[] {Groups.NAME, Groups._ID}, new int[] {android.R.id.text1, android.R.id.text2}); setListAdapter(adapter); } } custom_list_activity_view.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="8dp" android:paddingRight="8dp"> <ListView android:id="@id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#00FF00" android:layout_weight="1" android:drawSelectorOnTop="false" android:choiceMode="singleChoice" android:clickable="true" /> <TextView android:id="@id/android:empty" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FF0000" android:text="No data"/> </LinearLayout> two_line_list_item.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/text1" android:textSize="16sp" android:textStyle="bold" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/text2" android:textSize="16sp" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout> AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.simplelist" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="3" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MyListAdapter" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.READ_CONTACTS" /> </manifest> A: This should allow you to interact with selected item the way you want. MyListAdapter.java package com.example.simplelist; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.ListActivity; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.provider.Contacts.Groups; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class MyListAdapter extends ListActivity { List<ContactGroup> groups = new ArrayList<ContactGroup>(); @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); this.groups = getContacts(); ContactGroupAdapter cAdapter = new ContactGroupAdapter(this); setListAdapter(cAdapter); } private List<ContactGroup> getContacts(){ List<ContactGroup> grps = new ArrayList<ContactGroup>(); ContentResolver cr = getContentResolver(); Cursor groupCur = cr.query(Groups.CONTENT_URI, null, null, null, null); if (groupCur.getCount() > 0) { while (groupCur.moveToNext()) { ContactGroup newGroup = new ContactGroup(); newGroup.Id = groupCur.getString(groupCur.getColumnIndex(Groups._ID)); newGroup.Name = groupCur.getString(groupCur.getColumnIndex(Groups.NAME)); grps.add(newGroup); } } return grps; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { ContactGroup selectedGroup = new ContactGroup(); selectedGroup = groups.get(position); Toast.makeText(getBaseContext(), selectedGroup.Name + " ID #" + selectedGroup.Id, 1).show(); } public class ContactGroupAdapter extends BaseAdapter{ public ContactGroupAdapter(Context c) { mContext = c; } @Override public int getCount() { return groups.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ LayoutInflater vi = LayoutInflater.from(this.mContext); convertView = vi.inflate(R.layout.two_line_list_item, null); holder = new ViewHolder(); convertView.setTag(holder); } else { //Get view holder back holder = (ViewHolder) convertView.getTag(); } ContactGroup c = groups.get(position); if (c != null) { //Name holder.toptext = (TextView) convertView.findViewById(R.id.text1); holder.toptext.setText(c.Name); //ID holder.bottomtext = (TextView) convertView.findViewById(R.id.text2); holder.bottomtext.setText(c.Id); } return convertView; } private Context mContext; } public static class ViewHolder { TextView toptext; TextView bottomtext; } public class ContactGroup{ public String Id; public String Name; } } two_line_list_item.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <TextView android:id="@+id/text1" android:textSize="16sp" android:textStyle="bold" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/text2" android:textSize="16sp" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout> A: Since you are using ListActivity you need to override onListItemClick(). protected void onListItemClick(ListView l, View v, int position, long id) { // position is the position in the adapter and id is what adapter.getItemId() returns. // use one of them to get the group id from the data. }
[ "math.stackexchange", "0000294962.txt" ]
Q: Determining Height of Tree A surveyor needs to determine the height of a tree. She places a mirror on the ground and paces backwards until she sees the top of the tree reflected in the mirror. She marks where she is standing and then measures the distance from this spot to the mirror which is $10$ feet. She then measures the distance from the mirror to the base of the tree which is $90$ feet. The surveyor's height is $54$ inches from the ground to her eyes. How tall is the tree (in feet) assuming level ground from the surveyor's spot to the mirror and from the mirror to the tree? A: Let $T$ be the top of the tree, $R$ the base of the tree, $M$ the mirror, $F$ the point where she’s standing, and $E$ her eye. The angle of incidence equals the angle of reflection, so the triangles $\triangle TRM$ and $\triangle EFM$ are similar. This implies that if the height of the tree is $h$ inches, then $$\frac{h}{54}=\frac{90}{10}\;.$$ Now just do a little algebra to get $h$, and then convert to feet.
[ "stackoverflow", "0043043131.txt" ]
Q: 'unicode' object has no attribute 'has_header' I'm encountering and error on extracting data from db and converting it to excel, I'm using django-excel library for the task. I'm extracting user.email from my ClientContact model, and I'm creating service call that creates excel file, but I'm facing an Attribute error - 'unicode' object has no attribute 'has_header', so can someone help me understand this so I can fix it, thanks. The model field from ClientContact, from which I need to extract email: class ClientContact(models.Model): user = models.OneToOneField(User) FormView for making an excel file: from django.contrib.auth.models import User from django.http import HttpResponseBadRequest from django.http import HttpResponseForbidden from django.views.generic import FormView from django import forms import django_excel as excel from clients.models import ClientContact class UploadFileForm(forms.Form): pass class ExportClientsMailXls(FormView): template_name = 'clients/export_email/export_email.html' form_class = UploadFileForm def get(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if request.user.is_staff: return self.render_to_response( self.get_context_data(form=form, can_submit=True,)) else: return HttpResponseForbidden() def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if request.user.is_staff: if form.is_valid(): emails = ClientContact.objects.all() for email in emails: return email.user.email column_name = ['contact_email'] return excel.make_response_from_array(emails, column_name, "xls", file_name="export_client_mail") else: return HttpResponseBadRequest() else: return HttpResponseForbidden() A: You should change your post method as follows, because you are returning before converting to excel def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if request.user.is_staff: if form.is_valid(): emails = ClientContact.objects.all() # Look here list_of_emails = [] for email in emails: email_lst = [] email_lst.append(email.user.email) list_of_emails.append(email_lst) return excel.make_response_from_array(list_of_emails, "xls", file_name="export_client_mail", status=200) else: return HttpResponseBadRequest() else: return HttpResponseForbidden()
[ "stackoverflow", "0012450625.txt" ]
Q: Using mod_proxy to redirect asset requests to a CDN I'm interested in using a CDN for storing some assets in my web application. However, instead of hardcoding the CDN url into each of my assets (Javascript and CSS), I'd like to use a simple RewriteRule to redirect requests for assets to a CDN. However, I'm wondering if there are some disadvantages to this method. For one, the server is still processing requests for assets since it needs to identify and redirect such requests. And another, I'm concerned that the CDN will look at the location of my server as opposed to the location of my client. Has anyone ever dealt with this kind of strategy, and what was your solution? Thanks! A: That's not a great strategy, as it completely nullifies any benefits or using a CDN. For every request for a static asset, your server has to process a request, which is exactly what you're trying to avoid. Bite the bullet, and set up your application to be configurable (you do use basic configuration, correct?) enough so that you change base URLs for all your static assets.
[ "stackoverflow", "0058467091.txt" ]
Q: How can I connect to Google Cloud SQL database as an external mysql database from Google App Maker? I am trying to connect to a Google Cloud SQL database from my Google App Maker app. Unfortunately, my IT staff hasn't set up Google App Maker to use Google Cloud SQL as the default so I'm trying to connect to the database the same way I have connected to external MySQL databases in the past but it's not working with the public IP address. I have created a Google Cloud SQL database and I'm able to connect to it from MySQLWorkbench using the public IP address. I had to add my the IP address for my home computer in order to connect the database. I did not need to use SSL. I created a Google service account for my Google App Maker app. I then included this service account in the Google project that contains the Cloud SQL database. I assigned it permissions for Cloud SQL Admin and Cloud SQL Client. I am using this code in App Maker to try and connect. It's the same code I have used with other external MySQL databases. The ip address 34.xx.xx.xx is the public IP address listed in the overview page of the Google Cloud SQL instance. // App Settings // Important Note: This is for demo purposes only, storing passwords in scripts // is not recommended in production applications. // DB Credentials (you need to provide these) var address = '34.xx.xx.xx'; var db = 'Kenco_IoT_Template'; var dbUrl = 'jdbc:mysql://' + address + '/' + db; var user = 'real_username'; var userPwd = 'real_password'; I receive this error message: "Executing query for datasource ActivityTable: (Error) : Failed to establish a database connection. Check connection string, username and password. Please refer to the ReadMe and edit your database settings!" My guess is the issue is with setting up the Cloud SQL database to accept the connection from Google App Maker. The best solution will be to enable Cloud SQL as the default for Google App Maker but I'm hoping there is some alternative I can use for now. Any help appreciated. A: To make this an answer so others can more easily find it: The answer is that you needed to whitelist the IP ranges for appscript. Public IPs on Cloud SQL instances either require whitelisting of the IP addresses for access, or they need to use the Cloud SQL Proxy. The OP also mentioned that they had to switch which Jdbc method they used from getConnection() to getCloudSqlConnection().
[ "stackoverflow", "0052784007.txt" ]
Q: RegExp replacement with variable and anchor I've done some research, like 'How do you use a variable in a regular expression?' but no luck. Here is the given input const input = 'abc $apple 123 apple $banana' Each variable has its own value. Currently I'm able to query all variables from the given string using const variables = input.match(/([$]\w+)/g) Replacement through looping the variables array with the following codes is not successful const r = `/(\$${variable})/`; const target = new RegExp(r, 'gi'); input.replace(target, value); However, without using the variable, it will be executed, const target = new RegExp(/(\$apple)/, 'gi'); input.replace(target, value); I also changed the variable flag from $ to % or #, and it works with the following codes, // const target = new RegExp(`%{variable}`, 'gi'); // const target = new RegExp(`#{variable}`, 'gi'); input.replace(target, value); How to match the $ symbol with variable in this case? A: If understand correctly, uses (\\$${variable}). You can check below Fiddle, if only one slash, it will cause RegExp is /($apple)/gi (the slash and the following character are escaped: \$ => $), but $ indicates the end of string in Regex if not escaped. So the solution is add another slash. Like below demo: const input = 'abc $apple 123 apple $banana' let variable = 'apple' let value = '#test#' const r = `(\\$${variable})`; const target = new RegExp(r, 'gi'); console.log('template literals', r, `(\$${variable})`) console.log('regex:', target, new RegExp(`(\$${variable})`, 'gi')) console.log(input.replace(target, value))
[ "stackoverflow", "0018303837.txt" ]
Q: KVO or custom accessor methods? I got few entities for an iOS App which are linked by relations. To make a simple example, lets assume we got a relation like this (one-to-many): company <--->> person I'm using xcode 4.6 and the core data modelling tool for model generation, so I end up with //Company.h @class Person; @interface Company : NSManagedObject @property (nonatomic, retain) NSString * company_name; @property (nonatomic, retain) NSNumber *has_changed; @property (nonatomic, retain) NSSet *person; @end @interface Company (CoreDataGeneratedAccessors) - (void)addPersonObject:(Person *)value; - (void)removePersonObject:(Person *)value; - (void)addPerson:(NSSet *)values; - (void)removePerson:(NSSet *)values; @end //Company.m #import "Company.h" #import "Person.h" @implementation Company @dynamic company_name; @dynamic has_changed; @dynamic person; @end And //Person.h @class Company; @interface Person : NSManagedObject @property (nonatomic, retain) NSString * first_name; @property (nonatomic, retain) NSString * last_name; @property (nonatomic, retain) Company *company; @end //Person.m #import "Person.h" #import "Company.h" @implementation Person @dynamic first_name; @dynamic last_name; @dynamic company; @end Now, suppose I want to set the boolean (implemented as NSNumber in Core Data) attribute has_changed to TRUE every time one of the following occurs: a attribute of the company entity is changed, except the has_changed attribute itself of course (since this would cause a loop) a attribute of the person entity is changed What would be the best (easy to implement + fast to process) way to implement something like this? For what I was able to find out, is that there are two options: Key value observing (KVO) custom method accessors However, everything I find related to this topic seems to be outdated because of the changes in objective-c 2.0, core-data / cocoa or iOS. For example, automatically generating the accessor methods by using the core-data modelling editor dosn't seem to work when using xcode 4.6 with ARC enabled, since everything I get pasted are the @dynamic lines which core-data generates anyways (see code example above). Also I find it a bit confusing what the documentation says. What would be the best way to implement this? KVO? Custom accessors? Bit of both or even something compleatly different? And how would a possible implementation look like for the given example? A: You could do this as such: @implementation Company // ... - (void) didChangeValueForKey: (NSString *) key { [super didChangeValueForKey: key]; if (! [key isEqualToString: @"has_changed"]) self.has_changed = YES; } // ... @end and similar for Person though the company property. You'd also want to implement didChangeValueForKey:withSetMutation:usingObjects: Note that this suggestion does not address the common need of having a controller know about a change. There are other ways to do that.
[ "stackoverflow", "0018231958.txt" ]
Q: OAuth2 Login for Google Calendar API I'm making a website for a football club. they have one google calender (and just one google account). on the website I'd like to have a list of upcoming events. So I've to access to Google Calendar via Google API. For Authorisation I've to use OAuth2. Is it possible to login with OAuth2 automatically so that the website visitors don't have login always via redirect (to google login site)? For example I make a the login via Java, instead of a user login? Because it's no so comfortable if every user of the website have to login, for just viewing the club calendar. A: Not sure it is possible, Important note concerning your design: if you login automatically to the club's account, it means that everyone that uses this website is logged in to Google Calendar on behalf of the club's user name. hence, everyone can CHANGE the calendar, delete events, etc. Are you sure you want this to happen? (you can set the login params to "read-only", but even then, it means that the club shows ALL his calendar to everyone. there is no privacy...) I suggest that every user logins with his own creds, and the club's calendar can invite all registered users to his events....
[ "stackoverflow", "0050832663.txt" ]
Q: Javascript objects combining with Jquery? I have an issue with manipulating data in Javascript/jQuery and I could use some help. I have an array of objects that lools like this: var projects = [ {title:'project1'}, {title:'project2'}, {title:'project3'}, ]; I have another array of objects that looks like this: ganttEvents = [ { text: 'some text', start_date: '2018/06/13', end_date: '2018/06/14', id: '1', readonly: true, project: 'project1', category: 'scoping', } { text: 'some text2', start_date: '2018/06/14', end_date: '2018/06/15', id: '1', readonly: true, project: 'project2', category: 'scoping', } { text: 'some text3', start_date: '2018/06/15', end_date: '2018/06/16', id: '1', readonly: true, project: 'project2', category: 'design', } { text: 'some text4', start_date: '2018/06/13', end_date: '2018/06/14', id: '1', readonly: true, project: 'project2', category: 'scoping', } { text: 'some text5', start_date: '2018/06/14', end_date: '2018/06/15', id: '1', readonly: true, project: 'project3', category: 'testing', } { text: 'some text6', start_date: '2018/06/15', end_date: '2018/06/16', id: '1', readonly: true, project: 'project3', category: 'build', } ]; The project field in the second object will always be one of the objects in the first array. I then need to end up with an object that looks like this: source: [ { name: "project1", // a project defined in the projects array desc: "scoping", // the category from the ganttEvents array of objects values: [ { to: "2018/06/13", // the start_date from the ganttEvents array of objects from: "2018/06/14", // the end_date from the ganttEvents array of objects desc: "some text", // the text from the ganttEvents array of objects label: "some text", // the text from the ganttEvents array of objects } ] }, { name: "project2", // a project defined in the projects array desc: "scoping", // the category from the ganttEvents array of objects values: [ { to: "2018/06/14", from: "2018/06/15", desc: "some text2", label: "some text2", }, { to: "2018/06/13", from: "2018/06/14", desc: "some text4", label: "some text4", }, ] }, { name: "project3", // a project defined in the projects array desc: "testing", // the category from the ganttEvents array of objects values: [ { to: "2018/06/14", from: "2018/06/15", desc: "some text5", label: "some text5", } ] }, { name: "project3", // a project defined in the projects array desc: "build", // the category from the ganttEvents array of objects values: [ { to: "2018/06/15", from: "2018/06/16", desc: "some text6", label: "some text6", } ] }, ] There may be several values at all stages for each project and there maybe projects with no events at all that need to be omitted from the source object. Please can you assist? Edit: The background behind this is that I am pulling a list of events from a SharePoint list using SharePointPlus. This results in the ganttEvents array. I need to plug this in to the jQuery.Gantt library which requires the events to be formatted in a particular way. jQuery.Gantt I am sorry but i am relatively new to Javascript (Python programmer usually) I have tried different methods of doing this to no avail. A: You can use reduce to group the array into an object. Use the concatenated values of project and category as the key. Use Object.values to convert the object into an array. var ganttEvents = [{"text":"some text","start_date":"2018/06/13","end_date":"2018/06/14","id":"1","readonly":true,"project":"project1","category":"scoping"},{"text":"some text2","start_date":"2018/06/14","end_date":"2018/06/15","id":"1","readonly":true,"project":"project2","category":"scoping"},{"text":"some text3","start_date":"2018/06/15","end_date":"2018/06/16","id":"1","readonly":true,"project":"project2","category":"design"},{"text":"some text4","start_date":"2018/06/13","end_date":"2018/06/14","id":"1","readonly":true,"project":"project2","category":"scoping"},{"text":"some text5","start_date":"2018/06/14","end_date":"2018/06/15","id":"1","readonly":true,"project":"project3","category":"testing"},{"text":"some text6","start_date":"2018/06/15","end_date":"2018/06/16","id":"1","readonly":true,"project":"project3","category":"build"}]; var result = Object.values(ganttEvents.reduce((c, v) => { let k = v.project + "-" + v.category; c[k] = c[k] || {name: v.project,desc: v.category,values: []}; c[k].values.push({to: v.end_date,from: v.start_date,desc: v.text,label: v.text}); return c; }, {})); console.log(result); Without Object.values(), you can loop using for var ganttEvents = [{"text":"some text","start_date":"2018/06/13","end_date":"2018/06/14","id":"1","readonly":true,"project":"project1","category":"scoping"},{"text":"some text2","start_date":"2018/06/14","end_date":"2018/06/15","id":"1","readonly":true,"project":"project2","category":"scoping"},{"text":"some text3","start_date":"2018/06/15","end_date":"2018/06/16","id":"1","readonly":true,"project":"project2","category":"design"},{"text":"some text4","start_date":"2018/06/13","end_date":"2018/06/14","id":"1","readonly":true,"project":"project2","category":"scoping"},{"text":"some text5","start_date":"2018/06/14","end_date":"2018/06/15","id":"1","readonly":true,"project":"project3","category":"testing"},{"text":"some text6","start_date":"2018/06/15","end_date":"2018/06/16","id":"1","readonly":true,"project":"project3","category":"build"}]; var temp = ganttEvents.reduce((c, v) => { let k = v.project + "-" + v.category; c[k] = c[k] || {name: v.project,desc: v.category,values: []}; c[k].values.push({to: v.end_date,from: v.start_date,desc: v.text,label: v.text}); return c; }, {}); var result = []; for (var key in temp) result.push(temp[key]); console.log(result);
[ "magento.stackexchange", "0000108584.txt" ]
Q: Email templates customization - header, footer + css When I place an order, I'm receiving an email with the next content: {{template config_path="design/email/header"}} {{inlinecss file="email-inline.css"}} Thank you for your order from MYSITE. Once your package ships we will send an email with a link to track your order. Your order summary is below. Thank you again for your business. Your order #100000014 .... {{template config_path="design/email/footer"}} I've created my email-inline.css in the folder skin/frontend/mysite/default/css but don't know what to do for showing the header/footer and apply that css. A: I've fixed this upgrading my magento from version 1.9.0.1 to latest 1.9 one: 1.9.2.4. After this change {{template config_path="design/email/header"}} {{inlinecss file="email-inline.css"}} is replaced with the right content.
[ "stackoverflow", "0056342802.txt" ]
Q: Remove S3 object after assign tag I'd like to delete AWS S3 Object 30 days after assign tag. It seems to be easy when I tagged a new file during creation, but what if the file was created more than 30 days ago and I still want to be compliant with retention policy (30 days) and do not delete it too early. I was hoping that I could use transaction Lifecycle policy to the Glacier and then delete the file but it also based on creation date. Is there another option without lambda usage? { "Rules": [ { "Status": "Enabled", "NoncurrentVersionExpiration": { "NoncurrentDays": 31 }, "NoncurrentVersionTransitions": [ { "NoncurrentDays": 1, "StorageClass": "GLACIER" } ], "Filter": { "Tag": { "Value": "true", "Key": "toDelete" } }, "Expiration": { "Days": 31 }, "Transitions": [ { "Days": 1, "StorageClass": "GLACIER" } ], "ID": "delete-tagged-toDelete-after-31days" } ] } A: There is no "out-of-the-box" solution for what you wish to do. Amazon S3 Lifecycle Rules are based on Creation Date. Adding a tag to an object is not sufficient to "reset the clock" for a lifecycle rule. Some ideas: You might be able to copy the object to itself and add a tag. This might should the Create Date on the object. You can create an AWS Lambda function, triggered on a regular schedule by an Amazon CloudWatch Events rule, that scans the bucket for objects and deletes them based on tag. The tag could contain a delete date that the Lambda function uses to determine whether the delete date has passed.
[ "unix.stackexchange", "0000260368.txt" ]
Q: Why does mutt hang when running gpg in tmux? I run mutt in tmux and when I run gpg to sign or encrypt, gpg shows a blank screen where I would expect to type my passphrase. I've straced gpg and it shows that it's hanging waiting on a socket read() (presumably from gpg-agent. What's going on here? A: I was launching mutt by running tmux neww mutt. mutt was inheriting the environment set in tmux. This includes $GPG_TTY which is different for the new pane in which I'm running mutt (or unset if not in the tmux environment). I wrote a wrapper called gpgtty that sets $GPG_TTY correctly for new panes. #!/bin/sh GPG_TTY=$(tty) $* Then I launch mutt: tmux neww gpgtty mutt. gpg works correctly after that. FYI, this is all using pinentry-curses for gpg passphrase input. A: Short answer If you are using bash, then Chris W.’s wrapper script is the way to go. If perchance you are using zsh, then you can exploit the ~/.zshenv startup script to set GPG_TTY from there, no need for a wrapper. Since bash does not have a similar startup script (cf. Bash Startup Files), you’ll have to use the wrapper there. export GPG_TTY=${TTY} Some background: Interactive and non-interactive shells The gpg-agent expects GPG_TTY to point to the tty from where it is invoked, such that it can display its passphrase prompts in a secure manner. The GnuPG manual suggests putting the following in ~/.bashrc (or similar): GPG_TTY=$(tty) export GPG_TTY If you invoke mutt directly from your shell, this will work: GPG_TTY will be set, mutt will pick it up and pass it to gpg when it needs to. However, when you launch mutt via tmux’s new-window command or similar constructs, there is an important difference: Before, your mutt was in a so-called interactive shell—that is, you had a shell prompt open and launched mutt from there yourself. tmux new-window launches a non-interactive shell, since your shell is only needed to launch mutt and you won‘t be able to interact with it. In this case, bath won‘t read .bash_profile or .bashrc at all, since they are designed to set up your shell for interactive use. zsh does pretty much the same thing: .zshrc is read for interactive shells and skipped for non-interactive ones. However, in zsh, you can supply a third startup file, .zshenv, that is read for every shell, no matter whether it is interactive or not. Therefore, if you set GPG_TTY from there, it will always be available, no matter in which way mutt is started. And since $TTY is a shell builtin variable that always points to the current tty, you can avoid the overhead of spawning a tty process every time the shell comes up.
[ "stackoverflow", "0003120269.txt" ]
Q: iPhone: Preventing text truncation with UITableView of style UITableViewCellStyleValue1 As you can see, both the text (left) and the detail text (right) have been truncated. How can I ensure only the detail text on the right is truncated, while the text on the left remains in full? Thanks friends. A: I don't know of a way to do it simply other then 1) subclassing UITableViewCell and handle layout yourself, or 2) only display x number of characters in your detail text label. 2) is what I'd do.
[ "stackoverflow", "0006243086.txt" ]
Q: Java Swing - how to scroll down a JTextArea? I have an application with basic chat. I use JTextArea for the buffer. After adding a message I want to scroll to the bottom. How can this be achieved? I found no member function that would allow me to do this. A: You can do this by setting the caret position to the end of the text area, i.e., myTextArea.setCaretPosition(myTextArea.getDocument().getLength()); Edit: you can find out a lot more on this question by looking at the related questions listed on the lower right of this page. In particular, please check out camickr's answer and link in this thread: How to set AUTO-SCROLLING of JTextArea in Java GUI?. It's a far better and more complete answer than the one I've given (and I've just now up-voted it for this).
[ "stackoverflow", "0018993905.txt" ]
Q: Worklight Studio Rich Page Editor fails of WL.* call in page load I'm using Worklight Studio 6.0.0.20130917-1749 in 64 bit Eclipse Juno on OSX Lion. I'm finding that if I put a call to WL.Client.invokeProcedure(), or even WL.Logger.debug() in a jQueryMobile (1.3.1) pagebeforeshow handler, it causes the design portion of the rich page editor to hang when I try to switch to that page. $("#myPage").on("pagebeforeshow", function(){WL.Logger.debug("loading myPage...");}); If I double click on myPage in the Mobile Navigation view, the page doesn't display, and I am unable to switch to any other page in the app, or do anything with he design pane. The refresh button doesn't fix it (it just tries to load the same page and I am right back where I started) The only thing I can do is to close the html file and re-open it. This seems to be caused by a missing definition for WL.StaticAppProperites in the code that is run in the RPE. If I look at the html source of the common resources for the app under chrome I see a definition: <script> // Define WL namespace. var WL = WL ? WL : {}; /** * WLClient configuration variables. * Values are injected by the deployer that packs the gadget. */ WL.StaticAppProps = { "APP_DISPLAY_NAME": "MyApp", "APP_ID": "MyApp", "APP_SERVICES_URL": "\/MyApp\/apps\/services\/", "APP_VERSION": "1.0", "ENVIRONMENT": "preview", "LOGIN_DISPLAY_TYPE": "popup", "LOGIN_POPUP_HEIGHT": 610, "LOGIN_POPUP_WIDTH": 920, "PREVIEW_ENVIRONMENT": "common", "WORKLIGHT_PLATFORM_VERSION": "6.0.0", "WORKLIGHT_ROOT_URL": "\/MyApp\/apps\/services\/api\/MyApp\/common\/" };</script> There are similar definitions in the generated HTML for the various environments. But looking in weinre, I see that there is no corresponding script injected into the html that is displayed in the RPE. The lack of a definition for WL.StaticAppProperties is causing the code in worklight.js to fail just before the definition of WL.Utils. Is there any way for me to add WL.StaticAppProps = {} so that this would come before the code that gets injected to load worklight.js? Is there any other workaround for this problem? A: The editor is defining that WL.StaticAppProps property under-the-covers but it is in an additional injected .js file, not in an inline script block like in the running page. It's possible that the location of that script in the editor's markup is incorrect and we will investigate that. However there's a larger issue here, which is that a page in the editor is not able to make calls to the Worklight server. Because the editor always needs to operate independently of whether a preview server has been published and started, it uses its own mechanism to load web resources into the Design pane. Therefore the origin server is not the Worklight development server and attempted calls to server-side logic will go unanswered. I believe this is more likely the reason for the hang scenarios you see. A general recommendation is to use the editor to construct the page's UI markup and then start to wire in service calls after the UI is generally complete. At that point previewing the application should likely shift over to the Mobile Browser Simulator and/or native device testing. In order to continue to do incremental UI work in the editor you can also add some temporary conditional logic to avoid (or mock-up) server calls while doing design work, such as: var designMode = true; // switch to false for real server preview if(!designMode) { // your service invocations here }
[ "askubuntu", "0000178868.txt" ]
Q: Why do some PDFs have such ugly fonts in Document Viewer? Why are the fonts in Document Viewer so ugly and non-antialiased? A: My guess is that you see this behavior only for some documents, right? In that case I think that you see output from an old LaTeX version with standard LaTeX bitmap fonts. I have found the document that you are showing and the fonts are non-aliased also on my system -- although I know that regular documents look perfect. It's also non-aliased under Windows, so there.
[ "stackoverflow", "0044978717.txt" ]
Q: rails - adding html div tags while looping through array I'm trying to display a conversation in my html.erb file. I'm using a specific template and want to copy their chat section. Here's the chat section: http://webapplayers.com/inspinia_admin-v2.7.1/chat_view.html I noticed that their chat "bubbles" are just different divs. Like this: <div class="chat-message left"> <img class="message-avatar" src="<%= image_path('a1.jpg') %>" alt=""> <div class="message"> <a class="message-author" href="#"> Michael Smith </a> <span class="message-date"> Mon Jan 26 2015 - 18:39:23 </span> <span class="message-content"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </span> </div> </div> <div class="chat-message right"> <img class="message-avatar" src="<%= image_path('a4.jpg') %>" alt=""> <div class="message"> <a class="message-author" href="#"> Karl Jordan </a> <span class="message-date"> Fri Jan 25 2015 - 11:12:36 </span> <span class="message-content"> Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover. </span> </div> </div> If i have an array of @messages in my html.erb file, how can I traverse the array and for every message add one of those div sections in order to make my chat view? Alternatively, I will have to put it in some sort of table with each row styled depending on whether the message is incoming or outbound. A: You can do this by just iterating @messages with @messages.each do |message|...end and then within the block have your divs with the message contents. A cleaner way might be to set up a _chat_view.html.erb partial with these divs and then in your main html.erb file you can do render partial: 'chat_view', collection: @messages and you still get the message object in the partial that you can use.
[ "askubuntu", "0001250648.txt" ]
Q: Kept back upgrade of fwupd What's wrong now with fwupd? It was OK since May 1st, 2020 on newly installed Ubuntu 20.04 The following packages have been kept back: fwupd 0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded. A: It's a partial fix for a bug LP #1883568 Both packages, fwupd and fwupd-signed should be installed. One was uploaded, the other was uploaded later. So there was briefly a version mismatch, which prevented the new fwupd from installing. There is Bug report on the mismatch: LP #1883595, and the fwupd-signed package has been uploaded to -proposed. Time to be patient. Simply wait until fwupd-signed catches up, then both will install together automagically. Do not try to force the newer version using dist-upgrade or full-upgrade. If you already did, then simply ensure that you have both packages installed.
[ "ru.stackoverflow", "0000172772.txt" ]
Q: В Opera 10 не поддерживается $.getScript В Opera 10 не подключается /js/all.js, а в Opera 12 нормально. Как исправить? Или может естсь другое кроссбраузерное решение? $.get('/', function(data) { $.getScript('/js/all.js?'+Math.random()); }); A: Только что проверил на Opera 10 Beta, всё отлично работает. Также можно проверить на страничке документации: http://api.jquery.com/jQuery.getScript/ Проверяйте свой код на наличие ошибок.
[ "stackoverflow", "0046123260.txt" ]
Q: AngularDart: cannot cast to a material component I have a dart app that contains a template with a material-checkbox which I am unable to use in my component. Here is a simple template to demonstrate the problem (two_boxes.html): <!-- Simple HTML to test checkboxes --> <input type="checkbox" id="cb0"> <label>Standard Checkbox</label> <material-checkbox label="Material Checkbox" id="cb1"> </material-checkbox> <button (click)="doTest()">Test</button> and the corresponding component in which I try to use the checkboxes (two_boxes.dart). I can use the standard checkbox in a cast as expected but cannot find a way to do the same with the material checkbox: // Component for testing import 'package:angular/angular.dart'; import 'package:angular_components/angular_components.dart'; import 'dart:html'; @Component( selector: 'two-boxes', templateUrl: 'two_boxes.html', directives: const [MaterialCheckboxComponent], pipes: const [ COMMON_PIPES ]) class TwoBoxes { // Get the the two checkboxes and see if they are checked void doTest() { var checkbox_standard = querySelector("#cb0"); print(checkbox_standard.runtimeType.toString()); // InputElement print((checkbox_standard as CheckboxInputElement).checked); // Succeeds var checkbox_material = querySelector("#cb1"); print(checkbox_material.runtimeType.toString()); // HtmlElement print((checkbox_material as MaterialCheckboxComponent).checked); // Error! } } The last statement fails when I run the app in Dartium following a "pub serve" (no errors) with: VM54:1 EXCEPTION: type 'HtmlElementImpl' is not a subtype of type MaterialCheckboxComponent' in type cast where HtmlElementImpl is from dart:html MaterialCheckboxComponent is from package:angular_components/src/components/ material_checkbox/material_checkbox.dart Clearly this way of casting does not work. I searched for hours how to solve this error and find the correct way to do this but obviously in the wrong places. What am I missing here? I am using Dart VM version 1.24.2. A: There is no way to get the component instance from an element queried this way. You can use @ViewChild() class TwoBoxes implements AfterViewInit { @ViewChild(MaterialCheckboxComponent) MaterialCheckboxComponent cb; ngAfterViewInit() { print(cb.checked); } to get a specific one if you have more than one, you can use a template variable <material-checkbox #foo label="Material Checkbox"> with @ViewChild('foo') MaterialCheckboxComponent cb; You can find more information about this topic in this TypeScript answer angular 2 / typescript : get hold of an element in the template The syntax is a bit different (type annotations on the right and {} around the optional read parameter, which are not used in Dart.
[ "stackoverflow", "0034338125.txt" ]
Q: this Keyword and static Methods - Flex The this keyword cannot be used in static methods. I am using static methods by design but also need to pop up a window with the method. Here is the code I have. I observed the createPopUp method of PopUpManager class and it needs a DisplayObject as a first argument. this is the DisplayObject but I did not get what is DisplayObject at that point. So how can I replace this to corresponding/correct DisplayObject? public static function UniteDetayPopup(f:Function):void { var uniteler:UniteDetay = PopUpManager.createPopUp(this, UniteDetay, true) as UniteDetay; PopUpManager.centerPopUp(uniteler); } edit: it is in a TitleWindow component and it pops up with other component. A: You can just pass Application instance to this method. var uniteler:UniteDetay = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject, UniteDetay, true) as UniteDetay;
[ "stackoverflow", "0049695366.txt" ]
Q: Copy data in one column to a different column on another sheet based on a third column's data So, I'm very new to VBA and I am having a difficult time finding answers to what I believe should be a fairly straightforward question. I have a workbook that has 2 sheets, which we will call Sheet1 and Sheet2. I want to copy data from columns B, D and E on Sheet1 to the first available row in columns A, B and C on Sheet 2, with the following changes: Sheet1 Sheet2 Col E Col A Col D Col B Col B Col C But I only want the data to be copied if the cell value of each row in Sheet1 Column I is "Y". I don't have any code for this yet. UPDATE: After taking advice from a response, I ran a Macro record and got this: Sub VBlk() ' ' VBlk Macro ' V Block Copy ' ' Range("B2").Select Selection.Copy Sheets("Sheet2").Select Range("C3").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("B3").Select Sheets("Sheet1").Select Range("D2").Select Application.CutCopyMode = False Selection.Copy Sheets("Sheet2").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Sheets("Sheet1").Select Range("E2").Select Application.CutCopyMode = False Selection.Copy Sheets("Sheet2").Select Range("A3").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False End Sub A: Try the code below (Hope it helps) : Sub test() Dim ws1 As Worksheet Dim ws2 As Worksheet Set ws1 = Sheets("sheet1") Set ws2 = Sheets("sheet2") 'get the Last non empty row in sheet1 based on Column B lastrow1 = ws1.Cells(Rows.Count, 2).End(xlUp).Row For i = 1 To lastrow1 'get the Last non empty row in sheet2 based on Column A lastrow2 = ws2.Cells(Rows.Count, 1).End(xlUp).Row If ws1.Range("I" & i).Value = "Y" Then ws2.Range("A" & lastrow2 + 1).Value = ws1.Range("E" & i) ws2.Range("B" & lastrow2 + 1).Value = ws1.Range("D" & i) ws2.Range("C" & lastrow2 + 1).Value = ws1.Range("B" & i) End If Next i End Sub
[ "stackoverflow", "0030028501.txt" ]
Q: How to test hadoop job performance I've implemented a frequent itemset map-reduce algorithm based on SON for Apache Hadoop. Now I need to test its performance, i.e. study how its execution time varies using different datasets and compare it with different versions of the algorithm in order to choose the best one. So, I run several jobs on a 6-machines cluster and I have noticed that the execution time varies significantly even keeping the same dataset and the same algorithm version. I have come to the conclusion that in this type of environment the execution time is unpredictable because of the (un)availability of requested data in the machine where the computation runs. How can I run this type of test in a reliable way? A: Its common that at sometimes same Hadoop job takes varying over all time for the same dataset with same configurations. The main reason might be the availability of the execution containers to process the Map/Reduce tasks , which is uncertain. The Elapsed of time of a job can be uncertain because the cluster where you run the job might be much busy with other jobs at sometimes when you run the job, your job might be getting very lesser containers for the execution. If you are working on benchmarking job, dataset or configurations, then first make sure that the cluster very much free and the all the nodes are up and running. One thing we can always notice to observe the job performance is from the job completion page consider the values of Average Map Time, Average Reduce Time,Average Shuffle Time, Average Merge Time , these metrics provide you reliable statistics across many job runs. The Elapsed time value might vary due to the resource availability.
[ "stackoverflow", "0060214656.txt" ]
Q: PayPal Smart Payments: changing the currency code I'm trying to set up PayPal Smart Payments on a webpage. I'm using the example they give on here: https://developer.paypal.com/docs/checkout/integrate/ If I have currency_code set to USD it works fine, but if I change it to anything else, such as CAD or GBP the window won't load. What am I doing wrong? <script src="https://www.paypal.com/sdk/js?client-id=sb"></script> <script> paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ 'purchase_units': [{ 'amount': { 'currency_code': 'USD', 'value': '5', }, }] }) } }).render('body') </script> For some reason this example won't run here on Stack Overflow, but it runs fine on JSFiddle, so I have made two examples with the currency_code set differently. 'currency_code': 'USD': https://jsfiddle.net/liquidmetalrob/8y3p52fh/ 'currency_code': 'GBP': https://jsfiddle.net/liquidmetalrob/8y3p52fh/1 The first example will load the PayPal window, and you need a PayPal Sandbox account to log into it. So if you want to log in you can use the throwaway account that I just created. Username: [email protected] password: pRKCu9.> But the important question is why does the window not even load in the second example? A: I found the answer here: https://developer.paypal.com/docs/checkout/reference/customize-sdk/ You have to add the currency code to the script URL instead, and remove it from the JS. <script src="https://www.paypal.com/sdk/js?client-id=sb&currency=GBP"> </script> <script> paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ 'purchase_units': [{ 'amount': { 'value': '5', }, }] }) } }).render('body') </script> Note: The client-id can be set to sb for testing, but in production you use your own one.
[ "stackoverflow", "0005473580.txt" ]
Q: How to make a subview automatically resize with its superview? I have a view which contains one sub-view; this sub-view itself contains another sub-view, which is meant to be slightly smaller than its superview. I am creating the first subview full-screen size then shrinking it to a very small size on the screen. When the subview is tapped, I animate it from its small size to full-screen. The problem is that my second subview never resizes itself during this animation - it is always rendered full-size and overflows the bounds of its superview. Is there a simple way to get a subview to keep itself sized proportionally as its superview changes size? A: you could add the autoresizing-behavior programmatically Objective-C subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; Swift 3.x subview.autoresizingMask = [.flexibleWidth, .flexibleHeight] Swift 2.x subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] In Interface-Builder navigate to tab 3 and click on the arrows in the middle ;D Another workaround could be to implement the setFrame-method and always adapt it to the size of the superview (not the given frame.size). Don't forget to set up the origin as you need it. - (void) setFrame:(CGRect)frame { CGRect rect = self.superview.frame; rect.origin.x = 0; rect.origin.y = 0; [super setFrame:rect]; } A: this does the trick for me subview.frame = subview.superview.bounds; A: If you're using only [.flexibleWidth, .flexibleHeight] for your autoresizing mask, your subview will not get resized proportionally. The right answer is: autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
[ "stackoverflow", "0013507642.txt" ]
Q: mysql date comparison with date_format I googled and tried several ways to compare date but unfortunately didn't get the result as expected. I have current state of records like following: mysql> select date_format(date(starttime),'%d-%m-%Y') from data; +-----------------------------------------+ | date_format(date(starttime),'%d-%m-%Y') | +-----------------------------------------+ | 28-10-2012 | | 02-11-2012 | | 02-11-2012 | | 02-11-2012 | | 03-11-2012 | | 03-11-2012 | | 07-11-2012 | | 07-11-2012 | I would like to compare date and therefore do like this: mysql> select date_format(date(starttime),'%d-%m-%Y') from data where date_format(date(starttime),'%d-%m-%y') >= '02-11-2012'; +-----------------------------------------+ | date_format(date(starttime),'%d-%m-%Y') | +-----------------------------------------+ | 28-10-2012 | | 02-11-2012 | | 02-11-2012 | | 02-11-2012 | | 03-11-2012 | | 03-11-2012 | | 07-11-2012 | | 07-11-2012 | I believe that the result should not include '28-10-2012'. Any suggestion? Thanks in advance. A: Your format is fundamentally not a sortable one to start with - you're comparing strings, and the string "28-10-2012" is greater than "02-11-2012". Instead, you should be comparing dates as dates, and then only converting them into your target format for output. Try this: select date_format(date(starttime),'%d-%m-%Y') from data where date(starttime) >= date '2012-11-02'; (The input must always be in year-month-value form, as per the documentation.) Note that if starttime is a DATETIME field, you might want to consider changing the query to avoid repeated conversion. (The optimizer may well be smart enough to avoid it, but it's worth checking.) select date_format(date(starttime),'%d-%m-%Y') from data where starttime >= '2012-11-02 00:00:00'; (Note that it's unusual to format a date as d-m-Y to start with - it would be better to use y-M-d in general, being the ISO-8601 standard etc. However, the above code does what you asked for in the question.)
[ "stackoverflow", "0025213162.txt" ]
Q: Does calling an async method within BeginInvoke() spawn a 'new' thread? 'New' meaning from a thread pool. Given the example below, my assumptions are: Main method executes on one thread (eg. thread 1) BeginInvoke uses available thread in pool to execute AsyncDemo.TestMethod (thread 2) An async method call, eg WebClient.UploadStringAsync uses another available thread (thread 3) Number three is where my question stems from, The definition of WebClient.UploadStringAsync: Uploads the specified string to the specified resource. These methods do not block the calling thread. Does this mean it uses another available thread in the pool? Is this an ill-advised technique (async within an async)? My ultimate goal is to post some data asynchronously (fire and forget), and was using UploadStringAsync previously. Now I have decided to encapsulate the surrounding code with BeginInvoke as well, but thinking if I have to change the UploadStringAsync to a synchronous method instead (UploadString()). Thanks for any help! public class AsyncMain { // The delegate will be called asynchronously. public delegate string AsyncMethodCaller(out int threadId); public static void Main() { // The asynchronous method puts the thread id here. int threadId; //Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(AsyncDemo.TestMethod); // Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(out threadId, null, null); Console.WriteLine("In AsyncMain.Main() Thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); // Call EndInvoke to wait for the asynchronous call to complete, // and to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The async call executed on thread {0}, has responded with \"{1}\". The result is {2}", threadId, returnValue, result); } } public class AsyncDemo { // The method to be executed asynchronously. public static string TestMethod(out int threadId) { //get threadId, assign it. threadId = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("TestMethod() begins at thread {0}", threadId); //Do work //Do ASYNC Method such as: WebClient.UploadStringAsync return String.Format("I'm finished my work."); } } A: Does this mean it uses another available thread in the pool? Short answer: yes. According to the docs for UploadStringAsync: The string is sent asynchronously using thread resources that are automatically allocated from the thread pool. And BeginInvoke uses a thread from the thread pool to accomplish its asynchronous behavior. Is this an ill-advised technique (async within an async)? If you need asynchronous behavior at both levels, then you do what you gotta do. In general, though, the best advice is to write the simplest code you can that will work, so if you can get away with just one level of indirection, I'd say go for it. It's unfortunate that you can't upgrade to a newer version of .NET, because with newer versions you can accomplish the same thing much more simply using Tasks: public static void Main() { Task<string> task = AsyncDemo.TestMethod(); Console.WriteLine("In AsyncMain.Main() Thread {0} does some work.", Thread.CurrentThread.ManagedThreadId); string returnValue = task.Result; // This will cause the main thread to block until the result returns. Console.WriteLine("The async call executed on thread {0}, has responded with \"{1}\". The result is {2}", threadId, returnValue, result); } public class AsyncDemo { // The method to be executed asynchronously. public async static Task<string> TestMethod() { Console.WriteLine("TestMethod() begins"); //Do work await new WebClient().UploadStringTaskAsync("...", "..."); return String.Format("I'm finished my work."); } }
[ "stackoverflow", "0020038398.txt" ]
Q: runhaskell Setup install Setup error I am trying to install packages from haskell's Hackage using Cabal. In particular, I am trying to download the gloss package: cabal install gloss Comes up with this error: binary-0.7.1.0 failed during the building phase. The exception was: ExitFailure 1 bmp-1.2.5.2 depends on binary-0.7.1.0 which failed to install. gloss-1.8.1.1 depends on binary-0.7.1.0 which failed to install. I also tried binary-0.6.0.0. Because cabal install is not working, I am trying: runhaskell Setup configure runhaskell Setup build runhaskell Setup install ...in the directory of the package, and I get the same error for every package: Setup: Error: Could not find module: Data.Binary with any suffix: ["hi"] in the search path: ["dist/build"] I am also having trouble installing the newest version of Cabal. cabal-install version 1.16.0.2 using version 1.16.0 of the Cabal library The Glorious Glasgow Haskell Compilation System, version 7.6.3 Mac OSX 10.8 on MacBook Pro Retina A: The binary package fails to install on latest versions of osx because osx uses clang instead of gcc, and 'gcc' is usually just a symlink to clang. gcc is used in the pre-processor stage (haskell supports c-like macros) but clang does not support all the features for the pre-processor stage that gcc supports. To know if this is your problem, type 'gcc' in the terminal. If it says 'clang' somewhere, then this is the issue. The solution is to get gcc, and replace the symlink to gcc with real gcc. Using 'runhaskell' will still have the same issue. For the most part, you should never try to install packages without cabal, it is by far the easiest way.
[ "stackoverflow", "0000250849.txt" ]
Q: Thumbs up/Thumbs Down Rating Implementation Similar to the one here on StackOverFlow, I would be needing to implement a way for people to vote up and vote down comments in a forum like site. However instead of having a generic overall score, we will display the total amount of "thumbs up" and "thumbs down". The overall score will be needed for filtering purposes, such as "sort by highest rated", "show only ratings with + 3" What is the best implementation strategy? As a user suggested, I would also be storing the information who casted the vote A: Well you'll need to store ratings (Comment ID, UserID, Vote-Value) so you can calculate and stop duplicate voting but I would strongly suggest you also add a VotesUp and VotesDown fields on your main comment entity. Why the duplication? Speed. You're going to be doing disgusting amounts of SUM-WHERE statements otherwise and they'll run your database server into the ground. A few extra bytes on the header record and you'll be able to sort and filter to your heart's content. Edit: If you're going to also sort by overall score in some cases, you might want to add a third field (VoteTotal). Edit 2: The duplication is pointless if you're able to cache all the comment headers in memory. That's a lot of data though and you'd need a ton of memory to effectively cache it. If you're not a billionaire, I'd just duplicate the data.